yamahei21 commited on
Commit
f1a4107
·
verified ·
1 Parent(s): e218746

Add model-free uzu quant kit

Browse files
configs/config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "qwen35-9b",
3
+ "model": {
4
+ "repo": "huihui-ai/Huihui-Qwen3.5-9B-Claude-4.6-Opus-abliterated",
5
+ "tied_embedding": false,
6
+ "layers": 32,
7
+ "hidden": 4096
8
+ },
9
+ "eval": {
10
+ "max_sequences": 100,
11
+ "max_tokens": 128,
12
+ "min_tokens": 16,
13
+ "corpora": {
14
+ "en": "experiments/qwen35-0.8b/data/eval_en_wikitext2_dedup.txt",
15
+ "ja": "experiments/qwen35-0.8b/data/eval_ja_wikipedia_dedup.txt"
16
+ }
17
+ },
18
+ "calibration": {
19
+ "samples": 8,
20
+ "max_tokens": 512,
21
+ "output_block": "none",
22
+ "output_block_limit": 2048,
23
+ "damping": 0.001,
24
+ "layer_grouped": true,
25
+ "group_size": 4,
26
+ "corpora": {
27
+ "en": "experiments/qwen35-0.8b/data/calibration_en_wikitext2_dedup.txt",
28
+ "ja": "experiments/qwen35-0.8b/data/calibration_ja_wikipedia_dedup.txt",
29
+ "mixed50": "experiments/qwen35-0.8b/data/calibration_mixed_en_ja_dedup.txt",
30
+ "mix65": "experiments/qwen35-0.8b/data/calibration_mixed_ja65_en35_dedup.txt",
31
+ "mix35": "experiments/qwen35-0.8b/data/calibration_mixed_ja35_en65_dedup.txt"
32
+ }
33
+ },
34
+ "quantization": {
35
+ "bits": 4,
36
+ "embedding_bits": 4,
37
+ "group_size": 32,
38
+ "block_size": 32,
39
+ "symmetric": false,
40
+ "layout": "output_input"
41
+ },
42
+ "qad": {
43
+ "optimizer": "adamw",
44
+ "steps": 10,
45
+ "seq": 256,
46
+ "lr": 2e-05,
47
+ "save_every": 5,
48
+ "val_chunks": 2,
49
+ "val_every": 5,
50
+ "parallel": "tensor",
51
+ "corpus": "experiments/qwen35-0.8b/data/calibration_en_wikitext2_dedup.txt",
52
+ "scale_lr": 1e-06,
53
+ "early_stop_patience": 2
54
+ }
55
+ }
data/calibration_en_wikitext2_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/calibration_ja_wikipedia_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/calibration_mixed_en_ja_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/calibration_mixed_ja35_en65_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/calibration_mixed_ja65_en35_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/eval_en_wikitext2_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/eval_ja_wikipedia_dedup.txt ADDED
The diff for this file is too large to render. See raw diff
 
