Badge a model #

What is new: a TC Badge is a certificate for one exact model. Every tensor and every file that shapes its behaviour (the config, the tokenizer, the chat template) is fingerprinted on your machine. The badge adds your terms and what the model was built from, and the service signs it. Anyone who downloads the model checks their copy in one call, and the check names exactly what differs. Starting from the model alone, anyone can also find who badged it, by sending only tensor hashes.

Why it matters: a model file is opaque. Without a fingerprint per tensor, a changed layer or a planted trigger in a chat template is invisible. With one, a copy is either byte-identical to what its maker published or it is not, and the answer says where.

Badge it, then check a copy #

This block writes a tiny but real model folder (a safetensors file, a config, a chat template) and badges it.

import hashlib, json, shutil, struct
from pathlib import Path
from tensorchain import badge as B

def model_dir(d, tensors):
    d.mkdir()
    head, off, blob = {}, 0, b""
    for name, data in tensors.items():
        head[name] = {"dtype": "U8", "shape": [len(data)], "data_offsets": [off, off + len(data)]}
        off, blob = off + len(data), blob + data
    h = json.dumps(head).encode()
    (d / "model.safetensors").write_bytes(struct.pack("<Q", len(h)) + h + blob)
    (d / "config.json").write_text('{"hidden": 8}')
    (d / "tokenizer_config.json").write_text('{"chat_template": "{{ messages }}"}')
    return d

TENSORS = {"layers.0.w": b"\x01" * 64, "layers.1.w": b"\x02" * 64, "lm_head": b"\x03" * 32}
m = model_dir(Path("model"), TENSORS)
dataset = hashlib.sha256(b"the dataset this model was trained on").hexdigest()     # a dataset's root
b = B.make(m, "tiny", "Ada", terms={"commercial_use": "no", "redistribution": "yes"}, trained_on=[dataset])
print([k for k, _, _ in b["items"]])
print("terms:", b["terms"])

copy = Path("copy")
shutil.copytree(m, copy)
print("an exact copy:", B.verify(copy, b)["status"])
assert B.verify(copy, b)["status"] == "match"
Output (captured at build)
['file:config.json', 'file:tokenizer_config.json', 'tensor:layers.0.w', 'tensor:layers.1.w', 'tensor:lm_head']
terms: {'commercial_use': 'no', 'redistribution': 'yes', 'train_on_outputs': 'ask', 'fine_tuning': 'ask'}
an exact copy: match

One changed byte, named #

Flip a single bit inside one tensor, and the check names that tensor and nothing else.

raw = bytearray((copy / "model.safetensors").read_bytes())
off, _ = B.safetensors_index(copy / "model.safetensors")["layers.1.w"]
raw[off + 5] ^= 1
(copy / "model.safetensors").write_bytes(bytes(raw))
r = B.verify(copy, b)
print(r["status"], r["changed"])
assert (r["status"], r["changed"], r["missing"], r["extra"]) == ("mismatch", ["tensor:layers.1.w"], [], [])
Output (captured at build)
mismatch ['tensor:layers.1.w']

A trigger hidden in the chat template, with no tensor touched, is caught the same way. The template shapes what the model sees, so it is part of the badge.

shutil.rmtree(copy)
shutil.copytree(m, copy)
(copy / "tokenizer_config.json").write_text('{"chat_template": "{% if \'x\' in m %}secret{% endif %}"}')
r = B.verify(copy, b)
print(r["status"], r["changed"])
assert r["changed"] == ["file:tokenizer_config.json"]
Output (captured at build)
mismatch ['file:tokenizer_config.json']

Who badged this model? #

badge.lookup fingerprints a folder on your machine and sends only hashes: the whole-model fingerprint and one sha256 per tensor. It finds published badges with byte-identical tensors. This block runs the real service in-process, the same app as tensorchain.io: a maker badges and publishes, and someone holding only a copy looks it up.

from fastapi.testclient import TestClient
from tensorchain.service.app import create_app
from tensorchain.service.config import Settings
from tensorchain.service.keystore import key_digest

Path("keys.json").write_text(json.dumps({key_digest("key-maker"): "maker"}))
http = TestClient(create_app(Settings(data_dir=Path("data"), keys_file=Path("keys.json"), dev_key=None,
                                      anon_per_min=0, public_origin="https://tensorchain.io")))
auth = {"Authorization": "Bearer key-maker"}
root = http.post("/v1/badges", headers=auth, json={"badge": b}).json()["result"]["badge"]
http.post("/v1/badges/%s/publish" % root, headers=auth)

sent = []
def send(method, path, body=None):
    sent.append(body)
    r = http.request(method, path, json=body) if body is not None else http.request(method, path)
    return r.json()["result"]

found = B.lookup(m, send=send)
print("exact:", [(x["name"], x["status"]) for x in found["exact"]], "tensors sent:", found["tensors_sent"])
assert [x["badge"] for x in found["exact"]] == [root] and found["exact"][0]["status"] == "valid"
assert all(body is None or set(body) == {"tensors"} for body in sent)        # only hashes left the machine
Output (captured at build)
exact: [('tiny', 'valid')] tensors sent: 3

A copy with one tensor changed no longer matches the whole badge, but its other tensors still point to it:

one = model_dir(Path("one"), dict(TENSORS, lm_head=b"\x04" * 32))
r1 = B.lookup(one, send=send)
print("exact:", r1["exact"], "by tensor:", [(x["matched"], x["badge_tensors"]) for x in r1["by_tensor"]])
assert r1["exact"] == [] and [(x["badge"], x["matched"], x["badge_tensors"]) for x in r1["by_tensor"]] == [(root, 2, 3)]
Output (captured at build)
exact: [] by tensor: [(2, 3)]

When the maker revokes the badge, every lookup and every check says so at once:

http.post("/v1/provenance/revocations", headers=auth, json={"attestation": root, "reason": "withdrawn"})
status = B.lookup(m, send=send)["exact"][0]["status"]
print("after the revocation:", status)
assert status == "revoked"
http.close()
Output (captured at build)
after the revocation: revoked

What it does not prove #

Next: big models in small memory reads and checks a model chunk by chunk.