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/__init__.py +12 -0
- bantamtrain/data/__init__.py +1 -0
- bantamtrain/data/dedup.py +149 -0
- bantamtrain/data/gridpack.py +124 -0
- bantamtrain/data/tokpack.py +220 -0
- bantamtrain/device.py +179 -0
- bantamtrain/lowmem.py +127 -0
- bantamtrain/memory.py +170 -0
- bantamtrain/models/__init__.py +2 -0
- bantamtrain/models/gpt.py +177 -0
- bantamtrain/models/vit_weather.py +119 -0
- bantamtrain/optim.py +221 -0
- bantamtrain/qweights.py +130 -0
- bantamtrain/weightpack.py +154 -0
- bantamtrain/zoom.py +145 -0
- bantamtrain-0.1.0.dist-info/METADATA +107 -0
- bantamtrain-0.1.0.dist-info/RECORD +20 -0
- bantamtrain-0.1.0.dist-info/WHEEL +5 -0
- bantamtrain-0.1.0.dist-info/licenses/LICENSE +21 -0
- bantamtrain-0.1.0.dist-info/top_level.txt +1 -0
bantamtrain/optim.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Optimizers: Muon for hidden weight matrices, AdamW for everything else.
|
|
2
|
+
|
|
3
|
+
Muon (Jordan et al., 2024) replaces each 2-D weight update with the nearest
|
|
4
|
+
semi-orthogonal matrix of its momentum, computed by a few Newton-Schulz
|
|
5
|
+
iterations. It is all matmuls, so it runs the same on CPU and GPU, and it
|
|
6
|
+
needs no second-moment state (half of AdamW's optimizer memory for those
|
|
7
|
+
weights).
|
|
8
|
+
|
|
9
|
+
Update scaling follows Moonlight (Liu et al., 2025): scale = 0.2*sqrt(max(m, n))
|
|
10
|
+
makes the update RMS match AdamW's, so Muon and AdamW share one learning rate
|
|
11
|
+
and one weight decay. scale="jordan" uses the original max(1, m/n)**0.5.
|
|
12
|
+
|
|
13
|
+
Low-memory options (see bantamtrain.lowmem):
|
|
14
|
+
state_bits=8 blockwise 8-bit momentum / Adam moments (4x less state memory)
|
|
15
|
+
bf16 params updates are computed in fp32 and written back with
|
|
16
|
+
stochastic rounding, so no fp32 master copy is needed
|
|
17
|
+
"""
|
|
18
|
+
import math
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
from torch.optim import Optimizer
|
|
22
|
+
|
|
23
|
+
from .lowmem import QState, write_param
|
|
24
|
+
|
|
25
|
+
NS_COEFFS = (3.4445, -4.7750, 2.0315)
|
|
26
|
+
# Polar Express (Amsel et al., 2025): per-step minimax coefficients, same matmul
|
|
27
|
+
# cost as the quintic iteration; a, b, c of every tuple but the last are divided
|
|
28
|
+
# by 1.01, 1.01^3, 1.01^5 for safety, and the input is normalized with a 1.01 margin.
|
|
29
|
+
_PE = [(8.28721201814563, -23.595886519098837, 17.300387312530933),
|
|
30
|
+
(4.107059111542203, -2.9478499167379106, 0.5448431082926601),
|
|
31
|
+
(3.9486908534822946, -2.908902115962949, 0.5518191394370137),
|
|
32
|
+
(3.3184196573706015, -2.488488024314874, 0.51004894012372),
|
|
33
|
+
(2.300652019954817, -1.6689039845747493, 0.4188073119525673)]
|
|
34
|
+
POLAR_COEFFS = [(a / 1.01, b / 1.01 ** 3, c / 1.01 ** 5) for a, b, c in _PE[:-1]] + [_PE[-1]]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@torch.no_grad()
|
|
38
|
+
def newton_schulz(G, steps=5, eps=1e-7, variant="quintic"):
|
|
39
|
+
"""Approximate U V^T of G = U S V^T (batched over leading dims)."""
|
|
40
|
+
X = G.to(torch.bfloat16 if G.is_cuda else torch.float32)
|
|
41
|
+
transpose = X.size(-2) > X.size(-1)
|
|
42
|
+
if transpose:
|
|
43
|
+
X = X.mT
|
|
44
|
+
if variant == "polar":
|
|
45
|
+
coeffs = (POLAR_COEFFS + [POLAR_COEFFS[-1]] * steps)[:steps]
|
|
46
|
+
X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.01 + eps)
|
|
47
|
+
else:
|
|
48
|
+
coeffs = [NS_COEFFS] * steps
|
|
49
|
+
X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
|
|
50
|
+
for a, b, c in coeffs:
|
|
51
|
+
A = X @ X.mT
|
|
52
|
+
B = b * A + c * (A @ A)
|
|
53
|
+
X = a * X + B @ X
|
|
54
|
+
if transpose:
|
|
55
|
+
X = X.mT
|
|
56
|
+
return X.to(G.dtype)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Muon(Optimizer):
|
|
60
|
+
"""Muon for 2-D parameters.
|
|
61
|
+
|
|
62
|
+
A parameter may carry `p.muon_split = s` to be orthogonalized as s
|
|
63
|
+
independent row blocks (e.g. a fused qkv projection as q, k and v).
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, params, lr=1e-3, momentum=0.95, nesterov=True, ns_steps=5,
|
|
67
|
+
weight_decay=0.0, scale="moonlight", state_bits=32, stochastic=True,
|
|
68
|
+
ns="quintic"):
|
|
69
|
+
assert scale in ("moonlight", "jordan") and state_bits in (32, 8)
|
|
70
|
+
assert ns in ("quintic", "polar")
|
|
71
|
+
defaults = dict(lr=lr, momentum=momentum, nesterov=nesterov, ns_steps=ns_steps,
|
|
72
|
+
weight_decay=weight_decay, scale=scale, state_bits=state_bits,
|
|
73
|
+
stochastic=stochastic, ns=ns)
|
|
74
|
+
super().__init__(params, defaults)
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def _scale(m, n, mode):
|
|
78
|
+
if mode == "moonlight":
|
|
79
|
+
return 0.2 * math.sqrt(max(m, n))
|
|
80
|
+
return max(1.0, m / n) ** 0.5
|
|
81
|
+
|
|
82
|
+
@torch.no_grad()
|
|
83
|
+
def step(self, closure=None):
|
|
84
|
+
loss = closure() if closure is not None else None
|
|
85
|
+
for group in self.param_groups:
|
|
86
|
+
for p in group["params"]:
|
|
87
|
+
if p.grad is None:
|
|
88
|
+
continue
|
|
89
|
+
g = p.grad.float()
|
|
90
|
+
state = self.state[p]
|
|
91
|
+
if "buf" not in state:
|
|
92
|
+
state["buf"] = (QState(p, "signed") if group["state_bits"] == 8
|
|
93
|
+
else torch.zeros_like(p, dtype=torch.float32))
|
|
94
|
+
q = isinstance(state["buf"], QState)
|
|
95
|
+
buf = state["buf"].get() if q else state["buf"]
|
|
96
|
+
buf.lerp_(g, 1 - group["momentum"])
|
|
97
|
+
if q:
|
|
98
|
+
state["buf"].set(buf)
|
|
99
|
+
g = g.lerp(buf, group["momentum"]) if group["nesterov"] else buf
|
|
100
|
+
split = getattr(p, "muon_split", 1)
|
|
101
|
+
rows, cols = g.shape[0] // split, g.shape[1]
|
|
102
|
+
u = newton_schulz(g.reshape(split, rows, cols), group["ns_steps"],
|
|
103
|
+
variant=group["ns"])
|
|
104
|
+
u = u.reshape(p.shape) * self._scale(rows, cols, group["scale"])
|
|
105
|
+
new = p.float() * (1 - group["lr"] * group["weight_decay"]) - group["lr"] * u
|
|
106
|
+
write_param(p, new, group["stochastic"])
|
|
107
|
+
return loss
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AdamWLowMem(Optimizer):
|
|
111
|
+
"""AdamW with optional 8-bit moments and bf16 parameters (stochastic rounding).
|
|
112
|
+
|
|
113
|
+
Same update as torch.optim.AdamW (decoupled weight decay, bias correction).
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, params, lr=1e-3, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.0,
|
|
117
|
+
state_bits=8, stochastic=True):
|
|
118
|
+
assert state_bits in (32, 8)
|
|
119
|
+
super().__init__(params, dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay,
|
|
120
|
+
state_bits=state_bits, stochastic=stochastic))
|
|
121
|
+
|
|
122
|
+
@torch.no_grad()
|
|
123
|
+
def step(self, closure=None):
|
|
124
|
+
loss = closure() if closure is not None else None
|
|
125
|
+
for group in self.param_groups:
|
|
126
|
+
b1, b2 = group["betas"]
|
|
127
|
+
for p in group["params"]:
|
|
128
|
+
if p.grad is None:
|
|
129
|
+
continue
|
|
130
|
+
g = p.grad.float()
|
|
131
|
+
st = self.state[p]
|
|
132
|
+
if "step" not in st:
|
|
133
|
+
st["step"] = 0
|
|
134
|
+
if group["state_bits"] == 8:
|
|
135
|
+
st["m"], st["v"] = QState(p, "signed"), QState(p, "log")
|
|
136
|
+
else:
|
|
137
|
+
st["m"] = torch.zeros_like(p, dtype=torch.float32)
|
|
138
|
+
st["v"] = torch.zeros_like(p, dtype=torch.float32)
|
|
139
|
+
st["step"] += 1
|
|
140
|
+
q = isinstance(st["m"], QState)
|
|
141
|
+
m = st["m"].get() if q else st["m"]
|
|
142
|
+
v = st["v"].get() if q else st["v"]
|
|
143
|
+
m.lerp_(g, 1 - b1)
|
|
144
|
+
v.mul_(b2).addcmul_(g, g, value=1 - b2)
|
|
145
|
+
if q:
|
|
146
|
+
st["m"].set(m)
|
|
147
|
+
st["v"].set(v)
|
|
148
|
+
t = st["step"]
|
|
149
|
+
mhat = m / (1 - b1 ** t)
|
|
150
|
+
vhat = v / (1 - b2 ** t)
|
|
151
|
+
new = p.float() * (1 - group["lr"] * group["weight_decay"]) \
|
|
152
|
+
- group["lr"] * mhat / (vhat.sqrt() + group["eps"])
|
|
153
|
+
write_param(p, new, group["stochastic"])
|
|
154
|
+
return loss
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class CombinedOptimizer:
|
|
158
|
+
"""Steps several optimizers as one; exposes the union of their param groups."""
|
|
159
|
+
|
|
160
|
+
def __init__(self, optimizers):
|
|
161
|
+
self.optimizers = [o for o in optimizers if o is not None]
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def param_groups(self):
|
|
165
|
+
return [g for o in self.optimizers for g in o.param_groups]
|
|
166
|
+
|
|
167
|
+
def zero_grad(self, set_to_none=True):
|
|
168
|
+
for o in self.optimizers:
|
|
169
|
+
o.zero_grad(set_to_none=set_to_none)
|
|
170
|
+
|
|
171
|
+
def step(self):
|
|
172
|
+
for o in self.optimizers:
|
|
173
|
+
o.step()
|
|
174
|
+
|
|
175
|
+
def state_dict(self):
|
|
176
|
+
return [o.state_dict() for o in self.optimizers]
|
|
177
|
+
|
|
178
|
+
def load_state_dict(self, states):
|
|
179
|
+
for o, s in zip(self.optimizers, states):
|
|
180
|
+
o.load_state_dict(s)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def build_optimizer(model, name, lr, weight_decay, betas=(0.9, 0.95), fused=None,
|
|
184
|
+
state_bits=32, ns="quintic"):
|
|
185
|
+
"""name: 'adamw' or 'muon'.
|
|
186
|
+
|
|
187
|
+
Muon takes the 2-D weights the model lists in `model.muon_params()`
|
|
188
|
+
(hidden matrices inside the blocks). Embeddings, output head, norms, gates
|
|
189
|
+
and biases stay on AdamW, as recommended for Muon.
|
|
190
|
+
|
|
191
|
+
state_bits=8, or bf16 parameters, switch AdamW to AdamWLowMem (8-bit
|
|
192
|
+
moments / stochastic-rounding writes); otherwise torch's fused AdamW is used.
|
|
193
|
+
"""
|
|
194
|
+
muon_ids = set()
|
|
195
|
+
if name == "muon":
|
|
196
|
+
muon_ids = {id(p) for p in model.muon_params()}
|
|
197
|
+
muon_p, decay, no_decay = [], [], []
|
|
198
|
+
for n, p in model.named_parameters():
|
|
199
|
+
if not p.requires_grad:
|
|
200
|
+
continue
|
|
201
|
+
if id(p) in muon_ids:
|
|
202
|
+
muon_p.append(p)
|
|
203
|
+
elif p.dim() >= 2 and "gate" not in n and ".merge." not in n and ".unmerge." not in n:
|
|
204
|
+
decay.append(p)
|
|
205
|
+
else:
|
|
206
|
+
no_decay.append(p)
|
|
207
|
+
groups = [{"params": decay, "weight_decay": weight_decay},
|
|
208
|
+
{"params": no_decay, "weight_decay": 0.0}]
|
|
209
|
+
bf16_params = next(model.parameters()).dtype == torch.bfloat16
|
|
210
|
+
if state_bits == 8 or bf16_params:
|
|
211
|
+
adamw = AdamWLowMem(groups, lr=lr, betas=betas, eps=1e-8, state_bits=state_bits)
|
|
212
|
+
else:
|
|
213
|
+
kw = {}
|
|
214
|
+
if fused is None:
|
|
215
|
+
fused = next(model.parameters()).is_cuda
|
|
216
|
+
if fused:
|
|
217
|
+
kw["fused"] = True
|
|
218
|
+
adamw = torch.optim.AdamW(groups, lr=lr, betas=betas, eps=1e-8, **kw)
|
|
219
|
+
muon = (Muon(muon_p, lr=lr, weight_decay=weight_decay, state_bits=state_bits, ns=ns)
|
|
220
|
+
if muon_p else None)
|
|
221
|
+
return CombinedOptimizer([adamw, muon])
|
bantamtrain/qweights.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Weight-only quantized layers: keep weights in int8 / int4 in RAM, compute in float.
|
|
2
|
+
|
|
3
|
+
from bantamtrain.qweights import quantize_model
|
|
4
|
+
report = quantize_model(model, bits=4, block=64) # in place
|
|
5
|
+
print(report) # bytes before / after
|
|
6
|
+
|
|
7
|
+
Each weight matrix is split into blocks of `block` consecutive input columns;
|
|
8
|
+
every block stores one fp16 scale (absmax / qmax) and int codes:
|
|
9
|
+
|
|
10
|
+
bits=8: int8 in [-127, 127] ~1.03 B/param (block 128)
|
|
11
|
+
bits=4: int4 in [-7, 7], two codes per byte ~0.53 B/param (block 64)
|
|
12
|
+
|
|
13
|
+
The forward pass dequantizes the block-scaled codes to the activation dtype
|
|
14
|
+
and runs a normal matmul, so the model's output is that of a model whose
|
|
15
|
+
weights were rounded once; nothing else changes. Embeddings (including a
|
|
16
|
+
tied output head) are quantized the same way, row by row. Norm gains and
|
|
17
|
+
biases stay in float (they are a rounding error of the parameter count).
|
|
18
|
+
Quality is measured, not assumed: see experiments/weights_eval.py.
|
|
19
|
+
"""
|
|
20
|
+
import torch
|
|
21
|
+
import torch.nn as nn
|
|
22
|
+
import torch.nn.functional as F
|
|
23
|
+
|
|
24
|
+
QMAX = {8: 127, 4: 7}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def quantize_rows(w, bits, block):
|
|
28
|
+
"""(R, C) float -> (codes uint8/int8, fp16 scales (R, C/block), pad)."""
|
|
29
|
+
w = w.detach().float()
|
|
30
|
+
R, C = w.shape
|
|
31
|
+
pad = (-C) % block
|
|
32
|
+
if pad:
|
|
33
|
+
w = F.pad(w, (0, pad))
|
|
34
|
+
b = w.view(R, -1, block)
|
|
35
|
+
s = (b.abs().amax(dim=2) / QMAX[bits]).clamp_min(1e-12)
|
|
36
|
+
q = torch.round(b / s[..., None]).clamp_(-QMAX[bits], QMAX[bits]).to(torch.int8)
|
|
37
|
+
if bits == 4:
|
|
38
|
+
u = (q + 8).to(torch.uint8).view(R, -1) # 1..15, 0 unused
|
|
39
|
+
q = (u[:, 0::2] | (u[:, 1::2] << 4)).contiguous() # two codes per byte
|
|
40
|
+
return q, s.to(torch.float16), pad
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def dequantize_rows(q, s, pad, bits, block, dtype=torch.float32):
|
|
44
|
+
R = q.shape[0]
|
|
45
|
+
if bits == 4:
|
|
46
|
+
lo = (q & 0x0F).to(torch.int8) - 8
|
|
47
|
+
hi = (q >> 4).to(torch.int8) - 8
|
|
48
|
+
q = torch.stack([lo, hi], dim=-1).view(R, -1)
|
|
49
|
+
w = q.view(R, -1, block).to(dtype) * s.to(dtype)[..., None]
|
|
50
|
+
w = w.view(R, -1)
|
|
51
|
+
return w[:, :w.shape[1] - pad] if pad else w
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class QLinear(nn.Module):
|
|
55
|
+
def __init__(self, linear, bits=8, block=128):
|
|
56
|
+
super().__init__()
|
|
57
|
+
block = min(block, linear.in_features) # no padding waste on narrow rows
|
|
58
|
+
self.bits, self.block = bits, block
|
|
59
|
+
self.in_features, self.out_features = linear.in_features, linear.out_features
|
|
60
|
+
q, s, self.pad = quantize_rows(linear.weight, bits, block)
|
|
61
|
+
self.register_buffer("q", q)
|
|
62
|
+
self.register_buffer("s", s)
|
|
63
|
+
self.bias = None if linear.bias is None else nn.Parameter(linear.bias.detach().clone(),
|
|
64
|
+
requires_grad=False)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def weight(self):
|
|
68
|
+
return dequantize_rows(self.q, self.s, self.pad, self.bits, self.block)
|
|
69
|
+
|
|
70
|
+
def forward(self, x):
|
|
71
|
+
w = dequantize_rows(self.q, self.s, self.pad, self.bits, self.block, x.dtype)
|
|
72
|
+
return F.linear(x, w, None if self.bias is None else self.bias.to(x.dtype))
|
|
73
|
+
|
|
74
|
+
def nbytes(self):
|
|
75
|
+
n = self.q.numel() * self.q.element_size() + self.s.numel() * 2
|
|
76
|
+
return n + (0 if self.bias is None else self.bias.numel() * 4)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class QEmbedding(nn.Module):
|
|
80
|
+
"""Quantized embedding table; `.weight` dequantizes (for a tied output head)."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, emb, bits=8, block=128):
|
|
83
|
+
super().__init__()
|
|
84
|
+
block = min(block, emb.weight.shape[1])
|
|
85
|
+
self.bits, self.block = bits, block
|
|
86
|
+
self.num_embeddings, self.embedding_dim = emb.weight.shape
|
|
87
|
+
q, s, self.pad = quantize_rows(emb.weight, bits, block)
|
|
88
|
+
self.register_buffer("q", q)
|
|
89
|
+
self.register_buffer("s", s)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def weight(self):
|
|
93
|
+
return dequantize_rows(self.q, self.s, self.pad, self.bits, self.block)
|
|
94
|
+
|
|
95
|
+
def forward(self, idx):
|
|
96
|
+
return F.embedding(idx, self.weight)
|
|
97
|
+
|
|
98
|
+
def nbytes(self):
|
|
99
|
+
return self.q.numel() * self.q.element_size() + self.s.numel() * 2
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def model_bytes(model):
|
|
103
|
+
"""Bytes held by parameters, buffers and quantized codes (no double counting)."""
|
|
104
|
+
seen, total = set(), 0
|
|
105
|
+
for t in list(model.parameters()) + list(model.buffers()):
|
|
106
|
+
if id(t) in seen:
|
|
107
|
+
continue
|
|
108
|
+
seen.add(id(t))
|
|
109
|
+
total += t.numel() * t.element_size()
|
|
110
|
+
return total
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@torch.no_grad()
|
|
114
|
+
def quantize_model(model, bits=8, block=None, min_numel=4096):
|
|
115
|
+
"""Replace every nn.Linear / nn.Embedding with >= min_numel weights, in place."""
|
|
116
|
+
assert bits in (8, 4)
|
|
117
|
+
block = block or (128 if bits == 8 else 64)
|
|
118
|
+
before = model_bytes(model)
|
|
119
|
+
n_q = 0
|
|
120
|
+
for name, mod in list(model.named_modules()):
|
|
121
|
+
for cname, child in list(mod.named_children()):
|
|
122
|
+
if isinstance(child, nn.Linear) and child.weight.numel() >= min_numel:
|
|
123
|
+
setattr(mod, cname, QLinear(child, bits, block))
|
|
124
|
+
n_q += 1
|
|
125
|
+
elif isinstance(child, nn.Embedding) and child.weight.numel() >= min_numel:
|
|
126
|
+
setattr(mod, cname, QEmbedding(child, bits, block))
|
|
127
|
+
n_q += 1
|
|
128
|
+
after = model_bytes(model)
|
|
129
|
+
return {"bits": bits, "block": block, "modules_quantized": n_q,
|
|
130
|
+
"bytes_before": before, "bytes_after": after, "ratio": before / after}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""WeightPack: compact model checkpoints.
|
|
2
|
+
|
|
3
|
+
save(path, state_dict, bits=8) # 8: blockwise int8 matrices, 16: bf16, 32: fp32
|
|
4
|
+
state_dict = load(path) # fp32 tensors, ready for load_state_dict
|
|
5
|
+
|
|
6
|
+
bits=8 quantizes every floating tensor with >= 2 dims and >= 4096 elements
|
|
7
|
+
(weight matrices, embeddings) with blockwise absmax int8 along the last axis
|
|
8
|
+
(block = 256 columns, one fp16 scale per block, 0.8 % overhead); bits=4 uses
|
|
9
|
+
packed int4 codes with block 64 (bantamtrain.qweights), ~0.53 B/param; vectors
|
|
10
|
+
(norm gains, biases, merge gates) are kept exactly in fp32 because they are
|
|
11
|
+
tiny and sensitive. Everything is then byte-shuffled and zstd-compressed.
|
|
12
|
+
|
|
13
|
+
Sizes per matrix element: fp32 4 B, bf16 2 B, int8 ~1.03 B before zstd.
|
|
14
|
+
Quality is measured, not assumed: `roundtrip_delta()` reports the change in a
|
|
15
|
+
model's validation loss after save -> load.
|
|
16
|
+
"""
|
|
17
|
+
import io
|
|
18
|
+
import json
|
|
19
|
+
import struct
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import torch
|
|
23
|
+
import zstandard as zstd
|
|
24
|
+
|
|
25
|
+
from .qweights import dequantize_rows, quantize_rows
|
|
26
|
+
|
|
27
|
+
MAGIC = b"ZWPK1\0"
|
|
28
|
+
BLOCK = 256
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _q8(t):
|
|
32
|
+
x = t.float().reshape(-1, t.shape[-1])
|
|
33
|
+
pad = (-x.shape[1]) % BLOCK
|
|
34
|
+
if pad:
|
|
35
|
+
x = torch.nn.functional.pad(x, (0, pad))
|
|
36
|
+
b = x.view(x.shape[0], -1, BLOCK)
|
|
37
|
+
s = b.abs().amax(dim=2).clamp_min(1e-30)
|
|
38
|
+
q = torch.round(b / s[..., None] * 127).to(torch.int8)
|
|
39
|
+
return q.numpy(), s.to(torch.float16).numpy(), pad
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _dq8(q, s, pad, shape):
|
|
43
|
+
x = torch.from_numpy(q.copy()).float() / 127 * torch.from_numpy(s.copy()).float()[..., None]
|
|
44
|
+
x = x.reshape(x.shape[0], -1)
|
|
45
|
+
if pad:
|
|
46
|
+
x = x[:, :-pad]
|
|
47
|
+
return x.reshape(shape)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def save(path, state_dict, bits=8, level=10):
|
|
51
|
+
assert bits in (4, 8, 16, 32)
|
|
52
|
+
meta, blobs = [], []
|
|
53
|
+
for name, t in state_dict.items():
|
|
54
|
+
t = t.detach().cpu()
|
|
55
|
+
entry = {"name": name, "shape": list(t.shape), "dtype": str(t.dtype).split(".")[-1]}
|
|
56
|
+
if t.is_floating_point() and bits == 4 and t.dim() >= 2 and t.numel() >= 4096:
|
|
57
|
+
q, sc, pad = quantize_rows(t.reshape(-1, t.shape[-1]), 4, 64)
|
|
58
|
+
entry.update(enc="int4", pad=pad, q_shape=list(q.shape), scale_shape=list(sc.shape))
|
|
59
|
+
blobs += [q.numpy().tobytes(), sc.numpy().tobytes()]
|
|
60
|
+
entry["sizes"] = [len(blobs[-2]), len(blobs[-1])]
|
|
61
|
+
elif t.is_floating_point() and bits == 8 and t.dim() >= 2 and t.numel() >= 4096:
|
|
62
|
+
q, s, pad = _q8(t)
|
|
63
|
+
entry.update(enc="int8", pad=pad, scale_shape=list(s.shape))
|
|
64
|
+
blobs += [q.tobytes(), s.tobytes()]
|
|
65
|
+
entry["sizes"] = [len(blobs[-2]), len(blobs[-1])]
|
|
66
|
+
elif t.is_floating_point() and bits <= 16:
|
|
67
|
+
a = t.to(torch.bfloat16).view(torch.int16).numpy()
|
|
68
|
+
entry["enc"] = "bf16"
|
|
69
|
+
blobs.append(a.tobytes())
|
|
70
|
+
entry["sizes"] = [len(blobs[-1])]
|
|
71
|
+
else:
|
|
72
|
+
a = t.contiguous().numpy() if t.is_floating_point() else t.numpy()
|
|
73
|
+
entry["enc"] = "raw"
|
|
74
|
+
blobs.append(a.tobytes())
|
|
75
|
+
entry["sizes"] = [len(blobs[-1])]
|
|
76
|
+
meta.append(entry)
|
|
77
|
+
raw = b"".join(blobs)
|
|
78
|
+
# byte-shuffle (2-byte stride helps bf16/fp16 scales; int8 codes are unaffected)
|
|
79
|
+
arr = np.frombuffer(raw, dtype=np.uint8)
|
|
80
|
+
if len(arr) % 2:
|
|
81
|
+
arr = np.concatenate([arr, np.zeros(1, np.uint8)])
|
|
82
|
+
shuffled = np.ascontiguousarray(arr.reshape(-1, 2).T).tobytes()
|
|
83
|
+
payload = zstd.ZstdCompressor(level=level).compress(shuffled)
|
|
84
|
+
header = json.dumps({"bits": bits, "tensors": meta, "raw_len": len(raw)}).encode()
|
|
85
|
+
with open(path, "wb") as f:
|
|
86
|
+
f.write(MAGIC)
|
|
87
|
+
f.write(struct.pack("<I", len(header)))
|
|
88
|
+
f.write(header)
|
|
89
|
+
f.write(payload)
|
|
90
|
+
return len(payload) + len(header) + 10
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def load(path):
|
|
94
|
+
with open(path, "rb") as f:
|
|
95
|
+
assert f.read(6) == MAGIC, "not a WeightPack file"
|
|
96
|
+
hlen = struct.unpack("<I", f.read(4))[0]
|
|
97
|
+
h = json.loads(f.read(hlen))
|
|
98
|
+
payload = f.read()
|
|
99
|
+
shuffled = np.frombuffer(zstd.ZstdDecompressor().decompress(payload), dtype=np.uint8)
|
|
100
|
+
raw = np.ascontiguousarray(shuffled.reshape(2, -1).T).tobytes()[:h["raw_len"]]
|
|
101
|
+
out, pos = {}, 0
|
|
102
|
+
for e in h["tensors"]:
|
|
103
|
+
shape = tuple(e["shape"])
|
|
104
|
+
if e["enc"] == "int4":
|
|
105
|
+
n_q, n_s = e["sizes"]
|
|
106
|
+
q = torch.from_numpy(np.frombuffer(raw[pos:pos + n_q], dtype=np.uint8).copy())
|
|
107
|
+
sc = torch.from_numpy(np.frombuffer(raw[pos + n_q:pos + n_q + n_s],
|
|
108
|
+
dtype=np.float16).copy())
|
|
109
|
+
pos += n_q + n_s
|
|
110
|
+
w = dequantize_rows(q.view(e["q_shape"]), sc.view(e["scale_shape"]), e["pad"], 4, 64)
|
|
111
|
+
out[e["name"]] = w.reshape(shape)
|
|
112
|
+
elif e["enc"] == "int8":
|
|
113
|
+
n_q, n_s = e["sizes"]
|
|
114
|
+
q = np.frombuffer(raw[pos:pos + n_q], dtype=np.int8)
|
|
115
|
+
s = np.frombuffer(raw[pos + n_q:pos + n_q + n_s], dtype=np.float16)
|
|
116
|
+
pos += n_q + n_s
|
|
117
|
+
rows = int(np.prod(shape[:-1]))
|
|
118
|
+
q = q.reshape(rows, -1, BLOCK)
|
|
119
|
+
s = s.reshape(e["scale_shape"])
|
|
120
|
+
out[e["name"]] = _dq8(q, s, e["pad"], shape)
|
|
121
|
+
elif e["enc"] == "bf16":
|
|
122
|
+
n = e["sizes"][0]
|
|
123
|
+
a = np.frombuffer(raw[pos:pos + n], dtype=np.int16).copy()
|
|
124
|
+
pos += n
|
|
125
|
+
out[e["name"]] = torch.from_numpy(a).view(torch.bfloat16).float().reshape(shape)
|
|
126
|
+
else:
|
|
127
|
+
n = e["sizes"][0]
|
|
128
|
+
dt = getattr(torch, e["dtype"])
|
|
129
|
+
a = np.frombuffer(raw[pos:pos + n], dtype=np.dtype(str(dt).split(".")[-1]
|
|
130
|
+
.replace("float", "float")
|
|
131
|
+
if dt.is_floating_point
|
|
132
|
+
else np.int64)).copy()
|
|
133
|
+
pos += n
|
|
134
|
+
out[e["name"]] = torch.from_numpy(a).reshape(shape).to(dt)
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@torch.no_grad()
|
|
139
|
+
def roundtrip_delta(model, eval_fn, path, bits=8):
|
|
140
|
+
"""Save -> load -> reload into a copy of the model; return (loss_before, loss_after, bytes)."""
|
|
141
|
+
before = eval_fn(model)
|
|
142
|
+
nbytes = save(path, model.state_dict(), bits)
|
|
143
|
+
sd = load(path)
|
|
144
|
+
backup = {k: v.clone() for k, v in model.state_dict().items()}
|
|
145
|
+
model.load_state_dict({k: v.to(backup[k].dtype) for k, v in sd.items()})
|
|
146
|
+
after = eval_fn(model)
|
|
147
|
+
model.load_state_dict(backup)
|
|
148
|
+
return before, after, nbytes
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def torch_save_bytes(state_dict):
|
|
152
|
+
buf = io.BytesIO()
|
|
153
|
+
torch.save(state_dict, buf)
|
|
154
|
+
return buf.getbuffer().nbytes
|
bantamtrain/zoom.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Zoom Training: coarse-to-fine resolution annealing.
|
|
2
|
+
|
|
3
|
+
The transformer body is the expensive part of training and its cost scales with
|
|
4
|
+
the number of positions it processes. Zoom Training keeps *every* input
|
|
5
|
+
element and *every* target element, but early in training it merges each group
|
|
6
|
+
of K neighbouring elements (K tokens in text, a 2x2 block of patches on a
|
|
7
|
+
weather grid) into one position, runs the body on N/K positions, and unmerges
|
|
8
|
+
the result back to one prediction per original element. Over training K is
|
|
9
|
+
annealed 4 -> 2 -> 1, ending with an ordinary model.
|
|
10
|
+
|
|
11
|
+
Two small modules make the merge reversible enough to transfer:
|
|
12
|
+
|
|
13
|
+
* SlotMerge - gated sum: z = sum_j g_j * x_j. Each slot j inside a group has
|
|
14
|
+
its own per-channel gate g_j, so the order/layout of elements
|
|
15
|
+
inside the group survives the merge (a plain mean would not).
|
|
16
|
+
* SlotUnmerge - y_j = h * u_j: one gated copy of the coarse hidden state per
|
|
17
|
+
slot, so each original element gets its own prediction
|
|
18
|
+
instead of a single bag-of-tokens distribution.
|
|
19
|
+
|
|
20
|
+
Both cost K*d parameters per zoom level and are dropped at K=1.
|
|
21
|
+
mode="linear" replaces the per-channel gates with per-slot d x d maps
|
|
22
|
+
(z = sum_j W_j x_j, y_j = U_j h; init W_j = I/K, U_j = I): K*d^2 parameters
|
|
23
|
+
per level, i.e. a learned patch embedding / un-embedding over the slots.
|
|
24
|
+
"""
|
|
25
|
+
import math
|
|
26
|
+
|
|
27
|
+
import torch
|
|
28
|
+
import torch.nn as nn
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SlotMerge(nn.Module):
|
|
32
|
+
"""(B, N*K, d) grouped as (B, N, K, d) -> (B, N, d) by a slot-weighted sum.
|
|
33
|
+
|
|
34
|
+
mode: "gate" (per-slot, per-channel gate; K*d params), "mean" (fixed 1/K),
|
|
35
|
+
"linear" (per-slot d x d map, init I/K; K*d*d params).
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, k, d, gated=True, mode=None):
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.k = k
|
|
41
|
+
self.mode = mode or ("gate" if gated else "mean")
|
|
42
|
+
if self.mode == "linear":
|
|
43
|
+
w = torch.eye(d).unsqueeze(0).repeat(k, 1, 1) / k
|
|
44
|
+
self.weight = nn.Parameter(w)
|
|
45
|
+
else:
|
|
46
|
+
init = torch.full((k, d), 1.0 / k)
|
|
47
|
+
if self.mode == "gate":
|
|
48
|
+
self.gate = nn.Parameter(init)
|
|
49
|
+
else:
|
|
50
|
+
self.register_buffer("gate", init)
|
|
51
|
+
|
|
52
|
+
def forward(self, x): # x: (..., K, d)
|
|
53
|
+
if self.mode == "linear":
|
|
54
|
+
return torch.einsum("...kd,kde->...e", x, self.weight)
|
|
55
|
+
return (x * self.gate).sum(-2)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SlotUnmerge(nn.Module):
|
|
59
|
+
"""(B, N, d) -> (B, N, K, d): one slot-specific copy per slot (gate / linear)."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, k, d, gated=True, mode=None):
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.k = k
|
|
64
|
+
self.mode = mode or ("gate" if gated else "mean")
|
|
65
|
+
if self.mode == "linear":
|
|
66
|
+
self.weight = nn.Parameter(torch.eye(d).unsqueeze(0).repeat(k, 1, 1))
|
|
67
|
+
else:
|
|
68
|
+
init = torch.ones(k, d)
|
|
69
|
+
if self.mode == "gate":
|
|
70
|
+
self.gate = nn.Parameter(init)
|
|
71
|
+
else:
|
|
72
|
+
self.register_buffer("gate", init)
|
|
73
|
+
|
|
74
|
+
def forward(self, h): # h: (..., d)
|
|
75
|
+
if self.mode == "linear":
|
|
76
|
+
return torch.einsum("...d,kde->...ke", h, self.weight)
|
|
77
|
+
return h.unsqueeze(-2) * self.gate
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ZoomSchedule:
|
|
81
|
+
"""Piecewise-constant zoom level as a function of compute spent.
|
|
82
|
+
|
|
83
|
+
stages: list of (k, fraction_of_budget); fractions must sum to 1.
|
|
84
|
+
Example: [(4, .35), (2, .25), (1, .40)].
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, stages):
|
|
88
|
+
total = sum(f for _, f in stages)
|
|
89
|
+
assert abs(total - 1.0) < 1e-6, f"stage fractions sum to {total}"
|
|
90
|
+
self.stages = stages
|
|
91
|
+
|
|
92
|
+
def k_at(self, frac):
|
|
93
|
+
return self.stage_at(frac)[0]
|
|
94
|
+
|
|
95
|
+
def stage_at(self, frac):
|
|
96
|
+
"""(k, stage_start, stage_end) in budget fractions for the stage holding frac."""
|
|
97
|
+
acc = 0.0
|
|
98
|
+
for k, f in self.stages:
|
|
99
|
+
if frac < acc + f - 1e-12:
|
|
100
|
+
return k, acc, acc + f
|
|
101
|
+
acc += f
|
|
102
|
+
k, f = self.stages[-1]
|
|
103
|
+
return k, acc - f, acc
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def ks(self):
|
|
107
|
+
return sorted({k for k, _ in self.stages if k > 1})
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def parse(spec):
|
|
111
|
+
"""'4:0.35,2:0.25,1:0.4' -> ZoomSchedule; '1' -> baseline."""
|
|
112
|
+
if spec in ("1", "baseline", "", None):
|
|
113
|
+
return ZoomSchedule([(1, 1.0)])
|
|
114
|
+
stages = []
|
|
115
|
+
for part in spec.split(","):
|
|
116
|
+
k, f = part.split(":")
|
|
117
|
+
stages.append((int(k), float(f)))
|
|
118
|
+
return ZoomSchedule(stages)
|
|
119
|
+
|
|
120
|
+
def __repr__(self):
|
|
121
|
+
return ",".join(f"{k}:{f:g}" for k, f in self.stages)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def lr_at(frac, peak, warmup=0.05, final=0.1, stage=None, sched="cosine", decay_frac=0.45):
|
|
125
|
+
"""Learning rate at compute fraction `frac`.
|
|
126
|
+
|
|
127
|
+
sched="cosine": linear warmup, cosine decay to final*peak.
|
|
128
|
+
sched="wsd": linear warmup, flat at peak, then linear decay over the last
|
|
129
|
+
`decay_frac` of the budget to final*peak (warmup-stable-decay;
|
|
130
|
+
the NanoGPT-speedrun / budgeted-training choice).
|
|
131
|
+
stage=(start, end): restart the schedule inside that window.
|
|
132
|
+
"""
|
|
133
|
+
if stage is not None:
|
|
134
|
+
start, end = stage
|
|
135
|
+
frac = (frac - start) / max(end - start, 1e-12)
|
|
136
|
+
if frac < warmup:
|
|
137
|
+
return peak * frac / warmup
|
|
138
|
+
if sched == "wsd":
|
|
139
|
+
d0 = 1.0 - decay_frac
|
|
140
|
+
if frac < d0:
|
|
141
|
+
return peak
|
|
142
|
+
p = min(1.0, (frac - d0) / max(1.0 - d0, 1e-12))
|
|
143
|
+
return peak * (1 - (1 - final) * p)
|
|
144
|
+
p = min(1.0, (frac - warmup) / (1 - warmup))
|
|
145
|
+
return peak * (final + (1 - final) * 0.5 * (1 + math.cos(math.pi * p)))
|