Cion-lab commited on
Commit
8c59764
·
verified ·
1 Parent(s): c66bf84

publish_model: clean room before the import, cache_dir, two more required card fields, gated != empty (E-046)

Browse files
Files changed (1) hide show
  1. build/publish_model.py +363 -357
build/publish_model.py CHANGED
@@ -1,357 +1,363 @@
1
- """Phase 5: the final weights -> a public model repo with a card that only states measured facts.
2
-
3
- Everything quoted in the card is read back off the Hub at run time — the mix manifest, `audit.json`, the
4
- trainer's `run_summary.json` — rather than retyped from memory, because the card is the artifact a stranger
5
- will trust and `final-report.md` will cite (§3.12: the claim and the evidence must be the same object).
6
-
7
- Gate 5 is not this script: it is `--verify-only` running on a *fresh instance with an empty cache*, which is
8
- the only way to prove nothing the model needs lives on a Kaggle disk. This script therefore ends by printing
9
- the exact command for that second job.
10
- """
11
-
12
- import argparse
13
- import hashlib
14
- import json
15
- import os
16
- import shutil
17
- import struct
18
- import sys
19
- import urllib.request
20
-
21
- MIX = "Cion-lab/ounce100m-mix-v1"
22
- CKPT = "Cion-lab/ounce100m-ckpt"
23
- CARD_FILES = ("config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json",
24
- "special_tokens_map.json", "vocab.json", "merges.txt", "cursor.json",
25
- "run_summary.json", "generation_config.json")
26
-
27
-
28
- def sha(p):
29
- h = hashlib.sha256()
30
- with open(p, "rb") as fh:
31
- for c in iter(lambda: fh.read(1 << 20), b""):
32
- h.update(c)
33
- return h.hexdigest()
34
-
35
-
36
- def safetensors_counts(p):
37
- """(n_tensors, n_params, dtypes) straight from the file header — no torch, so this check runs on a
38
- CPU box and on any image, and it proves the *published bytes* have the parameter count the card claims."""
39
- with open(p, "rb") as fh:
40
- (n,) = struct.unpack("<Q", fh.read(8))
41
- hdr = json.loads(fh.read(n))
42
- total, dtypes = 0, set()
43
- for k, v in hdr.items():
44
- if k == "__metadata__":
45
- continue
46
- cnt = 1
47
- for d in v["shape"]:
48
- cnt *= d
49
- total += cnt
50
- dtypes.add(v["dtype"])
51
- return len([k for k in hdr if k != "__metadata__"]), total, sorted(dtypes)
52
-
53
-
54
- def get_json(url, token=None):
55
- req = urllib.request.Request(url)
56
- if token:
57
- req.add_header("Authorization", f"Bearer {token}")
58
- with urllib.request.urlopen(req, timeout=120) as r:
59
- return json.loads(r.read().decode())
60
-
61
-
62
- def card(cfg, man, aud, run, repo, files, n_params):
63
- p = cfg.get("num_hidden_layers"), cfg.get("hidden_size"), cfg.get("vocab_size")
64
- # The card states the architecture; half of it was typed rather than read, so a variant export would
65
- # have published a description of a model it is not. Derive it and refuse on drift.
66
- frozen = {"num_hidden_layers": 22, "hidden_size": 576, "intermediate_size": 1536,
67
- "num_attention_heads": 9, "num_key_value_heads": 3, "vocab_size": 49152,
68
- "tie_word_embeddings": True, "rms_norm_eps": 1e-5}
69
- drift = {k: (cfg.get(k), v) for k, v in frozen.items() if cfg.get(k) != v}
70
- if drift:
71
- raise SystemExit("config.json does not match the frozen architecture, so the card would be a false "
72
- "statement about this model: " + json.dumps(drift, default=str)[:600])
73
- rope = cfg.get("rope_theta") or (cfg.get("rope_parameters") or {}).get("rope_theta")
74
- cf = man.get('contamination_filter') or {}
75
- tok_consumed = int(run.get("tokens_consumed") or 0)
76
- loss = " -> ".join(str(x) for x in (run.get("prior_loss"), run.get("final_loss")) if x is not None)
77
- # Same rule as the architecture: anything the card states about *this* model comes from its own
78
- # `run_summary.json`, and a field that is not there stops the publish rather than rendering as None.
79
- # The Optimiser/Precision/Batch rows used to be typed prose, which is how a card ends up describing the
80
- # recipe somebody meant to run (review E-045/2).
81
- need = ("optim", "lr", "warmup_frac", "decay_frac", "world", "tokens_per_step", "seq_len",
82
- "micro_batch", "accum", "attn", "grad_ckpt", "tok_per_s", "seed", "data_seed")
83
- absent = [k for k in need if run.get(k) is None]
84
- if absent:
85
- raise SystemExit(f"run_summary.json carries no {absent}, so the card cannot state them without "
86
- "guessing. Publish the summary the trainer wrote, or say in the card what is "
87
- "unknown -- never both.")
88
- geom = run["micro_batch"] * run["accum"] * run["world"] * run["seq_len"]
89
- if geom != run["tokens_per_step"]:
90
- raise SystemExit(f"the batch row would be a false statement: {run['micro_batch']} x "
91
- f"{run['accum']} x {run['world']} x {run['seq_len']} = {geom} != "
92
- f"tokens_per_step {run['tokens_per_step']}")
93
- if run.get("val_ppl") is None and run.get("val_skipped") and run.get("val_loss_error") is None:
94
- val_row = ("not measured on this leg -- a session that stops at a checkpoint boundary skips the "
95
- "validation pass by design; the run's PPL comes from the horizon export")
96
- elif run.get("val_ppl") is None:
97
- val_row = f"NOT MEASURED ({run.get('val_loss_error')})"
98
- else:
99
- val_row = (f"**{run['val_ppl']:.2f}** on {MIX}'s held-out `val/` shards "
100
- f"({man['val_tokens']:,} tokens, never trained on)")
101
- rows = "\n".join(f"| `{k}` | {v['sha256'][:16]}… | {v['bytes']:,} |" for k, v in sorted(files.items()))
102
- return f"""---
103
- license: cc-by-sa-4.0
104
- base_model: {repo}
105
- language: en
106
- library_name: transformers
107
- pipeline_tag: text-generation
108
- tags: [ounce100m, from-scratch, base, decoder-only, {man['tokenizer']['id'].split('/')[0].lower()}]
109
- ---
110
-
111
- # {repo.split('/')[-1]}
112
-
113
- A **{n_params:,}-parameter decoder-only transformer trained from scratch on
114
- {tok_consumed:,} tokens** of `{MIX}`, in {run.get('steps_planned', '?')} optimiser steps on
115
- **2×Nvidia Tesla T4** inside Kaggle notebook sessions. It is the deliverable of a project whose whole point
116
- was to find out what a ~100 M-parameter model reaches from ~1 B tokens of a curated public mix, and to
117
- report it honestly, including where that is near chance.
118
-
119
- ## Measured facts
120
-
121
- | | |
122
- |---|---|
123
- | Parameters | **{n_params:,}** (recomputed from `model.safetensors`'s own header, not asserted) |
124
- | Architecture | {p[0]} layers, hidden {p[1]}, GQA {cfg["num_attention_heads"]} Q / {cfg["num_key_value_heads"]} KV heads, SwiGLU {cfg["intermediate_size"]}, RMSNorm {cfg["rms_norm_eps"]}, RoPE θ={rope}, **tied** embeddings, vocab {p[2]:,} |
125
- | Sequence length | {run['seq_len']} — which is why ARC's 25-shot prompts are truncated from the left by the eval harness |
126
- | Tokens consumed | **{tok_consumed:,}** ({100.0 * tok_consumed / 1e9:.2f} % of the 1.0 B target) |
127
- | Batch | micro {run['micro_batch']} × accum {run['accum']} × {run['world']} ranks = {run['tokens_per_step']:,} tokens/step |
128
- | Optimiser | `{run['optim']}`, LR {run['lr']}, warmup fraction {run['warmup_frac']}, trapezoid decay over the final {100.0 * (1.0 - (run['decay_frac'] or 0)):.1f} % of the schedule |
129
- | Precision | fp16 autocast + fp32 master weights + GradScaler — asserted at the start of every session, and each session's log line `precision: fp16=True bf16=False scaler=GradScaler` is the evidence |
130
- | Throughput | {run['tok_per_s']:,} tok/s in the session that produced this export |
131
- | Attention | `{run.get('effective_attn') or run['attn']}` |
132
- | Gradient checkpointing | `{run['grad_ckpt']}` |
133
- | Randomness | model seed {run['seed']}, data seed {run['data_seed']} |
134
- | Wall clock | {run.get('session_seconds', run.get('seconds', 0)) / 3600.0:.2f} h in the session that produced this export. The run is split across sessions at checkpoint boundaries, so this is **not** the total training time |
135
- | Loss | {loss} |
136
- | Validation PPL | {val_row} |
137
-
138
- ## Data
139
-
140
- `{MIX}`: {man['total_tokens']:,} training tokens in {man['n_shards']} shards + {man['val_tokens']:,}
141
- held-out validation tokens, cut with `{man['tokenizer']['id']}` ({man['tokenizer']['vocab_size']:,} vocab,
142
- Apache-2.0), from {len(man.get('stage') or {})} public sources at ≥{man.get('distinct_sources_per_shard_min')}
143
- per shard. Format and loading code are in that dataset's card.
144
-
145
- **Contamination.** Overlap was measured mechanically against benchmark **train/validation/dev** material of
146
- the eight evaluation tasks (13-token windows, counts only — no benchmark item text was ever read, and test
147
- splits stayed untouched until evaluation). `audit.json` in the dataset repo records
148
- `overlap_total = {aud.get('overlap_total')}` over {aud.get('mix_documents_audited'):,} documents and
149
- {aud.get('val_documents_audited'):,} held-out documents, `tasks_covered` = {len(aud.get('tasks_covered') or [])}/8.
150
- Building it required dropping {cf.get('docs_dropped', '?')} documents
151
- ({cf.get('tokens_dropped', 0):,} tokens)
152
- that matched reference material; the exact exclusion masks ship in `filter/` so the mix is reproducible.
153
-
154
- ## Evaluate it
155
-
156
- ```bash
157
- pip install "lm-eval==0.4.13"
158
- lm_eval --model hf --model_args pretrained={repo},dtype=float16,trust_remote_code=False \\
159
- --tasks arc_challenge,arc_easy,hellaswag,mmlu,piqa,truthfulqa_mc1,truthfulqa_mc2,winogrande,gsm8k \\
160
- --batch_size 8 --seed 42 --log_samples
161
- ```
162
-
163
- The run's own results, with shot counts and chance levels beside every number, are in `eval/` here. Four of
164
- the eight tasks (Winogrande, HellaSwag, PIQA, TruthfulQA) are scored by the harness on *validation* — the
165
- splits this project was allowed to read — and the other four on test.
166
-
167
- ## Files
168
-
169
- | file | sha256 | bytes |
170
- |---|---|---|
171
- {rows}
172
-
173
- `cursor.json` is the data position this checkpoint corresponds to: samples consumed, step, seed, the
174
- corpus fingerprint and a hash of the visit-order permutation, so the resume can be checked rather than
175
- trusted.
176
-
177
- ## Not in this model
178
-
179
- No instruction tuning, no RLHF, no chat template — it is a base model, deliberately. It has ~1 B tokens of
180
- training against the ~300 B of the comparable published reference models, so expect scores at or near
181
- chance on several tasks; that is the experiment's result, not a defect to be engineered around.
182
- """
183
-
184
-
185
- def main():
186
- ap = argparse.ArgumentParser()
187
- ap.add_argument("--repo", default="Cion-lab/ounce100m-v1")
188
- ap.add_argument("--src", default="/kaggle/working/mixroot", help="mix root (for tokenizer.json)")
189
- ap.add_argument("--from-dir", default="", help="local dir holding the trainer's final/ export")
190
- ap.add_argument("--verify-only", action="store_true",
191
- help="fresh-instance clean-room test: download the published repo and load it")
192
- ap.add_argument("--dry-run", action="store_true")
193
- a = ap.parse_args()
194
-
195
- sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # E-028
196
- import ounce100m_credentials
197
- ounce100m_credentials.install(verify=True)
198
- tok = os.environ["HF_TOKEN"]
199
- # Order matters: huggingface_hub resolves its cache locations at import time, so a "clean room" that
200
- # sets HF_HOME afterwards is testing Kaggle's warm disk instead of the Hub (review finding A6).
201
- if a.verify_only:
202
- os.environ["HF_HOME"] = "/tmp/cleanroom_hf"
203
- os.environ["HF_HUB_CACHE"] = "/tmp/cleanroom_hf/hub"
204
- from huggingface_hub import HfApi, create_repo, snapshot_download
205
-
206
- man = get_json(f"https://huggingface.co/datasets/{MIX}/resolve/main/manifest.json")
207
- aud = get_json(f"https://huggingface.co/datasets/{MIX}/resolve/main/audit.json")
208
-
209
- if a.verify_only:
210
- dest = "/tmp/cleanroom_" + os.path.basename(a.repo)
211
- shutil.rmtree(dest, ignore_errors=True)
212
- shutil.rmtree("/tmp/cleanroom_hf", ignore_errors=True)
213
- # Gate 5's whole claim is "a stranger can load this". `install()` above puts HF_TOKEN in the
214
- # environment and `huggingface_hub` picks it up from there, so without this the clean room would
215
- # be authenticated and a private or gated repo would pass (review E-045/1).
216
- for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HUGGING_FACE_TOKEN"):
217
- os.environ.pop(k, None)
218
- got = snapshot_download(a.repo, local_dir=dest, token=False)
219
- print("clean-room download (anonymous) ->", got, flush=True)
220
- import json as _j
221
- cfg = _j.load(open(os.path.join(dest, "config.json")))
222
- n_t, n_p, dt = safetensors_counts(os.path.join(dest, "model.safetensors"))
223
- print("VERIFY tensors", n_t, "params", f"{n_p:,}", "dtypes", dt, flush=True)
224
- import torch
225
- from transformers import AutoModelForCausalLM, AutoTokenizer
226
- tkn = AutoTokenizer.from_pretrained(dest)
227
- try: # transformers 5 renamed torch_dtype; Gate 5 is this very call
228
- m = AutoModelForCausalLM.from_pretrained(dest, dtype=torch.float16)
229
- except TypeError:
230
- m = AutoModelForCausalLM.from_pretrained(dest, torch_dtype=torch.float16)
231
- assert m.num_parameters() == n_p, (m.num_parameters(), n_p)
232
- assert cfg["tie_word_embeddings"] and m.get_input_embeddings().weight.data_ptr() == \
233
- m.get_output_embeddings().weight.data_ptr(), "tied embeddings did not survive the round trip"
234
- g = torch.Generator(device="cpu").manual_seed(20260919)
235
- torch.manual_seed(20260919)
236
- ids = tkn("The city of Paris is", return_tensors="pt").input_ids
237
- out = m.generate(ids, max_new_tokens=24, do_sample=True, temperature=1.0, top_k=50,
238
- top_p=0.9, pad_token_id=tkn.eos_token_id)
239
- text = tkn.decode(out[0], skip_special_tokens=True)
240
- print("GENERATED:", text, flush=True)
241
- print("GEN_SHA", hashlib.sha256(text.encode()).hexdigest()[:16], flush=True)
242
- print("VERDICT GATE5 load_ok=True generate_ok=%s params_ok=%s tied_ok=True vocab=%d"
243
- % (len(out[0]) > ids.shape[1], m.num_parameters() == n_p, cfg["vocab_size"]), flush=True)
244
- return
245
-
246
- src = a.from_dir
247
- if not src:
248
- ptr = get_json(f"https://huggingface.co/datasets/{CKPT}/resolve/main/latest.json", tok)
249
- print("ckpt latest.json ->", {k: ptr.get(k) for k in ("step", "path_in_repo")}, flush=True)
250
- src = snapshot_download(CKPT, repo_type="dataset", allow_patterns=[ptr["path_in_repo"] + "/*"],
251
- local_dir="/kaggle/working/from_hub")
252
- src = os.path.join(src, ptr["path_in_repo"])
253
- have = {f for f in os.listdir(src) if os.path.isfile(os.path.join(src, f))}
254
- need = {"config.json", "model.safetensors"}
255
- if not need <= have:
256
- raise SystemExit(f"{src} is missing {sorted(need - have)} -- nothing to publish")
257
- if "tokenizer.json" not in have and os.path.exists(os.path.join(a.src, "tokenizer.json")):
258
- import shutil
259
- shutil.copy(os.path.join(a.src, "tokenizer.json"), src) # ship the tokenizer that cut the mix
260
- have.add("tokenizer.json")
261
- cfg = json.load(open(os.path.join(src, "config.json")))
262
- run = {}
263
- if os.path.exists(os.path.join(src, "run_summary.json")):
264
- run = json.load(open(os.path.join(src, "run_summary.json")))
265
- n_t, n_p, dt = safetensors_counts(os.path.join(src, "model.safetensors"))
266
- # `params` in run_summary.json is a dict {sum_numel, unique, trainable}; comparing that to an integer
267
- # is always unequal and would have failed every real export (review finding A1).
268
- claim = run.get("params_total") or run.get("params")
269
- if isinstance(claim, dict):
270
- claim = claim.get("sum_numel")
271
- if claim and int(claim) != n_p:
272
- raise SystemExit(f"run_summary claims {claim} params, the published safetensors file has {n_p}")
273
- files = {f: {"sha256": sha(os.path.join(src, f)), "bytes": os.path.getsize(os.path.join(src, f))}
274
- for f in sorted(have) if f in CARD_FILES or f.endswith(".json")}
275
- print("tensors", n_t, "params", f"{n_p:,}", "dtypes", dt, flush=True)
276
- if not a.dry_run and not run:
277
- raise SystemExit("no run_summary.json next to the export: the card would be full of blanks. "
278
- "Pass --from-dir at the trainer's final/ export, or --dry-run to preview.")
279
- readme = card(cfg, man, aud, dict(run, params_total=n_p), a.repo, files, n_p)
280
- print("card:", f"{n_p:,} params from the safetensors header; {len(files)} files hashed", flush=True)
281
- if a.dry_run:
282
- # A preview that writes into the export is not a preview: it leaves a README behind that the next
283
- # real run then treats as one of the files to publish (review E-045, minor).
284
- print(readme.encode("utf-8", "replace").decode("utf-8", "replace"))
285
- return
286
- open(os.path.join(src, "README.md"), "w", encoding="utf-8").write(readme)
287
-
288
- api = HfApi(token=tok)
289
- create_repo(repo_id=a.repo, repo_type="model", private=False, exist_ok=True, token=tok)
290
- up = [(f, os.path.join(src, f)) for f in sorted(os.listdir(src))
291
- if os.path.isfile(os.path.join(src, f))]
292
- local_sha = {f: sha(p) for f, p in up}
293
- remote = {}
294
- try:
295
- for attempt in (1, 2, 3):
296
- try:
297
- for ent in api.model_info(a.repo, files_metadata=True).siblings or []:
298
- lfs = getattr(ent, "lfs", None)
299
- raw = (lfs.get("sha256") or lfs.get("oid")) if isinstance(lfs, dict) else None
300
- remote[ent.rfilename] = raw if isinstance(raw, str) and len(raw) == 64 else None
301
- break
302
- except Exception as e:
303
- # E-034 again: "this repo has nothing in it yet" and "the Hub did not answer" are different
304
- # facts. The first means upload everything; the second, swallowed into `remote = {}` here,
305
- # means silently re-uploading 1.3 GB of bytes that are already on the Hub.
306
- if type(e).__name__ in ("RepositoryNotFoundError", "GatedRepoError"):
307
- print("(remote listing empty -- first publish)", flush=True)
308
- break
309
- if attempt == 3:
310
- raise
311
- print(f"(listing failed {type(e).__name__}, retry {attempt}/3)", flush=True)
312
- import time as _t
313
- _t.sleep(10 * attempt)
314
- except Exception as e:
315
- raise SystemExit(f"cannot read the remote listing after 3 tries ({type(e).__name__}: "
316
- f"{str(e)[:160]}) -- refusing to guess what is already uploaded")
317
- todo = [f for f, _ in up if remote.get(f) != local_sha[f]]
318
- print(f"uploading {len(todo)} of {len(up)} files to {a.repo}", flush=True)
319
- if todo:
320
- for i in range(0, len(todo), 120): # one commit per 120 files: E-033's rate ceiling
321
- b = todo[i:i + 120]
322
- api.upload_folder(repo_id=a.repo, folder_path=src, path_in_repo="",
323
- allow_patterns=b, max_workers=2, repo_type="model",
324
- commit_message=f"publish weights: batch {i // 120 + 1} of {len(b)} file(s)")
325
- back = set(api.list_repo_files(repo_id=a.repo, repo_type="model"))
326
- missing = sorted({f for f, _ in up} - back)
327
- R = {"repo": a.repo, "params": n_p, "tensors": n_t, "files": len(back), "missing": missing}
328
- # Every file, not just the weights and the config: `list_repo_files` proves a name exists, and a
329
- # tokenizer whose bytes did not land loads as a *different* tokenizer, which is the failure that
330
- # silently invalidates every number in Phase 6 (E-031's rule, applied to the model repo).
331
- anon = {}
332
- for f, _ in up:
333
- try:
334
- h, nbytes = hashlib.sha256(), 0 # stream it: 1.7 GB does not belong in RAM
335
- with urllib.request.urlopen(f"https://huggingface.co/{a.repo}/resolve/main/{f}",
336
- timeout=900) as r:
337
- for chunk in iter(lambda: r.read(1 << 20), b""):
338
- nbytes += len(chunk)
339
- h.update(chunk)
340
- anon[f] = {"bytes": nbytes, "sha_ok": h.hexdigest() == local_sha[f]}
341
- except Exception as e:
342
- anon[f] = {"error": f"{type(e).__name__}: {str(e)[:120]}"}
343
- R["anon_readback"] = {k: (v.get("sha_ok") if "sha_ok" in v else v.get("error")) for k, v in anon.items()}
344
- bad = sorted(k for k, v in anon.items() if not v.get("sha_ok"))
345
- R["published_verified"] = bool(not missing and not bad)
346
- if bad:
347
- R["anon_failed"] = bad[:10]
348
- print("PUBLISH_JSON_BEGIN")
349
- print(json.dumps(R, indent=1, default=str))
350
- print("PUBLISH_JSON_END")
351
- print("NEXT (Gate 5, on a fresh instance with an empty cache): "
352
- f"python build/publish_model.py --repo {a.repo} --verify-only", flush=True)
353
- raise SystemExit(0 if R["published_verified"] else 11)
354
-
355
-
356
- if __name__ == "__main__":
357
- main()
 
 
 
 
 
 
 
