bantamtrain 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bantamtrain/lowmem.py ADDED
@@ -0,0 +1,127 @@
1
+ """Low-memory training primitives: 8-bit optimizer state and bf16 weights.
2
+
3
+ Memory per parameter during training (bytes):
4
+
5
+ config weights grads AdamW state Muon state
6
+ fp32 everything 4 4 8 4
7
+ bf16 weights + 8-bit state (here) 2 2 2 1
8
+
9
+ 8-bit state uses blockwise quantization (Dettmers et al., 2021): each block of
10
+ `block` consecutive values has its own fp32 scale, so one outlier cannot wipe
11
+ out the precision of its neighbours. Two value maps are provided:
12
+
13
+ * "sqrt" (default, signed): q = sign(x) * round(sqrt(|x| / absmax) * 127).
14
+ The square-root companding gives small values finer steps than a linear
15
+ int8 map, which matters because most momentum entries are far below the
16
+ block maximum.
17
+ * "log" (non-negative, for Adam's second moment): uint8 over
18
+ [min log v, max log v] in the block, so a block spanning many orders of
19
+ magnitude keeps ~2 % relative precision everywhere.
20
+
21
+ bf16 weights without an fp32 master copy lose small updates to rounding
22
+ (lr * update is often below bf16's 8-bit mantissa step). Stochastic rounding
23
+ (Zamirai et al., 2020) makes the rounding unbiased: the expected weight after
24
+ many steps equals the fp32 trajectory. `to_bf16_stochastic` implements it on
25
+ the raw bit pattern.
26
+ """
27
+ import math
28
+
29
+ import torch
30
+
31
+ QBLOCK = 256
32
+
33
+
34
+ def _blocks(x, block):
35
+ flat = x.reshape(-1)
36
+ pad = (-flat.numel()) % block
37
+ if pad:
38
+ flat = torch.cat([flat, flat.new_zeros(pad)])
39
+ return flat.view(-1, block), pad
40
+
41
+
42
+ def quantize_signed(x, block=QBLOCK, vmap="sqrt"):
43
+ """float tensor -> (int8 codes (n_blocks, block), fp32 absmax (n_blocks,))."""
44
+ b, _ = _blocks(x.float(), block)
45
+ absmax = b.abs().amax(dim=1).clamp_min(1e-30)
46
+ n = b / absmax[:, None]
47
+ if vmap == "sqrt":
48
+ n = n.sign() * n.abs().sqrt()
49
+ q = torch.round(n * 127).to(torch.int8)
50
+ return q, absmax
51
+
52
+
53
+ def dequantize_signed(q, absmax, shape, vmap="sqrt"):
54
+ n = q.float() / 127
55
+ if vmap == "sqrt":
56
+ n = n.sign() * n * n
57
+ return (n * absmax[:, None]).reshape(-1)[:math.prod(shape)].view(shape)
58
+
59
+
60
+ def quantize_log(v, block=QBLOCK, eps=1e-30):
61
+ """non-negative tensor -> (uint8 codes, fp32 lo, fp32 hi) in log space."""
62
+ b, _ = _blocks(v.float(), block)
63
+ lv = (b + eps).log()
64
+ lo = lv.amin(dim=1)
65
+ hi = lv.amax(dim=1)
66
+ span = (hi - lo).clamp_min(1e-12)
67
+ q = torch.round((lv - lo[:, None]) / span[:, None] * 255).to(torch.uint8)
68
+ return q, lo, hi
69
+
70
+
71
+ def dequantize_log(q, lo, hi, shape, eps=1e-30):
72
+ span = (hi - lo).clamp_min(1e-12)
73
+ lv = lo[:, None] + q.float() / 255 * span[:, None]
74
+ return (lv.exp() - eps).clamp_min(0).reshape(-1)[:math.prod(shape)].view(shape)
75
+
76
+
77
+ class QState:
78
+ """A quantized optimizer buffer with get()/set() in fp32."""
79
+
80
+ def __init__(self, like, kind="signed", block=QBLOCK, vmap="sqrt"):
81
+ self.shape, self.kind, self.block, self.vmap = tuple(like.shape), kind, block, vmap
82
+ self.set(torch.zeros_like(like, dtype=torch.float32))
83
+
84
+ def set(self, x):
85
+ if self.kind == "signed":
86
+ self.q, self.s = quantize_signed(x, self.block, self.vmap)
87
+ else:
88
+ self.q, self.lo, self.hi = quantize_log(x, self.block)
89
+
90
+ def get(self):
91
+ if self.kind == "signed":
92
+ return dequantize_signed(self.q, self.s, self.shape, self.vmap)
93
+ return dequantize_log(self.q, self.lo, self.hi, self.shape)
94
+
95
+ def nbytes(self):
96
+ n = self.q.numel()
97
+ return n + (self.s.numel() * 4 if self.kind == "signed" else self.lo.numel() * 8)
98
+
99
+
100
+ def to_bf16_stochastic(x):
101
+ """fp32 -> bf16 with stochastic rounding (unbiased), via the bit pattern."""
102
+ assert x.dtype == torch.float32
103
+ bits = x.contiguous().view(torch.int32)
104
+ noise = torch.randint(0, 1 << 16, bits.shape, dtype=torch.int32, device=x.device)
105
+ rounded = (bits + noise) & -65536 # keep the top 16 bits
106
+ return rounded.view(torch.float32).to(torch.bfloat16)
107
+
108
+
109
+ def write_param(p, new_fp32, stochastic=True):
110
+ """Store an fp32 result into parameter p in p's dtype (bf16 -> stochastic rounding)."""
111
+ if p.dtype == torch.bfloat16 and stochastic:
112
+ p.copy_(to_bf16_stochastic(new_fp32))
113
+ else:
114
+ p.copy_(new_fp32.to(p.dtype))
115
+
116
+
117
+ def state_bytes(optimizer):
118
+ """Bytes held by optimizer state (fp32 tensors and QState buffers)."""
119
+ total = 0
120
+ for o in getattr(optimizer, "optimizers", [optimizer]):
121
+ for st in o.state.values():
122
+ for v in st.values():
123
+ if isinstance(v, torch.Tensor):
124
+ total += v.numel() * v.element_size()
125
+ elif isinstance(v, QState):
126
+ total += v.nbytes()
127
+ return total
bantamtrain/memory.py ADDED
@@ -0,0 +1,170 @@
1
+ """Memory and time scoreboard for single-GPU LLM training.
2
+
3
+ python -m bantamtrain.memory # 5B model on one RTX PRO 6000 Blackwell
4
+ python -m bantamtrain.memory --tokens 2e10 # a 20B-token run
5
+ python -m bantamtrain.memory --markdown # table for docs
6
+
7
+ Each row adds one technique to the row above and reports static memory
8
+ (weights + grads + optimizer state), activation memory, whether it fits,
9
+ the largest micro-batch, training FLOPs and wall-clock days to reach the
10
+ same loss as the standard recipe trained on --tokens tokens.
11
+
12
+ Assumptions (defaults; every one is a flag):
13
+ GPU RTX PRO 6000 Blackwell Workstation: 96 GB, 503.8 TFLOPS dense BF16
14
+ (NVIDIA RTX Blackwell PRO architecture whitepaper, Appendix A).
15
+ MFU 0.40 of dense BF16 peak (conservative). nanochat on one RTX PRO 6000
16
+ measured ~297 TFLOPS = 59 % at 600 W and ~40 % at 300 W
17
+ (karpathy/nanochat #288, d20 = 3.49 GFLOP/token); 2 cards ~50 % (#28).
18
+ FP8 x1.20 throughput for FP8 linears (Transformer Engine current
19
+ scaling is supported on SM 12.0); reports range 20-30 %. Not
20
+ measured here.
21
+ Muon reaches AdamW's loss with 0.52x the FLOPs (Liu et al. 2025,
22
+ "Muon is Scalable for LLM Training", compute-optimal 1-16B runs).
23
+ Measured here at 5.8M params: Muon at 1/3 of the compute beat AdamW
24
+ at full compute (>= 3x), not used in the table.
25
+ bf16 + SR bf16 weights/grads with stochastic rounding match fp32-master mixed
26
+ precision up to 6.7B (Ozkara et al. 2025); 8-bit Adam states match
27
+ 32-bit up to 1.5B (Dettmers et al. 2021).
28
+ Power 450 W cap keeps ~95 % throughput on this card in a ResNet-50 training
29
+ sweep (naveen.ing); for LLM training the only datapoint is nanochat at
30
+ 300 W: -32 % throughput, +36 % tokens per watt (#288).
31
+ Activation memory (bf16, FlashAttention): 34*T*d bytes per layer per sequence
32
+ (Korthikanti et al. 2022; llm.c GPT-2 1.6B measured within ~1 %). HF-style
33
+ Llama code measured ~1.6x higher (LOMO) -> --act_factor 1.6. Full checkpointing
34
+ keeps 2*T*d per layer plus one layer's activations and costs one extra forward
35
+ (8ND instead of 6ND; Megatron measured +30-40 % wall-clock).
36
+ """
37
+ import argparse
38
+
39
+ GB = 1e9
40
+
41
+
42
+ def default_width(params):
43
+ """A conventional d_model for a parameter count (GPT-2/Llama-style aspect ratios)."""
44
+ for limit, d in ((2e7, 384), (6e7, 512), (2e8, 768), (5e8, 1024), (1.5e9, 2048),
45
+ (4e9, 3072), (1e10, 4096), (2e10, 5120)):
46
+ if params <= limit:
47
+ return d
48
+ return 8192
49
+
50
+
51
+ def model_dims(params, d, vocab):
52
+ """Layers for a target parameter count: 12*L*d^2 + 2*V*d (untied embeddings)."""
53
+ d = d or default_width(params)
54
+ L = max(1, round((params - 2 * vocab * d) / (12 * d * d)))
55
+ return L, 12 * L * d * d + 2 * vocab * d
56
+
57
+
58
+ def scoreboard(params=5e9, d=0, vocab=32000, seq=2048, gpu_gb=96.0, peak_tflops=503.8,
59
+ mfu=0.40, tokens=1e11, fp8_speedup=1.20, muon_flops=0.52, power_tput=0.95,
60
+ overhead_gb=3.0, hidden_frac=None, act_factor=1.0):
61
+ d = d or default_width(params)
62
+ L, N = model_dims(params, d, vocab)
63
+ if hidden_frac is None:
64
+ hidden_frac = 12 * L * d * d / N
65
+ act_seq = 34 * seq * d * L * act_factor # bytes per sequence, no recompute
66
+ act_seq_ckpt = 2 * seq * d * L # stored block inputs
67
+ act_layer = 34 * seq * d * act_factor # one layer recomputed at a time
68
+ logits_seq = seq * vocab * 6 # bf16 logits + fp32 loss buffer
69
+ logits_chunk = 1024 * vocab * 6 # chunked cross-entropy
70
+
71
+ def row(name, w, g, state, ckpt, chunked, tok_mult=1.0, speed=1.0, note=""):
72
+ static = N * (w + g + state)
73
+ per_seq = (act_seq_ckpt if ckpt else act_seq) + (0 if chunked else logits_seq)
74
+ fixed = static + overhead_gb * GB + (act_layer if ckpt else 0) + \
75
+ (logits_chunk if chunked else 0)
76
+ max_micro = int((gpu_gb * GB - fixed) // per_seq) if gpu_gb * GB > fixed else 0
77
+ micro = max(1, min(max_micro, 8))
78
+ flops = (8 if ckpt else 6) * N * tokens * tok_mult
79
+ secs = flops / (peak_tflops * 1e12 * mfu * speed)
80
+ return {"config": name, "bytes_per_param": w + g + state,
81
+ "static_gb": static / GB, "act_gb": micro * per_seq / GB,
82
+ "total_gb": (fixed + micro * per_seq) / GB, "fits": max_micro >= 1,
83
+ "max_micro": max_micro, "flops": flops, "days": secs / 86400, "note": note}
84
+
85
+ muon_state = hidden_frac * 1 + (1 - hidden_frac) * 2 # 8-bit momentum / 8-bit Adam
86
+ rows = []
87
+ r = row("1. Standard: AMP bf16, fp32 master + fp32 AdamW", 4 + 2, 4, 8, False, False,
88
+ note="fp32 weights + bf16 autocast copies")
89
+ if not r["fits"]:
90
+ r = row("1. Standard: AMP bf16, fp32 master + fp32 AdamW (+ act. ckpt to fit)",
91
+ 4 + 2, 4, 8, True, False, note="does not fit without activation checkpointing")
92
+ rows.append(r)
93
+ rows.append(row("2. + bf16 weights (stochastic rounding) + 8-bit AdamW + chunked CE",
94
+ 2, 2, 2, False, True, note="no fp32 master; fits without recompute"))
95
+ rows.append(row("3. + Muon (8-bit momentum)", 2, 2, muon_state, False, True,
96
+ tok_mult=muon_flops, note=f"same loss with {muon_flops:.2f}x the FLOPs"))
97
+ rows.append(row("4. + FP8 linears", 2, 2, muon_state, False, True, tok_mult=muon_flops,
98
+ speed=fp8_speedup, note=f"x{fp8_speedup:.2f} throughput (literature)"))
99
+ rows.append(row("5. + 450 W power cap (75 % power)", 2, 2, muon_state, False, True,
100
+ tok_mult=muon_flops, speed=fp8_speedup * power_tput,
101
+ note=f"x{power_tput:.2f} throughput, 25 % less power"))
102
+ return {"layers": L, "params": N, "d": d, "rows": rows}
103
+
104
+
105
+ def storage_table(N, tokens, bits_per_token=5.97):
106
+ """Disk/RAM sizes for weights, resumable checkpoints and the token corpus."""
107
+ return [
108
+ ("weights fp32 (RAM or disk)", 4 * N),
109
+ ("weights bf16", 2 * N),
110
+ ("weights bf16, lossless (WeightPack 16: byte-shuffle + zstd, ~71 %)", 1.42 * N),
111
+ ("weights int8 (qweights / WeightPack 8)", 1.03 * N),
112
+ ("weights int4 (qweights / WeightPack 4)", 0.53 * N),
113
+ ("resumable ckpt: fp32 weights + fp32 AdamW", 12 * N),
114
+ ("resumable ckpt: bf16 weights + 8-bit Muon", 3.1 * N),
115
+ ("corpus: raw UTF-8 text (~4 B/token)", 4 * tokens),
116
+ ("corpus: uint16 token ids", 2 * tokens),
117
+ (f"corpus: TokPack v2 ({bits_per_token:.2f} bits/token, measured on 117M TinyStories tokens)",
118
+ bits_per_token / 8 * tokens),
119
+ ]
120
+
121
+
122
+ def fmt(sb, tokens, markdown=False):
123
+ base = sb["rows"][0]["days"]
124
+ lines = []
125
+ if markdown:
126
+ lines.append("| configuration | bytes/param | static GB | total GB | fits | max micro-batch | days | speedup |")
127
+ lines.append("|---|---|---|---|---|---|---|---|")
128
+ for r in sb["rows"]:
129
+ lines.append(f"| {r['config']} | {r['bytes_per_param']:.1f} | {r['static_gb']:.0f} | "
130
+ f"{r['total_gb']:.0f} | {'yes' if r['fits'] else 'no'} | {r['max_micro']} | "
131
+ f"{r['days']:.0f} | {base / r['days']:.2f}x |")
132
+ return "\n".join(lines)
133
+ lines.append(f"model: {sb['params']/1e9:.2f}B params ({sb['layers']} layers), "
134
+ f"reference = standard recipe on {tokens:.1e} tokens")
135
+ hdr = f"{'configuration':72s} {'B/p':>5s} {'static':>7s} {'total':>6s} fit {'maxB':>5s} {'days':>6s} {'speedup':>7s}"
136
+ lines += [hdr, "-" * len(hdr)]
137
+ for r in sb["rows"]:
138
+ lines.append(f"{r['config']:72s} {r['bytes_per_param']:5.1f} {r['static_gb']:6.0f}G "
139
+ f"{r['total_gb']:5.0f}G {'yes' if r['fits'] else 'NO ':3s} {r['max_micro']:5d} "
140
+ f"{r['days']:6.0f} {base / r['days']:6.2f}x")
141
+ return "\n".join(lines)
142
+
143
+
144
+ def main():
145
+ ap = argparse.ArgumentParser()
146
+ ap.add_argument("--params", type=float, default=5e9)
147
+ ap.add_argument("--d", type=int, default=0, help="d_model (0 = pick from --params)")
148
+ ap.add_argument("--vocab", type=int, default=32000)
149
+ ap.add_argument("--seq", type=int, default=2048)
150
+ ap.add_argument("--gpu_gb", type=float, default=96)
151
+ ap.add_argument("--peak_tflops", type=float, default=503.8)
152
+ ap.add_argument("--mfu", type=float, default=0.40)
153
+ ap.add_argument("--tokens", type=float, default=1e11)
154
+ ap.add_argument("--fp8_speedup", type=float, default=1.20)
155
+ ap.add_argument("--muon_flops", type=float, default=0.52)
156
+ ap.add_argument("--power_tput", type=float, default=0.95)
157
+ ap.add_argument("--act_factor", type=float, default=1.0,
158
+ help="activation memory vs the 34*T*d formula (1.6 for HF Llama code)")
159
+ ap.add_argument("--markdown", action="store_true")
160
+ a = ap.parse_args()
161
+ sb = scoreboard(a.params, a.d, a.vocab, a.seq, a.gpu_gb, a.peak_tflops, a.mfu, a.tokens,
162
+ a.fp8_speedup, a.muon_flops, a.power_tput, act_factor=a.act_factor)
163
+ print(fmt(sb, a.tokens, a.markdown))
164
+ print()
165
+ for name, b in storage_table(sb["params"], a.tokens):
166
+ print(f"{name:66s} {b / GB:8.1f} GB")
167
+
168
+
169
+ if __name__ == "__main__":
170
+ main()
@@ -0,0 +1,2 @@
1
+ from .gpt import ZoomGPT # noqa: F401
2
+ from .vit_weather import ZoomViT # noqa: F401
@@ -0,0 +1,177 @@
1
+ """Small decoder-only transformer with Zoom Training support.
2
+
3
+ forward(idx, k):
4
+ idx: (B, T) token ids, T divisible by k.
5
+ k=1 is an ordinary causal LM. For k>1 every k consecutive tokens are merged
6
+ into one position; position p predicts all k tokens of group p+1.
7
+ """
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.utils.checkpoint import checkpoint
12
+
13
+ from ..zoom import SlotMerge, SlotUnmerge
14
+
15
+
16
+ class RMSNorm(nn.Module):
17
+ def __init__(self, d, eps=1e-6):
18
+ super().__init__()
19
+ self.eps = eps
20
+ self.weight = nn.Parameter(torch.ones(d))
21
+
22
+ def forward(self, x):
23
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
24
+
25
+
26
+ def rope_tables(positions, head_dim, base=10000.0):
27
+ """cos/sin tables for arbitrary (possibly fractional) positions."""
28
+ inv = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32,
29
+ device=positions.device) / head_dim))
30
+ ang = positions.float()[:, None] * inv[None, :]
31
+ return ang.cos(), ang.sin()
32
+
33
+
34
+ def apply_rope(x, cos, sin): # x: (B, H, T, Dh)
35
+ cos, sin = cos.to(x.dtype), sin.to(x.dtype)
36
+ x1, x2 = x[..., 0::2], x[..., 1::2]
37
+ out = torch.empty_like(x)
38
+ out[..., 0::2] = x1 * cos - x2 * sin
39
+ out[..., 1::2] = x1 * sin + x2 * cos
40
+ return out
41
+
42
+
43
+ class Block(nn.Module):
44
+ def __init__(self, d, n_head, mlp_mult=4, qk_norm=False, mlp="gelu"):
45
+ super().__init__()
46
+ self.n_head = n_head
47
+ self.mlp = mlp
48
+ self.ln1 = RMSNorm(d)
49
+ self.qkv = nn.Linear(d, 3 * d, bias=False)
50
+ self.qkv.weight.muon_split = 3 # orthogonalize q, k, v separately
51
+ self.proj = nn.Linear(d, d, bias=False)
52
+ self.ln2 = RMSNorm(d)
53
+ self.fc = nn.Linear(d, mlp_mult * d, bias=False)
54
+ self.fc_out = nn.Linear(mlp_mult * d, d, bias=False)
55
+ self.qk_norm = qk_norm
56
+ if qk_norm:
57
+ self.q_norm = RMSNorm(d // n_head)
58
+ self.k_norm = RMSNorm(d // n_head)
59
+
60
+ def forward(self, x, cos, sin):
61
+ B, T, D = x.shape
62
+ q, k, v = self.qkv(self.ln1(x)).split(D, dim=-1)
63
+ q = q.view(B, T, self.n_head, -1).transpose(1, 2)
64
+ k = k.view(B, T, self.n_head, -1).transpose(1, 2)
65
+ v = v.view(B, T, self.n_head, -1).transpose(1, 2)
66
+ if self.qk_norm:
67
+ q, k = self.q_norm(q), self.k_norm(k)
68
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
69
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
70
+ x = x + self.proj(y.transpose(1, 2).reshape(B, T, D))
71
+ h = self.fc(self.ln2(x))
72
+ h = F.relu(h).square() if self.mlp == "relu2" else F.gelu(h)
73
+ x = x + self.fc_out(h)
74
+ return x
75
+
76
+
77
+ class ZoomGPT(nn.Module):
78
+ def __init__(self, vocab, d=256, n_layer=6, n_head=4, zoom_ks=(),
79
+ gated=True, out_mode="slot", rope_pos="token", qk_norm=False,
80
+ merge_mode=None, grad_ckpt=False, mlp="gelu", softcap=0.0,
81
+ zero_init_proj=False):
82
+ super().__init__()
83
+ assert out_mode in ("slot", "bag")
84
+ assert rope_pos in ("token", "patch")
85
+ self.d, self.n_layer, self.vocab = d, n_layer, vocab
86
+ self.out_mode, self.rope_pos, self.grad_ckpt = out_mode, rope_pos, grad_ckpt
87
+ self.softcap = softcap
88
+ self.head_dim = d // n_head
89
+ self.emb = nn.Embedding(vocab, d)
90
+ self.blocks = nn.ModuleList(Block(d, n_head, qk_norm=qk_norm, mlp=mlp)
91
+ for _ in range(n_layer))
92
+ self.ln_f = RMSNorm(d)
93
+ self.merge = nn.ModuleDict({str(k): SlotMerge(k, d, gated, merge_mode) for k in zoom_ks})
94
+ self.unmerge = nn.ModuleDict(
95
+ {str(k): SlotUnmerge(k, d, gated, merge_mode) for k in zoom_ks} if out_mode == "slot" else {})
96
+ self._rope_cache = {}
97
+ self.apply(self._init)
98
+ for b in self.blocks: # scaled residual init, or zero-init (speedrun)
99
+ if zero_init_proj:
100
+ nn.init.zeros_(b.proj.weight)
101
+ nn.init.zeros_(b.fc_out.weight)
102
+ else:
103
+ nn.init.normal_(b.proj.weight, std=0.02 / (2 * n_layer) ** 0.5)
104
+ nn.init.normal_(b.fc_out.weight, std=0.02 / (2 * n_layer) ** 0.5)
105
+
106
+ @staticmethod
107
+ def _init(m):
108
+ if isinstance(m, (nn.Linear, nn.Embedding)):
109
+ nn.init.normal_(m.weight, std=0.02)
110
+
111
+ def muon_params(self):
112
+ """Hidden weight matrices (Muon); embedding/head/norms/gates stay on AdamW."""
113
+ return [p for b in self.blocks for p in
114
+ (b.qkv.weight, b.proj.weight, b.fc.weight, b.fc_out.weight)]
115
+
116
+ def _rope(self, n_pos, k):
117
+ key = (n_pos, k, self.emb.weight.device)
118
+ if key not in self._rope_cache:
119
+ p = torch.arange(n_pos, dtype=torch.float32, device=self.emb.weight.device)
120
+ if self.rope_pos == "token": # group p sits at its centre, in token units
121
+ p = p * k + (k - 1) / 2
122
+ self._rope_cache[key] = rope_tables(p, self.head_dim)
123
+ return self._rope_cache[key]
124
+
125
+ def hidden(self, idx, k=1):
126
+ B, T = idx.shape
127
+ x = self.emb(idx)
128
+ if k > 1:
129
+ x = self.merge[str(k)](x.view(B, T // k, k, self.d))
130
+ cos, sin = self._rope(x.shape[1], k)
131
+ for blk in self.blocks:
132
+ if self.grad_ckpt and self.training:
133
+ x = checkpoint(blk, x, cos, sin, use_reentrant=False)
134
+ else:
135
+ x = blk(x, cos, sin)
136
+ return self.ln_f(x)
137
+
138
+ def logits(self, h):
139
+ z = h @ self.emb.weight.t() # tied output head
140
+ if self.softcap > 0: # bounded logits (Gemma-2 / speedrun)
141
+ z = self.softcap * torch.tanh(z / self.softcap)
142
+ return z
143
+
144
+ def forward(self, idx, targets, k=1):
145
+ """idx: (B, T); targets: (B, T) where targets[:, i] = token at i + k."""
146
+ B, T = idx.shape
147
+ h = self.hidden(idx, k) # (B, T/k, d)
148
+ if k == 1:
149
+ return F.cross_entropy(self.logits(h).view(-1, self.vocab), targets.reshape(-1))
150
+ tgt = targets.view(B, T // k, k)
151
+ if self.out_mode == "slot":
152
+ z = self.logits(self.unmerge[str(k)](h)) # (B, T/k, k, V)
153
+ return F.cross_entropy(z.reshape(-1, self.vocab), tgt.reshape(-1))
154
+ logp = F.log_softmax(self.logits(h), dim=-1) # (B, T/k, V), one dist per group
155
+ return -logp.gather(-1, tgt).mean()
156
+
157
+ def flops_per_step(self, batch, seq, k):
158
+ """Analytic training FLOPs (fwd + bwd = 3x fwd) for one step."""
159
+ n = seq // k
160
+ d, L, V = self.d, self.n_layer, self.vocab
161
+ body = L * (24 * d * d + 2 * n * d) # per position, causal attention
162
+ head_slots = k if (k > 1 and self.out_mode == "slot") else 1
163
+ head = 2 * d * V * head_slots
164
+ return 3 * batch * n * (body + head)
165
+
166
+ @torch.no_grad()
167
+ def generate(self, idx, n_new, temperature=0.8, top_k=40, eos_id=None):
168
+ for _ in range(n_new):
169
+ h = self.hidden(idx[:, -256:], 1)[:, -1]
170
+ logits = self.logits(h) / temperature
171
+ v, _ = torch.topk(logits, top_k)
172
+ logits[logits < v[:, [-1]]] = -float("inf")
173
+ nxt = torch.multinomial(F.softmax(logits, -1), 1)
174
+ idx = torch.cat([idx, nxt], 1)
175
+ if eos_id is not None and nxt.item() == eos_id:
176
+ break
177
+ return idx
@@ -0,0 +1,119 @@
1
+ """ViT weather model (6 h step) with Zoom Training support.
2
+
3
+ The (lat, lon) grid is cut into 2x2-cell patches -> fine token grid. At zoom
4
+ level k = f*f, each f x f block of fine tokens is slot-merged into one token,
5
+ the transformer runs on 1/k as many tokens, and the result is slot-unmerged
6
+ back to the fine token grid. Inputs and targets stay at full resolution in
7
+ every stage; only the internal processing resolution changes.
8
+
9
+ coarse_mode="lowres" instead implements classic progressive resizing: the
10
+ fields are area-averaged to a coarser grid and the model is trained on that
11
+ coarser problem (the fine-scale data is simply not seen in that stage).
12
+ """
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+
17
+ from ..zoom import SlotMerge, SlotUnmerge
18
+
19
+
20
+ class Block(nn.Module):
21
+ def __init__(self, d, n_head, mlp_mult=4):
22
+ super().__init__()
23
+ self.n_head = n_head
24
+ self.ln1 = nn.LayerNorm(d)
25
+ self.qkv = nn.Linear(d, 3 * d)
26
+ self.qkv.weight.muon_split = 3
27
+ self.proj = nn.Linear(d, d)
28
+ self.ln2 = nn.LayerNorm(d)
29
+ self.fc = nn.Linear(d, mlp_mult * d)
30
+ self.fc_out = nn.Linear(mlp_mult * d, d)
31
+
32
+ def forward(self, x):
33
+ B, N, D = x.shape
34
+ q, k, v = self.qkv(self.ln1(x)).view(B, N, 3, self.n_head, -1).permute(2, 0, 3, 1, 4)
35
+ y = F.scaled_dot_product_attention(q, k, v)
36
+ x = x + self.proj(y.transpose(1, 2).reshape(B, N, D))
37
+ return x + self.fc_out(F.gelu(self.fc(self.ln2(x))))
38
+
39
+
40
+ class ZoomViT(nn.Module):
41
+ def __init__(self, c_in, c_out, grid=(32, 64), patch=2, d=128, n_layer=6, n_head=4,
42
+ zoom_ks=(), gated=True, merge_mode=None):
43
+ super().__init__()
44
+ self.c_in, self.c_out, self.patch, self.d, self.n_layer = c_in, c_out, patch, d, n_layer
45
+ self.gh, self.gw = grid[0] // patch, grid[1] // patch # fine token grid
46
+ self.embed = nn.Linear(c_in * patch * patch, d)
47
+ self.pos = nn.Parameter(torch.randn(1, self.gh, self.gw, d) * 0.02)
48
+ self.blocks = nn.ModuleList(Block(d, n_head) for _ in range(n_layer))
49
+ self.ln_f = nn.LayerNorm(d)
50
+ self.decode = nn.Linear(d, c_out * patch * patch)
51
+ nn.init.zeros_(self.decode.weight)
52
+ nn.init.zeros_(self.decode.bias)
53
+ self.merge = nn.ModuleDict({str(k): SlotMerge(k, d, gated, merge_mode) for k in zoom_ks})
54
+ self.unmerge = nn.ModuleDict({str(k): SlotUnmerge(k, d, gated, merge_mode) for k in zoom_ks})
55
+
56
+ def muon_params(self):
57
+ return [p for b in self.blocks for p in
58
+ (b.qkv.weight, b.proj.weight, b.fc.weight, b.fc_out.weight)]
59
+
60
+ # -- (B, C, H, W) <-> (B, H/p, W/p, C*p*p)
61
+ def patchify(self, x):
62
+ B, C, H, W = x.shape
63
+ p = self.patch
64
+ x = x.view(B, C, H // p, p, W // p, p).permute(0, 2, 4, 1, 3, 5)
65
+ return x.reshape(B, H // p, W // p, C * p * p)
66
+
67
+ def unpatchify(self, t, C):
68
+ B, h, w, _ = t.shape
69
+ p = self.patch
70
+ t = t.view(B, h, w, C, p, p).permute(0, 3, 1, 4, 2, 5)
71
+ return t.reshape(B, C, h * p, w * p)
72
+
73
+ @staticmethod
74
+ def _group(t, f): # (B, h, w, d) -> (B, h/f * w/f, f*f, d)
75
+ B, h, w, d = t.shape
76
+ t = t.view(B, h // f, f, w // f, f, d).permute(0, 1, 3, 2, 4, 5)
77
+ return t.reshape(B, (h // f) * (w // f), f * f, d)
78
+
79
+ @staticmethod
80
+ def _ungroup(t, h, w, f): # (B, h/f * w/f, f*f, d) -> (B, h, w, d)
81
+ B, _, _, d = t.shape
82
+ t = t.view(B, h // f, w // f, f, f, d).permute(0, 1, 3, 2, 4, 5)
83
+ return t.reshape(B, h, w, d)
84
+
85
+ def forward(self, x, k=1):
86
+ """x: (B, c_in, H, W) at full resolution -> (B, c_out, H, W)."""
87
+ tok = self.embed(self.patchify(x)) + self.pos # (B, gh, gw, d)
88
+ B, h, w, d = tok.shape
89
+ if k > 1:
90
+ f = int(round(k ** 0.5))
91
+ z = self.merge[str(k)](self._group(tok, f)) # (B, N/k, d)
92
+ else:
93
+ z = tok.view(B, h * w, d)
94
+ for blk in self.blocks:
95
+ z = blk(z)
96
+ z = self.ln_f(z)
97
+ if k > 1:
98
+ z = self._ungroup(self.unmerge[str(k)](z), h, w, f) # (B, gh, gw, d)
99
+ else:
100
+ z = z.view(B, h, w, d)
101
+ return self.unpatchify(self.decode(z), self.c_out)
102
+
103
+ def forward_lowres(self, x_coarse, f):
104
+ """Progressive-resizing stage: whole problem on an f-times coarser grid."""
105
+ pos = F.avg_pool2d(self.pos.permute(0, 3, 1, 2), f).permute(0, 2, 3, 1)
106
+ tok = self.embed(self.patchify(x_coarse)) + pos
107
+ B, h, w, d = tok.shape
108
+ z = tok.view(B, h * w, d)
109
+ for blk in self.blocks:
110
+ z = blk(z)
111
+ z = self.ln_f(z).view(B, h, w, d)
112
+ return self.unpatchify(self.decode(z), self.c_out)
113
+
114
+ def flops_per_step(self, batch, k):
115
+ n = self.gh * self.gw // k # tokens through the body
116
+ d, L = self.d, self.n_layer
117
+ body = n * L * (24 * d * d + 4 * n * d) # full (non-causal) attention
118
+ io = self.gh * self.gw * 2 * d * self.patch ** 2 * (self.c_in + self.c_out)
119
+ return 3 * batch * (body + io)