remg1997 commited on
Commit
9c897b5
·
verified ·
1 Parent(s): e722102

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertSmallForMaskedLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "attention_pattern": "alternating",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_modernbert_small.ModernBertSmallConfig",
9
+ "AutoModelForMaskedLM": "modeling_modernbert_small.ModernBertSmallForMaskedLM"
10
+ },
11
+ "dtype": "float32",
12
+ "embedding_dropout": 0.0,
13
+ "embedding_type": "factorized_linear",
14
+ "factorized_linear_bottleneck_dim": 128,
15
+ "factorized_mlp_bottleneck_dim": 128,
16
+ "global_attn_every_n_layers": 3,
17
+ "global_rope_theta": 160000.0,
18
+ "hidden_activation": "gelu",
19
+ "hidden_size": 384,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 576,
22
+ "local_attention_window": 128,
23
+ "local_rope_theta": 10000.0,
24
+ "mlp_dropout": 0.0,
25
+ "model_type": "modernbert_small",
26
+ "norm_eps": 1e-05,
27
+ "num_attention_heads": 6,
28
+ "num_hidden_layers": 16,
29
+ "pad_token_id": 0,
30
+ "tie_word_embeddings": false,
31
+ "transformers_version": "4.57.6",
32
+ "vocab_size": 30522
33
+ }
configuration_modernbert_small.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+ from transformers import PretrainedConfig
6
+
7
+ from babylm.config.schema import ModelConfig
8
+
9
+
10
+ class ModernBertSmallConfig(PretrainedConfig):
11
+ """HF-compatible config for the from-scratch ModernBERT-Small architecture.
12
+
13
+ Bridges to the pydantic `ModelConfig` (used for JSON validation/CLI) via `to_hf_config`,
14
+ while giving `save_pretrained`/`from_pretrained`/`AutoConfig` compatibility.
15
+ """
16
+
17
+ model_type = "modernbert_small"
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_size: int = 30522,
22
+ hidden_size: int = 384,
23
+ num_hidden_layers: int = 16,
24
+ num_attention_heads: int = 6,
25
+ intermediate_size: int = 576,
26
+ hidden_activation: str = "gelu",
27
+ attention_pattern: str = "alternating",
28
+ global_attn_every_n_layers: int = 3,
29
+ global_rope_theta: float = 160000.0,
30
+ local_rope_theta: float = 10000.0,
31
+ local_attention_window: int = 128,
32
+ norm_eps: float = 1e-5,
33
+ attention_dropout: float = 0.0,
34
+ mlp_dropout: float = 0.0,
35
+ embedding_dropout: float = 0.0,
36
+ embedding_type: str = "standard",
37
+ factorized_linear_bottleneck_dim: int = 128,
38
+ factorized_mlp_bottleneck_dim: int = 128,
39
+ initializer_range: float = 0.02,
40
+ pad_token_id: int = 0,
41
+ tie_word_embeddings: bool = True,
42
+ **kwargs,
43
+ ) -> None:
44
+ super().__init__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
45
+ self.vocab_size = vocab_size
46
+ self.hidden_size = hidden_size
47
+ self.num_hidden_layers = num_hidden_layers
48
+ self.num_attention_heads = num_attention_heads
49
+ self.intermediate_size = intermediate_size
50
+ self.hidden_activation = hidden_activation
51
+ self.attention_pattern = attention_pattern
52
+ self.global_attn_every_n_layers = global_attn_every_n_layers
53
+ self.global_rope_theta = global_rope_theta
54
+ self.local_rope_theta = local_rope_theta
55
+ self.local_attention_window = local_attention_window
56
+ self.norm_eps = norm_eps
57
+ self.attention_dropout = attention_dropout
58
+ self.mlp_dropout = mlp_dropout
59
+ self.embedding_dropout = embedding_dropout
60
+ self.embedding_type = embedding_type
61
+ self.factorized_linear_bottleneck_dim = factorized_linear_bottleneck_dim
62
+ self.factorized_mlp_bottleneck_dim = factorized_mlp_bottleneck_dim
63
+ self.initializer_range = initializer_range
64
+
65
+
66
+ def to_hf_config(model_cfg: ModelConfig, pad_token_id: Optional[int] = None) -> ModernBertSmallConfig:
67
+ """Builds a ModernBertSmallConfig from the pydantic ModelConfig, optionally overriding
68
+ pad_token_id with the value discovered from a trained tokenizer."""
69
+ data = model_cfg.model_dump()
70
+ if pad_token_id is not None:
71
+ data["pad_token_id"] = pad_token_id
72
+ return ModernBertSmallConfig(**data)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39335d6881ad2f82d46f33216ff40c73c2141c6c1069e1eae8904533cb6e0939
3
+ size 143701720
modeling_modernbert_small.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from transformers import PreTrainedModel
9
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
10
+
11
+ from babylm.model.attention import build_global_attention_mask, build_local_attention_mask, resolve_attention_types
12
+ from babylm.model.configuration_modernbert_small import ModernBertSmallConfig
13
+ from babylm.model.embeddings import get_embedding_class
14
+ from babylm.model.layer import ModernBertSmallEncoderLayer
15
+ from babylm.model.rotary import RotaryEmbedding
16
+
17
+
18
+ class ModernBertSmallPreTrainedModel(PreTrainedModel):
19
+ config_class = ModernBertSmallConfig
20
+ base_model_prefix = "model"
21
+ supports_gradient_checkpointing = False
22
+
23
+ def _init_weights(self, module: nn.Module) -> None:
24
+ std = self.config.initializer_range
25
+ if isinstance(module, nn.Linear):
26
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
27
+ if module.bias is not None:
28
+ module.bias.data.zero_()
29
+ elif isinstance(module, nn.Embedding):
30
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
31
+ if module.padding_idx is not None:
32
+ module.weight.data[module.padding_idx].zero_()
33
+ elif isinstance(module, nn.LayerNorm):
34
+ module.weight.data.fill_(1.0)
35
+ if module.bias is not None:
36
+ module.bias.data.zero_()
37
+
38
+
39
+ class ModernBertSmallModel(ModernBertSmallPreTrainedModel):
40
+ """The bare encoder: pluggable embeddings -> alternating/uniform-global attention stack ->
41
+ final LayerNorm. RoPE cos/sin and attention masks are computed once per forward pass (one
42
+ global-theta pair, one local-theta pair) and shared across every matching layer."""
43
+
44
+ def __init__(self, config: ModernBertSmallConfig) -> None:
45
+ super().__init__(config)
46
+ embedding_cls = get_embedding_class(config.embedding_type)
47
+ self.embeddings = embedding_cls(config)
48
+
49
+ attention_types = resolve_attention_types(
50
+ config.num_hidden_layers, config.attention_pattern, config.global_attn_every_n_layers
51
+ )
52
+ self.layers = nn.ModuleList(
53
+ [
54
+ ModernBertSmallEncoderLayer(config, layer_idx, attention_type)
55
+ for layer_idx, attention_type in enumerate(attention_types)
56
+ ]
57
+ )
58
+
59
+ head_dim = config.hidden_size // config.num_attention_heads
60
+ self.global_rotary_emb = RotaryEmbedding(head_dim, config.global_rope_theta)
61
+ self.local_rotary_emb = RotaryEmbedding(head_dim, config.local_rope_theta)
62
+ self.local_window_radius = config.local_attention_window // 2
63
+ self.final_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=False)
64
+
65
+ self.post_init()
66
+
67
+ def get_input_embeddings(self) -> nn.Module:
68
+ return self.embeddings
69
+
70
+ def set_input_embeddings(self, value: nn.Module) -> None:
71
+ self.embeddings = value
72
+
73
+ def forward(
74
+ self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs
75
+ ) -> BaseModelOutput:
76
+ batch, seq_len = input_ids.shape
77
+ device = input_ids.device
78
+ if attention_mask is None:
79
+ attention_mask = torch.ones(batch, seq_len, device=device, dtype=torch.long)
80
+
81
+ hidden_states = self.embeddings(input_ids)
82
+
83
+ global_mask = build_global_attention_mask(attention_mask)
84
+ local_mask = build_local_attention_mask(attention_mask, self.local_window_radius)
85
+ global_cos, global_sin = self.global_rotary_emb(seq_len, device, hidden_states.dtype)
86
+ local_cos, local_sin = self.local_rotary_emb(seq_len, device, hidden_states.dtype)
87
+
88
+ for layer in self.layers:
89
+ if layer.attn.attention_type == "global":
90
+ mask, cos, sin = global_mask, global_cos, global_sin
91
+ else:
92
+ mask, cos, sin = local_mask, local_cos, local_sin
93
+ hidden_states = layer(hidden_states, mask, cos, sin)
94
+
95
+ hidden_states = self.final_norm(hidden_states)
96
+ return BaseModelOutput(last_hidden_state=hidden_states)
97
+
98
+
99
+ class ModernBertSmallForMaskedLM(ModernBertSmallPreTrainedModel):
100
+ """MLM head: Dense(d->d, no bias) -> GELU -> LayerNorm(no bias) -> decoder(d->vocab, bias).
101
+ The decoder weight is tied to the embedding module's output weight (when it defines one)."""
102
+
103
+ def __init__(self, config: ModernBertSmallConfig) -> None:
104
+ super().__init__(config)
105
+ self.model = ModernBertSmallModel(config)
106
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
107
+ self.head_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=False)
108
+ output_weight = self.model.embeddings.get_output_embedding_weight()
109
+ self.output_proj: Optional[nn.Linear] = None
110
+ self.decoder_bias: Optional[nn.Parameter] = None
111
+
112
+ if (
113
+ config.tie_word_embeddings
114
+ and output_weight is not None
115
+ and output_weight.shape[1] != config.hidden_size
116
+ ):
117
+ bottleneck_dim = output_weight.shape[1]
118
+ self.output_proj = nn.Linear(config.hidden_size, bottleneck_dim, bias=False)
119
+ self.decoder = None
120
+ self.decoder_bias = nn.Parameter(torch.zeros(config.vocab_size))
121
+ self._tied_weights_keys = []
122
+ else:
123
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
124
+ self._tied_weights_keys = ["decoder.weight"] if config.tie_word_embeddings else []
125
+ self.post_init()
126
+
127
+ def get_input_embeddings(self) -> nn.Module:
128
+ return self.model.get_input_embeddings()
129
+
130
+ def set_input_embeddings(self, value: nn.Module) -> None:
131
+ self.model.set_input_embeddings(value)
132
+
133
+ def get_output_embeddings(self) -> nn.Module:
134
+ return self.decoder if self.decoder is not None else self.output_proj
135
+
136
+ def set_output_embeddings(self, value: nn.Module) -> None:
137
+ if self.decoder is not None:
138
+ self.decoder = value
139
+ else:
140
+ self.output_proj = value
141
+
142
+ def tie_weights(self) -> None:
143
+ if not getattr(self.config, "tie_word_embeddings", True):
144
+ return
145
+ output_weight = self.model.embeddings.get_output_embedding_weight()
146
+ if output_weight is None:
147
+ return
148
+ if self.decoder is None:
149
+ return
150
+ self.decoder.weight = output_weight
151
+
152
+ def forward(
153
+ self,
154
+ input_ids: torch.Tensor,
155
+ attention_mask: Optional[torch.Tensor] = None,
156
+ labels: Optional[torch.Tensor] = None,
157
+ **kwargs,
158
+ ) -> MaskedLMOutput:
159
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
160
+ hidden_states = self.head_norm(F.gelu(self.dense(outputs.last_hidden_state)))
161
+ if self.output_proj is not None:
162
+ output_weight = self.model.embeddings.get_output_embedding_weight()
163
+ logits = F.linear(self.output_proj(hidden_states), output_weight, self.decoder_bias)
164
+ else:
165
+ logits = self.decoder(hidden_states)
166
+
167
+ loss = None
168
+ if labels is not None:
169
+ loss = F.cross_entropy(
170
+ logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100
171
+ )
172
+
173
+ return MaskedLMOutput(loss=loss, logits=logits)
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3a00f6495d4933c2e93feb6bc9c81710648d078ed782024960720c95eba37f2
3
+ size 287499467
rng_state.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7400b318a43f4e8724299d15f445f881e45efa4886433be2c9449629bffe3a7c
3
+ size 14455
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c59d98e7f49d748953e6dfad099811cb493aa2b1d98d54450091e6a3176535ca
3
+ size 1465
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "extra_special_tokens": {},
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 1000000000000000019884624838656,
49
+ "pad_token": "[PAD]",
50
+ "sep_token": "[SEP]",
51
+ "tokenizer_class": "PreTrainedTokenizerFast",
52
+ "unk_token": "[UNK]"
53
+ }
trainer_state.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"step": 9069, "cumulative_wall_seconds": 18772.55534029007, "cumulative_gpu_seconds": 18772.55534029007, "cumulative_flops": 1.972650487106765e+16, "cumulative_words_seen": 100001352.76000977}