1
+ """Phase 5: the final weights -> a public model repo with a card that only states measured facts.
2
+
3
+ Everything quoted in the card is read back off the Hub at run time — the mix manifest, `audit.json`, the
4
+ trainer's `run_summary.json` — rather than retyped from memory, because the card is the artifact a stranger
5
+ will trust and `final-report.md` will cite (§3.12: the claim and the evidence must be the same object).
6
+
7
+ Gate 5 is not this script: it is `--verify-only` running on a *fresh instance with an empty cache*, which is
8
+ the only way to prove nothing the model needs lives on a Kaggle disk. This script therefore ends by printing
9
+ the exact command for that second job.
10
+ """
11
+
12
+ import argparse
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import shutil
17
+ import struct
18
+ import sys
19
+ import urllib.request
20
+
21
+ MIX = "Cion-lab/ounce100m-mix-v1"
22
+ CKPT = "Cion-lab/ounce100m-ckpt"
23
+ CARD_FILES = ("config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json",
24
+ "special_tokens_map.json", "vocab.json", "merges.txt", "cursor.json",
25
+ "run_summary.json", "generation_config.json")
26
+
27
+
28
+ def sha(p):
29
+ h = hashlib.sha256()
30
+ with open(p, "rb") as fh:
31
+ for c in iter(lambda: fh.read(1 << 20), b""):
32
+ h.update(c)
33
+ return h.hexdigest()
34
+
35
+
36
+ def safetensors_counts(p):
37
+ """(n_tensors, n_params, dtypes) straight from the file header — no torch, so this check runs on a
38
+ CPU box and on any image, and it proves the *published bytes* have the parameter count the card claims."""
39
+ with open(p, "rb") as fh:
40
+ (n,) = struct.unpack("<Q", fh.read(8))
41
+ hdr = json.loads(fh.read(n))
42
+ total, dtypes = 0, set()
43
+ for k, v in hdr.items():
44
+ if k == "__metadata__":
45
+ continue
46
+ cnt = 1
47
+ for d in v["shape"]:
48
+ cnt *= d
49
+ total += cnt
50
+ dtypes.add(v["dtype"])
51
+ return len([k for k in hdr if k != "__metadata__"]), total, sorted(dtypes)
52
+
53
+
54
+ def get_json(url, token=None):
55
+ req = urllib.request.Request(url)
56
+ if token:
57
+ req.add_header("Authorization", f"Bearer {token}")
58
+ with urllib.request.urlopen(req, timeout=120) as r:
59
+ return json.loads(r.read().decode())
60
+
61
+
62
+ def card(cfg, man, aud, run, repo, files, n_params):
63
+ p = cfg.get("num_hidden_layers"), cfg.get("hidden_size"), cfg.get("vocab_size")
64
+ # The card states the architecture; half of it was typed rather than read, so a variant export would
65
+ # have published a description of a model it is not. Derive it and refuse on drift.
66
+ frozen = {"num_hidden_layers": 22, "hidden_size": 576, "intermediate_size": 1536,
67
+ "num_attention_heads": 9, "num_key_value_heads": 3, "vocab_size": 49152,
68
+ "tie_word_embeddings": True, "rms_norm_eps": 1e-5}
69
+ drift = {k: (cfg.get(k), v) for k, v in frozen.items() if cfg.get(k) != v}
70
+ if drift:
71
+ raise SystemExit("config.json does not match the frozen architecture, so the card would be a false "
72
+ "statement about this model: " + json.dumps(drift, default=str)[:600])
73
+ rope = cfg.get("rope_theta") or (cfg.get("rope_parameters") or {}).get("rope_theta")
74
+ cf = man.get('contamination_filter') or {}
75
+ tok_consumed = int(run.get("tokens_consumed") or 0)
76
+ loss = " -> ".join(str(x) for x in (run.get("prior_loss"), run.get("final_loss")) if x is not None)
77
+ # Same rule as the architecture: anything the card states about *this* model comes from its own
78
+ # `run_summary.json`, and a field that is not there stops the publish rather than rendering as None.
79
+ # The Optimiser/Precision/Batch rows used to be typed prose, which is how a card ends up describing the
80
+ # recipe somebody meant to run (review E-045/2).
81
+ need = ("optim", "lr", "warmup_frac", "decay_frac", "world", "tokens_per_step", "seq_len",
82
+ "micro_batch", "accum", "attn", "grad_ckpt", "tok_per_s", "seed", "data_seed",
83
+ "tokens_consumed", "session_seconds")
84
+ absent = [k for k in need if run.get(k) is None]
85
+ if absent:
86
+ raise SystemExit(f"run_summary.json carries no {absent}, so the card cannot state them without "
87
+ "guessing. Publish the summary the trainer wrote, or say in the card what is "
88
+ "unknown -- never both.")
89
+ geom = run["micro_batch"] * run["accum"] * run["world"] * run["seq_len"]
90
+ if geom != run["tokens_per_step"]:
91
+ raise SystemExit(f"the batch row would be a false statement: {run['micro_batch']} x "
92
+ f"{run['accum']} x {run['world']} x {run['seq_len']} = {geom} != "
93
+ f"tokens_per_step {run['tokens_per_step']}")
94
+ if run.get("val_ppl") is None and run.get("val_skipped") and run.get("val_loss_error") is None:
95
+ val_row = ("not measured on this leg -- a session that stops at a checkpoint boundary skips the "
96
+ "validation pass by design; the run's PPL comes from the horizon export")
97
+ elif run.get("val_ppl") is None:
98
+ val_row = f"NOT MEASURED ({run.get('val_loss_error')})"
99
+ else:
100
+ val_row = (f"**{run['val_ppl']:.2f}** on {MIX}'s held-out `val/` shards "
101
+ f"({man['val_tokens']:,} tokens, never trained on)")
102
+ rows = "\n".join(f"| `{k}` | {v['sha256'][:16]}… | {v['bytes']:,} |" for k, v in sorted(files.items()))
103
+ return f"""---
104
+ license: cc-by-sa-4.0
105
+ base_model: {repo}
106
+ language: en
107
+ library_name: transformers
108
+ pipeline_tag: text-generation
109
+ tags: [ounce100m, from-scratch, base, decoder-only, {man['tokenizer']['id'].split('/')[0].lower()}]
110
+ ---
111
+
112
+ # {repo.split('/')[-1]}
113
+
114
+ A **{n_params:,}-parameter decoder-only transformer trained from scratch on
115
+ {tok_consumed:,} tokens** of `{MIX}`, in {run.get('steps_planned', '?')} optimiser steps on
116
+ **2×Nvidia Tesla T4** inside Kaggle notebook sessions. It is the deliverable of a project whose whole point
117
+ was to find out what a ~100 M-parameter model reaches from ~1 B tokens of a curated public mix, and to
118
+ report it honestly, including where that is near chance.
119
+
120
+ ## Measured facts
121
+
122
+ | | |
123
+ |---|---|
124
+ | Parameters | **{n_params:,}** (recomputed from `model.safetensors`'s own header, not asserted) |
125
+ | Architecture | {p[0]} layers, hidden {p[1]}, GQA {cfg["num_attention_heads"]} Q / {cfg["num_key_value_heads"]} KV heads, SwiGLU {cfg["intermediate_size"]}, RMSNorm {cfg["rms_norm_eps"]}, RoPE θ={rope}, **tied** embeddings, vocab {p[2]:,} |
126
+ | Sequence length | {run['seq_len']} — which is why ARC's 25-shot prompts are truncated from the left by the eval harness |
127
+ | Tokens consumed | **{tok_consumed:,}** ({100.0 * tok_consumed / 1e9:.2f} % of the 1.0 B target) |
128
+ | Batch | micro {run['micro_batch']} × accum {run['accum']} × {run['world']} ranks = {run['tokens_per_step']:,} tokens/step |
129
+ | Optimiser | `{run['optim']}`, LR {run['lr']}, warmup fraction {run['warmup_frac']}, trapezoid decay over the final {100.0 * (1.0 - (run['decay_frac'] or 0)):.1f} % of the schedule |
130
+ | Precision | fp16 autocast + fp32 master weights + GradScaler — asserted at the start of every session, and each session's log line `precision: fp16=True bf16=False scaler=GradScaler` is the evidence |
131
+ | Throughput | {run['tok_per_s']:,} tok/s in the session that produced this export |
132
+ | Attention | `{run.get('effective_attn') or run['attn']}` |
133
+ | Gradient checkpointing | `{run['grad_ckpt']}` |
134
+ | Randomness | model seed {run['seed']}, data seed {run['data_seed']} |
135
+ | Wall clock | {run.get('session_seconds', run.get('seconds', 0)) / 3600.0:.2f} h in the session that produced this export. The run is split across sessions at checkpoint boundaries, so this is **not** the total training time |
136
+ | Loss | {loss} |
137
+ | Validation PPL | {val_row} |
138
+
139
+ ## Data
140
+
141
+ `{MIX}`: {man['total_tokens']:,} training tokens in {man['n_shards']} shards + {man['val_tokens']:,}
142
+ held-out validation tokens, cut with `{man['tokenizer']['id']}` ({man['tokenizer']['vocab_size']:,} vocab,
143
+ Apache-2.0), from {len(man.get('stage') or {})} public sources at ≥{man.get('distinct_sources_per_shard_min')}
144
+ per shard. Format and loading code are in that dataset's card.
145
+
146
+ **Contamination.** Overlap was measured mechanically against benchmark **train/validation/dev** material of
147
+ the eight evaluation tasks (13-token windows, counts only — no benchmark item text was ever read, and test
148
+ splits stayed untouched until evaluation). `audit.json` in the dataset repo records
149
+ `overlap_total = {aud.get('overlap_total')}` over {aud.get('mix_documents_audited'):,} documents and
150
+ {aud.get('val_documents_audited'):,} held-out documents, `tasks_covered` = {len(aud.get('tasks_covered') or [])}/8.
151
+ Building it required dropping {cf.get('docs_dropped', '?')} documents
152
+ ({cf.get('tokens_dropped', 0):,} tokens)
153
+ that matched reference material; the exact exclusion masks ship in `filter/` so the mix is reproducible.
154
+
155
+ ## Evaluate it
156
+
157
+ ```bash
158
+ pip install "lm-eval==0.4.13"
159
+ lm_eval --model hf --model_args pretrained={repo},dtype=float16,trust_remote_code=False \\
160
+ --tasks arc_challenge,arc_easy,hellaswag,mmlu,piqa,truthfulqa_mc1,truthfulqa_mc2,winogrande,gsm8k \\
161
+ --batch_size 8 --seed 42 --log_samples
162
+ ```
163
+
164
+ The run's own results, with shot counts and chance levels beside every number, are in `eval/` here. Four of
165
+ the eight tasks (Winogrande, HellaSwag, PIQA, TruthfulQA) are scored by the harness on *validation* — the
166
+ splits this project was allowed to read — and the other four on test.
167
+
168
+ ## Files
169
+
170
+ | file | sha256 | bytes |
171
+ |---|---|---|
172
+ {rows}
173
+
174
+ `cursor.json` is the data position this checkpoint corresponds to: samples consumed, step, seed, the
175
+ corpus fingerprint and a hash of the visit-order permutation, so the resume can be checked rather than
176
+ trusted.
177
+
178
+ ## Not in this model
179
+
180
+ No instruction tuning, no RLHF, no chat template — it is a base model, deliberately. It has ~1 B tokens of
181
+ training against the ~300 B of the comparable published reference models, so expect scores at or near
182
+ chance on several tasks; that is the experiment's result, not a defect to be engineered around.
183
+ """
184
+
185
+
186
+ def main():
187
+ ap = argparse.ArgumentParser()
188
+ ap.add_argument("--repo", default="Cion-lab/ounce100m-v1")
189
+ ap.add_argument("--src", default="/kaggle/working/mixroot", help="mix root (for tokenizer.json)")
190
+ ap.add_argument("--from-dir", default="", help="local dir holding the trainer's final/ export")
191
+ ap.add_argument("--verify-only", action="store_true",
192
+ help="fresh-instance clean-room test: download the published repo and load it")
193
+ ap.add_argument("--dry-run", action="store_true")
194
+ a = ap.parse_args()
195
+
196
+ # Order matters twice over. huggingface_hub resolves its cache locations at *import* time, and
197
+ # `ounce100m_credentials` imports huggingface_hub -- so a clean room configured after that import is
198
+ # reading Kaggle's warm disk (review finding A6, which the first fix for it did not actually fix:
199
+ # E-046/1). Set the environment before anything is imported, and pass cache_dir explicitly as well,
200
+ # so the claim does not depend on which of the two the library honours.
201
+ if a.verify_only:
202
+ os.environ["HF_HOME"] = "/tmp/cleanroom_hf"
203
+ os.environ["HF_HUB_CACHE"] = "/tmp/cleanroom_hf/hub"
204
+ os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "120"
205
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # E-028
206
+ import ounce100m_credentials
207
+ ounce100m_credentials.install(verify=True)
208
+ tok = os.environ["HF_TOKEN"]
209
+ from huggingface_hub import HfApi, create_repo, snapshot_download
210
+
211
+ man = get_json(f"https://huggingface.co/datasets/{MIX}/resolve/main/manifest.json")
212
+ aud = get_json(f"https://huggingface.co/datasets/{MIX}/resolve/main/audit.json")
213
+
214
+ if a.verify_only:
215
+ dest = "/tmp/cleanroom_" + os.path.basename(a.repo)
216
+ shutil.rmtree(dest, ignore_errors=True)
217
+ shutil.rmtree("/tmp/cleanroom_hf", ignore_errors=True)
218
+ # Gate 5's whole claim is "a stranger can load this". `install()` above puts HF_TOKEN in the
219
+ # environment and `huggingface_hub` picks it up from there, so without this the clean room would
220
+ # be authenticated and a private or gated repo would pass (review E-045/1).
221
+ for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HUGGING_FACE_TOKEN"):
222
+ os.environ.pop(k, None)
223
+ got = snapshot_download(a.repo, local_dir=dest, cache_dir="/tmp/cleanroom_hf/hub",
224
+ token=False)
225
+ print("clean-room download (anonymous) ->", got, flush=True)
226
+ import json as _j
227
+ cfg = _j.load(open(os.path.join(dest, "config.json")))
228
+ n_t, n_p, dt = safetensors_counts(os.path.join(dest, "model.safetensors"))
229
+ print("VERIFY tensors", n_t, "params", f"{n_p:,}", "dtypes", dt, flush=True)
230
+ import torch
231
+ from transformers import AutoModelForCausalLM, AutoTokenizer
232
+ tkn = AutoTokenizer.from_pretrained(dest)
233
+ try: # transformers 5 renamed torch_dtype; Gate 5 is this very call
234
+ m = AutoModelForCausalLM.from_pretrained(dest, dtype=torch.float16)
235
+ except TypeError:
236
+ m = AutoModelForCausalLM.from_pretrained(dest, torch_dtype=torch.float16)
237
+ assert m.num_parameters() == n_p, (m.num_parameters(), n_p)
238
+ assert cfg["tie_word_embeddings"] and m.get_input_embeddings().weight.data_ptr() == \
239
+ m.get_output_embeddings().weight.data_ptr(), "tied embeddings did not survive the round trip"
240
+ g = torch.Generator(device="cpu").manual_seed(20260919)
241
+ torch.manual_seed(20260919)
242
+ ids = tkn("The city of Paris is", return_tensors="pt").input_ids
243
+ out = m.generate(ids, max_new_tokens=24, do_sample=True, temperature=1.0, top_k=50,
244
+ top_p=0.9, pad_token_id=tkn.eos_token_id)
245
+ text = tkn.decode(out[0], skip_special_tokens=True)
246
+ print("GENERATED:", text, flush=True)
247
+ print("GEN_SHA", hashlib.sha256(text.encode()).hexdigest()[:16], flush=True)
248
+ print("VERDICT GATE5 load_ok=True generate_ok=%s params_ok=%s tied_ok=True vocab=%d"
249
+ % (len(out[0]) > ids.shape[1], m.num_parameters() == n_p, cfg["vocab_size"]), flush=True)
250
+ return
251
+
252
+ src = a.from_dir
253
+ if not src:
254
+ ptr = get_json(f"https://huggingface.co/datasets/{CKPT}/resolve/main/latest.json", tok)
255
+ print("ckpt latest.json ->", {k: ptr.get(k) for k in ("step", "path_in_repo")}, flush=True)
256
+ src = snapshot_download(CKPT, repo_type="dataset", allow_patterns=[ptr["path_in_repo"] + "/*"],
257
+ local_dir="/kaggle/working/from_hub")
258
+ src = os.path.join(src, ptr["path_in_repo"])
259
+ have = {f for f in os.listdir(src) if os.path.isfile(os.path.join(src, f))}
260
+ need = {"config.json", "model.safetensors"}
261
+ if not need <= have:
262
+ raise SystemExit(f"{src} is missing {sorted(need - have)} -- nothing to publish")
263
+ if "tokenizer.json" not in have and os.path.exists(os.path.join(a.src, "tokenizer.json")):
264
+ import shutil
265
+ shutil.copy(os.path.join(a.src, "tokenizer.json"), src) # ship the tokenizer that cut the mix
266
+ have.add("tokenizer.json")
267
+ cfg = json.load(open(os.path.join(src, "config.json")))
268
+ run = {}
269
+ if os.path.exists(os.path.join(src, "run_summary.json")):
270
+ run = json.load(open(os.path.join(src, "run_summary.json")))
271
+ n_t, n_p, dt = safetensors_counts(os.path.join(src, "model.safetensors"))
272
+ # `params` in run_summary.json is a dict {sum_numel, unique, trainable}; comparing that to an integer
273
+ # is always unequal and would have failed every real export (review finding A1).
274
+ claim = run.get("params_total") or run.get("params")
275
+ if isinstance(claim, dict):
276
+ claim = claim.get("sum_numel")
277
+ if claim and int(claim) != n_p:
278
+ raise SystemExit(f"run_summary claims {claim} params, the published safetensors file has {n_p}")
279
+ files = {f: {"sha256": sha(os.path.join(src, f)), "bytes": os.path.getsize(os.path.join(src, f))}
280
+ for f in sorted(have) if f in CARD_FILES or f.endswith(".json")}
281
+ print("tensors", n_t, "params", f"{n_p:,}", "dtypes", dt, flush=True)
282
+ if not a.dry_run and not run:
283
+ raise SystemExit("no run_summary.json next to the export: the card would be full of blanks. "
284
+ "Pass --from-dir at the trainer's final/ export, or --dry-run to preview.")
285
+ readme = card(cfg, man, aud, dict(run, params_total=n_p), a.repo, files, n_p)
286
+ print("card:", f"{n_p:,} params from the safetensors header; {len(files)} files hashed", flush=True)
287
+ if a.dry_run:
288
+ # A preview that writes into the export is not a preview: it leaves a README behind that the next
289
+ # real run then treats as one of the files to publish (review E-045, minor).
290
+ print(readme.encode("utf-8", "replace").decode("utf-8", "replace"))
291
+ return
292
+ open(os.path.join(src, "README.md"), "w", encoding="utf-8").write(readme)
293
+
294
+ api = HfApi(token=tok)
295
+ create_repo(repo_id=a.repo, repo_type="model", private=False, exist_ok=True, token=tok)
296
+ up = [(f, os.path.join(src, f)) for f in sorted(os.listdir(src))
297
+ if os.path.isfile(os.path.join(src, f))]
298
+ local_sha = {f: sha(p) for f, p in up}
299
+ remote = {}
300
+ try:
301
+ for attempt in (1, 2, 3):
302
+ try:
303
+ for ent in api.model_info(a.repo, files_metadata=True).siblings or []:
304
+ lfs = getattr(ent, "lfs", None)
305
+ raw = (lfs.get("sha256") or lfs.get("oid")) if isinstance(lfs, dict) else None
306
+ remote[ent.rfilename] = raw if isinstance(raw, str) and len(raw) == 64 else None
307
+ break
308
+ except Exception as e:
309
+ # E-034 again: "this repo has nothing in it yet" and "the Hub did not answer" are different
310
+ # facts. The first means upload everything; the second, swallowed into `remote = {}` here,
311
+ # means silently re-uploading 1.3 GB of bytes that are already on the Hub.
312
+ if type(e).__name__ == "RepositoryNotFoundError":
313
+ print("(remote listing 404 -- this repo has nothing in it yet)", flush=True)
314
+ break
315
+ if attempt == 3:
316
+ raise
317
+ print(f"(listing failed {type(e).__name__}, retry {attempt}/3)", flush=True)
318
+ import time as _t
319
+ _t.sleep(10 * attempt)
320
+ except Exception as e:
321
+ raise SystemExit(f"cannot read the remote listing after 3 tries ({type(e).__name__}: "
322
+ f"{str(e)[:160]}) -- refusing to guess what is already uploaded")
323
+ todo = [f for f, _ in up if remote.get(f) != local_sha[f]]
324
+ print(f"uploading {len(todo)} of {len(up)} files to {a.repo}", flush=True)
325
+ if todo:
326
+ for i in range(0, len(todo), 120): # one commit per 120 files: E-033's rate ceiling
327
+ b = todo[i:i + 120]
328
+ api.upload_folder(repo_id=a.repo, folder_path=src, path_in_repo="",
329
+ allow_patterns=b, max_workers=2, repo_type="model",
330
+ commit_message=f"publish weights: batch {i // 120 + 1} of {len(b)} file(s)")
331
+ back = set(api.list_repo_files(repo_id=a.repo, repo_type="model"))
332
+ missing = sorted({f for f, _ in up} - back)
333
+ R = {"repo": a.repo, "params": n_p, "tensors": n_t, "files": len(back), "missing": missing}
334
+ # Every file, not just the weights and the config: `list_repo_files` proves a name exists, and a
335
+ # tokenizer whose bytes did not land loads as a *different* tokenizer, which is the failure that
336
+ # silently invalidates every number in Phase 6 (E-031's rule, applied to the model repo).
337
+ anon = {}
338
+ for f, _ in up:
339
+ try:
340
+ h, nbytes = hashlib.sha256(), 0 # stream it: 1.7 GB does not belong in RAM
341
+ with urllib.request.urlopen(f"https://huggingface.co/{a.repo}/resolve/main/{f}",
342
+ timeout=900) as r:
343
+ for chunk in iter(lambda: r.read(1 << 20), b""):
344
+ nbytes += len(chunk)
345
+ h.update(chunk)
346
+ anon[f] = {"bytes": nbytes, "sha_ok": h.hexdigest() == local_sha[f]}
347
+ except Exception as e:
348
+ anon[f] = {"error": f"{type(e).__name__}: {str(e)[:120]}"}
349
+ R["anon_readback"] = {k: (v.get("sha_ok") if "sha_ok" in v else v.get("error")) for k, v in anon.items()}
350
+ bad = sorted(k for k, v in anon.items() if not v.get("sha_ok"))
351
+ R["published_verified"] = bool(not missing and not bad)
352
+ if bad:
353
+ R["anon_failed"] = bad[:10]
354
+ print("PUBLISH_JSON_BEGIN")
355
+ print(json.dumps(R, indent=1, default=str))
356
+ print("PUBLISH_JSON_END")
357
+ print("NEXT (Gate 5, on a fresh instance with an empty cache): "
358
+ f"python build/publish_model.py --repo {a.repo} --verify-only", flush=True)
359
+ raise SystemExit(0 if R["published_verified"] else 11)
360
+
361
+
362
+ if __name__ == "__main__":
363
+ main()