-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_jepa_ssm.py
More file actions
1641 lines (1455 loc) · 74.4 KB
/
train_jepa_ssm.py
File metadata and controls
1641 lines (1455 loc) · 74.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
To JEPA Or Not To JEPA, That Is Le Question
=============================================
Ciprian-Florin Ifrim - 26 March 2026
Architecture: Tokens → Embedding → [Mamba-2 SSM + ReLU²/SwiGLU MLP] × L (U-Net skips) → RMSNorm → h
JEPA branch: h → Projector → z → Predictor (autoregressive rollout) → MSE loss
Decode branch: h → [optional GELU adapter] → tied/untied lm_head → logits → CE loss
SIGReg: z → per-timestep Gaussian regularization (Epps-Pulley characteristic function test)
Training: JEPA (MSE latent prediction) + SIGReg + CE (token decoding) + Z-loss
Evaluation: lm_head(h) → token logits → BPB
LeWM-style JEPA (Maes et al. 2026) + Mamba-2 SSM (Gu & Dao 2024) + byte-level I/O (Meta's BLT)
- The model learns to predict its own next latent state.
- SIGReg prevents representation collapse without EMA or stop-gradient.
- CE + lm_head decode hidden states to token probabilities.
- Supports byte (256 vocab) and BPE (8K+ vocab) tokenization.
"""
import copy
import glob
import io
import lzma
import math
import os
import random
import sys
import time
from pathlib import Path
import numpy as np
try:
import sentencepiece as spm
except ImportError:
spm = None # byte mode doesn't need sentencepiece
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import Tensor, nn
from torch.nn.parallel import DistributedDataParallel as DDP
# ---------------------------------------------------------------------------
# Mamba-2 (requires mamba_ssm package with CUDA kernels)
# ---------------------------------------------------------------------------
from mamba_ssm import Mamba2
# ---------------------------------------------------------------------------
# Hyperparameters
# ---------------------------------------------------------------------------
def _e(k, d, t=str):
v = os.environ.get(k, str(d))
if t == bool:
return bool(int(v))
return t(v)
class Hyperparameters:
# Data & Tokenizer
tokenizer = _e("TOKENIZER", "byte") # "byte" (256 vocab, no tokenizer) or "bpe"
tokenizer_path = _e("TOKENIZER_PATH", "") # path to .model file (BPE only)
vocab_size = _e("VOCAB_SIZE", 256, int) # 256 for byte, 8192 for BPE, etc.
data_path = _e("DATA_PATH", "./data/datasets/fineweb_bytes")
train_files = os.path.join(data_path, "fineweb_train_*.bin")
val_files = os.path.join(data_path, "fineweb_val_*.bin")
run_id = os.environ.get("RUN_ID", f"jepa_{int(time.time())}")
seed = _e("SEED", 42, int)
# Model
model_dim = _e("MODEL_DIM", 512, int)
num_layers = _e("NUM_LAYERS", 12, int)
d_state = _e("D_STATE", 64, int)
d_conv = _e("D_CONV", 4, int)
expand = _e("EXPAND", 2, int)
predictor_hidden_mult = _e("PREDICTOR_HIDDEN_MULT", 2, int)
embed_dim = _e("EMBED_DIM", 0, int) # 0 = same as model_dim
mlp_mult = _e("MLP_MULT", 3, int) # 0 = no MLP, >0 = hidden = mlp_mult * dim
mlp_every = _e("MLP_EVERY", 1, int) # 1 = every block, 2 = alternate, etc.
activation = _e("ACTIVATION", "relu2") # "relu2" or "swiglu"
tie_embeddings = _e("TIE_EMBEDDINGS", 0, int) # 0=separate, 1=tied, 2=tied+correction, 3=tied+adapter
projector_type = _e("PROJECTOR_TYPE", "linear") # "linear" or "mlp"
logit_softcap = _e("LOGIT_SOFTCAP", 15.0, float) # 0 = disabled
softcap_type = _e("SOFTCAP_TYPE", "poly") # "poly" or "tanh"
# JEPA / Loss
sigreg_lambda = _e("SIGREG_LAMBDA", 1.0, float) # was 0.01 when loss was scaled by N
sigreg_knots = _e("SIGREG_KNOTS", 17, int)
sigreg_num_proj = _e("SIGREG_NUM_PROJ", 0, int) # 0 = auto (2x embed_dim)
sigreg_schedule = _e("SIGREG_SCHEDULE", 0, bool) # ramp lambda from 0 to sigreg_lambda
ce_weight = _e("CE_WEIGHT", 1.0, float)
jepa_weight = _e("JEPA_WEIGHT", 1.0, float)
jepa_steps = _e("JEPA_STEPS", 1, int) # 0=disabled, 1=next step, 2+=multi-step
detach_targets = _e("DETACH_TARGETS", 0, bool)
# Training
train_seq_len = _e("TRAIN_SEQ_LEN", 4096, int)
train_batch_tokens = _e("TRAIN_BATCH_TOKENS", 524288, int)
iterations = _e("ITERATIONS", 10000, int)
warmup_steps = _e("WARMUP_STEPS", 10, int)
warmdown_fraction = _e("WARMDOWN_FRACTION", 0.15, float)
max_wallclock_seconds = _e("MAX_WALLCLOCK_SECONDS", 0.0, float)
val_batch_size = _e("VAL_BATCH_SIZE", 524288, int)
val_loss_every = _e("VAL_LOSS_EVERY", 500, int)
train_log_every = _e("TRAIN_LOG_EVERY", 100, int)
# Optimizer
matrix_lr = _e("MATRIX_LR", 0.02, float)
scalar_lr = _e("SCALAR_LR", 0.01, float)
embed_lr = _e("EMBED_LR", 0.01, float)
muon_momentum = _e("MUON_MOMENTUM", 0.95, float)
muon_backend_steps = _e("MUON_BACKEND_STEPS", 3, int)
muon_momentum_warmup_start = _e("MUON_MOMENTUM_WARMUP_START", 0.85, float)
muon_momentum_warmup_steps = _e("MUON_MOMENTUM_WARMUP_STEPS", 500, int)
muon_wd = _e("MUON_WD", 0.04, float)
adam_wd = _e("ADAM_WD", 0.05, float)
beta1 = _e("BETA1", 0.9, float)
beta2 = _e("BETA2", 0.95, float)
adam_eps = _e("ADAM_EPS", 1e-8, float)
grad_clip_norm = _e("GRAD_CLIP_NORM", 1.0, float)
# Quantization
quant_bits = _e("QUANT_BITS", 5, int) # INT-N for large matrices (4, 5, 6)
qat_fraction = _e("QAT_FRACTION", 1.0, float) # 1.0 = QAT from step 1
_fp_raw = os.environ.get("FP_STORAGE", "BF16")
fp_storage = "fp8" if _fp_raw == "FP8" else "bf16" # FP8 or BF16 for non-INT params
# Eval
sliding_eval = _e("SLIDING_EVAL", 0, bool)
sliding_eval_stride = _e("SLIDING_EVAL_STRIDE", 16, int)
sliding_batch_size = _e("SLIDING_BATCH_SIZE", 64, int)
temp_scaling = _e("TEMP_SCALING", 1, bool)
compile_mode = _e("COMPILE_MODE", "default")
# Checkpoint
checkpoint_every = _e("CHECKPOINT_EVERY", 0, int) # 0 = disabled
checkpoint_dir = _e("CHECKPOINT_DIR", "./checkpoints")
# ---------------------------------------------------------------------------
# SIGReg — Sketch Isotropic Gaussian Regularizer (from LeWorldModel)
# Prevents representation collapse by enforcing Gaussian latent distribution.
# Maes, Le Lidec, Scieur, LeCun, Balestriero (2026)
# ---------------------------------------------------------------------------
class SIGReg(nn.Module):
def __init__(self, d_model: int, knots: int = 17, num_proj: int = 1024):
super().__init__()
self.num_proj = num_proj
# Integration range [0.2, 4] matching LeWorldModel paper (Appendix A)
t = torch.linspace(0.2, 4.0, knots, dtype=torch.float32)
dt = (4.0 - 0.2) / (knots - 1)
weights = torch.full((knots,), 2 * dt, dtype=torch.float32)
weights[[0, -1]] = dt
window = torch.exp(-t.square() / 2.0)
self.register_buffer("t", t)
self.register_buffer("phi", window) # Gaussian characteristic function
self.register_buffer("weights", weights * window)
# Fixed random projection matrix — generated once, avoids CUDA RNG overhead per step.
A = torch.randn(d_model, num_proj)
A = A / A.norm(dim=0, keepdim=True)
self.register_buffer("A", A)
def _sigreg_1d(self, emb: Tensor) -> Tensor:
"""Compute SIGReg loss for a single (N, D) batch of embeddings."""
proj = emb @ self.A.to(dtype=emb.dtype) # (N, num_proj)
x_t = proj.unsqueeze(-1) * self.t # (N, num_proj, knots)
err = (x_t.cos().mean(0) - self.phi).square() + x_t.sin().mean(0).square()
return (err @ self.weights).mean()
def forward(self, embeddings: Tensor, max_timesteps: int = 64) -> Tensor:
"""
embeddings: (B, T, D) — apply SIGReg per-timestep across batch (matching paper).
Each timestep's batch of embeddings is independently pushed toward Gaussian.
Samples up to max_timesteps positions to keep compute bounded.
Returns: scalar regularization loss (mean over sampled timesteps).
"""
if embeddings.ndim == 2:
return self._sigreg_1d(embeddings)
B, T, D = embeddings.shape
# Sample timesteps if T is large
if T > max_timesteps:
t_idx = torch.randint(0, T, (max_timesteps,), device=embeddings.device)
emb = embeddings[:, t_idx, :] # (B, S, D) where S = max_timesteps
else:
emb = embeddings # (B, T, D)
S = emb.size(1)
# Vectorized per-timestep SIGReg:
# Project all timesteps at once: (B, S, D) @ (D, num_proj) -> (B, S, num_proj)
A = self.A.to(dtype=emb.dtype)
proj = torch.einsum("bsd,dp->bsp", emb, A) # (B, S, num_proj)
x_t = proj.unsqueeze(-1) * self.t # (B, S, num_proj, knots)
# Per-timestep mean over batch dim: mean(0) -> (S, num_proj, knots)
cos_mean = x_t.cos().mean(0)
sin_mean = x_t.sin().mean(0)
# Characteristic function error per timestep
err = (cos_mean - self.phi).square() + sin_mean.square() # (S, num_proj, knots)
per_t = (err @ self.weights).mean(-1) # (S,) — loss per timestep
return per_t.mean()
# ---------------------------------------------------------------------------
# Model components
# ---------------------------------------------------------------------------
class RMSNorm(nn.Module):
def __init__(self, eps: float = 1e-6):
super().__init__()
self.eps = eps
def forward(self, x: Tensor) -> Tensor:
return F.rms_norm(x, (x.size(-1),), eps=self.eps)
class SwiGLU(nn.Module):
"""SwiGLU MLP: gate-up projection -> SiLU gate -> norm -> down projection."""
def __init__(self, dim: int, hidden_mult: int = 2):
super().__init__()
hidden = dim * hidden_mult
self.gate_up = nn.Linear(dim, hidden * 2, bias=False)
self.norm = RMSNorm()
self.down = nn.Linear(hidden, dim, bias=False)
nn.init.zeros_(self.down.weight)
def forward(self, x: Tensor) -> Tensor:
gu = self.gate_up(x)
gate, up = gu.chunk(2, dim=-1)
return self.down(self.norm(F.silu(gate) * up))
class ReLU2MLP(nn.Module):
"""ReLU^2 MLP: fc -> relu^2 -> norm -> down. Fewer params than SwiGLU (no gate)."""
def __init__(self, dim: int, hidden_mult: int = 3):
super().__init__()
hidden = dim * hidden_mult
self.fc = nn.Linear(dim, hidden, bias=False)
self.norm = RMSNorm()
self.down = nn.Linear(hidden, dim, bias=False)
nn.init.zeros_(self.down.weight)
def forward(self, x: Tensor) -> Tensor:
return self.down(self.norm(F.relu(self.fc(x)).square()))
class SSMBlock(nn.Module):
"""SSM block with pre-RMSNorm, residual scales, x0 mixing, and optional MLP."""
def __init__(self, d_model: int, d_state: int = 64, d_conv: int = 4,
expand: int = 2, mlp_mult: int = 0, activation: str = "relu2"):
super().__init__()
self.norm = RMSNorm()
self.ssm = Mamba2(d_model=d_model, d_state=d_state, d_conv=d_conv, expand=expand)
# Learnable per-dim residual scales (like ternary code's attn_scale / mlp_scale)
self.ssm_scale = nn.Parameter(torch.ones(d_model, dtype=torch.float32))
# x0 residual mixing: mix[0]*x + mix[1]*x0 — gives every block direct
# access to the original input representation (gradient highway)
self.resid_mix = nn.Parameter(torch.stack((torch.ones(d_model), torch.zeros(d_model))).float())
self.mlp = None
if mlp_mult > 0:
self.mlp_norm = RMSNorm()
self.mlp_scale = nn.Parameter(torch.ones(d_model, dtype=torch.float32))
if activation == "swiglu":
self.mlp = SwiGLU(d_model, mlp_mult)
else: # relu2
self.mlp = ReLU2MLP(d_model, mlp_mult)
def forward(self, x: Tensor, x0: Tensor) -> Tensor:
mix = self.resid_mix.to(dtype=x.dtype)
x = mix[0] * x + mix[1] * x0
x = x + self.ssm_scale.to(dtype=x.dtype) * self.ssm(self.norm(x))
if self.mlp is not None:
x = x + self.mlp_scale.to(dtype=x.dtype) * self.mlp(self.mlp_norm(x))
return x
# ---------------------------------------------------------------------------
# The core model
# ---------------------------------------------------------------------------
class ProjectorMLP(nn.Module):
"""MLP projector with LayerNorm."""
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int):
super().__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.norm = nn.LayerNorm(hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x: Tensor) -> Tensor:
return self.fc2(self.act(self.norm(self.fc1(x))))
class Jepa(nn.Module):
"""JEPA with SSM backbone, aligned with LeWorldModel (Maes et al. 2026)."""
def __init__(self, vocab_size: int = 256, model_dim: int = 512, num_layers: int = 12,
d_state: int = 64, d_conv: int = 4, expand: int = 2,
embed_dim: int = 0, predictor_hidden_mult: int = 2,
mlp_mult: int = 3, mlp_every: int = 1, activation: str = "relu2",
tie_embeddings: int = 0, projector_type: str = "linear",
jepa_steps: int = 1, logit_softcap: float = 15.0,
softcap_type: str = "poly"):
super().__init__()
self.vocab_size = vocab_size
self.model_dim = model_dim
self.jepa_steps = jepa_steps
self.tie_embeddings = tie_embeddings
self.logit_softcap = logit_softcap
self.softcap_type = softcap_type
embed_dim = embed_dim if embed_dim > 0 else model_dim
self._embed_dim = embed_dim
# Token embedding (input)
self.token_embed = nn.Embedding(vocab_size, embed_dim)
nn.init.normal_(self.token_embed.weight, std=0.02)
# Optional embed projection (when embed_dim != model_dim)
self.embed_proj = nn.Linear(embed_dim, model_dim, bias=False) if embed_dim != model_dim else None
# Reverse projection for tied embeddings with dim mismatch (not needed for tie=3, adapter handles it)
self.embed_proj_rev = nn.Linear(model_dim, embed_dim, bias=False) if (
embed_dim != model_dim and tie_embeddings in (1, 2)) else None
# U-Net: split layers into encoder/decoder halves with skip connections.
# Standard U-Net pairing: encoder pushes LIFO, decoder pops LIFO, so
# skip_weights[0] pairs with the DEEPEST encoder output (standard U-Net).
# For odd num_layers (e.g. 13 → 6 enc + 7 dec), the first decoder block
# has no skip partner — the if-guard silently handles this.
self.num_encoder_layers = num_layers // 2
self.num_decoder_layers = num_layers - self.num_encoder_layers
self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers)
self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32))
# SSM encoder backbone (mlp_every controls which blocks get MLP: 1=all, 2=alternate, etc.)
self.blocks = nn.ModuleList([
SSMBlock(model_dim, d_state, d_conv, expand,
mlp_mult if (mlp_every > 0 and i % mlp_every == 0) else 0,
activation)
for i in range(num_layers)
])
self.norm = RMSNorm()
# Projector: h -> z (JEPA prediction space)
if projector_type == "mlp":
self.projector = ProjectorMLP(model_dim, model_dim * 2, model_dim)
self.pred_proj = ProjectorMLP(model_dim, model_dim * 2, model_dim)
else: # linear
self.projector = nn.Linear(model_dim, model_dim, bias=False)
self.pred_proj = nn.Linear(model_dim, model_dim, bias=False)
# Predictor: z_t -> predicted z_{t+1}
pred_hidden = model_dim * predictor_hidden_mult
self.predictor = nn.Sequential(
nn.Linear(model_dim, pred_hidden),
nn.GELU(),
nn.Linear(pred_hidden, model_dim),
)
nn.init.zeros_(self.predictor[-1].weight)
nn.init.zeros_(self.predictor[-1].bias)
# Vocab bias — learnable per-token output bias (free BPB calibration)
self.vocab_bias = nn.Parameter(torch.zeros(vocab_size, dtype=torch.float32))
# LM head: h -> vocab logits
# tie_embeddings: 0=separate lm_head, 1=tied, 2=tied+correction, 3=tied+nonlinear adapter
self.lm_head_adapter = None
if tie_embeddings == 3:
# Nonlinear adapter before tied projection: h -> Linear -> GELU -> F.linear(_, embed.weight)
self.lm_head_adapter = nn.Sequential(
nn.Linear(model_dim, embed_dim, bias=False),
nn.GELU(),
)
self.lm_head = None
self.lm_head_correction = None
elif tie_embeddings >= 1:
self.lm_head = None
self.lm_head_correction = nn.Parameter(
torch.zeros(vocab_size, embed_dim)) if tie_embeddings == 2 else None
else:
self.lm_head = nn.Linear(model_dim, vocab_size, bias=False)
self.lm_head_correction = None
def _softcap(self, logits: Tensor) -> Tensor:
"""Logit softcap: prevents overconfident predictions, stabilizes early training."""
s = self.logit_softcap
if s <= 0:
return logits
if self.softcap_type == "tanh":
return s * torch.tanh(logits / s)
# Polynomial approximation (faster, from ternary code)
x_sc = torch.clamp(logits / s, -2.0, 2.0)
x2 = x_sc * x_sc
return s * torch.clamp(x_sc * (1.0 - x2 / 3.0 + x2 * x2 / 15.0), -1.0, 1.0)
def _get_logits(self, h: Tensor) -> Tensor:
"""Compute logits from hidden states."""
if self.tie_embeddings >= 1:
if self.lm_head_adapter is not None:
# tie=3: nonlinear adapter -> tied projection
proj = self.lm_head_adapter(h)
elif self.embed_proj_rev is not None:
# tie=1,2 with dim mismatch: linear reverse projection
proj = self.embed_proj_rev(h)
else:
proj = h
weight = self.token_embed.weight
if self.lm_head_correction is not None:
weight = weight + self.lm_head_correction
logits_raw = F.linear(proj, weight.to(h.dtype))
else:
logits_raw = self.lm_head(h)
return self._softcap(logits_raw + self.vocab_bias.to(h.dtype))
def encode(self, input_ids: Tensor) -> Tensor:
"""input_ids: (B, T) -> hidden states h: (B, T, D)"""
x = self.token_embed(input_ids)
if self.embed_proj is not None:
x = self.embed_proj(x)
# Normalize embedding output before entering residual stream
x = F.rms_norm(x, (x.size(-1),))
x0 = x
# U-Net style encoder/decoder with skip connections
skips = []
for i in range(self.num_encoder_layers):
x = self.blocks[i](x, x0)
skips.append(x)
for i in range(self.num_decoder_layers):
bi = self.num_encoder_layers + i
if skips:
x = x + self.skip_weights[i].to(dtype=x.dtype) * skips.pop()
x = self.blocks[bi](x, x0)
return self.norm(x)
def forward(self, input_ids: Tensor, target_ids: Tensor,
reduction: str = "mean", temperature: float | None = None,
*, train_mode: bool = False, sigreg: SIGReg | None = None,
sigreg_lambda: float = 0.0, ce_weight: float = 1.0,
jepa_weight: float = 0.0, detach_targets: bool = False,
) -> Tensor | tuple[Tensor, dict]:
"""
Unified forward for both training and eval (DDP hooks into this method).
train_mode=False: returns NLL loss (for eval / BPB)
train_mode=True: returns (combined_loss, diagnostics_dict) with JEPA+SIGReg+CE
"""
h = self.encode(input_ids)
if not train_mode:
# --- Eval path: simple CE for BPB ---
logits = self._get_logits(h)
if temperature is not None and temperature != 1.0:
logits = logits / temperature
logits_flat = logits.reshape(-1, self.vocab_size)
targets_flat = target_ids.reshape(-1)
if reduction == "none":
return F.cross_entropy(logits_flat.float(), targets_flat,
reduction="none").reshape(input_ids.shape)
# CE loss without Z-loss (Z-loss is training-only regularization)
logits_f = logits_flat.float()
lse = torch.logsumexp(logits_f, dim=-1)
target_logits = logits_f.gather(1, targets_flat.unsqueeze(1)).squeeze(1)
return (lse - target_logits).mean()
# --- Training path: JEPA + SIGReg + CE ---
z = self.projector(h)
diagnostics = {}
loss = torch.zeros((), device=h.device)
# JEPA: predict next projected embedding(s) via autoregressive composition
if jepa_weight > 0 and self.jepa_steps > 0:
jepa_loss = torch.zeros((), device=h.device)
n_steps = 0
prev_z = z[:, :-1, :]
for k in range(1, self.jepa_steps + 1):
if k >= z.size(1):
break
pred_z = self.pred_proj(self.predictor(prev_z))
target_z = z[:, k:k + prev_z.size(1), :]
if detach_targets:
target_z = target_z.detach()
L = min(pred_z.size(1), target_z.size(1))
jepa_loss = jepa_loss + F.mse_loss(pred_z[:, :L], target_z[:, :L])
n_steps += 1
prev_z = pred_z[:, :L]
if n_steps > 0:
jepa_loss = jepa_loss / n_steps
loss = loss + jepa_weight * jepa_loss
diagnostics["jepa"] = jepa_loss.detach()
# SIGReg on projected embeddings
if sigreg is not None and sigreg_lambda > 0:
sig_loss = sigreg(z)
loss = loss + sigreg_lambda * sig_loss
diagnostics["sigreg"] = sig_loss.detach()
# CE: lm_head on raw hidden states + z-loss
if ce_weight > 0:
logits = self._get_logits(h)
logits_flat = logits.reshape(-1, self.vocab_size).float()
targets_flat = target_ids.reshape(-1)
# Fused CE + Z-loss (single logsumexp)
lse = torch.logsumexp(logits_flat, dim=-1)
target_logits = logits_flat.gather(1, targets_flat.unsqueeze(1)).squeeze(1)
ce_loss = (lse - target_logits).mean() + 1e-4 * (lse ** 2).mean()
loss = loss + ce_weight * ce_loss
diagnostics["ce"] = ce_loss.detach()
return loss, diagnostics
# ---------------------------------------------------------------------------
# Muon optimizer (Newton-Schulz orthogonalized momentum)
# ---------------------------------------------------------------------------
def _ns_orth(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor:
a, b, c = (3.4445, -4.7750, 2.0315)
X = G.bfloat16()
X /= X.norm() + eps
transposed = G.size(0) > G.size(1)
if transposed:
X = X.T
for _ in range(steps):
A = X @ X.T
B = b * A + c * A @ A
X = a * X + B @ X
return X.T if transposed else X
ns_orth = _ns_orth # will be compiled in main()
class Muon(torch.optim.Optimizer):
def __init__(self, params, lr: float, momentum: float,
backend_steps: int, nesterov: bool = True, wd: float = 0.0):
super().__init__(params, dict(lr=lr, momentum=momentum,
backend_steps=backend_steps, nesterov=nesterov, wd=wd))
@torch.no_grad()
def step(self, closure=None):
distributed = dist.is_available() and dist.is_initialized()
world_size = dist.get_world_size() if distributed else 1
rank = dist.get_rank() if distributed else 0
for group in self.param_groups:
params = group["params"]
if not params:
continue
lr, mom = group["lr"], group["momentum"]
steps, nesterov = group["backend_steps"], group["nesterov"]
wd = group.get("wd", 0.0)
total = sum(p.numel() for p in params)
flat = torch.zeros(total, device=params[0].device, dtype=torch.bfloat16)
cur = 0
for i, p in enumerate(params):
if i % world_size == rank and p.grad is not None:
g = p.grad
state = self.state[p]
if "buf" not in state:
state["buf"] = torch.zeros_like(g)
buf = state["buf"]
buf.mul_(mom).add_(g)
if nesterov:
g = g.add(buf, alpha=mom)
g = F.rms_norm(g.float(), (g.size(-1),)).bfloat16()
g = ns_orth(g, steps=steps)
g *= max(1, g.size(0) / g.size(1)) ** 0.5
flat[cur:cur + p.numel()] = g.reshape(-1)
cur += p.numel()
if distributed:
dist.all_reduce(flat, op=dist.ReduceOp.SUM)
cur = 0
for p in params:
g = flat[cur:cur + p.numel()].view_as(p).to(p.dtype)
if wd > 0:
p.mul_(1 - lr * wd)
p.add_(g, alpha=-lr)
cur += p.numel()
# ---------------------------------------------------------------------------
# Data loading — challenge-format shards (byte or BPE)
# ---------------------------------------------------------------------------
def load_shard(path: Path, byte_mode: bool = True) -> Tensor:
"""Load a challenge-format shard (header + uint16 values).
byte_mode=True: assert values < 256, return uint8.
byte_mode=False: return uint16 (BPE token IDs)."""
header_bytes = 256 * np.dtype("<i4").itemsize
header = np.fromfile(path, dtype="<i4", count=256)
if header.size != 256 or int(header[0]) != 20240520:
raise ValueError(f"Unexpected shard header for {path}")
num_tokens = int(header[2])
tokens = np.fromfile(path, dtype="<u2", count=num_tokens, offset=header_bytes)
if byte_mode:
if tokens.max() > 255:
raise ValueError(f"Shard {path} contains token IDs > 255 (max={tokens.max()}). "
f"This is not byte-level data — check your dataset.")
return torch.from_numpy(tokens.astype(np.uint8, copy=False))
# BPE: cast to int32 for safe PyTorch interop (uint16 has limited operator support)
return torch.from_numpy(tokens.astype(np.int32, copy=False))
class TokenStream:
def __init__(self, pattern: str, byte_mode: bool = True):
self.files = [Path(p) for p in sorted(glob.glob(pattern))]
if not self.files:
raise FileNotFoundError(f"No files for pattern: {pattern}")
self.byte_mode = byte_mode
self.file_idx = 0
self.data = load_shard(self.files[0], byte_mode)
self.pos = 0
def _advance(self):
self.file_idx = (self.file_idx + 1) % len(self.files)
self.data = load_shard(self.files[self.file_idx], self.byte_mode)
self.pos = 0
def take(self, n: int) -> Tensor:
chunks = []
remaining = n
while remaining > 0:
avail = self.data.numel() - self.pos
if avail <= 0:
self._advance()
continue
k = min(remaining, avail)
chunks.append(self.data[self.pos:self.pos + k])
self.pos += k
remaining -= k
return chunks[0] if len(chunks) == 1 else torch.cat(chunks)
class DistributedTokenLoader:
def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device,
byte_mode: bool = True):
self.rank, self.world_size, self.device = rank, world_size, device
self.stream = TokenStream(pattern, byte_mode)
def next_batch(self, global_tokens: int, seq_len: int,
grad_accum_steps: int) -> tuple[Tensor, Tensor]:
local_tokens = global_tokens // (self.world_size * grad_accum_steps)
per_rank_span = local_tokens + 1
chunk = self.stream.take(per_rank_span * self.world_size)
start = self.rank * per_rank_span
local = chunk[start:start + per_rank_span]
local = local.pin_memory().to(self.device, non_blocking=True).to(torch.int64)
x = local[:-1].reshape(-1, seq_len)
y = local[1:].reshape(-1, seq_len)
return x, y
# ---------------------------------------------------------------------------
# Validation
# ---------------------------------------------------------------------------
def load_val_tokens(pattern: str, seq_len: int, byte_mode: bool = True,
max_tokens: int = int(os.environ.get("VAL_MAX_TOKENS", 500_000))) -> Tensor:
files = sorted(glob.glob(pattern))
assert files, f"No files: {pattern}"
data = torch.cat([load_shard(Path(p), byte_mode) for p in files]).contiguous()
if max_tokens > 0:
data = data[:max_tokens + 1]
u = ((data.numel() - 1) // seq_len) * seq_len
return data[:u + 1]
def build_bpe_luts(sp, vocab_size: int, device: torch.device):
"""Build token-to-byte lookup tables for BPE BPB calculation (from ternary code)."""
sp_vocab_size = int(sp.vocab_size())
table_size = max(sp_vocab_size, vocab_size)
base_bytes_np = np.zeros((table_size,), dtype=np.int16)
has_leading_space_np = np.zeros((table_size,), dtype=np.bool_)
is_boundary_token_np = np.ones((table_size,), dtype=np.bool_)
for token_id in range(sp_vocab_size):
if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id):
continue
is_boundary_token_np[token_id] = False
if sp.is_byte(token_id):
base_bytes_np[token_id] = 1
continue
piece = sp.id_to_piece(token_id)
if piece.startswith("\u2581"):
has_leading_space_np[token_id] = True
piece = piece[1:]
base_bytes_np[token_id] = len(piece.encode("utf-8"))
return (
torch.tensor(base_bytes_np, dtype=torch.int16, device=device),
torch.tensor(has_leading_space_np, dtype=torch.bool, device=device),
torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device),
)
def eval_val(args, model, rank, world_size, device,
val_tokens: Tensor, temperature: float = 1.0,
bpe_luts: tuple | None = None):
"""Evaluate BPB on validation set.
bpe_luts: (base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) for BPE BPB.
If None, byte-level BPB = loss / ln(2)."""
local_batch_tokens = args.val_batch_size // world_size
local_batch_seqs = max(1, local_batch_tokens // args.train_seq_len)
total_seqs = (val_tokens.numel() - 1) // args.train_seq_len
seq_start = (total_seqs * rank) // world_size
seq_end = (total_seqs * (rank + 1)) // world_size
loss_sum = torch.zeros((), device=device, dtype=torch.float64)
token_count = torch.zeros((), device=device, dtype=torch.float64)
byte_count = torch.zeros((), device=device, dtype=torch.float64)
model.eval()
with torch.inference_mode():
for batch_start in range(seq_start, seq_end, local_batch_seqs):
batch_end = min(batch_start + local_batch_seqs, seq_end)
raw_start = batch_start * args.train_seq_len
raw_end = batch_end * args.train_seq_len + 1
local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64)
x = local[:-1].reshape(-1, args.train_seq_len)
y = local[1:].reshape(-1, args.train_seq_len)
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
batch_loss = model(x, y, temperature=temperature).detach()
n = float(y.numel())
loss_sum += batch_loss.to(torch.float64) * n
token_count += n
# BPE: count actual bytes per token for accurate BPB
if bpe_luts is not None:
base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = bpe_luts
prev_ids, tgt_ids = x.reshape(-1), y.reshape(-1)
tok_bytes = base_bytes_lut[tgt_ids].to(torch.int16)
tok_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(torch.int16)
byte_count += tok_bytes.to(torch.float64).sum()
if dist.is_available() and dist.is_initialized():
for t in (loss_sum, token_count, byte_count):
dist.all_reduce(t, op=dist.ReduceOp.SUM)
val_loss = loss_sum / token_count
if bpe_luts is not None:
# BPE: BPB = (loss / ln2) * (tokens / bytes)
bpb = (val_loss.item() / math.log(2.0)) * (token_count.item() / byte_count.item())
else:
# Byte: each prediction is one byte
bpb = val_loss.item() / math.log(2.0)
model.train()
return float(val_loss.item()), float(bpb)
def eval_val_sliding(args, model, rank, world_size, device,
val_tokens: Tensor, stride: int = 64, temperature: float = 1.0,
bpe_luts: tuple | None = None):
"""Sliding window evaluation for better BPB."""
seq_len = args.train_seq_len
batch_size = args.sliding_batch_size
total_tokens = val_tokens.numel() - 1
all_starts = list(range(0, total_tokens - seq_len, stride))
my_starts = all_starts[rank::world_size]
loss_sum = torch.zeros((), device=device, dtype=torch.float64)
token_count = torch.zeros((), device=device, dtype=torch.float64)
byte_count = torch.zeros((), device=device, dtype=torch.float64)
model.eval()
with torch.inference_mode():
for i in range(0, len(my_starts), batch_size):
batch_starts = my_starts[i:i + batch_size]
starts_t = torch.tensor(batch_starts, dtype=torch.int64)
offsets = torch.arange(seq_len + 1, dtype=torch.int64)
indices = starts_t.unsqueeze(1) + offsets.unsqueeze(0)
local_batch = val_tokens[indices].to(device=device, dtype=torch.int64, non_blocking=True)
x, y = local_batch[:, :-1], local_batch[:, 1:]
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
per_token_loss = model(x, y, reduction="none", temperature=temperature).detach()
for b, start in enumerate(batch_starts):
score_from = 0 if start == 0 else seq_len - stride
scored = per_token_loss[b, score_from:]
sx, sy = x[b, score_from:], y[b, score_from:]
loss_sum += scored.to(torch.float64).sum()
token_count += scored.numel()
if bpe_luts is not None:
base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = bpe_luts
tok_bytes = base_bytes_lut[sy].to(torch.int16)
tok_bytes += (has_leading_space_lut[sy] & ~is_boundary_token_lut[sx]).to(torch.int16)
byte_count += tok_bytes.to(torch.float64).sum()
if dist.is_available() and dist.is_initialized():
for t in (loss_sum, token_count, byte_count):
dist.all_reduce(t, op=dist.ReduceOp.SUM)
val_loss = loss_sum / token_count
if bpe_luts is not None:
bpb = (val_loss.item() / math.log(2.0)) * (token_count.item() / byte_count.item())
else:
bpb = val_loss.item() / math.log(2.0)
model.train()
return float(val_loss.item()), float(bpb)
# ---------------------------------------------------------------------------
# JEPA Diagnostics — verify representation quality independent of BPB
# ---------------------------------------------------------------------------
def jepa_diagnostics(model: nn.Module, val_tokens: Tensor, device: torch.device,
seq_len: int = 2048, max_samples: int = 50000):
model.eval()
base = model.module if hasattr(model, 'module') else model
base = base._orig_mod if hasattr(base, '_orig_mod') else base
n = min(max_samples + 1, val_tokens.numel())
data = val_tokens[:n].to(device=device, dtype=torch.int64)
usable = ((data.numel() - 1) // seq_len) * seq_len
x = data[:usable].reshape(-1, seq_len)
y = data[1:usable + 1].reshape(-1, seq_len)
n_seqs = min(x.shape[0], max_samples // seq_len)
x, y = x[:n_seqs], y[:n_seqs]
cos_sims, jepa_mses = [], []
lm_top1 = lm_top5 = lm_top10 = total = 0
all_hidden, all_targets = [], []
with torch.no_grad():
for i in range(n_seqs):
xi, yi = x[i:i+1], y[i:i+1]
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
h = base.encode(xi)
z = base.projector(h)
pred_z = base.pred_proj(base.predictor(z[:, :-1, :]))
target_z = z[:, 1:, :]
cos = F.cosine_similarity(pred_z[0].float(), target_z[0].float(), dim=-1)
cos_sims.append(cos.mean().item())
jepa_mses.append((pred_z - target_z).pow(2).mean().item())
h_f = h[0].float()
logits = base._get_logits(h[0]) # keep bfloat16 for model layers
targets = yi[0]
preds = logits.argsort(dim=-1, descending=True)
lm_top1 += (preds[:, :1] == targets.unsqueeze(1)).any(1).sum().item()
lm_top5 += (preds[:, :5] == targets.unsqueeze(1)).any(1).sum().item()
lm_top10 += (preds[:, :10] == targets.unsqueeze(1)).any(1).sum().item()
total += targets.numel()
if len(all_hidden) * seq_len < 100000:
all_hidden.append(h_f.cpu())
all_targets.append(targets.cpu())
# Linear probe on frozen hidden states
probe_bpb = float('nan')
if all_hidden:
H = torch.cat(all_hidden, dim=0)
T = torch.cat(all_targets, dim=0)
n_train = int(0.8 * H.shape[0])
H_tr, H_val = H[:n_train].to(device), H[n_train:].to(device)
T_tr, T_val = T[:n_train].to(device), T[n_train:].to(device)
probe = nn.Linear(H.shape[-1], base.vocab_size).to(device)
opt = torch.optim.Adam(probe.parameters(), lr=1e-3)
bs = min(4096, n_train)
for _ in range(200):
idx = torch.randint(0, n_train, (bs,), device=device)
loss = F.cross_entropy(probe(H_tr[idx]), T_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
with torch.inference_mode():
probe_bpb = F.cross_entropy(probe(H_val), T_val).item() / math.log(2.0)
model.train()
return {
"jepa_cos_sim": sum(cos_sims) / max(len(cos_sims), 1),
"jepa_mse": sum(jepa_mses) / max(len(jepa_mses), 1),
"lm_top1": lm_top1 / max(total, 1),
"lm_top5": lm_top5 / max(total, 1),
"lm_top10": lm_top10 / max(total, 1),
"probe_bpb": probe_bpb,
}
# ---------------------------------------------------------------------------
# Temperature search (eval-time calibration)
# ---------------------------------------------------------------------------
def find_best_temperature(args, model, rank, world_size, device, val_tokens,
bpe_luts: tuple | None = None):
"""Two-phase temperature search: coarse grid then fine-grained around best."""
best_t, best_loss = 1.0, float("inf")
# Phase 1: coarse grid
for t in [0.5, 0.7, 0.85, 0.95, 1.0, 1.1, 1.3, 1.5, 2.0]:
loss, _ = eval_val(args, model, rank, world_size, device,
val_tokens, temperature=t, bpe_luts=bpe_luts)
if loss < best_loss:
best_loss = loss
best_t = t
# Phase 2: fine grid around best (step 0.02)
center = best_t
for t in [center - 0.06, center - 0.04, center - 0.02,
center + 0.02, center + 0.04, center + 0.06]:
if t <= 0:
continue
loss, _ = eval_val(args, model, rank, world_size, device,
val_tokens, temperature=t, bpe_luts=bpe_luts)
if loss < best_loss:
best_loss = loss
best_t = t
return best_t
# ---------------------------------------------------------------------------
# Checkpointing
# ---------------------------------------------------------------------------
def _ckpt_path(checkpoint_dir: str, step: int) -> str:
return os.path.join(checkpoint_dir, f"ckpt_step{step:07d}.pt")
def _latest_checkpoint(checkpoint_dir: str) -> str | None:
if not os.path.isdir(checkpoint_dir):
return None
ckpts = sorted(glob.glob(os.path.join(checkpoint_dir, "ckpt_step*.pt")))
return ckpts[-1] if ckpts else None
def save_checkpoint(checkpoint_dir: str, step: int, base_model: nn.Module,
optimizers: list, training_time_ms: float) -> None:
os.makedirs(checkpoint_dir, exist_ok=True)
path = _ckpt_path(checkpoint_dir, step)
payload = {
"step": step,
"training_time_ms": training_time_ms,
"model": base_model.state_dict(),
"optimizers": [o.state_dict() for o in optimizers],
"rng_cpu": torch.get_rng_state(),
"rng_cuda": torch.cuda.get_rng_state(),
}
tmp = path + ".tmp"
torch.save(payload, tmp)
os.replace(tmp, path) # atomic on POSIX
def load_checkpoint(path: str, base_model: nn.Module, optimizers: list,
device: torch.device) -> tuple[int, float]:
payload = torch.load(path, map_location=device, weights_only=False)
base_model.load_state_dict(payload["model"], strict=True)
for opt, sd in zip(optimizers, payload["optimizers"]):
opt.load_state_dict(sd)
torch.set_rng_state(payload["rng_cpu"].cpu())
torch.cuda.set_rng_state(payload["rng_cuda"].cpu())
return payload["step"], payload["training_time_ms"]
# ---------------------------------------------------------------------------
# Training-only modules (discarded from artifact — not needed at eval time)
# ---------------------------------------------------------------------------
TRAINING_ONLY = ("predictor.", "projector.", "pred_proj.")
def _is_training_only(name: str) -> bool:
return any(name.startswith(p) or f".{p}" in name for p in TRAINING_ONLY)
def _is_large_matrix(name: str, tensor: Tensor, min_numel: int = 4096) -> bool:
"""Large 2D weight matrices suitable for INT quantization.
Excludes: token_embed (lookup table), A_log (SSM log-transition),
lm_head_correction (fine residual correction needs full precision),
skip_weights (small U-Net skips)."""
return (tensor.ndim == 2 and tensor.numel() >= min_numel
and "token_embed" not in name and "A_log" not in name
and "lm_head_correction" not in name and "skip_weight" not in name)
# ---------------------------------------------------------------------------
# QAT — Quantization-Aware Training (snap/restore for Mamba2 compatibility)
# Note: Mamba2's CUDA kernels use internal weight layouts that prevent
# standard STE injection. snap/restore computes gradients at the quantized
# point, then applies them to the full-precision weights. This is noisier
# than proper STE but necessary for external CUDA kernel modules.
# ---------------------------------------------------------------------------
def _build_qat_param_list(model: nn.Module) -> list[tuple[str, nn.Parameter]]:
"""Pre-compute list of parameters subject to INT-N QAT. Uses same filter as serialization."""
return [(name, param) for name, param in model.named_parameters()
if not _is_training_only(name) and _is_large_matrix(name, param)]
def _build_fp8_param_list(model: nn.Module) -> list[tuple[str, nn.Parameter]]:
"""Pre-compute list of parameters subject to FP8 QAT (non-INT 2D params like token_embed).
Excludes Mamba2 internals (their CUDA kernels require exact dtype matching)."""
return [(name, param) for name, param in model.named_parameters()
if not _is_training_only(name)
and not _is_large_matrix(name, param)
and param.ndim == 2 and param.numel() >= 256
and "A_log" not in name and ".ssm." not in name]
def _snap_weights_to_grid(qat_params: list[tuple[str, nn.Parameter]], bits: int = 6,
fp8_params: list[tuple[str, nn.Parameter]] | None = None,
) -> tuple[list[Tensor], list[Tensor]]:
"""Snap large matrices to INT-N grid and optionally FP8 grid. Returns originals for restoration."""
qmax = (1 << (bits - 1)) - 1
int_originals = []
with torch.no_grad():
for _, param in qat_params:
int_originals.append(param.data.clone())
absmax = param.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8)
scale = absmax / qmax
param.data.copy_(torch.clamp(torch.round(param / scale), -qmax, qmax) * scale)
fp8_originals = []
if fp8_params:
with torch.no_grad():
for _, param in fp8_params:
fp8_originals.append(param.data.clone())
# STE: snap to FP8 grid (same approach as ternary code's QATLinear)
param.data.copy_(param.data.to(torch.float8_e4m3fn).to(param.dtype))
return int_originals, fp8_originals
def _restore_weights(qat_params: list[tuple[str, nn.Parameter]], int_originals: list[Tensor],
fp8_params: list[tuple[str, nn.Parameter]] | None = None,
fp8_originals: list[Tensor] | None = None):
"""Restore original weights after QAT forward/backward."""
with torch.no_grad():
for (_, param), orig in zip(qat_params, int_originals):
param.data.copy_(orig)
if fp8_params and fp8_originals:
for (_, param), orig in zip(fp8_params, fp8_originals):
param.data.copy_(orig)
# ---------------------------------------------------------------------------
# Quantization + Compression Pipeline
# ---------------------------------------------------------------------------
def quantize_intN(t: Tensor, bits: int = 6) -> tuple[bytes, Tensor, list, int]:
"""Quantize a 2D tensor to N-bit integers with per-row absmax scaling.
Returns (packed_bytes, scales_bf16, original_shape, n_vals).
Uses np.packbits for fast bit packing. Input must be CPU tensor."""
assert not t.is_cuda, "quantize_intN expects CPU tensor"
t32 = t.float()
if t32.ndim < 2:
t32 = t32.unsqueeze(0)
qmax = (1 << (bits - 1)) - 1
absmax = t32.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8)
scale = absmax / qmax
q = torch.clamp(torch.round(t32 / scale), -qmax, qmax).to(torch.int16)
scale_bf16 = scale.bfloat16().squeeze(-1)
# Shift to unsigned for packing
flat = (q.reshape(-1) + qmax).numpy().astype(np.uint8)
n_vals = len(flat)
# Expand each value into its individual bits, flatten, then packbits
bits_array = ((flat[:, None] >> np.arange(bits, dtype=np.uint8)) & 1).ravel()