remg1997 commited on
Commit
4784dd3
·
verified ·
1 Parent(s): 989f61e

Upload folder using huggingface_hub

Browse files
config.json ADDED
The diff for this file is too large to render. See raw diff
 
configuration_modernbert_small.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sttp_rank: int = 8,
40
+ sttp_num_factors: int = 3,
41
+ pete_basis_dim: int = 384,
42
+ compositional_bottleneck_dim: int = 128,
43
+ compositional_num_buckets: int = 8192,
44
+ compositional_min_ngram: int = 1,
45
+ compositional_max_ngram: int = 4,
46
+ compositional_residual_mode: str = "none",
47
+ compositional_frequency_tau: float = 100.0,
48
+ compositional_frequency_shuffle_seed: int = 42,
49
+ geometry_penalty_mode: str = "none",
50
+ geometry_penalty_weight: float = 0.01,
51
+ geometry_sample_size: int = 2048,
52
+ geometry_sampling_mode: str = "zipfian",
53
+ compositional_token_strings: Optional[list[str]] = None,
54
+ token_frequencies: Optional[list[int]] = None,
55
+ special_token_ids: Optional[list[int]] = None,
56
+ initializer_range: float = 0.02,
57
+ pad_token_id: int = 0,
58
+ tie_word_embeddings: bool = True,
59
+ **kwargs,
60
+ ) -> None:
61
+ super().__init__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
62
+ self.vocab_size = vocab_size
63
+ self.hidden_size = hidden_size
64
+ self.num_hidden_layers = num_hidden_layers
65
+ self.num_attention_heads = num_attention_heads
66
+ self.intermediate_size = intermediate_size
67
+ self.hidden_activation = hidden_activation
68
+ self.attention_pattern = attention_pattern
69
+ self.global_attn_every_n_layers = global_attn_every_n_layers
70
+ self.global_rope_theta = global_rope_theta
71
+ self.local_rope_theta = local_rope_theta
72
+ self.local_attention_window = local_attention_window
73
+ self.norm_eps = norm_eps
74
+ self.attention_dropout = attention_dropout
75
+ self.mlp_dropout = mlp_dropout
76
+ self.embedding_dropout = embedding_dropout
77
+ self.embedding_type = embedding_type
78
+ self.factorized_linear_bottleneck_dim = factorized_linear_bottleneck_dim
79
+ self.factorized_mlp_bottleneck_dim = factorized_mlp_bottleneck_dim
80
+ self.sttp_rank = sttp_rank
81
+ self.sttp_num_factors = sttp_num_factors
82
+ self.pete_basis_dim = pete_basis_dim
83
+ self.compositional_bottleneck_dim = compositional_bottleneck_dim
84
+ self.compositional_num_buckets = compositional_num_buckets
85
+ self.compositional_min_ngram = compositional_min_ngram
86
+ self.compositional_max_ngram = compositional_max_ngram
87
+ self.compositional_residual_mode = compositional_residual_mode
88
+ self.compositional_frequency_tau = compositional_frequency_tau
89
+ self.compositional_frequency_shuffle_seed = compositional_frequency_shuffle_seed
90
+ self.geometry_penalty_mode = geometry_penalty_mode
91
+ self.geometry_penalty_weight = geometry_penalty_weight
92
+ self.geometry_sample_size = geometry_sample_size
93
+ self.geometry_sampling_mode = geometry_sampling_mode
94
+ self.compositional_token_strings = compositional_token_strings
95
+ self.token_frequencies = token_frequencies
96
+ self.special_token_ids = special_token_ids or []
97
+ self.initializer_range = initializer_range
98
+
99
+
100
+ def to_hf_config(model_cfg: ModelConfig, pad_token_id: Optional[int] = None) -> ModernBertSmallConfig:
101
+ """Builds a ModernBertSmallConfig from the pydantic ModelConfig, optionally overriding
102
+ pad_token_id with the value discovered from a trained tokenizer."""
103
+ data = model_cfg.model_dump()
104
+ if pad_token_id is not None:
105
+ data["pad_token_id"] = pad_token_id
106
+ return ModernBertSmallConfig(**data)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08073632af2bbb942c5ac108ff4ce6151453f4a948b96811f9a03cb7d064810d
3
+ size 101333640
modeling_modernbert_small.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import nn
9
+ from transformers import PreTrainedModel
10
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
11
+
12
+ from babylm.model.attention import build_global_attention_mask, build_local_attention_mask, resolve_attention_types
13
+ from babylm.model.configuration_modernbert_small import ModernBertSmallConfig
14
+ from babylm.model.embeddings import get_embedding_class
15
+ from babylm.model.geometry import geometry_penalty
16
+ from babylm.model.layer import ModernBertSmallEncoderLayer
17
+ from babylm.model.rotary import RotaryEmbedding
18
+
19
+
20
+ @dataclass
21
+ class MaskedLMGeometryOutput(MaskedLMOutput):
22
+ mlm_loss: Optional[torch.Tensor] = None
23
+ geometry_loss: Optional[torch.Tensor] = None
24
+ geometry_centering_loss: Optional[torch.Tensor] = None
25
+ geometry_whitening_loss: Optional[torch.Tensor] = None
26
+
27
+
28
+ class ModernBertSmallPreTrainedModel(PreTrainedModel):
29
+ config_class = ModernBertSmallConfig
30
+ base_model_prefix = "model"
31
+ supports_gradient_checkpointing = False
32
+
33
+ def _init_weights(self, module: nn.Module) -> None:
34
+ std = self.config.initializer_range
35
+ if isinstance(module, nn.Linear):
36
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
37
+ if module.bias is not None:
38
+ module.bias.data.zero_()
39
+ elif isinstance(module, (nn.Embedding, nn.EmbeddingBag)):
40
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
41
+ if module.padding_idx is not None:
42
+ module.weight.data[module.padding_idx].zero_()
43
+ elif isinstance(module, nn.LayerNorm):
44
+ module.weight.data.fill_(1.0)
45
+ if module.bias is not None:
46
+ module.bias.data.zero_()
47
+
48
+
49
+ class ModernBertSmallModel(ModernBertSmallPreTrainedModel):
50
+ """The bare encoder: pluggable embeddings -> alternating/uniform-global attention stack ->
51
+ final LayerNorm. RoPE cos/sin and attention masks are computed once per forward pass (one
52
+ global-theta pair, one local-theta pair) and shared across every matching layer."""
53
+
54
+ def __init__(self, config: ModernBertSmallConfig) -> None:
55
+ super().__init__(config)
56
+ embedding_cls = get_embedding_class(config.embedding_type)
57
+ self.embeddings = embedding_cls(config)
58
+
59
+ attention_types = resolve_attention_types(
60
+ config.num_hidden_layers, config.attention_pattern, config.global_attn_every_n_layers
61
+ )
62
+ self.layers = nn.ModuleList(
63
+ [
64
+ ModernBertSmallEncoderLayer(config, layer_idx, attention_type)
65
+ for layer_idx, attention_type in enumerate(attention_types)
66
+ ]
67
+ )
68
+
69
+ head_dim = config.hidden_size // config.num_attention_heads
70
+ self.global_rotary_emb = RotaryEmbedding(head_dim, config.global_rope_theta)
71
+ self.local_rotary_emb = RotaryEmbedding(head_dim, config.local_rope_theta)
72
+ self.local_window_radius = config.local_attention_window // 2
73
+ self.final_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=False)
74
+
75
+ self.post_init()
76
+
77
+ def get_input_embeddings(self) -> nn.Module:
78
+ return self.embeddings
79
+
80
+ def set_input_embeddings(self, value: nn.Module) -> None:
81
+ self.embeddings = value
82
+
83
+ def forward(
84
+ self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs
85
+ ) -> BaseModelOutput:
86
+ batch, seq_len = input_ids.shape
87
+ device = input_ids.device
88
+ if attention_mask is None:
89
+ attention_mask = torch.ones(batch, seq_len, device=device, dtype=torch.long)
90
+
91
+ hidden_states = self.embeddings(input_ids)
92
+
93
+ global_mask = build_global_attention_mask(attention_mask)
94
+ local_mask = build_local_attention_mask(attention_mask, self.local_window_radius)
95
+ global_cos, global_sin = self.global_rotary_emb(seq_len, device, hidden_states.dtype)
96
+ local_cos, local_sin = self.local_rotary_emb(seq_len, device, hidden_states.dtype)
97
+
98
+ for layer in self.layers:
99
+ if layer.attn.attention_type == "global":
100
+ mask, cos, sin = global_mask, global_cos, global_sin
101
+ else:
102
+ mask, cos, sin = local_mask, local_cos, local_sin
103
+ hidden_states = layer(hidden_states, mask, cos, sin)
104
+
105
+ hidden_states = self.final_norm(hidden_states)
106
+ return BaseModelOutput(last_hidden_state=hidden_states)
107
+
108
+
109
+ class ModernBertSmallForMaskedLM(ModernBertSmallPreTrainedModel):
110
+ """MLM head: Dense(d->d, no bias) -> GELU -> LayerNorm(no bias) -> decoder(d->vocab, bias).
111
+ The decoder weight is tied to the embedding module's output weight (when it defines one)."""
112
+
113
+ def __init__(self, config: ModernBertSmallConfig) -> None:
114
+ super().__init__(config)
115
+ self.model = ModernBertSmallModel(config)
116
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
117
+ self.head_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=False)
118
+ output_weight = self.model.embeddings.get_output_embedding_weight()
119
+ self.output_proj: Optional[nn.Linear] = None
120
+ self.decoder_bias: Optional[nn.Parameter] = None
121
+ self.structured_output_head: Optional[nn.Module] = None
122
+
123
+ if config.tie_word_embeddings:
124
+ self.structured_output_head = self.model.embeddings.build_output_head(config)
125
+
126
+ if self.structured_output_head is not None:
127
+ self.decoder = None
128
+ self._tied_weights_keys = []
129
+ elif (
130
+ config.tie_word_embeddings
131
+ and output_weight is not None
132
+ and output_weight.shape[1] != config.hidden_size
133
+ ):
134
+ bottleneck_dim = output_weight.shape[1]
135
+ self.output_proj = nn.Linear(config.hidden_size, bottleneck_dim, bias=False)
136
+ self.decoder = None
137
+ self.decoder_bias = nn.Parameter(torch.zeros(config.vocab_size))
138
+ self._tied_weights_keys = []
139
+ else:
140
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
141
+ self._tied_weights_keys = ["decoder.weight"] if config.tie_word_embeddings else []
142
+ if config.geometry_penalty_mode != "none":
143
+ if config.embedding_type != "compositional" or self.structured_output_head is None:
144
+ raise ValueError(
145
+ "Geometry penalties require tied compositional embeddings."
146
+ )
147
+ if config.geometry_penalty_weight < 0:
148
+ raise ValueError("geometry_penalty_weight must be non-negative.")
149
+ if config.geometry_sample_size <= 0:
150
+ raise ValueError("geometry_sample_size must be positive.")
151
+ self.post_init()
152
+
153
+ def get_input_embeddings(self) -> nn.Module:
154
+ return self.model.get_input_embeddings()
155
+
156
+ def set_input_embeddings(self, value: nn.Module) -> None:
157
+ self.model.set_input_embeddings(value)
158
+
159
+ def get_output_embeddings(self) -> nn.Module:
160
+ if self.decoder is not None:
161
+ return self.decoder
162
+ if self.output_proj is not None:
163
+ return self.output_proj
164
+ return self.structured_output_head
165
+
166
+ def set_output_embeddings(self, value: nn.Module) -> None:
167
+ if self.decoder is not None:
168
+ self.decoder = value
169
+ elif self.output_proj is not None:
170
+ self.output_proj = value
171
+ else:
172
+ self.structured_output_head = value
173
+
174
+ def tie_weights(self) -> None:
175
+ if not getattr(self.config, "tie_word_embeddings", True):
176
+ return
177
+ output_weight = self.model.embeddings.get_output_embedding_weight()
178
+ if output_weight is None:
179
+ return
180
+ if self.decoder is None:
181
+ return
182
+ self.decoder.weight = output_weight
183
+
184
+ def forward(
185
+ self,
186
+ input_ids: torch.Tensor,
187
+ attention_mask: Optional[torch.Tensor] = None,
188
+ labels: Optional[torch.Tensor] = None,
189
+ **kwargs,
190
+ ) -> MaskedLMGeometryOutput:
191
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
192
+ hidden_states = self.head_norm(F.gelu(self.dense(outputs.last_hidden_state)))
193
+ use_geometry = (
194
+ labels is not None
195
+ and self.training
196
+ and self.config.geometry_penalty_mode != "none"
197
+ )
198
+ token_representations = None
199
+ if self.structured_output_head is not None:
200
+ if use_geometry:
201
+ head_output = self.structured_output_head(
202
+ hidden_states, return_token_representations=True
203
+ )
204
+ logits, token_representations = head_output
205
+ else:
206
+ logits = self.structured_output_head(hidden_states)
207
+ elif self.output_proj is not None:
208
+ output_weight = self.model.embeddings.get_output_embedding_weight()
209
+ logits = F.linear(self.output_proj(hidden_states), output_weight, self.decoder_bias)
210
+ else:
211
+ logits = self.decoder(hidden_states)
212
+
213
+ loss = None
214
+ mlm_loss = None
215
+ geometry_loss = None
216
+ geometry_centering_loss = None
217
+ geometry_whitening_loss = None
218
+ if labels is not None:
219
+ mlm_loss = F.cross_entropy(
220
+ logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100
221
+ )
222
+ loss = mlm_loss
223
+ if use_geometry:
224
+ components = geometry_penalty(
225
+ token_representations,
226
+ self.config.token_frequencies,
227
+ self.config.special_token_ids,
228
+ self.config.geometry_penalty_mode,
229
+ self.config.geometry_sampling_mode,
230
+ self.config.geometry_sample_size,
231
+ )
232
+ geometry_loss = components.total
233
+ geometry_centering_loss = components.centering
234
+ geometry_whitening_loss = components.whitening
235
+ loss = mlm_loss + self.config.geometry_penalty_weight * geometry_loss
236
+
237
+ return MaskedLMGeometryOutput(
238
+ loss=loss,
239
+ mlm_loss=mlm_loss,
240
+ geometry_loss=geometry_loss,
241
+ geometry_centering_loss=geometry_centering_loss,
242
+ geometry_whitening_loss=geometry_whitening_loss,
243
+ logits=logits,
244
+ )
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93e3afcae817960703075fd1b5118b7a6d3a098c6632b287390a0a8f20620108
3
+ size 202520395
rng_state.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06d475bcff9f483e26b631b2347049c0672769aaf37747dbb82794cd30342266
3
+ size 14455
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8b76b363c4f9b730d55cb4d33faed7fa4f8b292e510f6a6a841e72fcadc0e75
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": 3027, "cumulative_wall_seconds": 220.5930519104004, "cumulative_gpu_seconds": 661.7791557312012, "cumulative_flops": 1.975260676305715e+16, "cumulative_words_seen": 100026227.7631836}