CLIWorks commited on
Commit
b20f0b4
·
verified ·
1 Parent(s): 863202c

Delete mythos-fineweb.py

Browse files
Files changed (1) hide show
  1. mythos-fineweb.py +0 -915
mythos-fineweb.py DELETED
@@ -1,915 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- SpiderPortal v5 pretraining on FineWeb-Edu with AdamW.
4
-
5
- Single GPU:
6
- python mythos-fineweb.py
7
-
8
- Multi-GPU:
9
- torchrun --nproc_per_node=$(python -c "import torch; print(torch.cuda.device_count())") mythos-fineweb.py
10
- """
11
-
12
- import os
13
- import math
14
- import time
15
- import torch
16
- import torch.nn as nn
17
- import torch.nn.functional as F
18
- import torch.distributed as dist
19
- from loguru import logger
20
- from torch.distributed.fsdp import (
21
- FullyShardedDataParallel as FSDP,
22
- ShardingStrategy,
23
- MixedPrecision,
24
- FullStateDictConfig,
25
- StateDictType,
26
- )
27
- from torch.distributed.fsdp.wrap import ModuleWrapPolicy
28
- from torch.utils.data import IterableDataset, DataLoader, get_worker_info
29
- from contextlib import nullcontext
30
- from dataclasses import dataclass
31
- from typing import Optional, Tuple, Dict, List
32
- from torch.nn import CrossEntropyLoss
33
-
34
- from datasets import load_dataset
35
- from transformers import AutoTokenizer
36
-
37
-
38
- # ---------------------------------------------------------------------------
39
- # SpiderPortal Model Architecture
40
- # ---------------------------------------------------------------------------
41
-
42
-
43
- @dataclass
44
- class SpiderPortalConfig:
45
- vocab_size: int = 50278
46
- hidden_size: int = 384
47
- num_hidden_layers: int = 8
48
- num_attention_heads: int = 8
49
- num_key_value_heads: int = 2
50
- intermediate_size: int = 1024
51
- hidden_act: str = "silu"
52
- num_experts: int = 64
53
- num_experts_per_tok: int = 1
54
- num_shared_experts: int = 1
55
- router_aux_loss_coef: float = 0.05
56
- max_loop_iters: int = 1
57
- act_threshold: float = 0.5
58
- max_position_embeddings: int = 131072
59
- rope_theta: float = 10000000.0
60
- rope_scaling: dict = None
61
- sliding_window: int = 4096
62
- attention_dropout: float = 0.0
63
- rms_norm_eps: float = 1e-6
64
- initializer_range: float = 0.02
65
- use_cache: bool = True
66
- tie_word_embeddings: bool = True
67
- prelude_layers: int = 2
68
- coda_layers: int = 2
69
- lora_rank: int = 32
70
- loop_embed_dim: int = 48
71
- vision_hidden_size: int = 384
72
- audio_hidden_size: int = 512
73
- vision_num_frames: int = 60
74
- vision_tokens_per_frame: int = 256
75
- vision_temporal_tokens: int = 64
76
- vision_temporal_layers: int = 2
77
- model_type: str = "spiderportal"
78
- torch_dtype: str = "bfloat16"
79
-
80
-
81
- def loop_index_embedding(h, loop_t, loop_dim, theta=10000.0):
82
- freqs = 1.0 / (theta ** (torch.arange(0, loop_dim, 2, device=h.device, dtype=h.dtype) / loop_dim))
83
- angles = loop_t * freqs
84
- emb = torch.cat([angles.sin(), angles.cos()], dim=-1)[:loop_dim]
85
- emb_full = torch.zeros(h.shape[-1], device=h.device, dtype=h.dtype)
86
- emb_full[:loop_dim] = emb
87
- return h + emb_full.unsqueeze(0).unsqueeze(0)
88
-
89
-
90
- class SpiderPortalRMSNorm(nn.Module):
91
- def __init__(self, hidden_size, eps=1e-6):
92
- super().__init__()
93
- self.weight = nn.Parameter(torch.ones(hidden_size))
94
- self.variance_epsilon = eps
95
- def forward(self, hidden_states):
96
- input_dtype = hidden_states.dtype
97
- hidden_states = hidden_states.to(torch.float32)
98
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
99
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
100
- return self.weight.to(input_dtype) * hidden_states.to(input_dtype)
101
-
102
-
103
- def compute_yarn_inv_freq(head_dim, rope_theta, factor, orig_max, beta_fast=32.0, beta_slow=1.0):
104
- dim = head_dim
105
- orig_inv_freq = 1.0 / (rope_theta ** (torch.arange(0, dim, 2).float() / dim))
106
- pos_freqs = torch.arange(0, dim, 2).float() / dim
107
- beta = (pos_freqs * math.log(rope_theta) / math.log(orig_max))
108
- scale = torch.where(beta < beta_slow, torch.ones_like(beta), torch.where(beta > beta_fast, torch.ones_like(beta) / factor, 1.0 - (beta - beta_slow) / (beta_fast - beta_slow) * (1.0 - 1.0 / factor)))
109
- return orig_inv_freq * scale
110
-
111
-
112
- class SpiderPortalGQA(nn.Module):
113
- def __init__(self, config):
114
- super().__init__()
115
- self.config = config
116
- self.hidden_size = config.hidden_size
117
- self.num_heads = config.num_attention_heads
118
- self.num_kv_heads = config.num_key_value_heads
119
- self.head_dim = config.hidden_size // config.num_attention_heads
120
- self.num_key_value_groups = self.num_heads // self.num_kv_heads
121
- self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
122
- self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
123
- self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
124
- self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
125
- self.attention_dropout = config.attention_dropout
126
- rope_scaling = getattr(config, 'rope_scaling', None)
127
- if rope_scaling and rope_scaling.get("type") == "yarn":
128
- factor = rope_scaling.get("factor", 1.0)
129
- orig_max_pos = rope_scaling.get("original_max_position_embeddings", config.max_position_embeddings)
130
- inv_freq = compute_yarn_inv_freq(self.head_dim, config.rope_theta, factor, orig_max_pos)
131
- else:
132
- inv_freq = 1.0 / (config.rope_theta ** (torch.arange(0, self.head_dim, 2).float() / self.head_dim))
133
- self.register_buffer("inv_freq", inv_freq, persistent=False)
134
- def _rotate_half(self, x):
135
- x1 = x[..., :x.shape[-1] // 2]
136
- x2 = x[..., x.shape[-1] // 2:]
137
- return torch.cat((-x2, x1), dim=-1)
138
- def _apply_rotary(self, x, cos, sin):
139
- return (x * cos) + (self._rotate_half(x) * sin)
140
- def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
141
- bsz, q_len, _ = hidden_states.size()
142
- query_states = self.q_proj(hidden_states)
143
- key_states = self.k_proj(hidden_states)
144
- value_states = self.v_proj(hidden_states)
145
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
146
- key_states = key_states.view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
147
- value_states = value_states.view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
148
- if position_ids is None:
149
- position_ids = torch.arange(q_len, device=hidden_states.device).unsqueeze(0).expand(bsz, -1)
150
- max_pos = position_ids.max().item() + 1
151
- seq_len = max(max_pos, q_len)
152
- t = torch.arange(seq_len, device=hidden_states.device, dtype=self.inv_freq.dtype)
153
- freqs = torch.outer(t, self.inv_freq)
154
- emb = torch.cat((freqs, freqs), dim=-1)
155
- cos, sin = emb.cos(), emb.sin()
156
- cos = cos[position_ids].unsqueeze(1)
157
- sin = sin[position_ids].unsqueeze(1)
158
- query_states = self._apply_rotary(query_states, cos, sin)
159
- key_states = self._apply_rotary(key_states, cos, sin)
160
- if past_key_value is not None:
161
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
162
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
163
- past_kv = (key_states, value_states) if use_cache else None
164
- key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
165
- value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
166
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
167
- if attention_mask is not None:
168
- attn_weights = attn_weights + attention_mask
169
- attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
170
- attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
171
- attn_output = torch.matmul(attn_weights, value_states)
172
- attn_output = attn_output.transpose(1, 2).contiguous()
173
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
174
- return self.o_proj(attn_output), past_kv
175
-
176
-
177
- class SpiderPortalExpert(nn.Module):
178
- def __init__(self, config, intermediate_size=None):
179
- super().__init__()
180
- inter_size = intermediate_size or config.intermediate_size
181
- self.gate_proj = nn.Linear(config.hidden_size, inter_size, bias=False)
182
- self.up_proj = nn.Linear(config.hidden_size, inter_size, bias=False)
183
- self.down_proj = nn.Linear(inter_size, config.hidden_size, bias=False)
184
- self.act_fn = nn.SiLU()
185
- def forward(self, hidden_states):
186
- return self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
187
-
188
-
189
- class SpiderPortalRouter(nn.Module):
190
- def __init__(self, config):
191
- super().__init__()
192
- self.num_experts = config.num_experts
193
- self.num_experts_per_tok = config.num_experts_per_tok
194
- self.weight = nn.Parameter(torch.randn(config.hidden_size, config.num_experts) * config.initializer_range)
195
- self.register_buffer("router_bias", torch.zeros(config.num_experts))
196
- def forward(self, hidden_states):
197
- router_logits = hidden_states.view(-1, hidden_states.size(-1)) @ self.weight
198
- routing_weights = F.softmax(router_logits, dim=-1, dtype=torch.float32)
199
- biased_logits = router_logits + self.router_bias
200
- biased_weights = F.softmax(biased_logits, dim=-1, dtype=torch.float32)
201
- top_weights, top_indices = torch.topk(biased_weights, self.num_experts_per_tok, dim=-1)
202
- top_weights = top_weights / top_weights.sum(dim=-1, keepdim=True)
203
- top_weights = top_weights.to(hidden_states.dtype)
204
- mean_probs = routing_weights.mean(dim=0)
205
- aux_loss = self.num_experts * (mean_probs * mean_probs).sum()
206
- return top_weights, top_indices, aux_loss
207
-
208
-
209
- class SpiderPortalMoE(nn.Module):
210
- def __init__(self, config):
211
- super().__init__()
212
- self.config = config
213
- self.num_experts = config.num_experts
214
- self.num_experts_per_tok = config.num_experts_per_tok
215
- self.experts = nn.ModuleList([SpiderPortalExpert(config) for _ in range(config.num_experts)])
216
- self.shared_expert = SpiderPortalExpert(config)
217
- self.router = SpiderPortalRouter(config)
218
- def forward(self, hidden_states):
219
- batch_size, seq_len, hidden_dim = hidden_states.shape
220
- top_weights, top_indices, aux_loss = self.router(hidden_states)
221
- flat_hidden = hidden_states.view(-1, hidden_dim)
222
- final_output = torch.zeros_like(flat_hidden)
223
- for expert_idx in range(self.num_experts_per_tok):
224
- expert_ids = top_indices[:, expert_idx]
225
- expert_weights = top_weights[:, expert_idx:expert_idx+1]
226
- for e in range(self.num_experts):
227
- mask = expert_ids == e
228
- if mask.any():
229
- expert_output = self.experts[e](flat_hidden[mask])
230
- final_output[mask] += expert_output * expert_weights[mask]
231
- shared_output = self.shared_expert(flat_hidden)
232
- final_output = final_output + shared_output
233
- return final_output.view(batch_size, seq_len, hidden_dim), aux_loss
234
-
235
-
236
- class SpiderPortalDenseLayer(nn.Module):
237
- def __init__(self, config):
238
- super().__init__()
239
- self.self_attn = SpiderPortalGQA(config)
240
- dense_intermediate = config.hidden_size * 4 // 3
241
- self.ffn = SpiderPortalExpert(config, intermediate_size=dense_intermediate)
242
- self.input_layernorm = SpiderPortalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
243
- self.post_attention_layernorm = SpiderPortalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
244
- def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
245
- attn_input = self.input_layernorm(hidden_states)
246
- attn_output, past_kv = self.self_attn(attn_input, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, use_cache=use_cache)
247
- hidden_states = hidden_states + attn_output
248
- ffn_input = self.post_attention_layernorm(hidden_states)
249
- ffn_output = self.ffn(ffn_input)
250
- hidden_states = hidden_states + ffn_output
251
- return hidden_states, past_kv
252
-
253
-
254
- class SpiderPortalMoELayer(nn.Module):
255
- def __init__(self, config, layer_idx):
256
- super().__init__()
257
- self.layer_idx = layer_idx
258
- self.self_attn = SpiderPortalGQA(config)
259
- self.moe = SpiderPortalMoE(config)
260
- self.input_layernorm = SpiderPortalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
261
- self.post_attention_layernorm = SpiderPortalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
262
- def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
263
- attn_input = self.input_layernorm(hidden_states)
264
- attn_output, past_kv = self.self_attn(attn_input, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, use_cache=use_cache)
265
- hidden_states = hidden_states + attn_output
266
- moe_input = self.post_attention_layernorm(hidden_states)
267
- moe_output, aux_loss = self.moe(moe_input)
268
- hidden_states = hidden_states + moe_output
269
- return hidden_states, aux_loss, past_kv
270
-
271
-
272
- class LTIInjection(nn.Module):
273
- def __init__(self, config):
274
- super().__init__()
275
- self.hidden_size = config.hidden_size
276
- self.log_A = nn.Parameter(torch.full((config.hidden_size,), -2.0))
277
- self.delta_t = nn.Parameter(torch.tensor(1.0))
278
- self.B = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
279
- with torch.no_grad():
280
- self.B.weight.data.normal_(mean=0.0, std=0.01)
281
- def get_A(self):
282
- return -torch.exp(self.log_A)
283
- def forward(self, h_t, e):
284
- A = self.get_A()
285
- return A * h_t + self.B(e)
286
-
287
-
288
- class ACTHalting(nn.Module):
289
- def __init__(self, config):
290
- super().__init__()
291
- self.halt_predictor = nn.Linear(config.hidden_size, 1)
292
- self.threshold = config.act_threshold
293
- def forward(self, hidden_states):
294
- return torch.sigmoid(self.halt_predictor(hidden_states))
295
-
296
-
297
- class LoRAAdapter(nn.Module):
298
- def __init__(self, config):
299
- super().__init__()
300
- rank = config.lora_rank
301
- self.down = nn.Linear(config.hidden_size, rank, bias=False)
302
- self.B = nn.Parameter(torch.randn(rank, config.hidden_size) * 0.02)
303
- self.scale = nn.Embedding(config.max_loop_iters, rank)
304
- with torch.no_grad():
305
- self.scale.weight.data.zero_()
306
- self.down.weight.data.normal_(mean=0.0, std=0.001)
307
- def forward(self, x, loop_t):
308
- max_t = self.scale.num_embeddings - 1
309
- t_idx = min(loop_t, max_t)
310
- s = self.scale(torch.tensor(t_idx, device=x.device))
311
- down = self.down(x) * s
312
- return down @ self.B
313
-
314
-
315
- class SpiderPortalMoEModel(nn.Module):
316
- def __init__(self, config):
317
- super().__init__()
318
- self.config = config
319
- self.prelude_layers = nn.ModuleList([SpiderPortalDenseLayer(config) for _ in range(config.prelude_layers)])
320
- self.recurrent_layers = nn.ModuleList([SpiderPortalMoELayer(config, i) for i in range(config.num_hidden_layers)])
321
- self.coda_layers = nn.ModuleList([SpiderPortalDenseLayer(config) for _ in range(config.coda_layers)])
322
- self.norm = SpiderPortalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
323
- self.injection = LTIInjection(config)
324
- self.act_halting = ACTHalting(config)
325
- self.lora_adapter = LoRAAdapter(config)
326
- self.loop_embed_dim = config.loop_embed_dim
327
- def forward(self, hidden_states, input_embedding=None, attention_mask=None, position_ids=None, past_key_values=None, use_cache=False, n_loops=None):
328
- n_loops = n_loops or self.config.max_loop_iters
329
- input_embedding = input_embedding if input_embedding is not None else hidden_states
330
- total_aux_loss = 0.0
331
- for layer in self.prelude_layers:
332
- hidden_states, _ = layer(hidden_states, attention_mask=attention_mask, position_ids=position_ids)
333
- e = hidden_states.clone()
334
- B, T_seq, D = hidden_states.shape
335
- halted = torch.zeros(B, T_seq, device=hidden_states.device, dtype=torch.bool)
336
- cumulative_p = torch.zeros(B, T_seq, device=hidden_states.device, dtype=hidden_states.dtype)
337
- h_out = torch.zeros_like(hidden_states)
338
- past_key_values = past_key_values if past_key_values is not None else [None] * len(self.recurrent_layers)
339
- for t in range(n_loops):
340
- h_loop = loop_index_embedding(hidden_states, t, self.loop_embed_dim)
341
- if t > 0:
342
- injection = self.injection(hidden_states, input_embedding)
343
- hidden_states = hidden_states + injection
344
- new_past_key_values = []
345
- for i, layer in enumerate(self.recurrent_layers):
346
- hidden_states, aux_loss, past_kv = layer(hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values[i] if t == 0 else None, use_cache=use_cache)
347
- total_aux_loss = total_aux_loss + aux_loss
348
- new_past_key_values.append(past_kv)
349
- lora_delta = self.lora_adapter(hidden_states, t)
350
- hidden_states = hidden_states + lora_delta
351
- halt_prob = self.act_halting(hidden_states).squeeze(-1)
352
- still_running = ~halted
353
- remainder = (1.0 - cumulative_p).clamp(min=0)
354
- weight = torch.where(cumulative_p + halt_prob >= self.config.act_threshold, remainder, halt_prob)
355
- weight = weight * still_running.to(hidden_states.dtype)
356
- h_out = h_out + weight.unsqueeze(-1) * hidden_states
357
- cumulative_p = cumulative_p + halt_prob * still_running.to(hidden_states.dtype)
358
- halted = halted | (cumulative_p >= self.config.act_threshold)
359
- if halted.all() and not self.training:
360
- break
361
- never_halted = (~halted).to(hidden_states.dtype).unsqueeze(-1)
362
- hidden_states = h_out + never_halted * hidden_states
363
- for layer in self.coda_layers:
364
- hidden_states, _ = layer(hidden_states, attention_mask=attention_mask, position_ids=position_ids)
365
- hidden_states = self.norm(hidden_states)
366
- return hidden_states, total_aux_loss, new_past_key_values
367
-
368
-
369
- class SpiderPortalForConditionalGeneration(nn.Module):
370
- def __init__(self, config):
371
- super().__init__()
372
- self.config = config
373
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
374
- self.model = SpiderPortalMoEModel(config)
375
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
376
- if config.tie_word_embeddings:
377
- self.lm_head.weight = self.embed_tokens.weight
378
- self.apply(self._init_weights)
379
- def _init_weights(self, module):
380
- if isinstance(module, nn.Linear):
381
- if hasattr(self, 'model') and module is self.model.injection.B:
382
- return
383
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
384
- if module.bias is not None:
385
- module.bias.data.zero_()
386
- elif isinstance(module, nn.Embedding):
387
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
388
- def forward(self, input_ids, attention_mask=None, position_ids=None, labels=None, n_loops=None, use_cache=False):
389
- hidden_states = self.embed_tokens(input_ids)
390
- model_dtype = next(self.model.parameters()).dtype
391
- hidden_states = hidden_states.to(model_dtype)
392
- input_embedding = hidden_states.clone()
393
- if attention_mask is None:
394
- attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
395
- causal_mask = torch.full((attention_mask.size(0), 1, attention_mask.size(1), attention_mask.size(1)), 0.0, dtype=hidden_states.dtype, device=hidden_states.device)
396
- causal_mask = causal_mask.masked_fill(~attention_mask.unsqueeze(1).unsqueeze(2), torch.finfo(hidden_states.dtype).min)
397
- causal_mask = causal_mask.triu(1)
398
- hidden_states, aux_loss, past_kv = self.model(hidden_states, input_embedding=input_embedding, attention_mask=causal_mask, position_ids=position_ids, use_cache=use_cache, n_loops=n_loops)
399
- logits = self.lm_head(hidden_states)
400
- loss = None
401
- if labels is not None:
402
- shift_logits = logits[..., :-1, :].contiguous()
403
- shift_labels = labels[..., 1:].contiguous()
404
- loss_fct = CrossEntropyLoss()
405
- loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
406
- loss = loss + self.config.router_aux_loss_coef * aux_loss
407
- return {"loss": loss, "logits": logits, "aux_loss": aux_loss, "past_key_values": past_kv}
408
- def get_num_params(self):
409
- total = sum(p.numel() for p in self.parameters())
410
- return {"total": total, "trainable": total}
411
-
412
-
413
- # ---------------------------------------------------------------------------
414
- # Dataset
415
- # ---------------------------------------------------------------------------
416
-
417
-
418
- class FineWebEduDataset(IterableDataset):
419
- """
420
- Streaming FineWeb-Edu loader yielding fixed-length (input, target) pairs.
421
-
422
- FineWeb-Edu is trillions of tokens, so `streaming=True` pulls shards on
423
- demand instead of materializing to disk. Sharding is two-dimensional —
424
- `world_size` ranks × `num_workers` DataLoader workers per rank — and each
425
- `(rank, worker_id)` deterministically owns one shard of the global stream.
426
- That gives disjoint coverage without any cross-process coordination.
427
-
428
- Streaming datasets are not seekable, so a resumed run re-enters its shard
429
- from the beginning. Acceptable at pretraining scale: the chance of
430
- re-playing the same tokens before the run ends is negligible versus the
431
- cost of a true resumable loader.
432
- """
433
-
434
- def __init__(self, tokenizer, seq_len: int, subset: str, rank: int, world_size: int):
435
- """
436
- Args:
437
- tokenizer -- HuggingFace tokenizer with .encode(str) -> list[int]
438
- seq_len -- context length; every yielded pair has this many tokens
439
- subset -- FineWeb-Edu config name (e.g. "sample-1BT", "sample-10BT")
440
- rank -- global rank of this process within the distributed job
441
- world_size -- total number of distributed processes
442
- """
443
- self.tokenizer = tokenizer
444
- self.seq_len = seq_len
445
- self.subset = subset
446
- self.rank = rank
447
- self.world_size = world_size
448
-
449
- def __iter__(self):
450
- """
451
- Yield `(input_ids, target_ids)` tensors of length `seq_len` forever.
452
-
453
- Inputs and targets are shifted by one for next-token prediction —
454
- `target[i] == input[i + 1]`. Documents are concatenated into a rolling
455
- buffer and sliced into fixed-length chunks, packing short docs together
456
- and splitting long ones. This keeps every step at the same shape,
457
- which under FSDP avoids recompute from variable-length inputs and
458
- removes the need for a pad-aware attention mask.
459
- """
460
- worker = get_worker_info()
461
- num_workers = worker.num_workers if worker else 1
462
- worker_id = worker.id if worker else 0
463
-
464
- total_shards = self.world_size * num_workers
465
- shard_index = self.rank * num_workers + worker_id
466
-
467
- ds = load_dataset(
468
- "HuggingFaceFW/fineweb-edu",
469
- name=self.subset,
470
- split="train",
471
- streaming=True,
472
- ).shard(num_shards=total_shards, index=shard_index)
473
-
474
- buf = []
475
- for sample in ds:
476
- buf.extend(self.tokenizer.encode(sample["text"]))
477
- while len(buf) >= self.seq_len + 1:
478
- chunk = buf[: self.seq_len + 1]
479
- buf = buf[self.seq_len + 1 :]
480
- yield (
481
- torch.tensor(chunk[:-1], dtype=torch.long),
482
- torch.tensor(chunk[1:], dtype=torch.long),
483
- )
484
-
485
-
486
- # ---------------------------------------------------------------------------
487
- # LR schedule: linear warmup → cosine decay
488
- # ---------------------------------------------------------------------------
489
-
490
-
491
- def get_lr(step: int, warmup: int, total: int, max_lr: float, min_lr: float) -> float:
492
- """
493
- Linear warmup → half-cosine decay to `min_lr`.
494
-
495
- Standard language-model pretraining schedule. The warmup phase prevents
496
- Adam's second-moment estimate from collapsing to a huge LR in the first
497
- few steps when gradients are noisy. The cosine tail lets the model make
498
- small, increasingly conservative updates near the end of training rather
499
- than crashing to `min_lr` at a fixed step.
500
-
501
- Behavior by region:
502
- step < warmup → linear ramp 0 → max_lr
503
- warmup ≤ step < total → cosine decay max_lr → min_lr
504
- step ≥ total → clamped at min_lr (safety for
505
- off-by-one step counters at the end
506
- of training)
507
-
508
- Args:
509
- step -- current global optimizer step (0-indexed)
510
- warmup -- number of warmup steps before cosine decay begins
511
- total -- step at which the cosine reaches `min_lr`
512
- max_lr -- peak learning rate reached at the end of warmup
513
- min_lr -- floor learning rate at and after `total` steps
514
-
515
- Returns:
516
- Scalar learning rate for this step.
517
- """
518
- if step < warmup:
519
- return max_lr * step / warmup
520
- if step >= total:
521
- return min_lr
522
- decay = (step - warmup) / (total - warmup)
523
- return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * decay))
524
-
525
-
526
- # ---------------------------------------------------------------------------
527
- # Checkpointing — weights-only every 500 steps, full at epoch end + best
528
- # ---------------------------------------------------------------------------
529
-
530
-
531
- def save_weights_only(model, step, epoch, ckpt_dir, ddp):
532
- """Save model weights only (~1.3GB for 3B bf16). For testing/transfer."""
533
- if ddp:
534
- with FSDP.state_dict_type(
535
- model,
536
- StateDictType.FULL_STATE_DICT,
537
- FullStateDictConfig(offload_to_cpu=True, rank0_only=True),
538
- ):
539
- model_state = model.state_dict()
540
- else:
541
- model_state = model.state_dict()
542
-
543
- ckpt_path = os.path.join(ckpt_dir, f"spiderportal-v5-ep{epoch}-step{step}.pt")
544
- tmp_path = ckpt_path + ".tmp"
545
- torch.save(model_state, tmp_path)
546
- os.replace(tmp_path, ckpt_path)
547
- size_mb = os.path.getsize(ckpt_path) / (1024 * 1024)
548
- return ckpt_path, size_mb
549
-
550
-
551
- def save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, ckpt_name="full"):
552
- """Save model + optimizer state (~18GB for 3B bf16). For resume training."""
553
- if ddp:
554
- with FSDP.state_dict_type(
555
- model,
556
- StateDictType.FULL_STATE_DICT,
557
- FullStateDictConfig(offload_to_cpu=True, rank0_only=True),
558
- ):
559
- model_state = model.state_dict()
560
- optim_state = FSDP.optim_state_dict(model, optimizer)
561
- else:
562
- model_state = model.state_dict()
563
- optim_state = optimizer.state_dict()
564
-
565
- if not master:
566
- return None, 0
567
-
568
- os.makedirs(ckpt_dir, exist_ok=True)
569
- final_path = os.path.join(ckpt_dir, f"spiderportal-v5-{ckpt_name}.pt")
570
- tmp_path = final_path + ".tmp"
571
- torch.save(
572
- {
573
- "step": step,
574
- "epoch": epoch,
575
- "model_state_dict": model_state,
576
- "optimizer_state_dict": optim_state,
577
- "cfg": cfg,
578
- "vocab_size": vocab_size,
579
- },
580
- tmp_path,
581
- )
582
- os.replace(tmp_path, final_path)
583
- size_mb = os.path.getsize(final_path) / (1024 * 1024)
584
- return final_path, size_mb
585
-
586
-
587
- def delete_step_checkpoints(ckpt_dir):
588
- """Delete all weights-only step checkpoints to free disk space."""
589
- deleted = 0
590
- for f in os.listdir(ckpt_dir):
591
- if f.startswith("spiderportal-v5-ep") and "-step" in f and f.endswith(".pt"):
592
- path = os.path.join(ckpt_dir, f)
593
- try:
594
- os.remove(path)
595
- deleted += 1
596
- except OSError:
597
- pass
598
- return deleted
599
-
600
-
601
- def load_checkpoint(model, optimizer, path, ddp):
602
- """Restore model + optimizer from full checkpoint."""
603
- ckpt = torch.load(path, map_location="cpu", weights_only=False)
604
-
605
- if ddp:
606
- with FSDP.state_dict_type(
607
- model,
608
- StateDictType.FULL_STATE_DICT,
609
- FullStateDictConfig(offload_to_cpu=True, rank0_only=False),
610
- ):
611
- model.load_state_dict(ckpt["model_state_dict"])
612
- optim_state = FSDP.optim_state_dict_to_load(
613
- model=model,
614
- optim=optimizer,
615
- optim_state_dict=ckpt["optimizer_state_dict"],
616
- )
617
- optimizer.load_state_dict(optim_state)
618
- else:
619
- model.load_state_dict(ckpt["model_state_dict"])
620
- optimizer.load_state_dict(ckpt["optimizer_state_dict"])
621
-
622
- return int(ckpt["step"]), int(ckpt.get("epoch", 0))
623
-
624
-
625
- # ---------------------------------------------------------------------------
626
- # Main
627
- # ---------------------------------------------------------------------------
628
-
629
-
630
- def main():
631
- """
632
- End-to-end pretraining entry point.
633
-
634
- Order matters: distributed init must run before any CUDA allocation, the
635
- tokenizer must exist before the model is built (vocab_size flows into
636
- cfg), and FSDP must wrap the model before the optimizer is constructed
637
- (FSDP re-flattens parameters, so an optimizer built on the unwrapped
638
- model would track stale param objects). Resume then loads state into the
639
- already-constructed optimizer in-place.
640
-
641
- Lifecycle:
642
- 1. Initialize torch.distributed (NCCL) if launched under torchrun.
643
- 2. Build tokenizer → derive vocab_size.
644
- 3. Construct OpenMythos with the 3B variant config.
645
- 4. Wrap in FSDP with FULL_SHARD + bf16/fp16 mixed precision (multi-GPU)
646
- or move to device + autocast (single-GPU).
647
- 5. Build fused AdamW on (possibly sharded) parameters.
648
- 6. Resume from the latest checkpoint in `ckpt_dir` if one exists.
649
- 7. Stream FineWeb-Edu through grad-accumulation microbatches with
650
- cosine LR schedule, per-step logging, and periodic checkpoints.
651
- 8. Write a final checkpoint if the last save wasn't aligned to
652
- `ckpt_every`, then barrier + tear down the process group.
653
-
654
- All hyperparameters are literal constants in this function by design —
655
- pretraining runs are long-lived and each run pins exact settings; a
656
- CLI/config layer is deliberately avoided to keep the file self-auditable.
657
- """
658
- # ------------------------------------------------------------------
659
- # Distributed init
660
- # ------------------------------------------------------------------
661
- ddp = int(os.environ.get("RANK", -1)) != -1
662
- if ddp:
663
- dist.init_process_group("nccl")
664
- rank = int(os.environ["RANK"])
665
- local_rank = int(os.environ["LOCAL_RANK"])
666
- world_size = int(os.environ["WORLD_SIZE"])
667
- device = f"cuda:{local_rank}"
668
- torch.cuda.set_device(device)
669
- else:
670
- rank = local_rank = 0
671
- world_size = 1
672
- device = "cuda" if torch.cuda.is_available() else "cpu"
673
-
674
- master = rank == 0
675
-
676
- if master:
677
- logger.info(
678
- f"GPUs: {torch.cuda.device_count()} | World size: {world_size} | Device: {device}"
679
- )
680
-
681
- # ------------------------------------------------------------------
682
- # Tokenizer
683
- # ------------------------------------------------------------------
684
- tokenizer = AutoTokenizer.from_pretrained("gpt2")
685
- tokenizer.pad_token = tokenizer.eos_token
686
- vocab_size = tokenizer.vocab_size
687
-
688
- if master:
689
- logger.info(f"Tokenizer: gpt2 | Vocab size: {vocab_size:,}")
690
-
691
- # ------------------------------------------------------------------
692
- # Hyperparameters
693
- # ------------------------------------------------------------------
694
- seq_len = 2048
695
- micro_batch = 32
696
- target_tokens = 1_000_000_000
697
- grad_accum = max(1, 256 // (world_size * micro_batch))
698
- global_batch_tok = world_size * micro_batch * grad_accum * seq_len
699
- total_steps = target_tokens // global_batch_tok
700
- warmup_steps = 200
701
- lr = 3e-4
702
- wd = 0.1
703
- log_every = 10
704
- ckpt_every = 500
705
- ckpt_dir = "checkpoints"
706
- dataset_subset = "sample-1BT"
707
-
708
- if master:
709
- logger.info(
710
- f"seq_len={seq_len} | micro_batch={micro_batch} | grad_accum={grad_accum} | "
711
- f"global_batch_tokens={global_batch_tok:,} | total_steps={total_steps:,}"
712
- )
713
-
714
- # ------------------------------------------------------------------
715
- # Model
716
- # ------------------------------------------------------------------
717
- cfg = SpiderPortalConfig(
718
- hidden_size=384, num_hidden_layers=8, num_attention_heads=8,
719
- num_key_value_heads=2, intermediate_size=1024,
720
- num_experts=64, num_experts_per_tok=1, num_shared_experts=1,
721
- router_aux_loss_coef=0.05, max_loop_iters=1,
722
- prelude_layers=2, coda_layers=2, lora_rank=32,
723
- rope_theta=10000000.0,
724
- rope_scaling={"type": "yarn", "factor": 4.0, "original_max_position_embeddings": 32768},
725
- max_position_embeddings=131072, sliding_window=4096,
726
- tie_word_embeddings=True,
727
- )
728
- cfg.vocab_size = vocab_size
729
-
730
- bf16_ok = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
731
- amp_dtype = torch.bfloat16 if bf16_ok else torch.float16
732
-
733
- model = SpiderPortalForConditionalGeneration(cfg)
734
-
735
- if ddp:
736
- mp_policy = MixedPrecision(
737
- param_dtype=amp_dtype,
738
- reduce_dtype=amp_dtype,
739
- buffer_dtype=amp_dtype,
740
- )
741
- wrap_policy = ModuleWrapPolicy({SpiderPortalDenseLayer, SpiderPortalMoELayer})
742
- model = FSDP(
743
- model,
744
- sharding_strategy=ShardingStrategy.FULL_SHARD,
745
- mixed_precision=mp_policy,
746
- auto_wrap_policy=wrap_policy,
747
- device_id=local_rank,
748
- )
749
- else:
750
- model = model.to(device)
751
- amp_ctx = (
752
- torch.amp.autocast(device_type="cuda", dtype=amp_dtype)
753
- if "cuda" in device
754
- else nullcontext()
755
- )
756
-
757
- # FSDP handles its own mixed precision; only need autocast for single-GPU
758
- amp_ctx = nullcontext() if ddp else amp_ctx # type: ignore[possibly-undefined]
759
-
760
- if master:
761
- n_params = sum(p.numel() for p in model.parameters())
762
- logger.info(f"Parameters: {n_params:,} | AMP dtype: {amp_dtype}")
763
-
764
- # Compile for 20-30% speedup (requires PyTorch 2.0+)
765
- try:
766
- model = torch.compile(model, mode="reduce-overhead")
767
- if master:
768
- logger.info("torch.compile: enabled")
769
- except Exception:
770
- if master:
771
- logger.info("torch.compile: not available, using eager mode")
772
-
773
- # ------------------------------------------------------------------
774
- # Optimizer
775
- # ------------------------------------------------------------------
776
- optimizer = torch.optim.AdamW(
777
- model.parameters(), lr=lr, weight_decay=wd, betas=(0.9, 0.95), fused=True
778
- )
779
-
780
- # ------------------------------------------------------------------
781
- # Resume from latest checkpoint (if any)
782
- # ------------------------------------------------------------------
783
- start_step = 0
784
- start_epoch = 1
785
- best_loss = float("inf")
786
- existing_ckpts = [f for f in os.listdir(ckpt_dir) if f.startswith("spiderportal-v5-ep") and f.endswith(".pt") and "-step" not in f] if os.path.isdir(ckpt_dir) else []
787
- if existing_ckpts:
788
- latest = os.path.join(ckpt_dir, sorted(existing_ckpts)[-1])
789
- if master:
790
- logger.info(f"Resuming from checkpoint: {latest}")
791
- start_step, start_epoch = load_checkpoint(model, optimizer, latest, ddp)
792
- if master:
793
- logger.success(f"Resumed at step {start_step}, epoch {start_epoch}")
794
-
795
- # ------------------------------------------------------------------
796
- # Dataset + DataLoader
797
- # ------------------------------------------------------------------
798
- dataset = FineWebEduDataset(tokenizer, seq_len, dataset_subset, rank, world_size)
799
- loader = DataLoader(dataset, batch_size=micro_batch, num_workers=8, pin_memory=True, prefetch_factor=2)
800
-
801
- # ------------------------------------------------------------------
802
- # Training loop
803
- # ------------------------------------------------------------------
804
- if master:
805
- os.makedirs(ckpt_dir, exist_ok=True)
806
-
807
- model.train()
808
- data_iter = iter(loader)
809
- t0 = time.perf_counter()
810
- step = start_step
811
- epoch = start_epoch
812
- step_ckpt_files = []
813
- tokens_in_epoch = 0
814
- tokens_per_epoch = target_tokens
815
-
816
- while step < total_steps:
817
- cur_lr = get_lr(step, warmup_steps, total_steps, lr, lr * 0.1)
818
- for g in optimizer.param_groups:
819
- g["lr"] = cur_lr
820
-
821
- optimizer.zero_grad()
822
- loss_accum = 0.0
823
-
824
- for micro_step in range(grad_accum):
825
- try:
826
- x, y = next(data_iter)
827
- except StopIteration:
828
- data_iter = iter(loader)
829
- x, y = next(data_iter)
830
-
831
- x = x.to(device if not ddp else f"cuda:{local_rank}", non_blocking=True)
832
- y = y.to(device if not ddp else f"cuda:{local_rank}", non_blocking=True)
833
-
834
- sync = (
835
- nullcontext()
836
- if (not ddp or micro_step == grad_accum - 1)
837
- else model.no_sync()
838
- )
839
- with sync, amp_ctx:
840
- logits = model(x)
841
- loss = nn.functional.cross_entropy(
842
- logits.view(-1, vocab_size), y.view(-1)
843
- )
844
- loss = loss / grad_accum
845
-
846
- loss.backward()
847
- loss_accum += loss.item()
848
-
849
- if ddp:
850
- grad_norm = model.clip_grad_norm_(1.0)
851
- else:
852
- grad_norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
853
- optimizer.step()
854
- step += 1
855
- tokens_in_epoch += global_batch_tok
856
-
857
- if master and step % log_every == 0:
858
- dt = time.perf_counter() - t0
859
- tok_per_sec = global_batch_tok * log_every / dt
860
- tokens_seen = step * global_batch_tok
861
- logger.info(
862
- f"Epoch {epoch} | step {step:6d}/{total_steps} | loss {loss_accum:.4f} "
863
- f"| gnorm {float(grad_norm):.2f} | lr {cur_lr:.2e} "
864
- f"| {tok_per_sec / 1e6:.2f}M tok/s "
865
- f"| {tokens_seen / 1e9:.2f}B tokens seen"
866
- )
867
- t0 = time.perf_counter()
868
-
869
- if step % ckpt_every == 0 and master:
870
- ckpt_path, size_mb = save_weights_only(model, step, epoch, ckpt_dir, ddp)
871
- step_ckpt_files.append(ckpt_path)
872
- logger.info(f"Saved weights-only: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
873
-
874
- if tokens_in_epoch >= tokens_per_epoch:
875
- epoch_loss = loss_accum
876
- if master:
877
- epoch_time = (time.perf_counter() - t0) / 60
878
- logger.info(f"Epoch {epoch} complete | loss={epoch_loss:.4f} | Time: {epoch_time:.1f}min")
879
-
880
- for f in step_ckpt_files:
881
- if os.path.exists(f):
882
- os.remove(f)
883
- logger.info(f" Deleted step checkpoint: {os.path.basename(f)}")
884
- step_ckpt_files.clear()
885
-
886
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, f"ep{epoch}")
887
- if ckpt_path:
888
- logger.info(f"Saved epoch checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
889
-
890
- if epoch_loss < best_loss:
891
- best_loss = epoch_loss
892
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, "best")
893
- if ckpt_path:
894
- logger.info(f"Saved best checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
895
-
896
- epoch += 1
897
- tokens_in_epoch = 0
898
-
899
- if step > start_step and master:
900
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, f"final-ep{epoch}")
901
- if ckpt_path:
902
- logger.info(f"Saved final checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
903
-
904
- if ddp:
905
- # Barrier so no rank exits while another is still finishing its
906
- # checkpoint gather — avoids NCCL "process group destroyed" noise.
907
- dist.barrier()
908
- dist.destroy_process_group()
909
-
910
- if master:
911
- logger.success("Training complete.")
912
-
913
-
914
- if __name__ == "__main__":
915
- main()