Big models in small memory #

What is new: a model is stored as content-addressed chunks, one record per tensor, and read back through a Streamer with a fixed memory budget. Any row range of any tensor reads exactly the chunks that cover it, each one checked against its fingerprint as it arrives. A changed byte is refused with its exact location: the tensor, the part, the chunk and the byte range. Checkpoints that share tensors store them once, and each tensor knows which checkpoint introduced it.

Why it matters: checking a multi-gigabyte model should not need the whole model in memory, or trust in the disk it came from. In our live test a 4.06 GB model was read and checked with its chunk cache held under 64 MiB.

Store a model, read it back under a budget #

import hashlib, random
from pathlib import Path
from tensorchain.weights import safetensors as ST, store as S
from tensorchain.weights.stream import Streamer
from tensorchain.workspace import Workspace

def model(d, seeds):
    d.mkdir(parents=True, exist_ok=True)
    ts = []
    for name, shape in (("a", [300, 512]), ("b", [64, 64]), ("e", [700, 256])):
        n = shape[0] * (shape[1] if len(shape) > 1 else 1)
        rnd = random.Random(seeds.get(name, 0) * 1000 + ord(name))
        ts.append((name, "BF16", shape, bytes(rnd.getrandbits(8) for _ in range(2 * n))))
    ST.make(d / "model.safetensors", ts, meta={"format": "pt"})
    (d / "config.json").write_text("{}")
    return d

m = model(Path("m"), {})
header = ST.read_header(m / "model.safetensors")
raw = (m / "model.safetensors").read_bytes()
ws = Workspace("ws.sqlite", actor="docs").__enter__()
ck = S.put_checkpoint(ws, m)
st = Streamer(ws, ck, budget_bytes=2 * S.CHUNK)                       # room for two chunks, no more

t = header["tensors"]["e"]
row = t["shape"][1] * 2
want = raw[t["start"] + 100 * row: t["start"] + 400 * row]            # rows 100..399, straight from the file
got = st.rows("e", 100, 400)
print("rows 100-399 of e:", len(got), "bytes; chunks read", st.chunk_reads, "; cache high water", st.high_water,
      "of", st.budget)
assert got == want and st.high_water <= st.budget
Output (captured at build)
rows 100-399 of e: 153600 bytes; chunks read 4 ; cache high water 131072 of 131072

Streaming a whole tensor goes chunk by chunk, and the result hashes to the fingerprint recorded when it was stored:

for name in ("a", "b", "e"):
    whole = b"".join(st.stream(name))
    assert hashlib.sha256(whole).hexdigest() == S.tensor_info(ws, st.tensors[name])["sha256"]
print("a, b, e streamed and matched their fingerprints; high water", st.high_water, "<= budget", st.budget)
assert st.high_water <= st.budget
ws.__exit__(None, None, None)
Output (captured at build)
a, b, e streamed and matched their fingerprints; high water 131072 <= budget 131072

A changed byte, refused where it is #

This block flips one bit inside one stored chunk, directly in the database, the way a corrupted disk or an attacker would. The read of that chunk is refused with its location. Other chunks and other tensors still read.

import sqlite3
with Workspace("ws.sqlite", actor="docs") as ws:
    target = S._read(ws, S.tensor_info(ws, Streamer(ws, ck).tensors["e"])["parts"][0], S.PART)["chunks"][1]
db = sqlite3.connect("ws.sqlite")
blob = bytearray(db.execute("SELECT raw FROM tc_object WHERE root=?", (target,)).fetchone()[0])
blob[100] ^= 1
db.execute("UPDATE tc_object SET raw=? WHERE root=?", (bytes(blob), target))
db.commit(); db.close()

with Workspace("ws.sqlite", actor="docs") as ws:
    st = Streamer(ws, ck)
    try:
        st.read("e", S.CHUNK + 5, 10)
        refused = None
    except S.StoreError as e:
        refused = e
    print(refused.code, "-", str(refused)[:120])
    assert refused.code == "chunk_tampered" and "e part 0 chunk 1" in str(refused)
    assert st.read("e", 0, 100) == raw[t["start"]: t["start"] + 100]   # chunk 0 of the same tensor still reads
    assert len(b"".join(st.stream("a"))) == 300 * 512 * 2              # another tensor still reads
Output (captured at build)
chunk_tampered - chunk_tampered: e part 0 chunk 1 bytes [65536, 131072) (89c64431f58c4b213006931a19d632406923ddef338e0b9a01f063152571e6d8

Layers: which checkpoint introduced each tensor #

A fine-tuned child that changes one tensor stores only that tensor anew. layers() walks the parent chain and names, for every tensor, the checkpoint it came from. (This uses a fresh workspace: the one above holds the chunk we corrupted, and the store refuses to reuse a chunk whose bytes no longer match its name.)

with Workspace("layers.sqlite", actor="docs") as ws:
    parent = S.put_checkpoint(ws, model(Path("p"), {}))
    child = S.put_checkpoint(ws, model(Path("c"), {"b": 1}), parent=parent)
    where = Streamer(ws, child).layers()
print({name: ("child" if at == child else "parent") for name, at in sorted(where.items())})
assert [n for n, at in where.items() if at == child] == ["b"]
assert sorted(n for n, at in where.items() if at == parent) == ["a", "e"]
Output (captured at build)
{'a': 'parent', 'b': 'child', 'e': 'parent'}

What it does not do #

Next: surgery on the weights changes exactly the tensors you name, and keeps the inverse.