dataset-metadata.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "title": "uzu quant kit public",
3
+ "id": "yamahei21python/uzu-quant-kit-public",
4
+ "licenses": [
5
+ {
6
+ "name": "CC-BY-SA-4.0"
7
+ }
8
+ ],
9
+ "subtitle": "Model-free uzu/lalamo quantization scripts and dedup corpora",
10
+ "description": "Public, model-free kit for reproducing uzu/lalamo INT4 quantization experiments.\n\nscripts/: rht_int4_convert, yaqa_calibration, eval_quantized, compute_bpc, merge_language_hessians, dedup/corpus guards, qad_finetune\nconfigs/: experiments/qwen35-{0.8b,4b,9b}/config.json\ntests/: model-free guard tests, BPC tests, tiny 2-device sharding probe\ndata/: dedup calibration and eval corpora\n\nCorpora:\n- eval_en_wikitext2_dedup.txt / calibration_en_wikitext2_dedup.txt: derived from WikiText-2 (CC BY-SA 4.0)\n- eval_ja_wikipedia_dedup.txt / calibration_ja_wikipedia_dedup.txt: derived from Japanese Wikipedia (CC BY-SA 4.0)\n- mixed*: deterministic EN/JA mixtures of the above\n\nNo model weights are included. No private data.\n\nRules enforced by the scripts:\n- calibration and eval corpora must not overlap (corpus_guard.py)\n- eval must report config_hash, corpus_sha256, and 100 chunks\n- QAD requires student provenance and refuses unverified students\n\nRepository: https://github.com/yamahei21python/uzu",
11
+ "resources": []
12
+ }
scripts/check_experiment.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fail fast when an experiment mixes incompatible eval/calibration settings."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ from collections import defaultdict
10
+ from pathlib import Path
11
+
12
+
13
+ def sha256_file(path: Path) -> str:
14
+ digest = hashlib.sha256()
15
+ with open(path, "rb") as file:
16
+ for chunk in iter(lambda: file.read(1 << 20), b""):
17
+ digest.update(chunk)
18
+ return digest.hexdigest()[:16]
19
+
20
+
21
+ def expected_eval(config: dict, corpus: str) -> dict:
22
+ eval_cfg = config["eval"]
23
+ corpus_path = Path(corpus)
24
+ return {
25
+ "corpus": str(corpus_path),
26
+ "corpus_sha256": sha256_file(corpus_path),
27
+ "max_sequences": eval_cfg["max_sequences"],
28
+ "max_tokens": eval_cfg["max_tokens"],
29
+ "min_tokens": eval_cfg["min_tokens"],
30
+ }
31
+
32
+
33
+ def config_hash(value: dict) -> str:
34
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode("utf-8")).hexdigest()[:16]
35
+
36
+
37
+ def main() -> None:
38
+ parser = argparse.ArgumentParser()
39
+ parser.add_argument("--config", type=Path, required=True)
40
+ parser.add_argument("--root", type=Path, default=None)
41
+ parser.add_argument("--json-out", type=Path, default=None)
42
+ args = parser.parse_args()
43
+
44
+ config = json.loads(args.config.read_text())
45
+ root = args.root or args.config.parent
46
+ eval_cfg = config["eval"]
47
+ calib_cfg = config["calibration"]
48
+ corpora = {Path(path).name: path for path in eval_cfg["corpora"].values()}
49
+ expected_by_name = {name: expected_eval(config, path) for name, path in corpora.items()}
50
+
51
+ errors: list[str] = []
52
+ warnings: list[str] = []
53
+ ppl_rows = []
54
+ baseline_by_corpus: dict[str, list[float]] = defaultdict(list)
55
+
56
+ for path in sorted(root.rglob("ppl_*.json")):
57
+ data = json.loads(path.read_text())
58
+ corpus_name = Path(data.get("corpus", "")).name
59
+ row = {"path": str(path), "corpus": corpus_name}
60
+ ppl_rows.append(row)
61
+
62
+ if corpus_name not in corpora:
63
+ errors.append(f"{path}: unknown corpus {corpus_name!r}")
64
+ continue
65
+
66
+ expected = expected_by_name[corpus_name]
67
+ if data.get("chunks") != expected["max_sequences"]:
68
+ errors.append(
69
+ f"{path}: chunks={data.get('chunks')} != config max_sequences={expected['max_sequences']}"
70
+ )
71
+ if data.get("tokens") is not None and data.get("chunks"):
72
+ approx = data["chunks"] * expected["max_tokens"] - data["chunks"]
73
+ if abs(int(data["tokens"]) - approx) > expected["max_sequences"]:
74
+ warnings.append(
75
+ f"{path}: tokens={data.get('tokens')} differs from approx {approx}"
76
+ )
77
+
78
+ if data.get("config"):
79
+ if data["config"] != expected:
80
+ errors.append(f"{path}: embedded eval config differs from model config")
81
+ if data.get("config_hash") != config_hash(expected):
82
+ errors.append(f"{path}: config_hash mismatch")
83
+ else:
84
+ warnings.append(f"{path}: legacy result without config/config_hash")
85
+
86
+ if "bf16_ppl" in data:
87
+ baseline_by_corpus[corpus_name].append(float(data["bf16_ppl"]))
88
+
89
+ for corpus_name, values in baseline_by_corpus.items():
90
+ if max(values) - min(values) > 0.01:
91
+ errors.append(
92
+ f"BF16 baseline drift for {corpus_name}: {sorted(set(round(value, 4) for value in values))}"
93
+ )
94
+
95
+ calibration_rows = []
96
+ calibration_corpora: set[Path] = set(
97
+ Path(path) for path in calib_cfg.get("corpora", {}).values()
98
+ )
99
+ qad_corpus = config.get("qad", {}).get("corpus")
100
+ if qad_corpus:
101
+ calibration_corpora.add(Path(qad_corpus))
102
+ for path in sorted(root.rglob("calibration.json")):
103
+ data = json.loads(path.read_text())
104
+ row = {"path": str(path), "corpus": Path(data.get("corpus", "")).name}
105
+ calibration_rows.append(row)
106
+ if data.get("corpus"):
107
+ calibration_corpora.add(Path(data["corpus"]))
108
+ checks = {
109
+ "samples": calib_cfg["samples"],
110
+ "max_tokens": calib_cfg["max_tokens"],
111
+ "output_block": calib_cfg["output_block"],
112
+ }
113
+ for key, expected in checks.items():
114
+ if data.get(key) != expected:
115
+ errors.append(f"{path}: {key}={data.get(key)!r} != config {expected!r}")
116
+ damping = float(data.get("damping", -1))
117
+ if abs(damping - float(calib_cfg["damping"])) > 1e-12:
118
+ errors.append(f"{path}: damping={damping} != config {calib_cfg['damping']}")
119
+
120
+ eval_corpora = {Path(path) for path in corpora.values()}
121
+
122
+ def long_lines(path: Path) -> set[str]:
123
+ return {
124
+ line.strip()
125
+ for line in path.read_text(encoding="utf-8").splitlines()
126
+ if len(line.strip()) >= 20
127
+ }
128
+
129
+ for eval_corpus in sorted(eval_corpora):
130
+ if not eval_corpus.exists():
131
+ continue
132
+ lines = [
133
+ line.strip()
134
+ for line in eval_corpus.read_text(encoding="utf-8").splitlines()
135
+ if len(line.strip()) >= 20
136
+ ]
137
+ duplicates = len(lines) - len(set(lines))
138
+ if duplicates:
139
+ errors.append(f"{eval_corpus}: {duplicates} duplicate long lines; dedup required")
140
+
141
+ overlap_checks = 0
142
+ for calibration_corpus in sorted(calibration_corpora):
143
+ if not calibration_corpus.exists():
144
+ errors.append(f"missing calibration corpus: {calibration_corpus}")
145
+ continue
146
+ for eval_corpus in sorted(eval_corpora):
147
+ if not eval_corpus.exists():
148
+ errors.append(f"missing eval corpus: {eval_corpus}")
149
+ continue
150
+ overlap_checks += 1
151
+ if calibration_corpus.resolve() == eval_corpus.resolve():
152
+ errors.append(f"calibration and eval use the same file: {eval_corpus}")
153
+ continue
154
+ overlap = long_lines(calibration_corpus) & long_lines(eval_corpus)
155
+ if overlap:
156
+ sample = next(iter(overlap))[:80]
157
+ errors.append(
158
+ f"corpus overlap: {calibration_corpus} vs {eval_corpus} "
159
+ f"({len(overlap)} lines, e.g. {sample!r})"
160
+ )
161
+
162
+ report = {
163
+ "config": str(args.config),
164
+ "config_name": config.get("name"),
165
+ "ppl_rows": len(ppl_rows),
166
+ "calibration_rows": len(calibration_rows),
167
+ "corpus_overlap_checks": overlap_checks,
168
+ "errors": errors,
169
+ "warnings": warnings,
170
+ "ok": not errors,
171
+ }
172
+ text = json.dumps(report, indent=2, ensure_ascii=False)
173
+ print(text)
174
+ if args.json_out:
175
+ args.json_out.parent.mkdir(parents=True, exist_ok=True)
176
+ args.json_out.write_text(text + "\n")
177
+ raise SystemExit(0 if not errors else 1)
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
scripts/compute_bpc.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Normalize evaluation perplexity to bits-per-character (BPC).
3
+
4
+ PPL is not comparable across languages or tokenizers: a tokenizer with higher
5
+ fertility (tokens per character) spreads the same text over more tokens, which
6
+ inflates PPL. BPC divides the total negative log-likelihood by characters
7
+ instead:
8
+
9
+ BPC = log2(PPL) * tokens / chars = log2(PPL) * fertility
10
+
11
+ Only the public tokenizer is needed. No model weights, no GPU.
12
+
13
+ ``tokens`` here means *scored* positions, matching what ``eval_quantized.py``
14
+ puts in its JSON: each chunk contributes ``len(chunk) - 1`` predictions, since
15
+ the first token of every chunk is only context. The character count is measured
16
+ on the same scored stream: the chunks are rebuilt with the same
17
+ ``chunks_from_text`` logic as ``eval_quantized.py``, the full stream is decoded
18
+ once, and the characters of the skipped first token of each chunk are removed.
19
+ This avoids counting every chunk boundary twice.
20
+
21
+ Usage:
22
+ python scripts/compute_bpc.py \
23
+ --ppl-json out/eval/ppl_en.json \
24
+ --ppl-json out/eval/ppl_ja.json \
25
+ --tokenizer Qwen/Qwen3.5-0.8B
26
+
27
+ python scripts/compute_bpc.py --ppl-json ppl_en.json --tokenizer ./tokenizer-dir --json report.json
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import hashlib
34
+ import json
35
+ import math
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+
40
+ def load_tokenizer(source: str):
41
+ from tokenizers import Tokenizer
42
+
43
+ path = Path(source)
44
+ if path.is_dir():
45
+ return Tokenizer.from_file(str(path / "tokenizer.json"))
46
+ if path.is_file():
47
+ return Tokenizer.from_file(str(path))
48
+ from huggingface_hub import hf_hub_download
49
+
50
+ return Tokenizer.from_file(hf_hub_download(source, "tokenizer.json"))
51
+
52
+
53
+ def chunks_from_text(tokenizer, text: str, max_tokens: int, min_tokens: int, limit: int) -> list[list[int]]:
54
+ """Mirror of eval_quantized.chunks_from_text; must stay identical."""
55
+ ids = tokenizer.encode(text, add_special_tokens=True).ids
56
+ chunks = [ids[start : start + max_tokens] for start in range(0, len(ids), max_tokens)]
57
+ chunks = [chunk for chunk in chunks if len(chunk) >= min_tokens]
58
+ return chunks[:limit]
59
+
60
+
61
+ def read_corpus(path: str) -> str:
62
+ text = Path(path).read_text(encoding="utf-8")
63
+ return text.replace("\x00", "")
64
+
65
+
66
+ def scored_tokens(chunks: list[list[int]]) -> int:
67
+ """Predictions per chunk: every token except the first (context only)."""
68
+ return sum(max(len(chunk) - 1, 0) for chunk in chunks)
69
+
70
+
71
+ def target_chars(tokenizer, chunks: list[list[int]]) -> int:
72
+ """Characters of the scored stream.
73
+
74
+ Decoding the whole stream at once keeps multi-byte characters intact; the
75
+ context-only first token of each chunk is then removed. A token that holds a
76
+ partial UTF-8 sequence at a chunk boundary can shift this by at most one
77
+ character per chunk.
78
+ """
79
+ flat: list[int] = []
80
+ for chunk in chunks:
81
+ flat.extend(chunk)
82
+ full = tokenizer.decode(flat)
83
+ skipped = sum(len(tokenizer.decode([chunk[0]])) for chunk in chunks if chunk)
84
+ return len(full) - skipped
85
+
86
+
87
+ def bpc(ppl: float, tokens: int, chars: int) -> float:
88
+ if chars <= 0:
89
+ raise ValueError("chars must be positive")
90
+ if tokens <= 0:
91
+ raise ValueError("tokens must be positive")
92
+ if ppl <= 0:
93
+ raise ValueError("ppl must be positive")
94
+ return math.log2(ppl) * tokens / chars
95
+
96
+
97
+ def sha256_text(path: str) -> str | None:
98
+ try:
99
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16]
100
+ except OSError:
101
+ return None
102
+
103
+
104
+ def analyze(payload: dict[str, Any], tokenizer_source: str, corpus_override: str | None) -> dict[str, Any]:
105
+ config = payload.get("config") or {}
106
+ corpus = corpus_override or config.get("corpus") or payload.get("corpus")
107
+ if not corpus:
108
+ raise SystemExit("no corpus in PPL JSON; pass --corpus")
109
+ max_tokens = int(config.get("max_tokens", 128))
110
+ min_tokens = int(config.get("min_tokens", 16))
111
+ max_sequences = int(config.get("max_sequences", payload.get("chunks", 0) or 0))
112
+ if max_sequences <= 0:
113
+ raise SystemExit("no max_sequences in PPL JSON; pass --max-sequences")
114
+
115
+ tokenizer = load_tokenizer(tokenizer_source)
116
+ text = read_corpus(corpus)
117
+ chunks = chunks_from_text(tokenizer, text, max_tokens, min_tokens, max_sequences)
118
+ if not chunks:
119
+ raise SystemExit(f"no chunks from {corpus}")
120
+
121
+ tokens = scored_tokens(chunks)
122
+ chars = target_chars(tokenizer, chunks)
123
+ fertility = tokens / chars
124
+
125
+ expected_chunks = payload.get("chunks")
126
+ expected_tokens = payload.get("tokens")
127
+ report: dict[str, Any] = {
128
+ "corpus": corpus,
129
+ "corpus_sha256": sha256_text(corpus),
130
+ "tokenizer": tokenizer_source,
131
+ "config": {
132
+ "max_tokens": max_tokens,
133
+ "min_tokens": min_tokens,
134
+ "max_sequences": max_sequences,
135
+ },
136
+ "chunks": len(chunks),
137
+ "tokens": tokens,
138
+ "chars": chars,
139
+ "tokens_per_char": fertility,
140
+ "reproduced": {
141
+ "chunks_match": expected_chunks is None or expected_chunks == len(chunks),
142
+ "tokens_match": expected_tokens is None or expected_tokens == tokens,
143
+ },
144
+ }
145
+
146
+ for key, value in payload.items():
147
+ if key.endswith("_ppl") and isinstance(value, (int, float)):
148
+ label = key[: -len("_ppl")] or "model"
149
+ report[f"bpc_{label}"] = bpc(float(value), tokens, chars)
150
+ report[f"ppl_{label}"] = float(value)
151
+
152
+ if "delta_nll_per_token" in payload:
153
+ report["bpc_delta"] = float(payload["delta_nll_per_token"]) / math.log(2) * fertility
154
+
155
+ return report
156
+
157
+
158
+ def format_table(reports: list[dict[str, Any]]) -> str:
159
+ lines = [
160
+ "| run | chunks | tokens | chars | tok/char | PPL | BPC |",
161
+ "|---|---:|---:|---:|---:|---:|---:|",
162
+ ]
163
+ for report in reports:
164
+ name = Path(report.get("source", "?")).parent.name or "?"
165
+ ppl = report.get("ppl_candidate", report.get("ppl_bf16"))
166
+ bp = report.get("bpc_candidate", report.get("bpc_bf16"))
167
+ lines.append(
168
+ f"| {name} | {report['chunks']} | {report['tokens']} | {report['chars']} "
169
+ f"| {report['tokens_per_char']:.4f} | {ppl:.2f} | {bp:.4f} |"
170
+ )
171
+ return "\n".join(lines)
172
+
173
+
174
+ def main() -> None:
175
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
176
+ parser.add_argument("--ppl-json", action="append", required=True, help="eval_quantized.py output (repeatable)")
177
+ parser.add_argument("--tokenizer", required=True, help="tokenizer dir, tokenizer.json, or HF repo id")
178
+ parser.add_argument("--corpus", default=None, help="override corpus path recorded in the PPL JSON")
179
+ parser.add_argument("--json", default=None, help="write the report here")
180
+ parser.add_argument("--strict", action="store_true", help="fail when chunk/token counts do not reproduce")
181
+ args = parser.parse_args()
182
+
183
+ reports = []
184
+ failed = False
185
+ for path in args.ppl_json:
186
+ payload = json.loads(Path(path).read_text(encoding="utf-8"))
187
+ report = analyze(payload, args.tokenizer, args.corpus)
188
+ report["source"] = str(path)
189
+ reports.append(report)
190
+ reproduced = report["reproduced"]
191
+ if args.strict and not (reproduced["chunks_match"] and reproduced["tokens_match"]):
192
+ failed = True
193
+ print(f"MISMATCH {path}: {reproduced}")
194
+
195
+ for report in reports:
196
+ print(json.dumps(report, indent=2, ensure_ascii=False))
197
+ print()
198
+ print(format_table(reports))
199
+
200
+ if args.json:
201
+ Path(args.json).write_text(json.dumps(reports, indent=2, ensure_ascii=False), encoding="utf-8")
202
+ print(f"\nwrote {args.json}")
203
+ if failed:
204
+ raise SystemExit(1)
205
+
206
+
207
+ if __name__ == "__main__":
208
+ main()
scripts/corpus_guard.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reject calibration corpora that overlap with evaluation corpora."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+
10
+ def long_lines(path: Path, min_chars: int) -> set[str]:
11
+ return {
12
+ line.strip()
13
+ for line in path.read_text(encoding="utf-8").splitlines()
14
+ if len(line.strip()) >= min_chars
15
+ }
16
+
17
+
18
+ def overlap_lines(calibration: Path, eval_corpora: list[Path], min_chars: int = 20) -> tuple[int, str | None]:
19
+ blocked: set[str] = set()
20
+ for path in eval_corpora:
21
+ blocked |= long_lines(path, min_chars)
22
+ if not blocked:
23
+ return 0, None
24
+ overlap = long_lines(calibration, min_chars) & blocked
25
+ if not overlap:
26
+ return 0, None
27
+ return len(overlap), next(iter(overlap))[:120]
28
+
29
+
30
+ def assert_disjoint(
31
+ calibration: Path,
32
+ eval_corpora: list[Path],
33
+ *,
34
+ min_chars: int = 20,
35
+ allow_overlap: bool = False,
36
+ ) -> None:
37
+ if not eval_corpora:
38
+ if allow_overlap:
39
+ return
40
+ raise SystemExit(
41
+ "at least one --eval-corpus is required; use --allow-overlap only for deliberate analysis"
42
+ )
43
+ for path in eval_corpora:
44
+ if not path.exists():
45
+ raise SystemExit(f"missing eval corpus: {path}")
46
+ count, sample = overlap_lines(calibration, eval_corpora, min_chars)
47
+ if count and not allow_overlap:
48
+ raise SystemExit(
49
+ f"calibration corpus overlaps evaluation corpora: {count} lines "
50
+ f"(e.g. {sample!r}). Deduplicate first or pass --allow-overlap."
51
+ )
52
+
53
+
54
+ def main() -> None:
55
+ parser = argparse.ArgumentParser()
56
+ parser.add_argument("--calibration", type=Path, required=True)
57
+ parser.add_argument("--eval", nargs="+", type=Path, required=True)
58
+ parser.add_argument("--min-chars", type=int, default=20)
59
+ parser.add_argument("--allow-overlap", action="store_true")
60
+ args = parser.parse_args()
61
+ assert_disjoint(
62
+ args.calibration,
63
+ args.eval,
64
+ min_chars=args.min_chars,
65
+ allow_overlap=args.allow_overlap,
66
+ )
67
+ print("corpus guard: ok")
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
scripts/dedup_lines.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Remove duplicate non-empty lines from a corpus, keeping first occurrence."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser()
12
+ parser.add_argument("--input", type=Path, required=True)
13
+ parser.add_argument("--output", type=Path, required=True)
14
+ args = parser.parse_args()
15
+
16
+ lines = args.input.read_text(encoding="utf-8").splitlines()
17
+ seen: set[str] = set()
18
+ kept: list[str] = []
19
+ removed = 0
20
+ for line in lines:
21
+ key = line.strip()
22
+ if key and key in seen:
23
+ removed += 1
24
+ continue
25
+ if key:
26
+ seen.add(key)
27
+ kept.append(line)
28
+ args.output.parent.mkdir(parents=True, exist_ok=True)
29
+ args.output.write_text("\n".join(kept) + "\n", encoding="utf-8")
30
+ print(f"{args.input} -> {args.output}: removed={removed} kept={len(kept)}")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
scripts/eval_quantized.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Teacher-forced evaluation: BF16 vs quantized model on a fixed corpus.
3
+
4
+ Computes, over fixed token chunks:
5
+ * Perplexity (independent chunks; identical chunking for both models)
6
+ * NLL delta per token
7
+ * Top-1 / Top-5 agreement
8
+ * KL(BF16 || candidate)
9
+ * Cosine similarity of logits
10
+ * Top-1 logit margin change
11
+
12
+ No sampling, no generation: the same token sequence is fed to both models.
13
+
14
+ Usage:
15
+ JAX_PLATFORM_NAME=cpu python scripts/eval_quantized.py \
16
+ --bf16-dir /tmp/qwen35_0.8b_bf16_lalamo_lalamo_origcfg \
17
+ --candidate-dir /tmp/qwen35_0.8b_rht_int4_lalamo_lalamo_origcfg \
18
+ --corpus experiments/qwen35-0.8b/data/wikitext2_sample.txt \
19
+ --max-sequences 100 --max-tokens 128 \
20
+ --json-out experiments/qwen35-0.8b/rtn-int4-g32/eval_wikitext2.json
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import hashlib
27
+ import json
28
+ import math
29
+ import os
30
+ import sys
31
+ import time
32
+ from pathlib import Path
33
+
34
+ os.environ.setdefault("JAX_PLATFORM_NAME", "cpu")
35
+
36
+
37
+ def parse_args() -> argparse.Namespace:
38
+ parser = argparse.ArgumentParser()
39
+ parser.add_argument("--bf16-dir", type=Path, required=True)
40
+ parser.add_argument("--candidate-dir", type=Path, required=True)
41
+ parser.add_argument("--corpus", type=Path, required=True, help="UTF-8 text file")
42
+ parser.add_argument("--lalamo-path", default=os.environ.get("LALAMO_PATH", "/tmp/lalamo-direct"))
43
+ parser.add_argument("--max-sequences", type=int, default=100)
44
+ parser.add_argument("--max-tokens", type=int, default=128)
45
+ parser.add_argument("--min-tokens", type=int, default=16)
46
+ parser.add_argument("--json-out", type=Path, default=None)
47
+ parser.add_argument(
48
+ "--progress-jsonl",
49
+ type=Path,
50
+ default=None,
51
+ help="default: <json-out>.progress.jsonl or <candidate-dir>/eval_progress.jsonl",
52
+ )
53
+ return parser.parse_args()
54
+
55
+
56
+ def chunks_from_text(tokenizer, text: str, max_tokens: int, min_tokens: int, limit: int) -> list[list[int]]:
57
+ ids = tokenizer.encode(text, add_special_tokens=True).ids
58
+ chunks = [ids[start : start + max_tokens] for start in range(0, len(ids), max_tokens)]
59
+ chunks = [chunk for chunk in chunks if len(chunk) >= min_tokens]
60
+ return chunks[:limit]
61
+
62
+
63
+ def main() -> None:
64
+ args = parse_args()
65
+ if args.progress_jsonl:
66
+ progress_path = args.progress_jsonl
67
+ elif args.json_out:
68
+ progress_path = args.json_out.with_suffix(".progress.jsonl")
69
+ else:
70
+ progress_path = args.candidate_dir / "eval_progress.jsonl"
71
+ progress_path.parent.mkdir(parents=True, exist_ok=True)
72
+ run_id = time.strftime("%Y%m%d-%H%M%S")
73
+ progress_path.write_text("", encoding="utf-8")
74
+ eval_config = {
75
+ "corpus": str(args.corpus),
76
+ "corpus_sha256": hashlib.sha256(args.corpus.read_bytes()).hexdigest()[:16],
77
+ "max_sequences": args.max_sequences,
78
+ "max_tokens": args.max_tokens,
79
+ "min_tokens": args.min_tokens,
80
+ }
81
+ config_hash = hashlib.sha256(json.dumps(eval_config, sort_keys=True).encode("utf-8")).hexdigest()[:16]
82
+
83
+ def progress(record: dict) -> None:
84
+ record = {"run_id": run_id, "config_hash": config_hash, **record}
85
+ with open(progress_path, "a", encoding="utf-8") as file:
86
+ file.write(json.dumps(record) + "\n")
87
+
88
+ corpus_lines = [
89
+ line.strip()
90
+ for line in args.corpus.read_text(encoding="utf-8").splitlines()
91
+ if line.strip()
92
+ ]
93
+ duplicate_lines = len(corpus_lines) - len(set(corpus_lines))
94
+ if duplicate_lines:
95
+ raise SystemExit(
96
+ f"eval corpus has {duplicate_lines} duplicate non-empty lines; "
97
+ "use scripts/dedup_lines.py first"
98
+ )
99
+ text = "\n".join(corpus_lines)
100
+
101
+ sys.path.insert(0, args.lalamo_path)
102
+
103
+ import jax
104
+ import jax.numpy as jnp
105
+ import numpy as np
106
+
107
+ from lalamo.model import Model
108
+ from lalamo.module import Keychain
109
+ from lalamo.modules import DecoderForwardPassConfig, ForwardPassMode
110
+ from lalamo.utils.sharding import ShardingConfig
111
+ from tokenizers import Tokenizer
112
+
113
+ for label, directory in (("bf16", args.bf16_dir), ("candidate", args.candidate_dir)):
114
+ config_path = directory / "config.json"
115
+ if not config_path.exists():
116
+ raise SystemExit(f"{label}: missing {config_path}")
117
+ lalamo_config = json.loads(config_path.read_text())
118
+ token_codec = lalamo_config.get("token_codec_config", {})
119
+ if "response_format" not in token_codec:
120
+ raise SystemExit(
121
+ f"{label}: {directory} is uzu-normalized; create a lalamo eval copy "
122
+ "(scripts/make_lalamo_eval_copy.py)"
123
+ )
124
+
125
+ def tokenizer_hash(directory: Path) -> str:
126
+ return hashlib.sha256((directory / "tokenizer.json").read_bytes()).hexdigest()
127
+
128
+ if tokenizer_hash(args.bf16_dir) != tokenizer_hash(args.candidate_dir):
129
+ raise SystemExit("bf16/candidate tokenizer.json mismatch")
130
+
131
+ sharding = ShardingConfig.replicated()
132
+ keychain = Keychain.init(seed=0, sharding_config=sharding)
133
+ forward_pass_config = DecoderForwardPassConfig.for_inference(mode=ForwardPassMode.MULTI_TOKEN)
134
+
135
+ print("loading BF16 model...")
136
+ bf16 = Model.load(args.bf16_dir, sharding, dtype=jnp.bfloat16)
137
+ print("loading candidate model...")
138
+ candidate = Model.load(args.candidate_dir, sharding, dtype=jnp.bfloat16)
139
+ tokenizer = Tokenizer.from_file(str(args.bf16_dir / "tokenizer.json"))
140
+ print("loaded")
141
+
142
+ text = "\n".join(corpus_lines)
143
+ chunks = chunks_from_text(tokenizer, text, args.max_tokens, args.min_tokens, args.max_sequences)
144
+ if not chunks:
145
+ raise SystemExit("no chunks: corpus too small or min-tokens too high")
146
+ print(f"chunks: {len(chunks)} mean tokens: {sum(len(c) for c in chunks) / len(chunks):.1f}")
147
+
148
+ def logits_for(model, ids: list[int]) -> np.ndarray:
149
+ token_ids = jnp.asarray([ids], dtype=jnp.int32)
150
+ positions = jnp.arange(len(ids), dtype=jnp.int32)[None, :]
151
+ result = model.decoder(
152
+ token_ids=token_ids,
153
+ token_positions=positions,
154
+ state=None,
155
+ return_updated_state=False,
156
+ lengths_without_padding=None,
157
+ forward_pass_config=forward_pass_config,
158
+ keychain=keychain.split(1)[0],
159
+ )
160
+ return np.asarray(result.logits[0], dtype=np.float32)
161
+
162
+ total_nll_bf16 = 0.0
163
+ total_nll_candidate = 0.0
164
+ total_positions = 0
165
+ top1_matches = 0
166
+ top5_overlap_sum = 0.0
167
+ kl_sum = 0.0
168
+ cosine_sum = 0.0
169
+ margin_delta_sum = 0.0
170
+ started_at = time.time()
171
+
172
+ for index, ids in enumerate(chunks):
173
+ bf_logits = logits_for(bf16, ids)
174
+ qa_logits = logits_for(candidate, ids)
175
+ # Predict token i+1 from position i.
176
+ bf_pred = bf_logits[:-1]
177
+ qa_pred = qa_logits[:-1]
178
+ targets = np.asarray(ids[1:], dtype=np.int64)
179
+
180
+ bf_log_prob = bf_pred - bf_pred.max(axis=-1, keepdims=True)
181
+ bf_log_prob = bf_log_prob - np.log(np.exp(bf_log_prob).sum(axis=-1, keepdims=True))
182
+ qa_log_prob = qa_pred - qa_pred.max(axis=-1, keepdims=True)
183
+ qa_log_prob = qa_log_prob - np.log(np.exp(qa_log_prob).sum(axis=-1, keepdims=True))
184
+
185
+ bf_target_log_prob = bf_log_prob[np.arange(len(targets)), targets]
186
+ qa_target_log_prob = qa_log_prob[np.arange(len(targets)), targets]
187
+ total_nll_bf16 -= float(bf_target_log_prob.sum())
188
+ total_nll_candidate -= float(qa_target_log_prob.sum())
189
+ total_positions += len(targets)
190
+
191
+ bf_top1 = bf_pred.argmax(axis=-1)
192
+ qa_top1 = qa_pred.argmax(axis=-1)
193
+ top1_matches += int((bf_top1 == qa_top1).sum())
194
+
195
+ bf_sorted = np.argsort(-bf_pred, axis=-1)[:, :5]
196
+ qa_sorted = np.argsort(-qa_pred, axis=-1)[:, :5]
197
+ for bf_row, qa_row in zip(bf_sorted, qa_sorted):
198
+ top5_overlap_sum += len(set(bf_row.tolist()) & set(qa_row.tolist())) / 5.0
199
+
200
+ bf_prob = np.exp(bf_log_prob)
201
+ qa_prob = np.exp(qa_log_prob)
202
+ kl_sum += float(
203
+ np.sum(bf_prob * (np.log(bf_prob + 1e-45) - np.log(qa_prob + 1e-45)), axis=-1).sum()
204
+ )
205
+ cosine_sum += float(
206
+ (
207
+ np.sum(bf_pred * qa_pred, axis=-1)
208
+ / (np.linalg.norm(bf_pred, axis=-1) * np.linalg.norm(qa_pred, axis=-1) + 1e-45)
209
+ ).sum()
210
+ )
211
+
212
+ bf_margin = np.sort(bf_pred, axis=-1)[:, -1] - np.sort(bf_pred, axis=-1)[:, -2]
213
+ qa_margin = np.sort(qa_pred, axis=-1)[:, -1] - np.sort(qa_pred, axis=-1)[:, -2]
214
+ margin_delta_sum += float(np.abs(bf_margin - qa_margin).sum())
215
+
216
+ if total_positions:
217
+ progress(
218
+ {
219
+ "chunk": index + 1,
220
+ "chunks": len(chunks),
221
+ "tokens": total_positions,
222
+ "bf16_ppl": math.exp(total_nll_bf16 / total_positions),
223
+ "candidate_ppl": math.exp(total_nll_candidate / total_positions),
224
+ "delta_nll_per_token": (total_nll_candidate - total_nll_bf16) / total_positions,
225
+ "top1_agreement": top1_matches / total_positions,
226
+ "kl_bf16_candidate": kl_sum / total_positions,
227
+ "elapsed_s": time.time() - started_at,
228
+ }
229
+ )
230
+ if (index + 1) % 10 == 0 or index + 1 == len(chunks):
231
+ print(f" {index + 1}/{len(chunks)} chunks")
232
+
233
+ mean_nll_bf16 = total_nll_bf16 / total_positions
234
+ mean_nll_candidate = total_nll_candidate / total_positions
235
+ results = {
236
+ "bf16_dir": str(args.bf16_dir),
237
+ "candidate_dir": str(args.candidate_dir),
238
+ "corpus": str(args.corpus),
239
+ "config": eval_config,
240
+ "config_hash": config_hash,
241
+ "chunks": len(chunks),
242
+ "tokens": total_positions,
243
+ "bf16_ppl": math.exp(mean_nll_bf16),
244
+ "candidate_ppl": math.exp(mean_nll_candidate),
245
+ "delta_nll_per_token": mean_nll_candidate - mean_nll_bf16,
246
+ "top1_agreement": top1_matches / total_positions,
247
+ "top5_overlap": top5_overlap_sum / total_positions,
248
+ "kl_bf16_candidate": kl_sum / total_positions,
249
+ "cosine_logits": cosine_sum / total_positions,
250
+ "mean_abs_top1_margin_delta": margin_delta_sum / total_positions,
251
+ }
252
+ print(json.dumps(results, indent=2))
253
+ if args.json_out:
254
+ args.json_out.parent.mkdir(parents=True, exist_ok=True)
255
+ args.json_out.write_text(json.dumps(results, indent=2) + "\n")
256
+ print(f"saved {args.json_out}")
257
+
258
+
259
+ if __name__ == "__main__":
260
+ main()
scripts/make_lalamo_eval_copy.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Create a lalamo-loadable evaluation copy from a uzu-normalized model directory.
3
+
4
+ Conversion rewrites two things for uzu:
5
+ * config.json (strict fields, no response_format)
6
+ * HybridSpec metadata (flat form, original kept as model.safetensors.lalamo.bak)
7
+
8
+ lalamo evaluation (PPL / logits) needs the opposite form. This script links the
9
+ original weights and writes a lalamo config without duplicating tensor bytes.
10
+
11
+ Usage:
12
+ python scripts/make_lalamo_eval_copy.py \
13
+ --source /tmp/qwen35_0.8b_rht_int4_lalamo \
14
+ --dest /tmp/qwen35_0.8b_rht_int4_lalamo_lalamo
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import shutil
23
+ from pathlib import Path
24
+
25
+ RESPONSE_FORMAT = {
26
+ "reasoning_pattern": r"(?: response|(?:(?: think|(?=.* response))(?P<chain_of_thought>.*?)(?: response\s*|\Z)))?(?P<response>.*)",
27
+ "prefixes": [" think", " response"],
28
+ "turn_pattern": None,
29
+ "tool_calls": {
30
+ "tags": ["<tool_call>", "</tool_call>"],
31
+ "function_pattern": r"<function=([^>\n]+)>(.*?)</function>",
32
+ "parameter_pattern": r"<parameter=([^>\n]+)>\n?(.*?)\n?</parameter>",
33
+ },
34
+ }
35
+
36
+
37
+ def link_or_copy(source: Path, destination: Path) -> None:
38
+ if destination.exists():
39
+ destination.unlink()
40
+ try:
41
+ os.link(source, destination)
42
+ except OSError:
43
+ shutil.copy2(source, destination)
44
+
45
+
46
+ def lalamo_config(source: Path) -> dict:
47
+ saved = source / "config.lalamo.json"
48
+ if saved.exists():
49
+ return json.loads(saved.read_text())
50
+
51
+ config = json.loads((source / "config.json").read_text())
52
+ token_codec = config.get("token_codec_config")
53
+ if token_codec is not None:
54
+ token_codec.pop("end_of_thinking_tag", None)
55
+ token_codec.pop("output_parser_regex", None)
56
+ token_codec["response_format"] = RESPONSE_FORMAT
57
+ return config
58
+
59
+
60
+ def main() -> None:
61
+ parser = argparse.ArgumentParser()
62
+ parser.add_argument("--source", type=Path, required=True)
63
+ parser.add_argument("--dest", type=Path, required=True)
64
+ args = parser.parse_args()
65
+
66
+ args.dest.mkdir(parents=True, exist_ok=True)
67
+ (args.dest / "config.json").write_text(json.dumps(lalamo_config(args.source), indent=2) + "\n")
68
+
69
+ weights = args.source / "model.safetensors"
70
+ original_weights = args.source / "model.safetensors.lalamo.bak"
71
+ link_or_copy(original_weights if original_weights.exists() else weights, args.dest / "model.safetensors")
72
+
73
+ for name in ("tokenizer.json", "encoding.json"):
74
+ source = args.source / name
75
+ if source.exists():
76
+ link_or_copy(source, args.dest / name)
77
+
78
+ print(f"created {args.dest}")
79
+ for file in sorted(args.dest.iterdir()):
80
+ print(f" {file.name}: {file.stat().st_size / 1e6:.1f} MB")
81
+
82
+
83
+ if __name__ == "__main__":
84
+ main()
scripts/merge_calibration_groups.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate and merge layer-grouped YAQA calibration NPZ files."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import os
8
+ import re
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ GROUP_RE = re.compile(r"group-(\d+)-(\d+)\.npz$")
14
+ LAYER_RE = re.compile(r"/\[(\d+)\]/")
15
+
16
+
17
+ def parse_args() -> argparse.Namespace:
18
+ parser = argparse.ArgumentParser()
19
+ parser.add_argument("--output", type=Path, required=True)
20
+ parser.add_argument("--layers", type=int, required=True)
21
+ parser.add_argument("--group-size", type=int, default=4)
22
+ parser.add_argument("inputs", nargs="+", type=Path)
23
+ return parser.parse_args()
24
+
25
+
26
+ def main() -> None:
27
+ args = parse_args()
28
+ expected = []
29
+ for start in range(0, args.layers, args.group_size):
30
+ end = min(start + args.group_size, args.layers)
31
+ expected.append((start, end))
32
+
33
+ seen_ranges: dict[tuple[int, int], Path] = {}
34
+ merged: dict[str, np.ndarray] = {}
35
+ covered_layers: set[int] = set()
36
+
37
+ for path in args.inputs:
38
+ match = GROUP_RE.search(path.name)
39
+ if not match:
40
+ raise SystemExit(f"unexpected group filename: {path}")
41
+ start, end = int(match.group(1)), int(match.group(2))
42
+ if (start, end) in seen_ranges:
43
+ raise SystemExit(f"duplicate group {start}-{end}: {seen_ranges[(start, end)]} and {path}")
44
+ seen_ranges[(start, end)] = path
45
+
46
+ with np.load(path) as data:
47
+ keys = [key for key in data.files if key != "__meta__"]
48
+ if not keys:
49
+ raise SystemExit(f"empty group: {path}")
50
+ for key in keys:
51
+ layer_match = LAYER_RE.search(key)
52
+ if not layer_match:
53
+ raise SystemExit(f"key has no layer index: {key} in {path}")
54
+ layer = int(layer_match.group(1))
55
+ if not (start <= layer < end):
56
+ raise SystemExit(f"key {key} outside group {start}-{end} in {path}")
57
+ if key in merged:
58
+ raise SystemExit(f"duplicate calibration key: {key}")
59
+ merged[key] = data[key]
60
+ covered_layers.add(layer)
61
+
62
+ missing_groups = [f"{start}-{end}" for start, end in expected if (start, end) not in seen_ranges]
63
+ if missing_groups:
64
+ raise SystemExit(f"missing groups: {missing_groups}")
65
+ missing_layers = sorted(set(range(args.layers)) - covered_layers)
66
+ if missing_layers:
67
+ raise SystemExit(f"missing layers: {missing_layers}")
68
+
69
+ args.output.parent.mkdir(parents=True, exist_ok=True)
70
+ tmp = args.output.with_name(args.output.name + ".tmp.npz")
71
+ np.savez(tmp, **merged)
72
+ os.replace(tmp, args.output)
73
+ print(
74
+ f"merged {len(seen_ranges)} groups / {len(merged)} arrays / "
75
+ f"{len(covered_layers)} layers -> {args.output}"
76
+ )
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
scripts/merge_language_hessians.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Merge EN/JA raw Hessian calibrations with per-language normalization."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+
14
+ def parse_args() -> argparse.Namespace:
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("--en", type=Path, required=True)
17
+ parser.add_argument("--ja", type=Path, required=True)
18
+ parser.add_argument("--ja-ratio", type=float, default=0.5)
19
+ parser.add_argument("--damping", type=float, default=1e-3)
20
+ parser.add_argument("--output", type=Path, required=True)
21
+ parser.add_argument("--json-out", type=Path, default=None)
22
+ return parser.parse_args()
23
+
24
+
25
+ def normalize(matrix: np.ndarray) -> np.ndarray:
26
+ scale = float(np.mean(np.diagonal(matrix, axis1=-2, axis2=-1)))
27
+ return matrix / max(scale, 1e-30)
28
+
29
+
30
+ def regularize(matrix: np.ndarray, damping: float) -> tuple[np.ndarray, float | None]:
31
+ sigma = damping
32
+ for _ in range(8):
33
+ candidate = matrix + np.eye(matrix.shape[-1], dtype=matrix.dtype) * sigma
34
+ try:
35
+ np.linalg.cholesky(candidate)
36
+ return candidate.astype(np.float32), sigma
37
+ except np.linalg.LinAlgError:
38
+ sigma *= 10.0
39
+ eigenvalues, eigenvectors = np.linalg.eigh(matrix)
40
+ eigenvalues = np.clip(eigenvalues, 1e-6, None)
41
+ rebuilt = (eigenvectors * eigenvalues[..., None, :]) @ np.swapaxes(eigenvectors, -1, -2)
42
+ return rebuilt.astype(np.float32), None
43
+
44
+
45
+ def main() -> None:
46
+ args = parse_args()
47
+ if not 0.0 <= args.ja_ratio <= 1.0:
48
+ raise SystemExit("--ja-ratio must be within [0, 1]")
49
+
50
+ with np.load(args.en) as en_data, np.load(args.ja) as ja_data:
51
+ en_keys = set(en_data.files)
52
+ ja_keys = set(ja_data.files)
53
+ keys = sorted(en_keys & ja_keys)
54
+ if not keys:
55
+ raise SystemExit("EN/JA calibration have no common keys")
56
+ if en_keys != ja_keys:
57
+ print(f"warning: key mismatch en_only={sorted(en_keys - ja_keys)} ja_only={sorted(ja_keys - en_keys)}")
58
+
59
+ arrays: dict[str, np.ndarray] = {}
60
+ records = []
61
+ for key in keys:
62
+ en = np.asarray(en_data[key], dtype=np.float64)
63
+ ja = np.asarray(ja_data[key], dtype=np.float64)
64
+ if en.shape != ja.shape:
65
+ raise SystemExit(f"shape mismatch for {key}: {en.shape} vs {ja.shape}")
66
+ mixed = (1.0 - args.ja_ratio) * normalize(en) + args.ja_ratio * normalize(ja)
67
+ mixed, used_damping = regularize(mixed, args.damping)
68
+ arrays[key] = mixed
69
+ records.append(
70
+ {
71
+ "key": key,
72
+ "shape": list(mixed.shape),
73
+ "damping": used_damping,
74
+ "en_trace": float(np.trace(normalize(en), axis1=-2, axis2=-1).sum()),
75
+ "ja_trace": float(np.trace(normalize(ja), axis1=-2, axis2=-1).sum()),
76
+ }
77
+ )
78
+
79
+ args.output.parent.mkdir(parents=True, exist_ok=True)
80
+ tmp = args.output.with_name(args.output.name + ".tmp")
81
+ np.savez(tmp, **arrays)
82
+ os.replace(tmp, args.output)
83
+
84
+ summary = {
85
+ "en": str(args.en),
86
+ "ja": str(args.ja),
87
+ "ja_ratio": args.ja_ratio,
88
+ "damping": args.damping,
89
+ "arrays": len(arrays),
90
+ "overlap_checked": True,
91
+ "calibration_corpora": [str(args.en), str(args.ja)],
92
+ "records": records,
93
+ }
94
+ if args.json_out:
95
+ args.json_out.parent.mkdir(parents=True, exist_ok=True)
96
+ args.json_out.write_text(json.dumps(summary, indent=2) + "\n")
97
+ print(f"merged {len(arrays)} arrays -> {args.output}")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
scripts/qad_finetune.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Minimal Quantization-Aware Distillation (QAD) for lalamo HybridMatrix models.
3
+
4
+ Pipeline:
5
+ 1. Load a BF16 teacher and an RHT+INT4 PTQ student (lalamo format).
6
+ 2. Switch student HybridMatrix nodes to CompressionImplementation.TRAINING.
7
+ 3. Teacher-forced forward on a corpus; KL(teacher || student) loss.
8
+ 4. Optimize:
9
+ - master_weights: Muon (optax.contrib.muon)
10
+ - scales / zero points: AdamW
11
+ with deterministic STE from lalamo's rounding.
12
+ 5. Switch back to INFERENCE, save, rewrite metadata for uzu.
13
+
14
+ This is a first-stage QAD: the loss uses teacher-forced corpus text. For the
15
+ full Mirai recipe, replace the corpus with teacher-generated rollouts.
16
+
17
+ Usage:
18
+ JAX_PLATFORM_NAME=cpu python scripts/qad_finetune.py \
19
+ --teacher-dir /tmp/qwen35_0.8b_bf16_lalamo_lalamo_origcfg \
20
+ --student-dir /tmp/qwen35_0.8b_yaqa_hin_hout_lalamo_eval \
21
+ --corpus experiments/qwen35-0.8b/data/calibration_en_wikitext2_dedup.txt \
22
+ --eval-corpus experiments/qwen35-0.8b/data/eval_en_wikitext2.txt \
23
+ --eval-corpus experiments/qwen35-0.8b/data/eval_ja_wikipedia.txt \
24
+ --output-dir /tmp/qwen35_0.8b_qad_lalamo \
25
+ --steps 50 --seq 128 --lr 1e-4
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import hashlib
32
+ import json
33
+ import os
34
+ import pickle
35
+ import shutil
36
+ import sys
37
+ import time
38
+ from pathlib import Path
39
+
40
+ os.environ.setdefault("JAX_PLATFORM_NAME", "cpu")
41
+
42
+
43
+ def parse_args() -> argparse.Namespace:
44
+ parser = argparse.ArgumentParser()
45
+ parser.add_argument("--teacher-dir", type=Path, required=True)
46
+ parser.add_argument("--student-dir", type=Path, required=True)
47
+ parser.add_argument("--output-dir", type=Path, required=True)
48
+ parser.add_argument("--corpus", type=Path, required=True)
49
+ parser.add_argument("--eval-corpus", type=Path, action="append", default=[], help="evaluation corpus to keep disjoint")
50
+ parser.add_argument("--allow-overlap", action="store_true", help="allow training/eval overlap for analysis only")
51
+ parser.add_argument("--lalamo-path", default=os.environ.get("LALAMO_PATH", "/tmp/lalamo-direct"))
52
+ parser.add_argument("--steps", type=int, default=50)
53
+ parser.add_argument("--seq", type=int, default=128)
54
+ parser.add_argument("--lr", type=float, default=1e-4)
55
+ parser.add_argument("--muon-lr", type=float, default=1e-3)
56
+ parser.add_argument(
57
+ "--optimizer",
58
+ choices=("muon", "adamw"),
59
+ default="muon",
60
+ help="muon: master=Muon + scales=AdamW; adamw: all trainables=AdamW",
61
+ )
62
+ parser.add_argument("--adam-b1", type=float, default=0.9)
63
+ parser.add_argument("--adam-b2", type=float, default=0.95, help="short QAD (<100 steps) uses 0.95, not 0.999")
64
+ parser.add_argument("--scale-min", type=float, default=1e-6, help="lower clamp for scale params; 0 disables")
65
+ parser.add_argument("--grad-clip", type=float, default=1.0, help="global norm clip; 0 disables")
66
+ parser.add_argument("--scale-lr", type=float, default=1e-6, help="AdamW lr for scales/zero-points")
67
+ parser.add_argument("--early-stop-patience", type=int, default=2, help="stop after N non-improving val evals")
68
+ parser.add_argument("--student-provenance", type=Path, default=None, help="default: <student-dir>/provenance.json")
69
+ parser.add_argument("--allow-unverified-student", action="store_true")
70
+ parser.add_argument("--temperature", type=float, default=1.0)
71
+ parser.add_argument("--seed", type=int, default=0)
72
+ parser.add_argument("--val-chunks", type=int, default=2, help="fixed chunks used for comparable validation loss")
73
+ parser.add_argument("--val-every", type=int, default=5, help="evaluate fixed validation chunks every N steps")
74
+ parser.add_argument("--save-every", type=int, default=10, help="checkpoint interval; 0 = only final")
75
+ parser.add_argument("--checkpoint-dir", type=Path, default=None, help="default: <output-dir>/checkpoints")
76
+ parser.add_argument("--resume", default=None, help="'auto' or a checkpoint directory")
77
+ parser.add_argument("--keep-checkpoints", type=int, default=2, help="retain the newest N checkpoints")
78
+ parser.add_argument("--parallel", choices=("replicated", "tensor", "fsdp", "data"), default="replicated")
79
+ parser.add_argument("--dry-run", action="store_true")
80
+ return parser.parse_args()
81
+
82
+
83
+ def main() -> None:
84
+ args = parse_args()
85
+ sys.path.insert(0, args.lalamo_path)
86
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
87
+
88
+ from corpus_guard import assert_disjoint
89
+
90
+ assert_disjoint(args.corpus, args.eval_corpus, allow_overlap=args.allow_overlap)
91
+
92
+ import equinox as eqx
93
+ import jax
94
+ import jax.numpy as jnp
95
+ import numpy as np
96
+ import optax
97
+
98
+ from lalamo.compressed.hybrid import HybridMatrix
99
+ from lalamo.model import Model
100
+ from lalamo.module import Keychain
101
+ from lalamo.modules import DecoderForwardPassConfig, ForwardPassMode
102
+ from lalamo.utils.sharding import ShardingConfig
103
+ from lalamo.utils.surgery import map_nodes_of_type_with_path
104
+ from lalamo.weight_matrix import CompressionImplementation, GradientEstimator
105
+
106
+ from normalize_lalamo_config import normalize
107
+ from rewrite_lalamo_hybrid_spec import rewrite
108
+
109
+ if args.parallel == "tensor":
110
+ sharding = ShardingConfig.tensor_parallel()
111
+ elif args.parallel == "fsdp":
112
+ sharding = ShardingConfig.fully_sharded_data_parallel()
113
+ elif args.parallel == "data":
114
+ sharding = ShardingConfig.data_parallel()
115
+ else:
116
+ sharding = ShardingConfig.replicated()
117
+ keychain = Keychain.init(seed=args.seed, sharding_config=sharding)
118
+ inference_config = DecoderForwardPassConfig.for_inference(mode=ForwardPassMode.MULTI_TOKEN)
119
+ training_config = DecoderForwardPassConfig.for_training(
120
+ gradient_estimator=GradientEstimator.DETERMINISTIC_ROUNDING
121
+ )
122
+
123
+ def tokenizer_hash(directory: Path) -> str:
124
+ return hashlib.sha256((directory / "tokenizer.json").read_bytes()).hexdigest()
125
+
126
+ for label, directory in (("teacher", args.teacher_dir), ("student", args.student_dir)):
127
+ config = json.loads((directory / "config.json").read_text())
128
+ if "response_format" not in config.get("token_codec_config", {}):
129
+ raise SystemExit(
130
+ f"{label}: {directory} is uzu-normalized; QAD requires raw lalamo config"
131
+ )
132
+ if tokenizer_hash(args.teacher_dir) != tokenizer_hash(args.student_dir):
133
+ raise SystemExit("teacher/student tokenizer.json mismatch")
134
+
135
+ provenance_path = args.student_provenance or (args.student_dir / "provenance.json")
136
+ if not provenance_path.exists():
137
+ if not args.allow_unverified_student:
138
+ raise SystemExit(
139
+ f"student provenance missing: {provenance_path}. "
140
+ "Rebuild the student with a clean calibration or pass --allow-unverified-student for analysis."
141
+ )
142
+ provenance = {"overlap_checked": False, "kind": "unknown"}
143
+ else:
144
+ provenance = json.loads(provenance_path.read_text(encoding="utf-8"))
145
+ if not provenance.get("overlap_checked") and not args.allow_unverified_student:
146
+ raise SystemExit(
147
+ f"student provenance says overlap_checked=false: {provenance_path}"
148
+ )
149
+ print(f"student provenance: kind={provenance.get('kind')} overlap_checked={provenance.get('overlap_checked')}")
150
+
151
+ print("loading teacher...")
152
+ teacher = Model.load(args.teacher_dir, sharding, dtype=jnp.bfloat16)
153
+ print("loading student...")
154
+ student = Model.load(args.student_dir, sharding, dtype=jnp.bfloat16)
155
+
156
+ def to_training(path, matrix: HybridMatrix) -> HybridMatrix:
157
+ return matrix.switch_implementation(CompressionImplementation.TRAINING)
158
+
159
+ student = map_nodes_of_type_with_path(HybridMatrix, to_training, student)
160
+ print("student switched to TRAINING implementation")
161
+
162
+ def logits_for(model, ids, config):
163
+ token_ids = jnp.asarray([ids], dtype=jnp.int32)
164
+ positions = jnp.arange(len(ids), dtype=jnp.int32)[None, :]
165
+ result = model.decoder(
166
+ token_ids=token_ids,
167
+ token_positions=positions,
168
+ state=None,
169
+ return_updated_state=False,
170
+ lengths_without_padding=None,
171
+ forward_pass_config=config,
172
+ keychain=keychain.split(1)[0],
173
+ )
174
+ return result.logits[0]
175
+
176
+ texts = [line.strip() for line in args.corpus.read_text(encoding="utf-8").splitlines() if line.strip()]
177
+ token_ids = teacher.token_codec.tokenizer.encode("\n\n".join(texts), add_special_tokens=True).ids
178
+ chunks = [token_ids[start : start + args.seq] for start in range(0, len(token_ids), args.seq)]
179
+ chunks = [chunk for chunk in chunks if len(chunk) >= 16]
180
+ if not chunks:
181
+ raise SystemExit("no usable calibration chunks")
182
+ print(f"chunks: {len(chunks)} x {args.seq} tokens")
183
+ val_ids = chunks[-args.val_chunks :] if args.val_chunks > 0 else []
184
+
185
+ def collect_params(model):
186
+ params = {}
187
+ for path, leaf in jax.tree_util.tree_flatten_with_path(model)[0]:
188
+ key = jax.tree_util.keystr(path)
189
+ if any(name in key for name in ("master_weights", "scales", "master_zero_points")) and isinstance(leaf, jax.Array):
190
+ params[key] = leaf
191
+ return params
192
+
193
+ def inject_params(model, params):
194
+ return jax.tree_util.tree_map_with_path(
195
+ lambda path, leaf: params.get(jax.tree_util.keystr(path), leaf),
196
+ model,
197
+ )
198
+
199
+ params = collect_params(student)
200
+ print(f"trainable arrays: {len(params)}")
201
+ total_elements = sum(int(np.prod(value.shape)) for value in params.values())
202
+ print(f"trainable elements: {total_elements / 1e6:.1f}M")
203
+
204
+ def is_scale_key(key: str) -> bool:
205
+ return key.endswith("scales") or key.endswith("master_zero_points")
206
+
207
+ if args.optimizer == "adamw":
208
+ labels = {
209
+ key: ("scale" if is_scale_key(key) else "weight")
210
+ for key in params
211
+ }
212
+ optimizer = optax.multi_transform(
213
+ {
214
+ "weight": optax.adamw(args.lr, b1=args.adam_b1, b2=args.adam_b2, weight_decay=0.0),
215
+ "scale": optax.adamw(args.scale_lr, b1=args.adam_b1, b2=args.adam_b2, weight_decay=0.0),
216
+ },
217
+ labels,
218
+ )
219
+ print(f"optimizer: AdamW weight_lr={args.lr} scale_lr={args.scale_lr}", flush=True)
220
+ else:
221
+ labels = {
222
+ key: (
223
+ "muon"
224
+ if key.endswith("master_weights") and value.ndim >= 2
225
+ else "scale"
226
+ if is_scale_key(key)
227
+ else "adam"
228
+ )
229
+ for key, value in params.items()
230
+ }
231
+ optimizer = optax.multi_transform(
232
+ {
233
+ "muon": optax.contrib.muon(args.muon_lr),
234
+ # weight_decay=0.0 is required: optax.adamw defaults to 1e-4 and would
235
+ # shrink scales/zero-points towards zero every step (scale collapse).
236
+ "adam": optax.adamw(args.lr, b1=args.adam_b1, b2=args.adam_b2, weight_decay=0.0),
237
+ "scale": optax.adamw(args.scale_lr, b1=args.adam_b1, b2=args.adam_b2, weight_decay=0.0),
238
+ },
239
+ labels,
240
+ )
241
+ print(f"optimizer: Muon(master) + AdamW(scale_lr={args.scale_lr})", flush=True)
242
+
243
+ if args.grad_clip > 0:
244
+ optimizer = optax.chain(optax.clip_by_global_norm(args.grad_clip), optimizer)
245
+ print(f"grad clip: global norm {args.grad_clip}", flush=True)
246
+
247
+ scale_min = float(args.scale_min)
248
+
249
+ def clamp_scales(model_params):
250
+ if scale_min <= 0.0:
251
+ return model_params
252
+ return {
253
+ key: (jnp.maximum(value, scale_min) if key.endswith("scales") else value)
254
+ for key, value in model_params.items()
255
+ }
256
+
257
+ params = clamp_scales(params)
258
+ opt_state = optimizer.init(params)
259
+
260
+ def loss_fn(current_params, ids):
261
+ model = inject_params(student, current_params)
262
+ teacher_logits = jax.lax.stop_gradient(logits_for(teacher, ids, inference_config))
263
+ student_logits = logits_for(model, ids, training_config)
264
+ temperature = args.temperature
265
+ teacher_log_probs = jax.nn.log_softmax(teacher_logits / temperature, axis=-1)
266
+ student_log_probs = jax.nn.log_softmax(student_logits / temperature, axis=-1)
267
+ teacher_probs = jnp.exp(teacher_log_probs)
268
+ kl = jnp.sum(teacher_probs * (teacher_log_probs - student_log_probs), axis=-1).mean()
269
+ return kl * (temperature**2)
270
+
271
+ @jax.jit
272
+ def train_step(current_params, opt_state, ids):
273
+ loss, grads = jax.value_and_grad(loss_fn)(current_params, ids)
274
+ grad_norm = optax.global_norm(grads)
275
+ updates, new_state = optimizer.update(grads, opt_state, current_params)
276
+ new_params = optax.apply_updates(current_params, updates)
277
+ new_params = clamp_scales(new_params)
278
+ return new_params, new_state, loss, grad_norm
279
+
280
+ def validation_loss(current_params):
281
+ if not val_ids:
282
+ return None
283
+ values = [float(loss_fn(current_params, ids)) for ids in val_ids]
284
+ return sum(values) / len(values)
285
+
286
+ if args.dry_run:
287
+ print("dry-run: no training")
288
+ return
289
+
290
+ import orbax.checkpoint as ocp
291
+
292
+ args.output_dir.mkdir(parents=True, exist_ok=True)
293
+ checkpoint_dir = args.checkpoint_dir or (args.output_dir / "checkpoints")
294
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
295
+ checkpointer = ocp.PyTreeCheckpointer()
296
+ checkpoint_meta = {
297
+ "teacher_dir": str(args.teacher_dir),
298
+ "student_dir": str(args.student_dir),
299
+ "eval_corpora": [str(path) for path in args.eval_corpus],
300
+ "overlap_checked": bool(args.eval_corpus),
301
+ "seq": args.seq,
302
+ "optimizer": args.optimizer,
303
+ "lr": args.lr,
304
+ "scale_lr": args.scale_lr,
305
+ "muon_lr": args.muon_lr,
306
+ "student_provenance_sha256": (
307
+ hashlib.sha256(provenance_path.read_bytes()).hexdigest()
308
+ if provenance_path.exists()
309
+ else None
310
+ ),
311
+ "adam_b1": args.adam_b1,
312
+ "adam_b2": args.adam_b2,
313
+ "scale_min": args.scale_min,
314
+ }
315
+
316
+ def save_checkpoint(step: int, current_params, current_state, current_rng) -> None:
317
+ path = checkpoint_dir / f"step_{step:05d}"
318
+ tmp_path = checkpoint_dir / f".{path.name}.tmp"
319
+ if tmp_path.exists():
320
+ shutil.rmtree(tmp_path)
321
+ checkpointer.save(
322
+ tmp_path,
323
+ {"params": current_params, "opt_state": current_state, "step": step},
324
+ force=True,
325
+ )
326
+ with open(tmp_path / "rng.pkl", "wb") as file:
327
+ pickle.dump(current_rng.bit_generator.state, file)
328
+ with open(tmp_path / "meta.json", "w", encoding="utf-8") as file:
329
+ json.dump(checkpoint_meta, file, indent=2, sort_keys=True)
330
+ (tmp_path / "COMPLETE").write_text("ok\n", encoding="utf-8")
331
+ if path.exists():
332
+ shutil.rmtree(path)
333
+ os.replace(tmp_path, path)
334
+ keep = max(args.keep_checkpoints, 1)
335
+ for old in sorted(checkpoint_dir.glob("step_*"))[:-keep]:
336
+ shutil.rmtree(old, ignore_errors=True)
337
+ print(f"checkpoint -> {path}", flush=True)
338
+
339
+ rng = np.random.default_rng(args.seed)
340
+ start_step = 0
341
+ if args.resume:
342
+ if args.resume == "auto":
343
+ candidates = sorted(
344
+ path for path in checkpoint_dir.glob("step_*") if (path / "COMPLETE").exists()
345
+ )
346
+ resume_path = candidates[-1] if candidates else None
347
+ else:
348
+ resume_path = Path(args.resume)
349
+ if resume_path is None:
350
+ print("resume: no complete checkpoint found; starting from 0", flush=True)
351
+ elif not resume_path.exists():
352
+ raise SystemExit(f"checkpoint not found: {resume_path}")
353
+ else:
354
+ meta_file = resume_path / "meta.json"
355
+ if not meta_file.exists():
356
+ raise RuntimeError(f"checkpoint missing meta.json: {resume_path}")
357
+ saved_meta = json.loads(meta_file.read_text(encoding="utf-8"))
358
+ for key, expected in checkpoint_meta.items():
359
+ if saved_meta.get(key) != expected:
360
+ raise RuntimeError(
361
+ f"checkpoint meta mismatch for {key}: saved={saved_meta.get(key)!r} current={expected!r}"
362
+ )
363
+ restored = checkpointer.restore(resume_path)
364
+ params = restored["params"]
365
+ opt_state = restored["opt_state"]
366
+ start_step = int(restored["step"])
367
+ rng_file = resume_path / "rng.pkl"
368
+ if not rng_file.exists():
369
+ raise RuntimeError(f"checkpoint missing rng.pkl: {resume_path}")
370
+ with open(rng_file, "rb") as file:
371
+ rng.bit_generator.state = pickle.load(file)
372
+ print(f"resumed from {resume_path} at step {start_step}", flush=True)
373
+
374
+ run_id = time.strftime("%Y%m%d-%H%M%S")
375
+ progress_path = args.output_dir / "progress.jsonl"
376
+ if not args.resume:
377
+ progress_path.write_text("", encoding="utf-8")
378
+
379
+ def progress(record: dict) -> None:
380
+ record = {"run_id": run_id, **record}
381
+ with open(progress_path, "a", encoding="utf-8") as file:
382
+ file.write(json.dumps(record) + "\n")
383
+
384
+ def scale_stats(current_params):
385
+ values = [
386
+ np.asarray(value, dtype=np.float32).ravel()
387
+ for key, value in current_params.items()
388
+ if key.endswith("scales")
389
+ ]
390
+ if not values:
391
+ return 0.0, 0.0
392
+ merged = np.concatenate(values)
393
+ return float(merged.min()), float(merged.max())
394
+
395
+ initial_scale_min, initial_scale_max = scale_stats(params)
396
+ started_at = time.time()
397
+ initial_val = validation_loss(params)
398
+ best_val = initial_val
399
+ bad_val_evals = 0
400
+ if initial_val is not None:
401
+ progress({"step": 0, "val_loss": initial_val, "elapsed_s": 0.0})
402
+ print(f"step 0/{args.steps} val_kl={initial_val:.6f}", flush=True)
403
+
404
+ for step in range(start_step, args.steps):
405
+ ids = chunks[int(rng.integers(0, len(chunks)))]
406
+ step_started = time.time()
407
+ params, opt_state, loss, grad_norm = train_step(params, opt_state, ids)
408
+ jax.block_until_ready(params)
409
+ now = time.time()
410
+ loss_value = float(loss)
411
+ grad_value = float(grad_norm)
412
+ scale_lo, scale_hi = scale_stats(params)
413
+ bad = not (
414
+ np.isfinite(loss_value)
415
+ and np.isfinite(grad_value)
416
+ and np.isfinite(scale_lo)
417
+ and np.isfinite(scale_hi)
418
+ )
419
+ collapsed = initial_scale_max > scale_min * 10 and scale_hi <= scale_min * 10
420
+ if bad or collapsed:
421
+ reason = "non-finite loss/grad/scale" if bad else "scale collapse"
422
+ progress(
423
+ {
424
+ "step": step + 1,
425
+ "status": "failed",
426
+ "reason": reason,
427
+ "loss": loss_value,
428
+ "grad_norm": grad_value,
429
+ "scale_min": scale_lo,
430
+ "scale_max": scale_hi,
431
+ "elapsed_s": now - started_at,
432
+ }
433
+ )
434
+ raise RuntimeError(f"QAD stopped at step {step + 1}: {reason}")
435
+ val_loss = None
436
+ if val_ids and ((step + 1) % args.val_every == 0 or step + 1 == args.steps):
437
+ val_loss = validation_loss(params)
438
+ if val_loss is not None:
439
+ if best_val is None or val_loss < best_val:
440
+ best_val = val_loss
441
+ bad_val_evals = 0
442
+ else:
443
+ bad_val_evals += 1
444
+ if args.early_stop_patience > 0 and bad_val_evals >= args.early_stop_patience:
445
+ progress(
446
+ {
447
+ "step": step + 1,
448
+ "status": "early_stop",
449
+ "val_loss": val_loss,
450
+ "best_val_loss": best_val,
451
+ "elapsed_s": now - started_at,
452
+ }
453
+ )
454
+ raise RuntimeError(
455
+ f"QAD early stop at step {step + 1}: val loss did not improve "
456
+ f"(best={best_val:.6f}, current={val_loss:.6f})"
457
+ )
458
+ record = {
459
+ "run_id": run_id,
460
+ "step": step + 1,
461
+ "loss": loss_value,
462
+ "val_loss": val_loss,
463
+ "grad_norm": grad_value,
464
+ "scale_min": scale_lo,
465
+ "scale_max": scale_hi,
466
+ "step_s": now - step_started,
467
+ "elapsed_s": now - started_at,
468
+ }
469
+ with open(progress_path, "a", encoding="utf-8") as file:
470
+ file.write(json.dumps(record) + "\n")
471
+ val_text = "" if val_loss is None else f" val_kl={val_loss:.6f}"
472
+ print(
473
+ f"step {step + 1}/{args.steps} kl={loss_value:.6f}{val_text} "
474
+ f"grad={grad_value:.3g} scale=[{scale_lo:.3g},{scale_hi:.3g}] "
475
+ f"step_s={now - step_started:.2f} elapsed_s={now - started_at:.1f}",
476
+ flush=True,
477
+ )
478
+ if args.save_every and (step + 1) % args.save_every == 0:
479
+ save_checkpoint(step + 1, params, opt_state, rng)
480
+
481
+ if args.steps > 0 and (not args.save_every or args.steps % args.save_every != 0):
482
+ save_checkpoint(args.steps, params, opt_state, rng)
483
+
484
+ trained = inject_params(student, params)
485
+ trained = map_nodes_of_type_with_path(
486
+ HybridMatrix,
487
+ lambda path, matrix: matrix.switch_implementation(CompressionImplementation.INFERENCE),
488
+ trained,
489
+ )
490
+ args.output_dir.mkdir(parents=True, exist_ok=True)
491
+ trained.save(args.output_dir)
492
+ rewrite(args.output_dir / "model.safetensors")
493
+ normalize(args.output_dir)
494
+ print(f"saved QAD model -> {args.output_dir}")
495
+
496
+
497
+ if __name__ == "__main__":
498
+ main()
scripts/rht_int4_convert.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert a supported Hugging Face model to uzu with RHT + INT4 Group32.
3
+
4
+ This bypasses MLX quantization and applies lalamo's HybridSpec directly:
5
+ BF16 Linear -> RHT (Hadamard block 32) -> asymmetric INT4 group 32 -> HybridMatrix
6
+
7
+ The resulting lalamo model is saved, its HybridSpec metadata is rewritten to
8
+ uzu's flat form, and encoding.json is added.
9
+
10
+ Example (0.8B, local CPU):
11
+ JAX_PLATFORM_NAME=cpu python scripts/rht_int4_convert.py \
12
+ --spec-name Qwen3.5-0.8B \
13
+ --lalamo-path /tmp/lalamo-direct \
14
+ --output-dir /tmp/qwen35_0.8b_rht_int4_lalamo \
15
+ --bf16-dir /tmp/qwen35_0.8b_bf16_lalamo
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import sys
24
+ import time
25
+ from dataclasses import replace
26
+ from pathlib import Path
27
+
28
+
29
+ def parse_args() -> argparse.Namespace:
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument("--spec-name", default="Qwen3.5-0.8B", help="Built-in lalamo model spec name")
32
+ parser.add_argument("--hf-repo", default=None, help="Override origin with this Hugging Face repo")
33
+ parser.add_argument("--hf-dir", default=None, help="Use a local HF snapshot directory instead of downloading")
34
+ parser.add_argument("--vendor", default=None)
35
+ parser.add_argument("--name", default=None)
36
+ parser.add_argument("--output-dir", required=True)
37
+ parser.add_argument("--bf16-dir", default=None, help="Also save the unquantized model here")
38
+ parser.add_argument(
39
+ "--load-from",
40
+ default=None,
41
+ help="Load an existing lalamo model directory instead of importing from Hugging Face",
42
+ )
43
+ parser.add_argument("--lalamo-path", default=os.environ.get("LALAMO_PATH", "/tmp/lalamo-direct"))
44
+ parser.add_argument(
45
+ "--parallel",
46
+ choices=("replicated", "tensor", "fsdp", "data"),
47
+ default="replicated",
48
+ help="JAX device sharding: tensor/fsdp use all visible GPUs as one memory pool",
49
+ )
50
+ parser.add_argument("--bits", type=int, default=4, choices=(4, 8))
51
+ parser.add_argument(
52
+ "--embedding-bits",
53
+ type=int,
54
+ default=None,
55
+ choices=(4, 8),
56
+ help="Override --bits for the tied/untied embedding and readout only",
57
+ )
58
+ parser.add_argument("--group-size", type=int, default=32)
59
+ parser.add_argument("--block-size", type=int, default=32, choices=(32, 64, 128))
60
+ parser.add_argument(
61
+ "--no-rht",
62
+ action="store_true",
63
+ help="Disable RHT and quantize with plain INT4 Group (isolation baseline)",
64
+ )
65
+ parser.add_argument(
66
+ "--quantize-embedding",
67
+ action="store_true",
68
+ help="Also quantize the tied token embedding with RHT output-only (matches Mirai-M)",
69
+ )
70
+ parser.add_argument("--dtype", default="bfloat16")
71
+ parser.add_argument("--skip-incompatible", action="store_true", help="Leave non-divisible Linears full precision")
72
+ parser.add_argument("--dry-run", action="store_true")
73
+ parser.add_argument("--hf-token", default=None)
74
+ parser.add_argument(
75
+ "--preconditioners",
76
+ default=None,
77
+ help="NPZ from scripts/yaqa_calibration.py; keys are '<path>/input_block' and optional '/output_block'",
78
+ )
79
+ parser.add_argument(
80
+ "--calibration-json",
81
+ type=Path,
82
+ default=None,
83
+ help="calibration.json paired with --preconditioners; embedded into provenance.json",
84
+ )
85
+ parser.add_argument(
86
+ "--progress-jsonl",
87
+ type=Path,
88
+ default=None,
89
+ help="default: <output-dir>/convert_progress.jsonl",
90
+ )
91
+ return parser.parse_args()
92
+
93
+
94
+ # uzu config strictness:
95
+ # * every struct uses `#[serde(deny_unknown_fields)]`
96
+ # * every field is required, even `Option<T>` (missing != null)
97
+ # lalamo emits a newer token_codec schema that violates both rules.
98
+ _UZU_TOKEN_CODEC_REQUIRED = ("output_parser_regex", "end_of_thinking_tag")
99
+ _UZU_TOKEN_CODEC_UNSUPPORTED = ("response_format", "reasoning_effort")
100
+
101
+
102
+ def normalize_config_for_uzu(output_dir: Path) -> None:
103
+ path = output_dir / "config.json"
104
+ config = json.loads(path.read_text())
105
+
106
+ # Keep the untouched lalamo form for lalamo-side evaluation (PPL / logits).
107
+ lalamo_path = output_dir / "config.lalamo.json"
108
+ if not lalamo_path.exists():
109
+ lalamo_path.write_text(json.dumps(config, indent=2) + "\n")
110
+
111
+ token_codec = config.get("token_codec_config")
112
+ if token_codec is None:
113
+ return
114
+
115
+ removed = [key for key in _UZU_TOKEN_CODEC_UNSUPPORTED if token_codec.pop(key, None) is not None]
116
+ added = [key for key in _UZU_TOKEN_CODEC_REQUIRED if key not in token_codec]
117
+ for key in added:
118
+ token_codec[key] = None
119
+
120
+ if removed or added:
121
+ path.write_text(json.dumps(config, indent=2) + "\n")
122
+ print(f"normalize config.json: removed={removed or '[]'} added={added or '[]'}")
123
+
124
+
125
+ def find_spec(qwen_models, name: str):
126
+ for spec in qwen_models:
127
+ if spec.name == name:
128
+ return spec
129
+ raise ValueError(f"model spec {name!r} not found")
130
+
131
+
132
+ def main() -> None:
133
+ args = parse_args()
134
+ os.environ.setdefault("JAX_PLATFORM_NAME", "cpu")
135
+ if args.hf_token:
136
+ os.environ["HF_TOKEN"] = args.hf_token
137
+
138
+ progress_path = args.progress_jsonl or (Path(args.output_dir) / "convert_progress.jsonl")
139
+ progress_path.parent.mkdir(parents=True, exist_ok=True)
140
+ run_id = time.strftime("%Y%m%d-%H%M%S")
141
+ progress_path.write_text("", encoding="utf-8")
142
+
143
+ def progress(record: dict) -> None:
144
+ record = {"run_id": run_id, **record}
145
+ with open(progress_path, "a", encoding="utf-8") as file:
146
+ file.write(json.dumps(record) + "\n")
147
+
148
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
149
+ sys.path.insert(0, args.lalamo_path)
150
+
151
+ import jax
152
+ import jax.numpy as jnp
153
+ import equinox as eqx
154
+ import numpy as np
155
+
156
+ from lalamo.compressed.hybrid import HybridSpec
157
+ from lalamo.compressed.int import IntSpec
158
+ from lalamo.compressed.incoherence import HadamardSpec, IncoherenceProcessingMode
159
+ from lalamo.model_import.common import import_model
160
+ from lalamo.model_import.model_specs.qwen import QWEN_MODELS
161
+ from lalamo.modules.linear import Linear
162
+ from lalamo.preconditioner import Preconditioner
163
+ from lalamo.utils.sharding import ShardingConfig
164
+ from lalamo.utils.surgery import map_nodes_of_type_with_path, select_nodes_of_type
165
+ from lalamo.weight_matrix import Layout
166
+ from rewrite_lalamo_hybrid_spec import rewrite
167
+
168
+ if args.parallel == "tensor":
169
+ sharding = ShardingConfig.tensor_parallel()
170
+ elif args.parallel == "fsdp":
171
+ sharding = ShardingConfig.fully_sharded_data_parallel()
172
+ elif args.parallel == "data":
173
+ sharding = ShardingConfig.data_parallel()
174
+ else:
175
+ sharding = ShardingConfig.replicated()
176
+
177
+ if args.load_from:
178
+ from lalamo.model import Model
179
+
180
+ print(f"load lalamo model <- {args.load_from}")
181
+ model = Model.load(args.load_from, sharding, dtype=jnp.dtype(args.dtype))
182
+ print("load done")
183
+ else:
184
+ spec = find_spec(QWEN_MODELS, args.spec_name)
185
+ if args.hf_dir:
186
+ from pathlib import Path as _Path
187
+
188
+ from lalamo.model_import.origins import LocalOrigin
189
+
190
+ weight_files = tuple(sorted(path.name for path in _Path(args.hf_dir).glob("*.safetensors")))
191
+ if not weight_files:
192
+ raise SystemExit(f"no safetensors files in {args.hf_dir}")
193
+ spec = replace(
194
+ spec,
195
+ vendor=args.vendor or spec.vendor,
196
+ name=args.name or spec.name,
197
+ origin=LocalOrigin(root=args.hf_dir, weight_files=weight_files),
198
+ )
199
+ elif args.hf_repo:
200
+ from lalamo.model_import.origins import HuggingFaceOrigin
201
+
202
+ spec = replace(
203
+ spec,
204
+ vendor=args.vendor or spec.vendor,
205
+ name=args.name or spec.name,
206
+ origin=HuggingFaceOrigin(repo=args.hf_repo),
207
+ )
208
+
209
+ print(f"import {spec.vendor}/{spec.name} <- {spec.origin.description}")
210
+ results = import_model(
211
+ spec,
212
+ sharding_config=sharding,
213
+ dtype=jnp.dtype(args.dtype),
214
+ )
215
+ model = results.model
216
+ print("import done")
217
+
218
+ if args.bf16_dir:
219
+ bf16_dir = Path(args.bf16_dir)
220
+ bf16_dir.mkdir(parents=True, exist_ok=True)
221
+ print(f"save BF16 baseline -> {bf16_dir}")
222
+ model.save(bf16_dir)
223
+ normalize_config_for_uzu(bf16_dir)
224
+ (bf16_dir / "COMPLETE").write_text("ok\n", encoding="utf-8")
225
+ print("BF16 baseline saved")
226
+
227
+ linear_list = select_nodes_of_type(Linear, model)
228
+ required_divisor = args.group_size if args.no_rht else max(args.block_size, args.group_size)
229
+ bad = []
230
+ for path, linear in linear_list:
231
+ shape = tuple(int(x) for x in linear.weights.shape)
232
+ if len(shape) != 2 or any(dimension % required_divisor for dimension in shape):
233
+ bad.append(("/".join(path), shape))
234
+
235
+ print(f"Linear layers: {len(linear_list)}, incompatible: {len(bad)}")
236
+ for path, shape in bad:
237
+ print(f" {path}: {shape}")
238
+ if bad and not args.skip_incompatible:
239
+ raise SystemExit("incompatible Linear shapes; use --skip-incompatible to leave them full precision")
240
+
241
+ hybrid_spec = HybridSpec(
242
+ quantization_spec=IntSpec(
243
+ bits=args.bits,
244
+ group_size=args.group_size,
245
+ is_symmetric=False,
246
+ layout=Layout.OUTPUT_INPUT,
247
+ ),
248
+ adapter_spec=None,
249
+ incoherence_spec=None
250
+ if args.no_rht
251
+ else HadamardSpec(
252
+ block_size=args.block_size,
253
+ processing_mode=IncoherenceProcessingMode.INPUT_OUTPUT,
254
+ ),
255
+ )
256
+ quantize_key = jax.random.key(0)
257
+ counts = {"quantized": 0, "skipped": 0, "yaqa": 0}
258
+
259
+ calibration = None
260
+ if args.preconditioners:
261
+ calibration = np.load(args.preconditioners)
262
+ print(f"preconditioners: {args.preconditioners} ({len(calibration.files)} arrays)")
263
+
264
+ def preconditioner_for(path) -> Preconditioner | None:
265
+ if calibration is None:
266
+ return None
267
+ key = "/".join(path)
268
+ input_key = f"{key}/input_block"
269
+ if input_key not in calibration:
270
+ return None
271
+ output_key = f"{key}/output_block"
272
+ return Preconditioner.init(
273
+ input_block=jnp.asarray(calibration[input_key], dtype=jnp.float32),
274
+ output_block=jnp.asarray(calibration[output_key], dtype=jnp.float32)
275
+ if output_key in calibration
276
+ else None,
277
+ )
278
+
279
+ def quantize_linear(path, linear: Linear) -> Linear:
280
+ started = time.time()
281
+ key = "/".join(path)
282
+ shape = tuple(int(x) for x in linear.weights.shape)
283
+ if len(shape) != 2 or any(dimension % required_divisor for dimension in shape):
284
+ counts["skipped"] += 1
285
+ progress({"path": key, "shape": shape, "status": "skipped", "elapsed_s": time.time() - started})
286
+ if not args.skip_incompatible:
287
+ raise ValueError(f"incompatible Linear {path}: {shape}")
288
+ return linear
289
+ counts["quantized"] += 1
290
+ preconditioner = preconditioner_for(path)
291
+ if preconditioner is not None:
292
+ counts["yaqa"] += 1
293
+ progress({"path": key, "shape": shape, "status": "started"})
294
+ try:
295
+ new_weights = hybrid_spec.compress(
296
+ linear.weights.decompress(),
297
+ key=quantize_key,
298
+ preconditioner=preconditioner,
299
+ sharding_config=linear.weights.sharding_config,
300
+ is_sharded=linear.weights.is_sharded,
301
+ )
302
+ except Exception as error:
303
+ progress(
304
+ {
305
+ "path": key,
306
+ "shape": shape,
307
+ "status": "failed",
308
+ "error": repr(error),
309
+ "elapsed_s": time.time() - started,
310
+ }
311
+ )
312
+ raise
313
+ progress(
314
+ {
315
+ "path": key,
316
+ "shape": shape,
317
+ "status": "quantized",
318
+ "yaqa": preconditioner is not None,
319
+ "elapsed_s": time.time() - started,
320
+ }
321
+ )
322
+ return eqx.tree_at(lambda x: x.weights, linear, new_weights)
323
+
324
+ if args.dry_run:
325
+ print("dry-run: no quantization performed")
326
+ return
327
+
328
+ if args.no_rht:
329
+ print(f"quantize -> plain INT{args.bits} group {args.group_size} (symmetric=False, layout=output_input)")
330
+ if args.embedding_bits is not None:
331
+ print(f"embedding quantize -> plain INT{args.embedding_bits} group {args.group_size} (symmetric=False)")
332
+ else:
333
+ print(
334
+ f"quantize -> RHT block {args.block_size} + INT{args.bits} group {args.group_size} "
335
+ f"(symmetric=False, layout=output_input)"
336
+ )
337
+ if args.embedding_bits is not None:
338
+ print(
339
+ f"embedding quantize -> RHT block {args.block_size} + INT{args.embedding_bits} group {args.group_size} "
340
+ f"(symmetric=False)"
341
+ )
342
+ quantized_model = map_nodes_of_type_with_path(Linear, quantize_linear, model)
343
+ print(f"quantized: {counts['quantized']}, skipped: {counts['skipped']}, yaqa: {counts['yaqa']}")
344
+
345
+ def embedding_spec(layout: Layout, mode: IncoherenceProcessingMode | None) -> HybridSpec:
346
+ embedding_bits = args.embedding_bits if args.embedding_bits is not None else args.bits
347
+ return HybridSpec(
348
+ quantization_spec=IntSpec(
349
+ bits=embedding_bits,
350
+ group_size=args.group_size,
351
+ is_symmetric=False,
352
+ layout=layout,
353
+ ),
354
+ adapter_spec=None,
355
+ incoherence_spec=None
356
+ if args.no_rht or mode is None
357
+ else HadamardSpec(block_size=args.block_size, processing_mode=mode),
358
+ )
359
+
360
+ def quantize_matrix(matrix, layout: Layout, mode: IncoherenceProcessingMode | None, label: str):
361
+ started = time.time()
362
+ embedding_dim = int(matrix.shape[-1])
363
+ if not args.no_rht and embedding_dim % args.block_size:
364
+ raise SystemExit(f"{label} dim {embedding_dim} is not divisible by block size {args.block_size}")
365
+ new_matrix = embedding_spec(layout, mode).compress(
366
+ matrix.decompress(),
367
+ key=quantize_key,
368
+ sharding_config=matrix.sharding_config,
369
+ is_sharded=matrix.is_sharded,
370
+ )
371
+ shape = tuple(int(x) for x in matrix.shape)
372
+ print(f"{label} quantized: shape={shape}")
373
+ progress({"path": label, "shape": shape, "status": "quantized", "yaqa": False, "elapsed_s": time.time() - started})
374
+ return new_matrix
375
+
376
+ if args.quantize_embedding:
377
+ embedding = getattr(quantized_model.decoder, "embedding", None)
378
+ tied = getattr(embedding, "embedding", None)
379
+ if tied is not None:
380
+ matrix = quantize_matrix(
381
+ tied,
382
+ Layout.INPUT_OUTPUT,
383
+ IncoherenceProcessingMode.OUTPUT,
384
+ "tied embedding",
385
+ )
386
+ new_embedding = eqx.tree_at(lambda node: node.embedding, embedding, matrix)
387
+ quantized_model = eqx.tree_at(
388
+ lambda root: root.decoder.embedding,
389
+ quantized_model,
390
+ new_embedding,
391
+ )
392
+ elif hasattr(embedding, "input_embedding") and hasattr(embedding, "output_embedding"):
393
+ input_embedding = quantize_matrix(
394
+ embedding.input_embedding,
395
+ Layout.INPUT_OUTPUT,
396
+ IncoherenceProcessingMode.OUTPUT,
397
+ "input_embedding",
398
+ )
399
+ output_embedding = quantize_matrix(
400
+ embedding.output_embedding,
401
+ Layout.OUTPUT_INPUT,
402
+ IncoherenceProcessingMode.INPUT,
403
+ "output_embedding (lm_head)",
404
+ )
405
+ embedding = eqx.tree_at(lambda node: node.input_embedding, embedding, input_embedding)
406
+ embedding = eqx.tree_at(lambda node: node.output_embedding, embedding, output_embedding)
407
+ quantized_model = eqx.tree_at(
408
+ lambda root: root.decoder.embedding,
409
+ quantized_model,
410
+ embedding,
411
+ )
412
+ else:
413
+ print("embedding: neither tied nor untied embedding found, skipped")
414
+
415
+ output_dir = Path(args.output_dir)
416
+ output_dir.mkdir(parents=True, exist_ok=True)
417
+ print(f"save quantized model -> {output_dir}")
418
+ quantized_model.save(output_dir)
419
+
420
+ print("rewrite HybridSpec metadata for uzu")
421
+ rewrite(output_dir / "model.safetensors")
422
+
423
+ normalize_config_for_uzu(output_dir)
424
+
425
+ encoding = {"type": "hanashi", "name": "qwen3.5"}
426
+ (output_dir / "encoding.json").write_text(json.dumps(encoding, indent=2) + "\n")
427
+
428
+ calibration_summary = None
429
+ if args.calibration_json and args.calibration_json.exists():
430
+ calibration_summary = json.loads(args.calibration_json.read_text())
431
+ source = args.hf_repo or (str(args.hf_dir) if args.hf_dir else None) or args.load_from or args.spec_name
432
+ provenance = {
433
+ "kind": "yaqa" if args.preconditioners else "rtn",
434
+ "source": source,
435
+ "preconditioners": args.preconditioners,
436
+ "calibration_json": str(args.calibration_json) if args.calibration_json else None,
437
+ "calibration": calibration_summary,
438
+ "overlap_checked": (
439
+ bool(calibration_summary.get("overlap_checked"))
440
+ if calibration_summary is not None
441
+ else args.preconditioners is None
442
+ ),
443
+ }
444
+ (output_dir / "provenance.json").write_text(
445
+ json.dumps(provenance, indent=2, ensure_ascii=False) + "\n",
446
+ encoding="utf-8",
447
+ )
448
+ (output_dir / "COMPLETE").write_text("ok\n", encoding="utf-8")
449
+ print("encoding.json / provenance.json written")
450
+
451
+ for f in sorted(output_dir.iterdir()):
452
+ if f.is_file():
453
+ print(f" {f.name}: {f.stat().st_size / 1e6:.1f} MB")
454
+
455
+
456
+ if __name__ == "__main__":
457
+ main()
scripts/tiny_sharding_probe.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Tiny 2-device sharding probe for uzu/lalamo TP semantics.
3
+
4
+ Usage on Kaggle T4x2:
5
+ python scripts/tiny_sharding_probe.py
6
+
7
+ Usage on CPU with 2 forced devices:
8
+ FORCE_2_CPU=1 python scripts/tiny_sharding_probe.py
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+
16
+ if os.environ.get("FORCE_2_CPU") == "1":
17
+ os.environ.setdefault("XLA_FLAGS", "--xla_force_host_platform_device_count=2")
18
+
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+ from jax.sharding import AxisType, Mesh, NamedSharding, PartitionSpec as P
23
+
24
+
25
+ def main() -> None:
26
+ devices = jax.devices()
27
+ report = {"devices": [str(device) for device in devices], "cases": [], "ok": False}
28
+ if len(devices) < 2:
29
+ report["error"] = f"need >=2 devices, got {len(devices)}"
30
+ print(json.dumps(report, indent=2))
31
+ raise SystemExit(1)
32
+
33
+ mesh = Mesh(np.asarray(devices[:2]), ("tensor",), axis_types=(AxisType.Explicit,))
34
+ base = jnp.asarray(np.arange(64, dtype=np.float32).reshape(8, 8))
35
+
36
+ def record(name: str, expect_error: bool, expected: str, fn) -> None:
37
+ try:
38
+ fn()
39
+ except Exception as error: # noqa: BLE001 - probe records the exact runtime error
40
+ message = str(error)
41
+ passed = expect_error and expected in message
42
+ report["cases"].append(
43
+ {"name": name, "expected": expected, "ok": passed, "error": message[:500]}
44
+ )
45
+ else:
46
+ report["cases"].append(
47
+ {"name": name, "expected": expected, "ok": not expect_error, "error": None}
48
+ )
49
+
50
+ def column_sharded_matmul() -> None:
51
+ sharding = NamedSharding(mesh, P(None, "tensor"))
52
+ with jax.set_mesh(mesh):
53
+ x = jax.device_put(base, sharding)
54
+ _ = x @ x.T
55
+
56
+ def row_sharded_matmul() -> None:
57
+ sharding = NamedSharding(mesh, P("tensor", None))
58
+ with jax.set_mesh(mesh):
59
+ x = jax.device_put(base, sharding)
60
+ _ = x @ x.T
61
+
62
+ def replicated_reshard_matmul() -> None:
63
+ sharded = NamedSharding(mesh, P(None, "tensor"))
64
+ replicated = NamedSharding(mesh, P())
65
+ with jax.set_mesh(mesh):
66
+ x = jax.device_put(base, sharded)
67
+ x_rep = jax.device_put(x, replicated)
68
+ result = x_rep @ x_rep.T
69
+ expected = base @ base.T
70
+ diff = float(jnp.max(jnp.abs(result - expected)))
71
+ report["reshard_max_abs_diff"] = diff
72
+ if diff > 1e-4:
73
+ raise RuntimeError(f"reshard mismatch: {diff}")
74
+
75
+ record("column_sharded_matmul", True, "Contracting dimensions are sharded", column_sharded_matmul)
76
+ record("row_sharded_matmul", True, "illegally sharded", row_sharded_matmul)
77
+ record("replicated_reshard_matmul", False, "", replicated_reshard_matmul)
78
+
79
+ report["ok"] = all(case["ok"] for case in report["cases"])
80
+ print(json.dumps(report, indent=2))
81
+ raise SystemExit(0 if report["ok"] else 1)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
scripts/yaqa_calibration.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sketch B YAQA calibration for lalamo language models.
3
+
4
+ Universal part of the pipeline (Layer 2 in YAQA_CALIBRATION_DESIGN.md):
5
+
6
+ forward -> pseudo target sampling from the model's own logits
7
+ backward -> per-sample weight gradient G_b for every selected Linear
8
+ H_I = mean_b G_b^T G_b
9
+ H_O = mean_b G_b G_b^T
10
+ damping + PSD checks -> preconditioners.npz
11
+
12
+ Per-model work is limited to selecting LinearSite entries.
13
+
14
+ Usage:
15
+ JAX_PLATFORM_NAME=cpu python scripts/yaqa_calibration.py \
16
+ --model-dir /tmp/qwen35_0.8b_bf16_lalamo_lalamo_origcfg \
17
+ --corpus experiments/qwen35-0.8b/data/calibration.txt \
18
+ --output experiments/qwen35-0.8b/yaqa-hin/calibration.npz \
19
+ --samples 32 --max-tokens 128 --output-block none
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import time
27
+ import os
28
+ import sys
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+
32
+ os.environ.setdefault("JAX_PLATFORM_NAME", "cpu")
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class LinearSite:
37
+ path: tuple[str, ...]
38
+ linear: object
39
+ out_dim: int
40
+ in_dim: int
41
+ components: tuple[int, ...]
42
+
43
+ @property
44
+ def key(self) -> str:
45
+ return "/".join(self.path)
46
+
47
+
48
+ def parse_args() -> argparse.Namespace:
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument("--model-dir", type=Path, default=None, help="saved lalamo model directory")
51
+ parser.add_argument("--spec-name", default="Qwen3.5-0.8B", help="built-in lalamo spec for direct HF import")
52
+ parser.add_argument("--hf-repo", default=None, help="load directly from this Hugging Face repo (no save)")
53
+ parser.add_argument("--hf-dir", default=None, help="load directly from a local HF snapshot directory")
54
+ parser.add_argument("--corpus", type=Path, required=True)
55
+ parser.add_argument("--output", type=Path, required=True)
56
+ parser.add_argument("--lalamo-path", default=os.environ.get("LALAMO_PATH", "/tmp/lalamo-direct"))
57
+ parser.add_argument(
58
+ "--parallel",
59
+ choices=("replicated", "tensor", "fsdp", "data"),
60
+ default="replicated",
61
+ help="JAX device sharding: tensor/fsdp use all visible GPUs as one memory pool",
62
+ )
63
+ parser.add_argument("--samples", type=int, default=32)
64
+ parser.add_argument("--max-tokens", type=int, default=128)
65
+ parser.add_argument("--min-tokens", type=int, default=32, help="drop shorter trailing chunks")
66
+ parser.add_argument("--layer-filter", default="", help="only paths containing this substring")
67
+ parser.add_argument("--output-block", choices=("none", "small", "all"), default="none")
68
+ parser.add_argument("--output-block-limit", type=int, default=2048)
69
+ parser.add_argument("--raw-output", action="store_true", help="save raw H before normalization/damping (for language-balanced merge)")
70
+ parser.add_argument("--damping", type=float, default=1e-2, help="initial sigma_reg after mean-diagonal normalization")
71
+ parser.add_argument("--seed", type=int, default=0)
72
+ parser.add_argument(
73
+ "--calib-dtype",
74
+ choices=("float32", "bfloat16"),
75
+ default="float32",
76
+ help="model dtype during calibration; bfloat16 halves memory for 4B/9B",
77
+ )
78
+ parser.add_argument("--json-out", type=Path, default=None)
79
+ parser.add_argument("--eval-corpus", type=Path, action="append", default=[], help="evaluation corpus to keep disjoint")
80
+ parser.add_argument("--allow-overlap", action="store_true", help="allow calibration/eval overlap for analysis only")
81
+ parser.add_argument("--progress-jsonl", type=Path, default=None, help="default: <output>.progress.jsonl")
82
+ parser.add_argument("--checkpoint-every", type=int, default=0, help="save partial accumulators every N samples; 0=off")
83
+ parser.add_argument("--checkpoint-path", type=Path, default=None, help="default: <output>.partial.npz")
84
+ parser.add_argument("--resume", default=None, help="'auto' or a partial npz path")
85
+ return parser.parse_args()
86
+
87
+
88
+ def main() -> None:
89
+ args = parse_args()
90
+ from corpus_guard import assert_disjoint
91
+
92
+ assert_disjoint(args.corpus, args.eval_corpus, allow_overlap=args.allow_overlap)
93
+ progress_path = args.progress_jsonl or args.output.with_suffix(".progress.jsonl")
94
+ progress_path.parent.mkdir(parents=True, exist_ok=True)
95
+ checkpoint_path = args.checkpoint_path or args.output.with_suffix(".partial.npz")
96
+ if checkpoint_path.suffix != ".npz":
97
+ checkpoint_path = checkpoint_path.with_suffix(".npz")
98
+ if checkpoint_path.resolve() == args.output.resolve():
99
+ raise SystemExit("--checkpoint-path must differ from --output")
100
+ run_id = time.strftime("%Y%m%d-%H%M%S")
101
+ if not args.resume:
102
+ progress_path.write_text("", encoding="utf-8")
103
+
104
+ def progress(record: dict) -> None:
105
+ record = {"run_id": run_id, **record}
106
+ with open(progress_path, "a", encoding="utf-8") as file:
107
+ file.write(json.dumps(record) + "\n")
108
+
109
+ sys.path.insert(0, args.lalamo_path)
110
+
111
+ import equinox as eqx
112
+ import jax
113
+ import jax.numpy as jnp
114
+ import numpy as np
115
+
116
+ from lalamo.model import Model
117
+ from lalamo.module import Keychain
118
+ from lalamo.modules import DecoderForwardPassConfig, ForwardPassMode
119
+ from lalamo.modules.linear import Linear
120
+ from lalamo.utils.sharding import ShardingConfig
121
+ from lalamo.utils.surgery import select_nodes_of_type
122
+ from tokenizers import Tokenizer
123
+
124
+ if args.parallel == "tensor":
125
+ sharding = ShardingConfig.tensor_parallel()
126
+ elif args.parallel == "fsdp":
127
+ sharding = ShardingConfig.fully_sharded_data_parallel()
128
+ elif args.parallel == "data":
129
+ sharding = ShardingConfig.data_parallel()
130
+ else:
131
+ sharding = ShardingConfig.replicated()
132
+ keychain = Keychain.init(seed=args.seed, sharding_config=sharding)
133
+ forward_pass_config = DecoderForwardPassConfig.for_inference(mode=ForwardPassMode.MULTI_TOKEN)
134
+
135
+ dtype = jnp.dtype(args.calib_dtype)
136
+ if args.hf_repo or args.hf_dir:
137
+ from dataclasses import replace as dataclass_replace
138
+ from pathlib import Path as _Path
139
+
140
+ from lalamo.model_import.common import import_model
141
+ from lalamo.model_import.model_specs.qwen import QWEN_MODELS
142
+
143
+ spec = next((item for item in QWEN_MODELS if item.name == args.spec_name), None)
144
+ if spec is None:
145
+ raise SystemExit(f"lalamo spec {args.spec_name!r} not found")
146
+ if args.hf_dir:
147
+ from lalamo.model_import.origins import LocalOrigin
148
+
149
+ weight_files = tuple(sorted(path.name for path in _Path(args.hf_dir).glob("*.safetensors")))
150
+ if not weight_files:
151
+ raise SystemExit(f"no safetensors in {args.hf_dir}")
152
+ origin = LocalOrigin(root=args.hf_dir, weight_files=weight_files)
153
+ else:
154
+ from lalamo.model_import.origins import HuggingFaceOrigin
155
+
156
+ origin = HuggingFaceOrigin(repo=args.hf_repo)
157
+ print(f"importing {args.spec_name} from {origin.description} ({args.calib_dtype})...")
158
+ results = import_model(dataclass_replace(spec, origin=origin), sharding_config=sharding, dtype=dtype)
159
+ model = results.model
160
+ tokenizer = model.token_codec.tokenizer
161
+ else:
162
+ if args.model_dir is None:
163
+ raise SystemExit("provide --model-dir, --hf-repo, or --hf-dir")
164
+ print(f"loading model ({args.calib_dtype})...")
165
+ model = Model.load(args.model_dir, sharding, dtype=dtype)
166
+ tokenizer = Tokenizer.from_file(str(args.model_dir / "tokenizer.json"))
167
+ print("loaded")
168
+
169
+ def module_at(root, attribute_path):
170
+ node = root
171
+ for part in attribute_path:
172
+ if part.startswith("["):
173
+ node = node[int(part[1:-1])]
174
+ else:
175
+ node = getattr(node, part.lstrip("."))
176
+ return node
177
+
178
+ layer_filters = [item for item in args.layer_filter.split(",") if item]
179
+ sites: list[LinearSite] = []
180
+ for path, linear in select_nodes_of_type(Linear, model):
181
+ joined = "/".join(path)
182
+ if layer_filters and not any(item in joined for item in layer_filters):
183
+ continue
184
+ shape = tuple(int(x) for x in linear.weights.shape)
185
+ if len(shape) < 2:
186
+ continue
187
+ components = shape[:-2]
188
+ out_dim, in_dim = shape[-2], shape[-1]
189
+ sites.append(LinearSite(path=path, linear=linear, out_dim=out_dim, in_dim=in_dim, components=components))
190
+ if not sites:
191
+ raise SystemExit("no LinearSite selected")
192
+ print(f"sites: {len(sites)}")
193
+
194
+ def logits_for(m, ids):
195
+ token_ids = jnp.asarray([ids], dtype=jnp.int32)
196
+ positions = jnp.arange(len(ids), dtype=jnp.int32)[None, :]
197
+ result = m.decoder(
198
+ token_ids=token_ids,
199
+ token_positions=positions,
200
+ state=None,
201
+ return_updated_state=False,
202
+ lengths_without_padding=None,
203
+ forward_pass_config=forward_pass_config,
204
+ keychain=keychain.split(1)[0],
205
+ )
206
+ return result.logits[0]
207
+
208
+ def cross_entropy(logits, targets):
209
+ log_probs = jax.nn.log_softmax(logits.astype(jnp.float32), axis=-1)
210
+ # Official get_hess_llama.py uses F.cross_entropy(..., reduction="mean")
211
+ # over all tokens of the batch. Per-sample mean keeps the same scale
212
+ # independently of sequence length.
213
+ return -jnp.mean(jnp.take_along_axis(log_probs, targets[:, None], axis=-1))
214
+
215
+ base_arrays = tuple(site.linear.weights.weights for site in sites)
216
+
217
+ def model_with_weights(arrays):
218
+ updated = model
219
+ for site, array in zip(sites, arrays):
220
+ current = module_at(updated, site.path)
221
+ new_weights = eqx.tree_at(lambda wm: wm.weights, current.weights, array)
222
+ new_linear = eqx.tree_at(lambda linear: linear.weights, current, new_weights)
223
+ updated = eqx.tree_at(lambda root, path=site.path: module_at(root, path), updated, new_linear)
224
+ return updated
225
+
226
+ current_ids: list[int] = []
227
+ current_targets = None
228
+
229
+ def per_sample_loss(arrays):
230
+ m = model_with_weights(arrays)
231
+ logits = logits_for(m, current_ids)
232
+ return cross_entropy(logits, current_targets)
233
+
234
+ texts = [line.strip() for line in args.corpus.read_text(encoding="utf-8").splitlines() if line.strip()]
235
+ if not texts:
236
+ raise SystemExit("empty calibration corpus")
237
+
238
+ def build_chunks() -> list[list[int]]:
239
+ # Concatenate documents and cut into full-context windows, matching the
240
+ # official calibration flow (continuous sequences instead of single lines).
241
+ joined = "\n\n".join(texts)
242
+ ids = tokenizer.encode(joined, add_special_tokens=True).ids
243
+ chunks = [ids[start : start + args.max_tokens] for start in range(0, len(ids), args.max_tokens)]
244
+ chunks = [chunk for chunk in chunks if len(chunk) >= args.min_tokens]
245
+ if not chunks:
246
+ raise SystemExit("no usable calibration chunks")
247
+ rng = np.random.default_rng(args.seed)
248
+ rng.shuffle(chunks)
249
+ return chunks
250
+
251
+ chunks = build_chunks()
252
+ if len(chunks) < args.samples:
253
+ print(f"warning: only {len(chunks)} calibration chunks available, using all")
254
+ args.samples = len(chunks)
255
+
256
+ accumulators = []
257
+ for site in sites:
258
+ components = site.components or ()
259
+ input_shape = (*components, site.in_dim, site.in_dim)
260
+ accumulators.append(
261
+ {
262
+ "input": np.zeros(input_shape, dtype=np.float32),
263
+ "output": np.zeros((*components, site.out_dim, site.out_dim), dtype=np.float32)
264
+ if args.output_block == "all"
265
+ or (args.output_block == "small" and site.out_dim <= args.output_block_limit)
266
+ else None,
267
+ "samples": 0,
268
+ }
269
+ )
270
+
271
+ meta = {
272
+ "site_keys": [site.key for site in sites],
273
+ "site_shapes": [[site.in_dim, site.out_dim] for site in sites],
274
+ "output_block": args.output_block,
275
+ "output_block_limit": args.output_block_limit,
276
+ "corpus": str(args.corpus),
277
+ "seed": args.seed,
278
+ "samples": args.samples,
279
+ "model_dir": str(args.model_dir) if args.model_dir else None,
280
+ "calib_dtype": args.calib_dtype,
281
+ "parallel": args.parallel,
282
+ }
283
+
284
+ def save_partial() -> None:
285
+ arrays: dict[str, np.ndarray] = {}
286
+ for site, accumulator in zip(sites, accumulators):
287
+ arrays[f"{site.key}/input"] = accumulator["input"]
288
+ if accumulator["output"] is not None:
289
+ arrays[f"{site.key}/output"] = accumulator["output"]
290
+ arrays[f"{site.key}/samples"] = np.asarray([accumulator["samples"]], dtype=np.int64)
291
+ arrays["processed"] = np.asarray([processed], dtype=np.int64)
292
+ arrays["sample_index"] = np.asarray([sample_index], dtype=np.int64)
293
+ arrays["__meta__"] = np.asarray(json.dumps(meta, sort_keys=True))
294
+ checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
295
+ tmp_path = checkpoint_path.with_name(checkpoint_path.name + ".tmp.npz")
296
+ np.savez(tmp_path, **arrays)
297
+ os.replace(tmp_path, checkpoint_path)
298
+ print(f" checkpoint -> {checkpoint_path}", flush=True)
299
+
300
+ processed = 0
301
+ sample_index = 0
302
+ if args.resume:
303
+ if args.resume == "auto":
304
+ resume_path = checkpoint_path if checkpoint_path.exists() else None
305
+ else:
306
+ resume_path = Path(args.resume)
307
+ if resume_path is None:
308
+ print("resume: no partial checkpoint found; starting from 0", flush=True)
309
+ elif not resume_path.exists():
310
+ raise SystemExit(f"checkpoint not found: {resume_path}")
311
+ else:
312
+ with np.load(resume_path) as saved:
313
+ if "__meta__" not in saved:
314
+ raise SystemExit("partial checkpoint missing __meta__; refusing to resume")
315
+ saved_meta = json.loads(str(saved["__meta__"]))
316
+ if saved_meta != meta:
317
+ raise SystemExit(
318
+ "partial checkpoint metadata mismatch; refusing to mix runs\n"
319
+ f"saved={saved_meta}\ncurrent={meta}"
320
+ )
321
+ for site, accumulator in zip(sites, accumulators):
322
+ accumulator["input"] = saved[f"{site.key}/input"]
323
+ if accumulator["output"] is not None and f"{site.key}/output" in saved:
324
+ accumulator["output"] = saved[f"{site.key}/output"]
325
+ accumulator["samples"] = int(saved[f"{site.key}/samples"][0])
326
+ processed = int(saved["processed"][0])
327
+ sample_index = int(saved["sample_index"][0])
328
+ print(f"resumed from {resume_path}: processed={processed} sample_index={sample_index}", flush=True)
329
+
330
+ grad_fn = jax.grad(per_sample_loss)
331
+ rng = np.random.default_rng(args.seed)
332
+ started_at = time.time()
333
+ while processed < args.samples:
334
+ ids = chunks[sample_index]
335
+ sample_index += 1
336
+ current_ids = ids
337
+ logits = logits_for(model, ids)
338
+ current_targets = jax.random.categorical(
339
+ jax.random.key(args.seed + processed), logits, axis=-1
340
+ )
341
+ grads = grad_fn(base_arrays)
342
+ for site, accumulator, gradient in zip(sites, accumulators, grads):
343
+ G = np.asarray(gradient, dtype=np.float64)
344
+ if G.ndim == 2:
345
+ accumulator["input"] += G.T @ G
346
+ if accumulator["output"] is not None:
347
+ accumulator["output"] += G @ G.T
348
+ else:
349
+ # MoE-style leading component axes: one Hessian per component.
350
+ for component in np.ndindex(*site.components):
351
+ g = G[component]
352
+ accumulator["input"][component] += g.T @ g
353
+ if accumulator["output"] is not None:
354
+ accumulator["output"][component] += g @ g.T
355
+ accumulator["samples"] += 1
356
+ processed += 1
357
+ progress(
358
+ {
359
+ "sample": processed,
360
+ "samples": args.samples,
361
+ "sample_index": sample_index,
362
+ "elapsed_s": time.time() - started_at,
363
+ }
364
+ )
365
+ if args.checkpoint_every and processed % args.checkpoint_every == 0:
366
+ save_partial()
367
+ if processed % 4 == 0:
368
+ print(f" sample {processed}/{args.samples}")
369
+
370
+ records = []
371
+ arrays: dict[str, np.ndarray] = {}
372
+
373
+ def regularize(matrix: np.ndarray, name: str):
374
+ # Official pipeline: H /= mean(diag), then add sigma_reg (1e-2) until
375
+ # Cholesky succeeds. Fall back to eigenvalue clipping if needed.
376
+ scale = float(np.mean(np.diagonal(matrix, axis1=-2, axis2=-1)))
377
+ normalized = matrix / max(scale, 1e-30)
378
+ sigma = args.damping
379
+ for _ in range(8):
380
+ candidate = normalized + np.eye(normalized.shape[-1]) * sigma
381
+ try:
382
+ np.linalg.cholesky(candidate)
383
+ return candidate.astype(np.float32), sigma
384
+ except np.linalg.LinAlgError:
385
+ sigma *= 10.0
386
+ eigenvalues, eigenvectors = np.linalg.eigh(normalized)
387
+ eigenvalues = np.clip(eigenvalues, 1e-6, None)
388
+ rebuilt = (eigenvectors * eigenvalues[..., None, :]) @ np.swapaxes(eigenvectors, -1, -2)
389
+ print(f"warning: {name} needed eigenvalue clipping")
390
+ return rebuilt.astype(np.float32), None
391
+
392
+ for site, accumulator in zip(sites, accumulators):
393
+ count = max(accumulator["samples"], 1)
394
+ H_I = accumulator["input"] / count
395
+ H_O = None if accumulator["output"] is None else accumulator["output"] / count
396
+ if args.raw_output:
397
+ damping_input = None
398
+ else:
399
+ H_I, damping_input = regularize(H_I, f"{site.key}/input_block")
400
+ record = {
401
+ "path": site.key,
402
+ "in_dim": site.in_dim,
403
+ "out_dim": site.out_dim,
404
+ "components": list(site.components),
405
+ "samples": accumulator["samples"],
406
+ "input_trace": float(np.trace(H_I, axis1=-2, axis2=-1).sum()),
407
+ "input_min_eig": None,
408
+ "input_max_eig": None,
409
+ "input_condition": None,
410
+ "input_damping": damping_input,
411
+ "output_block": H_O is not None,
412
+ }
413
+ try:
414
+ eigenvalues = np.linalg.eigvalsh(H_I)
415
+ record["input_min_eig"] = float(eigenvalues.min())
416
+ record["input_max_eig"] = float(eigenvalues.max())
417
+ record["input_condition"] = float(eigenvalues.max() / max(eigenvalues.min(), 1e-30))
418
+ except np.linalg.LinAlgError:
419
+ record["input_condition"] = float("inf")
420
+ arrays[f"{site.key}/input_block"] = H_I
421
+ if H_O is not None:
422
+ if args.raw_output:
423
+ damping_output = None
424
+ else:
425
+ H_O, damping_output = regularize(H_O, f"{site.key}/output_block")
426
+ arrays[f"{site.key}/output_block"] = H_O
427
+ record["output_damping"] = damping_output
428
+ try:
429
+ eigenvalues = np.linalg.eigvalsh(H_O)
430
+ record["output_min_eig"] = float(eigenvalues.min())
431
+ record["output_max_eig"] = float(eigenvalues.max())
432
+ record["output_condition"] = float(eigenvalues.max() / max(eigenvalues.min(), 1e-30))
433
+ except np.linalg.LinAlgError:
434
+ record["output_condition"] = float("inf")
435
+ records.append(record)
436
+
437
+ args.output.parent.mkdir(parents=True, exist_ok=True)
438
+ np.savez(args.output, **arrays)
439
+ if checkpoint_path.exists():
440
+ checkpoint_path.unlink()
441
+ print(f"saved {args.output} ({len(arrays)} arrays)")
442
+
443
+ summary = {
444
+ "model_dir": str(args.model_dir),
445
+ "corpus": str(args.corpus),
446
+ "eval_corpora": [str(path) for path in args.eval_corpus],
447
+ "overlap_checked": bool(args.eval_corpus),
448
+ "raw_output": bool(args.raw_output),
449
+ "samples": args.samples,
450
+ "max_tokens": args.max_tokens,
451
+ "output_block": args.output_block,
452
+ "damping": args.damping,
453
+ "layers": records,
454
+ }
455
+ if args.json_out:
456
+ args.json_out.parent.mkdir(parents=True, exist_ok=True)
457
+ args.json_out.write_text(json.dumps(summary, indent=2) + "\n")
458
+ print(f"saved {args.json_out}")
459
+ for record in records:
460
+ print(
461
+ f" {record['path']} in={record['in_dim']} out={record['out_dim']} "
462
+ f"cond={record['input_condition']:.3e} out_block={record['output_block']}"
463
+ )
464
+
465
+
466
+ if __name__ == "__main__":
467
+ main()
tests/test_compute_bpc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ pytest.importorskip("tokenizers")
12
+
13
+ from tokenizers import Tokenizer, models, pre_tokenizers # noqa: E402
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+
17
+
18
+ def build_tokenizer(path: Path) -> None:
19
+ vocab = {
20
+ "<unk>": 0,
21
+ "the": 1,
22
+ "quick": 2,
23
+ "brown": 3,
24
+ "fox": 4,
25
+ "jumps": 5,
26
+ "over": 6,
27
+ "lazy": 7,
28
+ "dog": 8,
29
+ "second": 9,
30
+ "line": 10,
31
+ "here": 11,
32
+ "third": 12,
33
+ "another": 13,
34
+ }
35
+ tokenizer = Tokenizer(models.WordLevel(vocab=vocab, unk_token="<unk>"))
36
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
37
+ tokenizer.save(str(path / "tokenizer.json"))
38
+
39
+
40
+ def write_fixture(tmp_path: Path, *, tokens: int, chunks: int, ppl: float) -> tuple[Path, Path]:
41
+ corpus = tmp_path / "corpus.txt"
42
+ corpus.write_text(
43
+ "the quick brown fox jumps over the lazy dog\n"
44
+ "second line here\n"
45
+ "third another line here\n" * 4,
46
+ encoding="utf-8",
47
+ )
48
+ tokenizer_dir = tmp_path / "tok"
49
+ tokenizer_dir.mkdir()
50
+ build_tokenizer(tokenizer_dir)
51
+ payload = {
52
+ "corpus": str(corpus),
53
+ "config": {
54
+ "corpus": str(corpus),
55
+ "max_sequences": chunks,
56
+ "max_tokens": 4,
57
+ "min_tokens": 1,
58
+ },
59
+ "chunks": chunks,
60
+ "tokens": tokens,
61
+ "bf16_ppl": ppl,
62
+ "candidate_ppl": ppl * 1.1,
63
+ }
64
+ ppl_json = tmp_path / "ppl_en.json"
65
+ ppl_json.write_text(json.dumps(payload), encoding="utf-8")
66
+ return ppl_json, tokenizer_dir
67
+
68
+
69
+ def run(*args: str) -> subprocess.CompletedProcess[str]:
70
+ return subprocess.run(
71
+ [sys.executable, str(ROOT / "scripts" / "compute_bpc.py"), *args],
72
+ cwd=ROOT,
73
+ text=True,
74
+ capture_output=True,
75
+ check=False,
76
+ )
77
+
78
+
79
+ def test_bpc_is_log2_ppl_times_fertility(tmp_path: Path) -> None:
80
+ ppl_json, tokenizer_dir = write_fixture(tmp_path, tokens=9, chunks=3, ppl=8.0)
81
+ out = tmp_path / "report.json"
82
+ result = run("--ppl-json", str(ppl_json), "--tokenizer", str(tokenizer_dir), "--json", str(out))
83
+ assert result.returncode == 0, result.stdout + result.stderr
84
+ report = json.loads(out.read_text(encoding="utf-8"))[0]
85
+ assert report["chunks"] == 3
86
+ # every chunk contributes len(chunk) - 1 scored predictions
87
+ assert report["tokens"] == report["chunks"] * 3
88
+ assert report["chars"] > 0
89
+ expected = math.log2(8.0) * report["tokens"] / report["chars"]
90
+ assert report["bpc_bf16"] == pytest.approx(expected)
91
+ assert report["bpc_candidate"] == pytest.approx(math.log2(8.8) * report["tokens"] / report["chars"])
92
+ assert report["reproduced"]["chunks_match"] is True
93
+ assert report["reproduced"]["tokens_match"] is True
94
+
95
+
96
+ def test_strict_mode_flags_token_drift(tmp_path: Path) -> None:
97
+ ppl_json, tokenizer_dir = write_fixture(tmp_path, tokens=99, chunks=3, ppl=8.0)
98
+ result = run("--ppl-json", str(ppl_json), "--tokenizer", str(tokenizer_dir), "--strict")
99
+ assert result.returncode == 1
100
+ assert "tokens_match" in result.stdout
101
+
102
+
103
+ def test_accepts_corpus_override(tmp_path: Path) -> None:
104
+ ppl_json, tokenizer_dir = write_fixture(tmp_path, tokens=9, chunks=3, ppl=8.0)
105
+ payload = json.loads(ppl_json.read_text(encoding="utf-8"))
106
+ payload["corpus"] = str(tmp_path / "missing.txt")
107
+ payload["config"]["corpus"] = str(tmp_path / "missing.txt")
108
+ ppl_json.write_text(json.dumps(payload), encoding="utf-8")
109
+ override = tmp_path / "corpus.txt"
110
+ result = run("--ppl-json", str(ppl_json), "--tokenizer", str(tokenizer_dir), "--corpus", str(override))
111
+ assert result.returncode == 0, result.stdout + result.stderr
tests/test_experiment_guards.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ SCRIPTS = ROOT / "scripts"
13
+
14
+
15
+ def run(script: str, *args: str) -> subprocess.CompletedProcess[str]:
16
+ return subprocess.run(
17
+ [sys.executable, str(SCRIPTS / script), *args],
18
+ cwd=ROOT,
19
+ text=True,
20
+ capture_output=True,
21
+ check=False,
22
+ )
23
+
24
+
25
+ def test_corpus_guard_rejects_overlap(tmp_path: Path) -> None:
26
+ eval_corpus = tmp_path / "eval.txt"
27
+ calib = tmp_path / "calib.txt"
28
+ eval_corpus.write_text("this is a long evaluation line\n", encoding="utf-8")
29
+ calib.write_text("this is a long evaluation line\n", encoding="utf-8")
30
+ result = run(
31
+ "corpus_guard.py",
32
+ "--calibration",
33
+ str(calib),
34
+ "--eval",
35
+ str(eval_corpus),
36
+ )
37
+ assert result.returncode == 1
38
+ assert "overlaps" in result.stderr
39
+
40
+
41
+ def test_corpus_guard_accepts_disjoint(tmp_path: Path) -> None:
42
+ eval_corpus = tmp_path / "eval.txt"
43
+ calib = tmp_path / "calib.txt"
44
+ eval_corpus.write_text("evaluation only line with enough length\n", encoding="utf-8")
45
+ calib.write_text("calibration only line with enough length\n", encoding="utf-8")
46
+ result = run(
47
+ "corpus_guard.py",
48
+ "--calibration",
49
+ str(calib),
50
+ "--eval",
51
+ str(eval_corpus),
52
+ )
53
+ assert result.returncode == 0
54
+
55
+
56
+ def test_dedup_lines_removes_duplicates(tmp_path: Path) -> None:
57
+ source = tmp_path / "source.txt"
58
+ output = tmp_path / "output.txt"
59
+ source.write_text("a\nb\na\nc\nb\n", encoding="utf-8")
60
+ result = run("dedup_lines.py", "--input", str(source), "--output", str(output))
61
+ assert result.returncode == 0
62
+ assert output.read_text(encoding="utf-8").splitlines() == ["a", "b", "c"]
63
+
64
+
65
+ def _write_config(tmp_path: Path, *, overlap: bool = False) -> tuple[Path, Path]:
66
+ eval_en = tmp_path / "eval_en.txt"
67
+ eval_ja = tmp_path / "eval_ja.txt"
68
+ calib = tmp_path / "calib.txt"
69
+ eval_en.write_text(
70
+ "the quick brown fox jumps over the lazy dog\n"
71
+ "a second distinct evaluation sentence for the fixture\n"
72
+ "a third distinct evaluation sentence for the fixture\n",
73
+ encoding="utf-8",
74
+ )
75
+ eval_ja.write_text(
76
+ "日本語の評価用の長い文章です。これは十分な長さがあります。\n"
77
+ "二つ目の評価用文章です。これも十分な長さがあります。\n"
78
+ "三つ目の評価用文章です。これも十分な長さがあります。\n",
79
+ encoding="utf-8",
80
+ )
81
+ if overlap:
82
+ calib.write_text("the quick brown fox jumps over the lazy dog\n", encoding="utf-8")
83
+ else:
84
+ calib.write_text("a completely separate calibration sentence for testing\n", encoding="utf-8")
85
+ config = {
86
+ "name": "fixture",
87
+ "model": {},
88
+ "eval": {
89
+ "max_sequences": 2,
90
+ "max_tokens": 4,
91
+ "min_tokens": 1,
92
+ "corpora": {"en": str(eval_en), "ja": str(eval_ja)},
93
+ },
94
+ "calibration": {
95
+ "samples": 2,
96
+ "max_tokens": 4,
97
+ "output_block": "small",
98
+ "damping": 0.001,
99
+ "corpora": {"calib": str(calib)},
100
+ },
101
+ }
102
+ path = tmp_path / "config.json"
103
+ path.write_text(json.dumps(config), encoding="utf-8")
104
+ return path, calib
105
+
106
+
107
+ def _write_ppl(root: Path, corpus: Path, chunks: int = 2) -> None:
108
+ directory = root / "condition"
109
+ directory.mkdir()
110
+ payload = {
111
+ "corpus": str(corpus),
112
+ "chunks": chunks,
113
+ "tokens": chunks * 4 - chunks,
114
+ "bf16_ppl": 1.0,
115
+ "candidate_ppl": 1.1,
116
+ }
117
+ (directory / "ppl_en.json").write_text(json.dumps(payload), encoding="utf-8")
118
+
119
+
120
+ def test_check_experiment_accepts_consistent_fixture(tmp_path: Path) -> None:
121
+ config, calib = _write_config(tmp_path)
122
+ eval_en = tmp_path / "eval_en.txt"
123
+ _write_ppl(tmp_path, eval_en)
124
+ (tmp_path / "condition" / "calibration.json").write_text(
125
+ json.dumps(
126
+ {
127
+ "corpus": str(calib),
128
+ "samples": 2,
129
+ "max_tokens": 4,
130
+ "output_block": "small",
131
+ "damping": 0.001,
132
+ }
133
+ ),
134
+ encoding="utf-8",
135
+ )
136
+ result = run("check_experiment.py", "--config", str(config), "--root", str(tmp_path))
137
+ assert result.returncode == 0, result.stdout + result.stderr
138
+
139
+
140
+ def test_check_experiment_rejects_chunk_drift(tmp_path: Path) -> None:
141
+ config, calib = _write_config(tmp_path)
142
+ eval_en = tmp_path / "eval_en.txt"
143
+ _write_ppl(tmp_path, eval_en, chunks=3)
144
+ result = run("check_experiment.py", "--config", str(config), "--root", str(tmp_path))
145
+ assert result.returncode == 1
146
+ assert "chunks=3" in result.stdout
147
+
148
+
149
+ def test_check_experiment_rejects_corpus_overlap(tmp_path: Path) -> None:
150
+ config, _ = _write_config(tmp_path, overlap=True)
151
+ eval_en = tmp_path / "eval_en.txt"
152
+ _write_ppl(tmp_path, eval_en)
153
+ result = run("check_experiment.py", "--config", str(config), "--root", str(tmp_path))
154
+ assert result.returncode == 1
155
+ assert "corpus overlap" in result.stdout
156
+
157
+
158
+ def test_merge_calibration_groups_validates_coverage(tmp_path: Path) -> None:
159
+ def write_group(name: str, layer: int) -> Path:
160
+ path = tmp_path / name
161
+ np.savez(
162
+ path,
163
+ **{f"decoder/transformer/layers/[{layer}]/mixer/in_proj/input_block": np.eye(2, dtype=np.float32)},
164
+ )
165
+ return path
166
+
167
+ first = write_group("group-0-1.npz", 0)
168
+ second = write_group("group-1-2.npz", 1)
169
+ output = tmp_path / "merged.npz"
170
+ result = run(
171
+ "merge_calibration_groups.py",
172
+ "--output",
173
+ str(output),
174
+ "--layers",
175
+ "2",
176
+ "--group-size",
177
+ "1",
178
+ str(first),
179
+ str(second),
180
+ )
181
+ assert result.returncode == 0, result.stderr
182
+ with np.load(output) as data:
183
+ assert len(data.files) == 2
184
+
185
+
186
+ def test_merge_calibration_groups_rejects_missing_group(tmp_path: Path) -> None:
187
+ first = tmp_path / "group-0-1.npz"
188
+ np.savez(
189
+ first,
190
+ **{"decoder/transformer/layers/[0]/mixer/in_proj/input_block": np.eye(2, dtype=np.float32)},
191
+ )
192
+ output = tmp_path / "merged.npz"
193
+ result = run(
194
+ "merge_calibration_groups.py",
195
+ "--output",
196
+ str(output),
197
+ "--layers",
198
+ "2",
199
+ "--group-size",
200
+ "1",
201
+ str(first),
202
+ )
203
+ assert result.returncode == 1
204
+ assert "missing groups" in result.stderr
tests/test_tiny_sharding.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ pytest.importorskip("jax")
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+
15
+
16
+ def test_tiny_sharding_probe_on_two_cpu_devices() -> None:
17
+ env = os.environ.copy()
18
+ env["FORCE_2_CPU"] = "1"
19
+ result = subprocess.run(
20
+ [sys.executable, str(ROOT / "scripts" / "tiny_sharding_probe.py")],
21
+ cwd=ROOT,
22
+ env=env,
23
+ text=True,
24
+ capture_output=True,
25
+ check=False,
26
+ )
27
+ assert result.returncode == 0, result.stdout + result.stderr
28
+ report = json.loads(result.stdout)
29
+ assert report["ok"] is True
30
+ assert len(report["devices"]) == 2
31
+ names = {case["name"] for case in report["cases"]}
32
+ assert names == {"column_sharded_matmul", "row_sharded_matmul", "replicated_reshard_matmul"}