bantamtrain 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nathan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: bantamtrain
3
+ Version: 0.1.0
4
+ Summary: Bantam: train small language models and weather models faster and cheaper on limited compute - Zoom Training, Muon, 8-bit/bf16 low-memory training, int8/int4 weights, compressed token and weather-grid stores
5
+ Author: Nathan
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/Wisk-inc/AboxRebuildcode
8
+ Keywords: llm,training,efficiency,muon,optimizer,quantization,weather,era5,pytorch
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: torch>=2.2
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: zstandard>=0.21
21
+ Provides-Extra: data
22
+ Requires-Dist: tokenizers; extra == "data"
23
+ Requires-Dist: pyarrow; extra == "data"
24
+ Requires-Dist: huggingface_hub; extra == "data"
25
+ Provides-Extra: weather
26
+ Requires-Dist: xarray; extra == "weather"
27
+ Requires-Dist: zarr; extra == "weather"
28
+ Requires-Dist: fsspec; extra == "weather"
29
+ Requires-Dist: aiohttp; extra == "weather"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # Bantam (`bantamtrain`)
35
+
36
+ **Train small language models and weather models faster and cheaper on limited
37
+ compute, without throwing away data.** Made by Nathan, Jamaica.
38
+
39
+ Bantam is the library behind a set of measured results on real data (TinyStories
40
+ from HuggingFace, ERA5 from WeatherBench2), all obtained in a 4-core CPU sandbox;
41
+ the same code runs on a GPU with mixed precision and `torch.compile`.
42
+
43
+ ```bash
44
+ pip install bantamtrain
45
+ ```
46
+
47
+ ## What is inside
48
+
49
+ | module | what it does | measured (5.8M-param LM on TinyStories unless noted) |
50
+ |---|---|---|
51
+ | `bantamtrain.zoom` | **Zoom Training**: merge neighbouring tokens / grid patches into one position early in training, anneal back to full resolution | k=2 for the first half with batch x2: loss 2.685 +- 0.004 vs 2.737 +- 0.011 at equal FLOPs (3 seeds) |
52
+ | `bantamtrain.optim` | **Muon** optimizer (Jordan 2024; quintic or Polar Express orthogonalizer), AdamW for the rest, 8-bit state | 2.74 vs 3.33 (AdamW) at equal FLOPs |
53
+ | `bantamtrain.lowmem` | 8-bit blockwise optimizer state; bf16 weights with stochastic rounding (no fp32 master copy) | weights + state 3x smaller, loss 2.728 vs 2.737 |
54
+ | `bantamtrain.qweights` | int8 / int4 weight-only `Linear` and `Embedding` kept compressed in RAM | int8: 3.9x smaller, +0.0002 loss; int4: 7.5x smaller, +0.026 |
55
+ | `bantamtrain.weightpack` | compressed checkpoints: fp32 / lossless bf16 / int8 / int4 | lossless bf16 file 2.9x smaller than fp32 |
56
+ | `bantamtrain.data.tokpack` | TokPack v2: random-access compressed token store (rank remap + LEB128 + zstd dictionary) | 2.68x smaller than uint16 ids (5.97 bits/token), exact |
57
+ | `bantamtrain.data.dedup` | exact + MinHash-LSH near-duplicate removal on token streams, vectorised | 4 % exact duplicates found in TinyStories |
58
+ | `bantamtrain.data.gridpack` | GridPack: error-bounded int16 + temporal delta + zstd for gridded fields | ERA5 5.2x smaller than float32, error <= 5 % of a 6 h change |
59
+ | `bantamtrain.device` | runtime: flush-to-zero on CPU, AMP, TF32, compile, batch finder, duty-cycle limiter | the FTZ fix made affected CPU matmuls up to 23x faster |
60
+ | `bantamtrain.memory` | memory / time scoreboard for single-GPU training | `python -m bantamtrain.memory` |
61
+ | `bantamtrain.models` | `ZoomGPT` (decoder LM) and `ZoomViT` (weather grid forecaster) with every option above | |
62
+
63
+ ## Quick start
64
+
65
+ ```python
66
+ import torch
67
+ from bantamtrain.models import ZoomGPT
68
+ from bantamtrain.optim import build_optimizer
69
+ from bantamtrain.zoom import ZoomSchedule, lr_at
70
+
71
+ model = ZoomGPT(vocab=4096, d=256, n_layer=6, n_head=4, zoom_ks=[2])
72
+ opt = build_optimizer(model, "muon", lr=1.6e-2, weight_decay=0.1, state_bits=8)
73
+ sched = ZoomSchedule.parse("2:0.5,1:0.5") # k=2 for the first half of the budget
74
+
75
+ x = torch.randint(0, 4096, (16, 258))
76
+ for frac in (0.1, 0.6): # fraction of the compute budget spent
77
+ k = sched.k_at(frac)
78
+ for g in opt.param_groups:
79
+ g["lr"] = lr_at(frac, 1.6e-2, sched="wsd")
80
+ loss = model(x[:, :256], x[:, k:256 + k], k=k)
81
+ opt.zero_grad(); loss.backward(); opt.step()
82
+ ```
83
+
84
+ Store a trained model small:
85
+
86
+ ```python
87
+ from bantamtrain import qweights, weightpack
88
+ weightpack.save("model.zwpk", model.state_dict(), bits=8) # int8 checkpoint file
89
+ qweights.quantize_model(model, bits=4) # int4 weights in RAM, float compute
90
+ ```
91
+
92
+ Size a run on one GPU:
93
+
94
+ ```bash
95
+ python -m bantamtrain.memory --params 5e9 --gpu_gb 96 --tokens 1e11
96
+ ```
97
+
98
+ ## Honest notes
99
+
100
+ - Muon, 8-bit optimizer state, stochastic-rounding bf16 and blockwise weight
101
+ quantization are published techniques re-implemented here; Zoom Training and
102
+ the storage formats are this project's own.
103
+ - All quality numbers above were measured on a 5.8M-parameter model; gains at
104
+ larger scale are expected to be smaller for the optimizer and are untested for
105
+ Zoom. Nothing has been run on a GPU yet.
106
+ - Source, experiments, tests and the full write-up:
107
+ https://github.com/Wisk-inc/AboxRebuildcode
@@ -0,0 +1,74 @@
1
+ # Bantam (`bantamtrain`)
2
+
3
+ **Train small language models and weather models faster and cheaper on limited
4
+ compute, without throwing away data.** Made by Nathan, Jamaica.
5
+
6
+ Bantam is the library behind a set of measured results on real data (TinyStories
7
+ from HuggingFace, ERA5 from WeatherBench2), all obtained in a 4-core CPU sandbox;
8
+ the same code runs on a GPU with mixed precision and `torch.compile`.
9
+
10
+ ```bash
11
+ pip install bantamtrain
12
+ ```
13
+
14
+ ## What is inside
15
+
16
+ | module | what it does | measured (5.8M-param LM on TinyStories unless noted) |
17
+ |---|---|---|
18
+ | `bantamtrain.zoom` | **Zoom Training**: merge neighbouring tokens / grid patches into one position early in training, anneal back to full resolution | k=2 for the first half with batch x2: loss 2.685 +- 0.004 vs 2.737 +- 0.011 at equal FLOPs (3 seeds) |
19
+ | `bantamtrain.optim` | **Muon** optimizer (Jordan 2024; quintic or Polar Express orthogonalizer), AdamW for the rest, 8-bit state | 2.74 vs 3.33 (AdamW) at equal FLOPs |
20
+ | `bantamtrain.lowmem` | 8-bit blockwise optimizer state; bf16 weights with stochastic rounding (no fp32 master copy) | weights + state 3x smaller, loss 2.728 vs 2.737 |
21
+ | `bantamtrain.qweights` | int8 / int4 weight-only `Linear` and `Embedding` kept compressed in RAM | int8: 3.9x smaller, +0.0002 loss; int4: 7.5x smaller, +0.026 |
22
+ | `bantamtrain.weightpack` | compressed checkpoints: fp32 / lossless bf16 / int8 / int4 | lossless bf16 file 2.9x smaller than fp32 |
23
+ | `bantamtrain.data.tokpack` | TokPack v2: random-access compressed token store (rank remap + LEB128 + zstd dictionary) | 2.68x smaller than uint16 ids (5.97 bits/token), exact |
24
+ | `bantamtrain.data.dedup` | exact + MinHash-LSH near-duplicate removal on token streams, vectorised | 4 % exact duplicates found in TinyStories |
25
+ | `bantamtrain.data.gridpack` | GridPack: error-bounded int16 + temporal delta + zstd for gridded fields | ERA5 5.2x smaller than float32, error <= 5 % of a 6 h change |
26
+ | `bantamtrain.device` | runtime: flush-to-zero on CPU, AMP, TF32, compile, batch finder, duty-cycle limiter | the FTZ fix made affected CPU matmuls up to 23x faster |
27
+ | `bantamtrain.memory` | memory / time scoreboard for single-GPU training | `python -m bantamtrain.memory` |
28
+ | `bantamtrain.models` | `ZoomGPT` (decoder LM) and `ZoomViT` (weather grid forecaster) with every option above | |
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ import torch
34
+ from bantamtrain.models import ZoomGPT
35
+ from bantamtrain.optim import build_optimizer
36
+ from bantamtrain.zoom import ZoomSchedule, lr_at
37
+
38
+ model = ZoomGPT(vocab=4096, d=256, n_layer=6, n_head=4, zoom_ks=[2])
39
+ opt = build_optimizer(model, "muon", lr=1.6e-2, weight_decay=0.1, state_bits=8)
40
+ sched = ZoomSchedule.parse("2:0.5,1:0.5") # k=2 for the first half of the budget
41
+
42
+ x = torch.randint(0, 4096, (16, 258))
43
+ for frac in (0.1, 0.6): # fraction of the compute budget spent
44
+ k = sched.k_at(frac)
45
+ for g in opt.param_groups:
46
+ g["lr"] = lr_at(frac, 1.6e-2, sched="wsd")
47
+ loss = model(x[:, :256], x[:, k:256 + k], k=k)
48
+ opt.zero_grad(); loss.backward(); opt.step()
49
+ ```
50
+
51
+ Store a trained model small:
52
+
53
+ ```python
54
+ from bantamtrain import qweights, weightpack
55
+ weightpack.save("model.zwpk", model.state_dict(), bits=8) # int8 checkpoint file
56
+ qweights.quantize_model(model, bits=4) # int4 weights in RAM, float compute
57
+ ```
58
+
59
+ Size a run on one GPU:
60
+
61
+ ```bash
62
+ python -m bantamtrain.memory --params 5e9 --gpu_gb 96 --tokens 1e11
63
+ ```
64
+
65
+ ## Honest notes
66
+
67
+ - Muon, 8-bit optimizer state, stochastic-rounding bf16 and blockwise weight
68
+ quantization are published techniques re-implemented here; Zoom Training and
69
+ the storage formats are this project's own.
70
+ - All quality numbers above were measured on a 5.8M-parameter model; gains at
71
+ larger scale are expected to be smaller for the optimizer and are untested for
72
+ Zoom. Nothing has been run on a GPU yet.
73
+ - Source, experiments, tests and the full write-up:
74
+ https://github.com/Wisk-inc/AboxRebuildcode
@@ -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)