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.
@@ -0,0 +1,12 @@
1
+ """bantamtrain (Bantam): train small LLMs and weather models faster on limited compute.
2
+
3
+ Components
4
+ zoom - Zoom Training (coarse-to-fine resolution annealing), schedules
5
+ optim - Muon + AdamW
6
+ device - CPU/GPU runtime (FTZ, AMP, compile, batch finder, duty limiter)
7
+ models - ZoomGPT (text), ZoomViT (weather grids)
8
+ data - TokPack token store, dedup, GridPack weather store
9
+ """
10
+ from .zoom import SlotMerge, SlotUnmerge, ZoomSchedule, lr_at # noqa: F401
11
+
12
+ __version__ = "0.1.0"
@@ -0,0 +1 @@
1
+ """Data layer: compact storage and deduplication."""
@@ -0,0 +1,149 @@
1
+ """Exact + near-duplicate detection on a pre-tokenized corpus.
2
+
3
+ Works directly on the uint16 token stream (documents separated by EOS), fully
4
+ vectorized with numpy: no per-document Python loops in the hot path.
5
+
6
+ * exact: 64-bit hash of each document's token sequence.
7
+ * near: MinHash over token n-gram shingles + LSH banding (b bands x r rows).
8
+ Candidate pairs from a shared bucket are confirmed when their
9
+ estimated Jaccard similarity >= threshold; duplicates are clustered
10
+ with union-find and one document per cluster is kept.
11
+
12
+ Duplicates are redundant compute when data is plentiful (one copy carries the
13
+ same information) and are known to hurt generalization/memorization
14
+ (Lee et al., 2021, "Deduplicating Training Data Makes Language Models Better").
15
+ """
16
+ from collections import defaultdict
17
+
18
+ import numpy as np
19
+
20
+ M61 = np.uint64((1 << 61) - 1)
21
+
22
+
23
+ def doc_bounds(tokens, eos):
24
+ ends = np.flatnonzero(tokens == eos) + 1 # exclusive end, includes EOS
25
+ starts = np.concatenate([[0], ends[:-1]])
26
+ return starts, ends
27
+
28
+
29
+ def _ngram_hash(tokens, n):
30
+ """Polynomial hash of every length-n window (uint64 arithmetic wraps)."""
31
+ t = tokens.astype(np.uint64) + np.uint64(1)
32
+ L = len(t) - n + 1
33
+ h = np.zeros(L, dtype=np.uint64)
34
+ base = np.uint64(0x100000001B3)
35
+ with np.errstate(over="ignore"):
36
+ for j in range(n):
37
+ h = h * base + t[j:j + L]
38
+ h ^= h >> np.uint64(29)
39
+ h *= np.uint64(0xBF58476D1CE4E5B9)
40
+ h ^= h >> np.uint64(32)
41
+ return h
42
+
43
+
44
+ def exact_hashes(tokens, starts, ends):
45
+ """One 64-bit hash per document (order-sensitive, length-aware)."""
46
+ t = tokens[:ends[-1]].astype(np.uint64) + np.uint64(1)
47
+ pos = np.arange(len(t), dtype=np.uint64)
48
+ # mix each token with its position *within its document*, then sum per doc
49
+ rel = pos - np.repeat(starts.astype(np.uint64), ends - starts)
50
+ with np.errstate(over="ignore"):
51
+ rel_mixed = t * np.uint64(0x9E3779B97F4A7C15) ^ (rel * np.uint64(0xC2B2AE3D27D4EB4F))
52
+ rel_mixed ^= rel_mixed >> np.uint64(31)
53
+ rel_mixed *= np.uint64(0x94D049BB133111EB)
54
+ sums = np.add.reduceat(rel_mixed, starts)
55
+ with np.errstate(over="ignore"):
56
+ return sums ^ (ends - starts).astype(np.uint64) * np.uint64(0xD6E8FEB86659FD93)
57
+
58
+
59
+ def minhash(tokens, starts, ends, eos, n=8, num_perm=64, seed=0):
60
+ """(n_docs, num_perm) uint32 MinHash signatures; docs shorter than n get all-max."""
61
+ h = _ngram_hash(tokens, n)
62
+ L = len(h)
63
+ # a window is valid if it lies inside one document (no EOS among its first n-1 tokens)
64
+ is_eos = (tokens == eos).astype(np.int32)
65
+ c = np.concatenate([[0], np.cumsum(is_eos)])
66
+ valid = (c[n - 1:n - 1 + L] - c[:L]) == 0
67
+ rng = np.random.default_rng(seed)
68
+ a = rng.integers(1, 1 << 61, size=num_perm, dtype=np.uint64) | np.uint64(1)
69
+ b = rng.integers(0, 1 << 61, size=num_perm, dtype=np.uint64)
70
+ seg_starts = np.minimum(starts, L - 1)
71
+ sig = np.empty((len(starts), num_perm), dtype=np.uint32)
72
+ maxv = np.uint64(0xFFFFFFFFFFFFFFFF)
73
+ for k in range(num_perm):
74
+ with np.errstate(over="ignore"):
75
+ v = (h * a[k] + b[k]) >> np.uint64(32)
76
+ v = np.where(valid, v, maxv)
77
+ sig[:, k] = np.minimum(np.minimum.reduceat(v, seg_starts), 0xFFFFFFFF).astype(np.uint32)
78
+ return sig
79
+
80
+
81
+ class _UF:
82
+ def __init__(self, n):
83
+ self.p = np.arange(n)
84
+
85
+ def find(self, x):
86
+ while self.p[x] != x:
87
+ self.p[x] = self.p[self.p[x]]
88
+ x = self.p[x]
89
+ return x
90
+
91
+ def union(self, a, b):
92
+ ra, rb = self.find(a), self.find(b)
93
+ if ra != rb:
94
+ self.p[max(ra, rb)] = min(ra, rb)
95
+
96
+
97
+ def dedup(tokens, eos, n=8, num_perm=64, bands=8, threshold=0.8, seed=0):
98
+ """Return (keep_mask over documents, stats dict)."""
99
+ assert num_perm % bands == 0
100
+ starts, ends = doc_bounds(tokens, eos)
101
+ nd = len(starts)
102
+ keep = np.ones(nd, dtype=bool)
103
+
104
+ # exact duplicates: keep first occurrence
105
+ eh = exact_hashes(tokens, starts, ends)
106
+ _, first = np.unique(eh, return_index=True)
107
+ exact_keep = np.zeros(nd, dtype=bool)
108
+ exact_keep[first] = True
109
+ n_exact = int(nd - exact_keep.sum())
110
+ keep &= exact_keep
111
+
112
+ # near duplicates among the exact-unique docs
113
+ sig = minhash(tokens, starts, ends, eos, n, num_perm, seed)
114
+ has_sh = (ends - starts) > n
115
+ cand = np.flatnonzero(keep & has_sh)
116
+ r = num_perm // bands
117
+ uf = _UF(nd)
118
+ n_pairs = 0
119
+ for bi in range(bands):
120
+ band = np.ascontiguousarray(sig[cand, bi * r:(bi + 1) * r])
121
+ key = band.view(np.dtype((np.void, band.dtype.itemsize * r))).ravel()
122
+ order = np.argsort(key, kind="stable")
123
+ ks = key[order]
124
+ same = np.flatnonzero(ks[1:] == ks[:-1])
125
+ for i in same: # consecutive equal keys -> candidate pair
126
+ x, y = cand[order[i]], cand[order[i + 1]]
127
+ if np.mean(sig[x] == sig[y]) >= threshold:
128
+ uf.union(x, y)
129
+ n_pairs += 1
130
+ roots = np.array([uf.find(i) for i in cand])
131
+ near_keep = np.zeros(nd, dtype=bool)
132
+ near_keep[np.unique(roots)] = True # root = smallest index in cluster
133
+ near_drop = np.zeros(nd, dtype=bool)
134
+ near_drop[cand] = ~near_keep[cand]
135
+ keep &= ~near_drop
136
+
137
+ stats = {"docs": nd, "exact_dups": n_exact, "near_dups": int(near_drop.sum()),
138
+ "near_pairs_confirmed": n_pairs, "kept_docs": int(keep.sum()),
139
+ "kept_frac": float(keep.mean()),
140
+ "tokens": int(len(tokens)), "kept_tokens": int((ends - starts)[keep].sum()),
141
+ "params": {"ngram": n, "num_perm": num_perm, "bands": bands,
142
+ "threshold": threshold}}
143
+ return keep, stats
144
+
145
+
146
+ def filter_tokens(tokens, eos, keep):
147
+ starts, ends = doc_bounds(tokens, eos)
148
+ mask = np.repeat(keep, ends - starts)
149
+ return tokens[:len(mask)][mask]
@@ -0,0 +1,124 @@
1
+ """GridPack: error-bounded, compressed storage for gridded weather fields.
2
+
3
+ Why float16 is the wrong tool: float16 has 10 mantissa bits, so at
4
+ z500 ~ 5.4e4 m^2/s^2 its step is 32 m^2/s^2 (the size of a 6 h forecast
5
+ error), and surface pressure ~ 1e5 Pa cannot be represented at all above
6
+ 65504. bfloat16 keeps the range but only 7 mantissa bits.
7
+
8
+ GridPack instead stores each (channel, time) slab as linear int16 quantization
9
+ around the channel's per-step mean with a per-slab scale chosen so the
10
+ quantization error is at most `err_frac` of the channel's 6-hour change
11
+ standard deviation (an error the model cannot resolve anyway). Residuals
12
+ are then byte-shuffled and zstd compressed per chunk of `chunk` time steps.
13
+ Inside a chunk the quantized integers are stored as temporal deltas
14
+ (q[t] - q[t-1], exact in int16): consecutive 6 h states differ by ~diff_std,
15
+ i.e. ~1/(2*err_frac) quantization steps, so the deltas are small integers
16
+ with low entropy regardless of the field's absolute magnitude. Chunk
17
+ boundaries restart from an absolute slab, so random access decodes one chunk.
18
+
19
+ Every value is reconstructed with |x_hat - x| <= scale/2 <= err_frac * diff_std.
20
+
21
+ Layout
22
+ b"ZGPK1\\0" | u32 hlen | header JSON (shape, dtype, chunk, scales, means)
23
+ | u64[n_chunks + 1] offsets | chunk payloads (int16 residual, byte-shuffled, zstd)
24
+ """
25
+ import json
26
+ import struct
27
+
28
+ import numpy as np
29
+ import zstandard as zstd
30
+
31
+ MAGIC = b"ZGPK1\0"
32
+
33
+
34
+ def _shuffle(a16):
35
+ b = a16.view(np.uint8).reshape(-1, 2)
36
+ return np.ascontiguousarray(b.T).tobytes()
37
+
38
+
39
+ def _unshuffle(raw, n):
40
+ b = np.frombuffer(raw, dtype=np.uint8).reshape(2, n)
41
+ return np.ascontiguousarray(b.T).view(np.int16).reshape(n)
42
+
43
+
44
+ def quantize_slab(x, scale, mean):
45
+ q = np.round((x - mean) / scale)
46
+ assert np.abs(q).max() < 32767, "field range exceeds int16 at this scale"
47
+ return q.astype(np.int16)
48
+
49
+
50
+ def write(path, fields, diff_std, err_frac=0.05, chunk=64, level=10):
51
+ """fields: (T, C, H, W) float32; diff_std: (C,) std of one-step change per channel."""
52
+ T, C, H, W = fields.shape
53
+ scales = (np.asarray(diff_std, dtype=np.float64) * 2 * err_frac).astype(np.float32)
54
+ # per-channel offset = channel mean; per-chunk int16 range check happens in quantize
55
+ means = fields.reshape(T, C, -1).mean(axis=(0, 2)).astype(np.float32)
56
+ cctx = zstd.ZstdCompressor(level=level)
57
+ payloads, offsets, max_err = [], [0], np.zeros(C)
58
+ for s in range(0, T, chunk):
59
+ blk = fields[s:s + chunk]
60
+ qs = []
61
+ for c in range(C):
62
+ q = quantize_slab(blk[:, c], scales[c], means[c])
63
+ max_err[c] = max(max_err[c], np.abs(q.astype(np.float32) * scales[c] + means[c]
64
+ - blk[:, c]).max())
65
+ qs.append(q)
66
+ q = np.stack(qs, axis=1) # (t, C, H, W) int16
67
+ d = q.astype(np.int32)
68
+ d[1:] -= d[:-1].copy() # temporal delta, first slab absolute
69
+ assert np.abs(d).max() < 32767
70
+ p = cctx.compress(_shuffle(d.astype(np.int16).ravel()))
71
+ payloads.append(p)
72
+ offsets.append(offsets[-1] + len(p))
73
+ header = json.dumps({"shape": [T, C, H, W], "chunk": chunk, "err_frac": err_frac,
74
+ "scales": scales.tolist(), "means": means.tolist(),
75
+ "max_abs_err": max_err.tolist(), "n_chunks": len(payloads),
76
+ "pipeline": "int16-linear|temporal-delta|byte-shuffle|zstd"}).encode()
77
+ with open(path, "wb") as f:
78
+ f.write(MAGIC)
79
+ f.write(struct.pack("<I", len(header)))
80
+ f.write(header)
81
+ f.write(np.asarray(offsets, dtype=np.uint64).tobytes())
82
+ for p in payloads:
83
+ f.write(p)
84
+ return offsets[-1], max_err
85
+
86
+
87
+ class GridPack:
88
+ def __init__(self, path):
89
+ self.mm = np.memmap(path, dtype=np.uint8, mode="r")
90
+ assert bytes(self.mm[:6]) == MAGIC, "not a GridPack file"
91
+ hlen = struct.unpack("<I", bytes(self.mm[6:10]))[0]
92
+ self.h = json.loads(bytes(self.mm[10:10 + hlen]))
93
+ pos = 10 + hlen
94
+ nc = self.h["n_chunks"]
95
+ self.offsets = np.frombuffer(self.mm[pos:pos + 8 * (nc + 1)].tobytes(), dtype=np.uint64)
96
+ self.data_start = pos + 8 * (nc + 1)
97
+ self.T, self.C, self.H, self.W = self.h["shape"]
98
+ self.chunk = self.h["chunk"]
99
+ self.scales = np.asarray(self.h["scales"], dtype=np.float32).reshape(1, -1, 1, 1)
100
+ self.means = np.asarray(self.h["means"], dtype=np.float32).reshape(1, -1, 1, 1)
101
+ self.dctx = zstd.ZstdDecompressor()
102
+
103
+ @property
104
+ def compressed_bytes(self):
105
+ return int(self.offsets[-1])
106
+
107
+ def read_chunk(self, i):
108
+ a = self.data_start + int(self.offsets[i])
109
+ b = self.data_start + int(self.offsets[i + 1])
110
+ t = min(self.chunk, self.T - i * self.chunk)
111
+ n = t * self.C * self.H * self.W
112
+ d = _unshuffle(self.dctx.decompress(self.mm[a:b].tobytes()), n)
113
+ q = np.cumsum(d.reshape(t, self.C, self.H, self.W).astype(np.int32), axis=0)
114
+ return q.astype(np.float32) * self.scales + self.means
115
+
116
+ def read(self, start, length):
117
+ c0, c1 = start // self.chunk, (start + length - 1) // self.chunk
118
+ parts = [self.read_chunk(i) for i in range(c0, c1 + 1)]
119
+ joined = parts[0] if len(parts) == 1 else np.concatenate(parts)
120
+ off = start - c0 * self.chunk
121
+ return joined[off:off + length]
122
+
123
+ def read_all(self):
124
+ return self.read(0, self.T)
@@ -0,0 +1,220 @@
1
+ """TokPack: lossless, random-access, compressed storage for token streams.
2
+
3
+ Format v2 (default, b"ZTPK2\\0"):
4
+ 1. frequency-rank remap: token id -> rank of its corpus frequency, so the
5
+ common tokens become small integers;
6
+ 2. LEB128 varint: ranks < 128 take one byte, < 16384 two, < 2^21 three;
7
+ 3. zstd-19 per chunk of `chunk` tokens, all chunks sharing one zstd
8
+ dictionary trained on a sample of the corpus and stored in the file.
9
+ The dictionary is what lets small chunks (fast random access) compress
10
+ like large ones: measured on 18M held-out TinyStories tokens (4096 vocab),
11
+ 16K-token chunks reach 5.96 bits/token (0.75 B/token) with a 1 MB
12
+ dictionary vs 7.08 bits/token without one, and decompress in 0.05 ms.
13
+
14
+ Format v1 (b"ZTPK1\\0", read-only): rank remap -> byte-plane shuffle -> zstd.
15
+ Kept so old files still load. The byte shuffle turned out to *hurt*
16
+ (8.55 bits/token vs 7.86 for plain zstd on uint16), which is why v2
17
+ replaced it.
18
+
19
+ Layout (little endian)
20
+ magic | u32 header_len | header JSON
21
+ | u64[n_chunks + 1] byte offsets (relative to data start)
22
+ | u16/u32[vocab] rank -> token id table
23
+ | (v2) zstd dictionary bytes
24
+ | chunk payloads
25
+ All steps are invertible, so decode(encode(x)) == x exactly.
26
+ """
27
+ import json
28
+ import struct
29
+ from collections import OrderedDict
30
+
31
+ import numpy as np
32
+ import zstandard as zstd
33
+
34
+ MAGIC_V1 = b"ZTPK1\0"
35
+ MAGIC_V2 = b"ZTPK2\0"
36
+
37
+
38
+ # ---------------------------------------------------------------- varint codec
39
+ def leb128_encode(a):
40
+ """Non-negative ints < 2^21 -> LEB128 bytes (vectorized)."""
41
+ a = np.asarray(a, dtype=np.uint32)
42
+ assert a.size == 0 or int(a.max()) < (1 << 21)
43
+ lens = 1 + (a >= 128).astype(np.int64) + (a >= 16384).astype(np.int64)
44
+ pos = np.concatenate([[0], np.cumsum(lens)[:-1]])
45
+ out = np.empty(int(lens.sum()), dtype=np.uint8)
46
+ out[pos] = (a & 0x7F) | np.where(lens > 1, 0x80, 0).astype(np.uint32)
47
+ m2 = lens >= 2
48
+ out[pos[m2] + 1] = ((a[m2] >> 7) & 0x7F) | np.where(lens[m2] > 2, 0x80, 0).astype(np.uint32)
49
+ m3 = lens == 3
50
+ out[pos[m3] + 2] = a[m3] >> 14
51
+ return out
52
+
53
+
54
+ def leb128_decode(b, n=None):
55
+ """LEB128 bytes -> uint32 values (vectorized, values < 2^21)."""
56
+ b = np.frombuffer(b, dtype=np.uint8) if isinstance(b, (bytes, bytearray)) else b
57
+ cont = b >= 128
58
+ starts = np.flatnonzero(np.concatenate([[True], ~cont[:-1]]))
59
+ v = (b[starts] & 0x7F).astype(np.uint32)
60
+ has2 = cont[starts]
61
+ i2 = starts[has2] + 1
62
+ v[has2] |= (b[i2] & 0x7F).astype(np.uint32) << 7
63
+ has3 = np.zeros_like(has2)
64
+ has3[has2] = cont[i2]
65
+ v[has3] |= b[starts[has3] + 2].astype(np.uint32) << 14
66
+ if n is not None:
67
+ assert len(v) == n, f"decoded {len(v)} values, expected {n}"
68
+ return v
69
+
70
+
71
+ # ---------------------------------------------------------------- v1 helpers
72
+ def _unshuffle_bytes(raw, n):
73
+ b = np.frombuffer(raw, dtype=np.uint8).reshape(2, n)
74
+ return np.ascontiguousarray(b.T).view(np.uint16).reshape(n)
75
+
76
+
77
+ # ---------------------------------------------------------------- writer
78
+ def write(path, tokens, vocab, chunk=16384, level=19, dict_size=1 << 20,
79
+ dict_sample_tokens=2_000_000, threads=0):
80
+ """Write a v2 TokPack. Returns the total payload bytes (chunks + dictionary)."""
81
+ tokens = np.asarray(tokens)
82
+ assert tokens.size == 0 or int(tokens.max()) < vocab
83
+ n = len(tokens)
84
+ counts = np.bincount(tokens, minlength=vocab)
85
+ rank_to_tok = np.argsort(-counts, kind="stable").astype(np.uint32)
86
+ tok_to_rank = np.empty(vocab, dtype=np.uint32)
87
+ tok_to_rank[rank_to_tok] = np.arange(vocab, dtype=np.uint32)
88
+ ranks = tok_to_rank[tokens]
89
+
90
+ dict_bytes = b""
91
+ # the dictionary must pay for itself: cap it at ~5 % of the varint stream
92
+ approx_varint = int(n * (1 + (counts[rank_to_tok[128:]].sum() / max(n, 1))))
93
+ dict_size = min(dict_size, approx_varint // 20)
94
+ if dict_size >= 4096 and n >= 8 * chunk:
95
+ sample = ranks[:dict_sample_tokens]
96
+ samples = [leb128_encode(sample[s:s + 4096]).tobytes()
97
+ for s in range(0, len(sample), 4096)]
98
+ try:
99
+ d = zstd.train_dictionary(dict_size, samples, level=level, threads=threads or 1)
100
+ dict_bytes = d.as_bytes()
101
+ except zstd.ZstdError:
102
+ dict_bytes = b""
103
+ zd = zstd.ZstdCompressionDict(dict_bytes) if dict_bytes else None
104
+ cctx = zstd.ZstdCompressor(level=level, dict_data=zd, threads=threads)
105
+ payloads, offsets = [], [0]
106
+ for s in range(0, n, chunk):
107
+ p = cctx.compress(leb128_encode(ranks[s:s + chunk]).tobytes())
108
+ payloads.append(p)
109
+ offsets.append(offsets[-1] + len(p))
110
+ tdtype = "u16" if vocab <= 65536 else "u32"
111
+ header = json.dumps({"version": 2, "n_tokens": n, "vocab": vocab, "chunk": chunk,
112
+ "n_chunks": len(payloads), "codec": f"zstd-{level}",
113
+ "dict_bytes": len(dict_bytes), "table_dtype": tdtype,
114
+ "pipeline": "rank-remap|leb128|zstd+dict"}).encode()
115
+ with open(path, "wb") as f:
116
+ f.write(MAGIC_V2)
117
+ f.write(struct.pack("<I", len(header)))
118
+ f.write(header)
119
+ f.write(np.asarray(offsets, dtype=np.uint64).tobytes())
120
+ f.write(rank_to_tok.astype(np.uint16 if tdtype == "u16" else np.uint32).tobytes())
121
+ f.write(dict_bytes)
122
+ for p in payloads:
123
+ f.write(p)
124
+ return offsets[-1] + len(dict_bytes)
125
+
126
+
127
+ # ---------------------------------------------------------------- reader
128
+ class TokPack:
129
+ def __init__(self, path, cache_chunks=64):
130
+ self.mm = np.memmap(path, dtype=np.uint8, mode="r")
131
+ magic = bytes(self.mm[:6])
132
+ assert magic in (MAGIC_V1, MAGIC_V2), "not a TokPack file"
133
+ self.version = 2 if magic == MAGIC_V2 else 1
134
+ hlen = struct.unpack("<I", bytes(self.mm[6:10]))[0]
135
+ self.h = json.loads(bytes(self.mm[10:10 + hlen]))
136
+ pos = 10 + hlen
137
+ nc = self.h["n_chunks"]
138
+ self.offsets = np.frombuffer(self.mm[pos:pos + 8 * (nc + 1)].tobytes(), dtype=np.uint64)
139
+ pos += 8 * (nc + 1)
140
+ v = self.h["vocab"]
141
+ if self.version == 1:
142
+ self.rank_to_tok = None
143
+ if self.h["remap"]:
144
+ self.rank_to_tok = np.frombuffer(self.mm[pos:pos + 2 * v].tobytes(), dtype=np.uint16)
145
+ pos += 2 * v
146
+ self.dctx = zstd.ZstdDecompressor()
147
+ self.dict_bytes = 0
148
+ else:
149
+ tdt = np.uint16 if self.h["table_dtype"] == "u16" else np.uint32
150
+ w = np.dtype(tdt).itemsize
151
+ self.rank_to_tok = np.frombuffer(self.mm[pos:pos + w * v].tobytes(), dtype=tdt)
152
+ pos += w * v
153
+ nd = self.h["dict_bytes"]
154
+ self.dict_bytes = nd
155
+ zd = zstd.ZstdCompressionDict(self.mm[pos:pos + nd].tobytes()) if nd else None
156
+ pos += nd
157
+ self.dctx = zstd.ZstdDecompressor(dict_data=zd)
158
+ self.data_start = pos
159
+ self.n = self.h["n_tokens"]
160
+ self.chunk = self.h["chunk"]
161
+ self.out_dtype = np.uint16 if v <= 65536 else np.uint32
162
+ self.cache = OrderedDict()
163
+ self.cache_chunks = cache_chunks
164
+
165
+ def __len__(self):
166
+ return self.n
167
+
168
+ @property
169
+ def compressed_bytes(self):
170
+ return int(self.offsets[-1]) + self.dict_bytes
171
+
172
+ def _chunk(self, i):
173
+ if i in self.cache:
174
+ self.cache.move_to_end(i)
175
+ return self.cache[i]
176
+ a = self.data_start + int(self.offsets[i])
177
+ b = self.data_start + int(self.offsets[i + 1])
178
+ n = min(self.chunk, self.n - i * self.chunk)
179
+ raw = self.dctx.decompress(self.mm[a:b].tobytes())
180
+ if self.version == 1:
181
+ arr = _unshuffle_bytes(raw, n)
182
+ if self.rank_to_tok is not None:
183
+ arr = self.rank_to_tok[arr]
184
+ else:
185
+ arr = self.rank_to_tok[leb128_decode(raw, n)].astype(self.out_dtype, copy=False)
186
+ self.cache[i] = arr
187
+ if len(self.cache) > self.cache_chunks:
188
+ self.cache.popitem(last=False)
189
+ return arr
190
+
191
+ def read(self, start, length):
192
+ end = start + length
193
+ assert 0 <= start and end <= self.n
194
+ c0, c1 = start // self.chunk, (end - 1) // self.chunk
195
+ parts = [self._chunk(i) for i in range(c0, c1 + 1)]
196
+ joined = parts[0] if len(parts) == 1 else np.concatenate(parts)
197
+ off = start - c0 * self.chunk
198
+ return joined[off:off + length]
199
+
200
+ def __getitem__(self, sl):
201
+ start, stop, step = sl.indices(self.n)
202
+ assert step == 1
203
+ return self.read(start, stop - start)
204
+
205
+ def stream(self, seq, seed=0, buffer_chunks=32):
206
+ """Yield length-`seq` windows in a shuffled order, one decompression per chunk."""
207
+ rng = np.random.default_rng(seed)
208
+ order = rng.permutation(self.h["n_chunks"])
209
+ pool = []
210
+ per_chunk = max(1, self.chunk // seq)
211
+ for i in order:
212
+ c = self._chunk(int(i))
213
+ pool.extend(c[j:j + seq] for j in range(0, len(c) - seq + 1, seq))
214
+ if len(pool) >= buffer_chunks * per_chunk:
215
+ rng.shuffle(pool)
216
+ half = len(pool) // 2
217
+ yield from pool[half:]
218
+ pool = pool[:half]
219
+ rng.shuffle(pool)
220
+ yield from pool
bantamtrain/device.py ADDED
@@ -0,0 +1,179 @@
1
+ """Runtime setup: one code path for CPU and GPU.
2
+
3
+ CPU
4
+ * flush-to-zero / denormals-are-zero. Must be enabled before the first
5
+ parallel op so every OpenMP worker inherits it; call `enable_ftz()` right
6
+ after `import torch`. Measured here: denormal softmax gradients made a
7
+ (8192x4096)@(4096x256) matmul 15x slower (897 ms -> 57 ms with FTZ).
8
+ GPU
9
+ * bf16 autocast (fp16 + GradScaler on pre-Ampere), TF32 matmuls,
10
+ fused AdamW, torch.compile, SDPA/FlashAttention (used by the models).
11
+ * "Maximize compute without stressing": a memory-headroom batch finder so
12
+ runs never sit at the OOM edge, and a duty-cycle limiter that caps the
13
+ average load when a hard power cap (nvidia-smi -pl) is not available.
14
+ """
15
+ import contextlib
16
+ import os
17
+ import threading
18
+ import time
19
+ from dataclasses import dataclass
20
+ from queue import Queue
21
+
22
+ import torch
23
+
24
+
25
+ def enable_ftz():
26
+ torch.set_flush_denormal(True)
27
+
28
+
29
+ @dataclass
30
+ class Runtime:
31
+ device: torch.device
32
+ amp_dtype: torch.dtype | None
33
+ scaler: "torch.amp.GradScaler | None"
34
+ compile: bool
35
+
36
+ def autocast(self):
37
+ if self.amp_dtype is None:
38
+ return contextlib.nullcontext()
39
+ return torch.autocast(self.device.type, dtype=self.amp_dtype)
40
+
41
+ def backward(self, loss, optimizer, params, clip=1.0, step=True):
42
+ """loss.backward() (+ unscale + clip + step unless step=False), AMP-aware."""
43
+ if self.scaler is not None:
44
+ self.scaler.scale(loss).backward()
45
+ else:
46
+ loss.backward()
47
+ if step:
48
+ self.step(optimizer, params, clip)
49
+
50
+ def step(self, optimizer, params, clip=1.0):
51
+ if self.scaler is not None:
52
+ for o in getattr(optimizer, "optimizers", [optimizer]):
53
+ self.scaler.unscale_(o)
54
+ torch.nn.utils.clip_grad_norm_(params, clip)
55
+ for o in getattr(optimizer, "optimizers", [optimizer]):
56
+ self.scaler.step(o)
57
+ self.scaler.update()
58
+ else:
59
+ torch.nn.utils.clip_grad_norm_(params, clip)
60
+ optimizer.step()
61
+
62
+ def to(self, x):
63
+ if self.device.type == "cuda":
64
+ return x.pin_memory().to(self.device, non_blocking=True)
65
+ return x
66
+
67
+
68
+ def setup_runtime(device="auto", precision="auto", compile=False, threads=None, seed=0):
69
+ """precision: 'auto' | 'fp32' | 'bf16' | 'fp16'."""
70
+ if device == "auto":
71
+ device = "cuda" if torch.cuda.is_available() else "cpu"
72
+ dev = torch.device(device)
73
+ torch.manual_seed(seed)
74
+ if dev.type == "cpu":
75
+ enable_ftz()
76
+ if threads:
77
+ torch.set_num_threads(threads)
78
+ amp_dtype, scaler = None, None
79
+ if dev.type == "cuda":
80
+ torch.backends.cuda.matmul.allow_tf32 = True
81
+ torch.backends.cudnn.allow_tf32 = True
82
+ torch.set_float32_matmul_precision("high")
83
+ if precision == "auto":
84
+ precision = "bf16" if torch.cuda.is_bf16_supported() else "fp16"
85
+ if precision == "bf16":
86
+ amp_dtype = torch.bfloat16
87
+ elif precision == "fp16":
88
+ amp_dtype = torch.float16
89
+ scaler = torch.amp.GradScaler("cuda")
90
+ return Runtime(dev, amp_dtype, scaler, compile)
91
+
92
+
93
+ def maybe_compile(model, rt):
94
+ if rt.compile and hasattr(torch, "compile"):
95
+ return torch.compile(model, dynamic=False)
96
+ return model
97
+
98
+
99
+ def find_batch_size(try_step, start=8, limit=4096, headroom=0.85, device=None):
100
+ """Largest power-of-two batch whose peak memory stays under `headroom` x total.
101
+
102
+ try_step(batch) must run one full fwd/bwd/step. CPU: returns `start`.
103
+ Staying below the OOM edge avoids allocator thrash and fragmentation
104
+ retries, which cost more throughput than the last few % of batch size.
105
+ """
106
+ if device is None or device.type != "cuda":
107
+ return start
108
+ total = torch.cuda.get_device_properties(device).total_memory
109
+ best, b = None, start
110
+ while b <= limit:
111
+ try:
112
+ torch.cuda.empty_cache()
113
+ torch.cuda.reset_peak_memory_stats(device)
114
+ try_step(b)
115
+ torch.cuda.synchronize(device)
116
+ if torch.cuda.max_memory_allocated(device) > headroom * total:
117
+ break
118
+ best, b = b, b * 2
119
+ except torch.OutOfMemoryError:
120
+ break
121
+ torch.cuda.empty_cache()
122
+ return best or start
123
+
124
+
125
+ class DutyCycleLimiter:
126
+ """Cap average accelerator load at `target` (0 < target <= 1).
127
+
128
+ After a step that took t seconds, idles t * (1/target - 1). Throughput
129
+ scales ~linearly with target. A hardware power cap is more efficient
130
+ (GPUs typically keep most of their throughput at ~70% power because
131
+ clocks/voltage drop super-linearly), so prefer `nvidia-smi -pl <watts>`
132
+ when you have permission; this is the portable fallback.
133
+ """
134
+
135
+ def __init__(self, target=1.0, device=None):
136
+ self.target = target
137
+ self.device = device
138
+
139
+ def __call__(self, step_seconds):
140
+ if self.target >= 1.0:
141
+ return
142
+ if self.device is not None and self.device.type == "cuda":
143
+ torch.cuda.synchronize(self.device)
144
+ time.sleep(step_seconds * (1.0 / self.target - 1.0))
145
+
146
+ @staticmethod
147
+ def power_cap_hint(fraction=0.7):
148
+ return (f"sudo nvidia-smi -pl <{int(fraction * 100)}% of default TDP> "
149
+ "# e.g. -pl 250 on a 350 W card")
150
+
151
+
152
+ class Prefetcher:
153
+ """Background thread that builds the next batches while the model trains."""
154
+
155
+ def __init__(self, make_batch, depth=2):
156
+ self.q = Queue(maxsize=depth)
157
+ self.make_batch = make_batch
158
+ self._stop = False
159
+ self.t = threading.Thread(target=self._run, daemon=True)
160
+ self.t.start()
161
+
162
+ def _run(self):
163
+ while not self._stop:
164
+ self.q.put(self.make_batch())
165
+
166
+ def next(self):
167
+ return self.q.get()
168
+
169
+ def close(self):
170
+ self._stop = True
171
+
172
+
173
+ def describe(rt):
174
+ s = f"device={rt.device} amp={rt.amp_dtype} compile={rt.compile}"
175
+ if rt.device.type == "cpu":
176
+ s += f" threads={torch.get_num_threads()}"
177
+ elif rt.device.type == "cuda":
178
+ s += f" gpu={torch.cuda.get_device_name(rt.device)}"
179
+ return s + f" pid={os.getpid()}"