File size: 34,728 Bytes
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
7f04381
 
 
 
 
 
 
fbd4e33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
2b2dfe2
 
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
82490ac
7f04381
 
 
 
 
 
 
82490ac
fbd4e33
 
1908b80
 
 
 
 
 
 
fbd4e33
 
 
 
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471461a
 
 
 
 
 
 
 
 
 
 
 
 
2b2dfe2
471461a
 
fbd4e33
 
 
 
 
 
 
 
 
d2136d7
 
 
fbd4e33
 
 
 
 
 
 
 
7f04381
 
 
 
 
 
fbd4e33
7f04381
 
 
 
 
 
 
 
 
 
 
82490ac
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2dfe2
 
 
 
 
 
 
 
 
82490ac
 
 
 
 
 
 
7f04381
3fcb931
 
 
 
 
 
 
 
 
7f04381
3fcb931
 
 
 
 
7f04381
fbd4e33
 
 
 
 
7f04381
3fcb931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1908b80
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1908b80
 
 
ccd07f7
 
 
 
7f04381
 
 
 
 
 
ccd07f7
7f04381
ccd07f7
7f04381
ccd07f7
 
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
 
471461a
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccd07f7
 
 
 
 
 
 
471461a
 
2288fa5
471461a
 
082eff0
 
2b42850
 
2288fa5
 
 
 
471461a
 
 
 
7f04381
 
 
 
 
 
 
 
 
471461a
1908b80
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbd4e33
 
 
 
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2288fa5
7f04381
 
082eff0
 
7f04381
 
 
 
 
 
 
 
471461a
1908b80
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82490ac
7f04381
 
 
 
471461a
2b2dfe2
1908b80
7f04381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426ccd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
 
 
 
 
 
 
 
 
426ccd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
 
 
 
426ccd2
 
 
 
 
7f04381
 
1aac20a
 
 
fbd4e33
 
 
 
 
bb36191
 
 
 
 
 
 
7f04381
 
 
 
 
 
 
bb36191
 
 
 
 
 
 
 
 
 
 
 
fbd4e33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aac20a
 
 
 
 
 
 
7f04381
 
 
 
 
 
 
82490ac
7f04381
426ccd2
 
 
 
 
 
 
 
 
 
 
 
7f04381
 
 
426ccd2
 
 
7f04381
 
426ccd2
 
7f04381
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
#!/usr/bin/env python3
"""Run a quantization experiment lane from a JSON spec.

The point is that the owner defines an experiment as data and the Kaggle
operator only runs it. Every step still goes through the existing scripts, so
guards and provenance stay in force:

  yaqa_calibration.py -> rht_int4_convert.py -> make_lalamo_eval_copy.py -> eval_quantized.py
  (+ merge_language_hessians.py when the spec asks for a language-balanced merge)

Usage:
    python scripts/run_lane.py --spec lanes/clean-suite-08b.json --dry-run
    python scripts/run_lane.py --spec lanes/clean-suite-08b.json
    python scripts/run_lane.py --spec lanes/clean-suite-08b.json --hf-results <user>/uzu-results

Resume is the default: a condition whose ``result.json`` exists and passes the
sanity checks is skipped, so a kernel that dies at the 12h limit can be rerun.
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
from typing import Any

DEFAULT_CONDITION = {
    "samples": 32,
    "calib_dtype": "float32",
    "max_tokens": 128,
    "output_block": "small",
    "output_block_limit": 2048,
    "damping": 1e-3,
    "raw_output": False,
}
DEFAULT_EVAL = {"max_sequences": 100, "max_tokens": 128, "min_tokens": 16}
TRITON_MIN_CAPABILITY = 8.0


def parse_compute_capabilities(output: str) -> list[float]:
    capabilities = []
    for line in output.splitlines():
        text = line.strip().split(",")[0].strip()
        try:
            capabilities.append(float(text))
        except ValueError:
            continue
    return capabilities


def needs_triton_off(capabilities: list[float]) -> bool:
    """XLA's Triton GEMM path only supports Ampere (cc 8.0) and newer."""
    return any(capability < TRITON_MIN_CAPABILITY for capability in capabilities)


def detect_compute_capabilities() -> list[float]:
    try:
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"],
            text=True,
            capture_output=True,
            check=False,
            timeout=20,
        )
    except (OSError, subprocess.TimeoutExpired):
        return []
    if result.returncode != 0:
        return []
    return parse_compute_capabilities(result.stdout)


def find_dataset_dir(root: Path, name: str) -> Path | None:
    """Locate a mounted dataset regardless of the /kaggle/input layout."""
    candidates = [
        root / name,
        *sorted(root.glob(f"datasets/*/{name}")),
        *sorted(root.glob(f"datasets/*/*/{name}")),
    ]
    for candidate in candidates:
        if (candidate / "model.safetensors").exists():
            return candidate
    # last resort: any directory with both weights and a tokenizer
    for weights in sorted(root.rglob("model.safetensors")):
        directory = weights.parent
        if (directory / "tokenizer.json").exists():
            return directory
    return None


try:
    from env_fingerprint import fingerprint, lalamo_provenance, parse_direct_url
except Exception:  # noqa: BLE001 - older kits may not ship env_fingerprint.py
    def parse_direct_url(text: str) -> dict[str, str]:
        return {}

    def lalamo_provenance() -> dict[str, str]:
        return {}

    def fingerprint() -> dict[str, str]:
        return {}


class Runner:
    def __init__(self, spec: dict[str, Any], spec_path: Path, *, dry_run: bool = False) -> None:
        self.spec = spec
        self.spec_path = spec_path
        self.dry_run = dry_run
        self.commands: list[list[str]] = []

        paths = spec.get("paths", {})
        kit = Path(paths.get("kit", "kit")).expanduser()
        work = Path(paths.get("work", "/kaggle/working")).expanduser()
        self.kit = kit
        self.work = work
        self.scripts = {
            "preflight": self._script(paths.get("preflight", "scripts/preflight.py")),
            "calibrate": self._script(paths.get("calibrate", "scripts/yaqa_calibration.py")),
            "convert": self._script(paths.get("convert", "scripts/rht_int4_convert.py")),
            "merge": self._script(paths.get("merge", "scripts/merge_language_hessians.py")),
            "eval": self._script(paths.get("eval", "scripts/eval_quantized.py")),
            "copy": self._script(paths.get("copy", "scripts/make_lalamo_eval_copy.py")),
        }
        self.lane = spec.get("lane") or spec_path.stem
        self.preflight: dict | None = None
        capabilities = detect_compute_capabilities()
        self.triton_off = needs_triton_off(capabilities)
        # T4 (cc 7.5) has no BF16 matmul: ALG_DOT_BF16_BF16_F32 is unsupported.
        # Fall back to float32 so the lane can run at all.
        configured_dtype = (spec.get("eval") or {}).get("dtype")
        self.eval_dtype = configured_dtype or ("float32" if self.triton_off else "bfloat16")
        if self.triton_off and configured_dtype == "bfloat16":
            print("GPU cannot do BF16 matmul; overriding eval dtype to float32", flush=True)
            self.eval_dtype = "float32"
        if self.triton_off:
            print(
                f"GPU caps {capabilities}: disabling XLA Triton GEMM (needs >= {TRITON_MIN_CAPABILITY})",
                flush=True,
            )
        self.lane_dir = work / "out" / self.lane
        self.jax_platform = paths.get("jax_platform") or os.environ.get("JAX_PLATFORM_NAME") or None

    # ---------- helpers ----------

    def _script(self, relative: str) -> Path:
        path = Path(relative)
        return path if path.is_absolute() else self.kit / path

    def resolve(self, value: str | None) -> Path | None:
        if value is None:
            return None
        path = Path(value).expanduser()
        return path if path.is_absolute() else self.kit / path

    def env_provenance(self) -> dict[str, str]:
        """Environment knobs that change numerics must travel with the results."""
        prefixes = ("XLA_FLAGS", "JAX_", "UZU_")
        seen = {}
        for key, value in self.environment().items():
            if key.startswith(prefixes):
                seen[key] = value
        try:
            from importlib.metadata import version

            seen["jax_version"] = version("jax")
        except Exception:  # noqa: BLE001 - provenance must never break a run
            pass
        seen.update(lalamo_provenance())
        return seen

    def environment(self, base: dict[str, str] | None = None) -> dict[str, str]:
        env = dict(os.environ if base is None else base)
        if self.jax_platform:
            env["JAX_PLATFORM_NAME"] = self.jax_platform
        for key, value in (self.spec.get("paths", {}).get("env") or {}).items():
            env[str(key)] = str(value)
        flags = list(self.spec.get("paths", {}).get("xla_flags", []))
        if self.triton_off:
            flags.append("--xla_gpu_enable_triton_gemm=false")
            # lalamo inference defaults to the Pallas-Triton flash attention kernel,
            # which T4 cannot compile. XLA attention is the supported path there.
            env.setdefault("UZU_ATTENTION_IMPL", "xla")
        existing = env.get("XLA_FLAGS", "")
        for flag in flags:
            if flag not in existing:
                existing = (existing + " " + flag).strip()
        if existing:
            env["XLA_FLAGS"] = existing
        return env

    def run(self, step: str, command: list[str], log: Path) -> None:
        display = " ".join(str(part) for part in command)
        print(f"$ {display}", flush=True)
        self.commands.append([str(part) for part in command])
        if self.dry_run:
            return
        env = self.environment()
        started = time.time()
        with log.open("a", encoding="utf-8") as handle:
            handle.write(f"\n=== {step} {time.strftime('%H:%M:%S')} ===\n$ {display}\n")
            handle.flush()
            result = subprocess.run(command, stdout=handle, stderr=subprocess.STDOUT, env=env, check=False)
        if result.returncode != 0:
            raise SystemExit(f"{step} failed with code {result.returncode}; see {log}")
        print(f"  {step} ok ({time.time() - started:.0f}s)", flush=True)

    # ---------- steps ----------

    def run_preflight(self) -> dict | None:
        """Refuse to burn ten minutes on a GPU that cannot run the attention path."""
        script = self.scripts.get("preflight")
        if script is None or not Path(script).exists() or self.dry_run:
            return None
        report_path = self.lane_dir / "preflight.json"
        command = [sys.executable, str(script), "--json", str(report_path)]
        env = self.environment()
        result = subprocess.run(command, text=True, capture_output=True, env=env, check=False)
        print(result.stdout.strip()[:800], flush=True)
        if result.returncode != 0 or not report_path.exists():
            print(f"preflight failed to produce a report (rc={result.returncode})", flush=True)
            return None
        report = json.loads(report_path.read_text(encoding="utf-8"))
        probes = report.get("probes") or {}
        if probes.get("quant_roundtrip") == "fail":
            error = (report.get("probe_errors") or {}).get("quant_roundtrip", "")
            raise SystemExit(
                "preflight: lalamo has no working RHT quantize/dequantize path. "
                "This is the PyPI 0.17.0 trap: install "
                "git+https://github.com/trymirai/lalamo@e401e177 instead. "
                f"{error}".strip()
            )
        if (self.jax_platform or "").startswith("gpu") and report.get("attention") == "unavailable":
            raise SystemExit(
                "preflight: dot_product_attention is unavailable on this GPU "
                f"({report.get('gpu_names')}). Use --jax-platform cpu or Modal."
            )
        return report

    def ensure_bf16(self) -> Path:
        """Return a lalamo-loadable BF16 directory.

        The import path (rht_int4_convert --dry-run) normalizes config.json for
        uzu: it drops ``response_format`` and adds ``output_parser_regex`` /
        ``end_of_thinking_tag``. Pinned lalamo refuses that schema, so
        calibration cannot load the imported directory directly. The import is
        therefore written to a raw directory and ``make_lalamo_eval_copy``
        produces the loadable copy that both calibration and eval use.
        """
        model = self.spec.get("model", {})
        target = self.resolve(model.get("bf16_dir", "bf16-lalamo"))
        assert target is not None
        if (target / "model.safetensors").exists():
            return target

        source = self.resolve(model.get("bf16_source"))
        if source and not (source / "model.safetensors").exists() and model.get("bf16_source_auto"):
            found = find_dataset_dir(Path("/kaggle/input"), source.name)
            if found is not None:
                print(f"bf16 source resolved to {found}", flush=True)
                source = found
        if source and (source / "model.safetensors").exists():
            print(f"copy bf16 from {source} -> {target}", flush=True)
            if not self.dry_run:
                shutil.copytree(source, target, dirs_exist_ok=True)
            return target

        raw = self.resolve(model.get("bf16_raw_dir", "bf16-raw"))
        assert raw is not None
        if not (raw / "model.safetensors").exists():
            command = [
                sys.executable,
                str(self.scripts["convert"]),
                "--spec-name",
                model.get("spec_name", "Qwen3.5-0.8B"),
                "--output-dir",
                str(self.work / "import"),
                "--dry-run",
                "--bf16-dir",
                str(raw),
            ]
            if model.get("hf_repo"):
                command += ["--hf-repo", model["hf_repo"]]
            if model.get("hf_dir"):
                command += ["--hf-dir", str(self.resolve(model["hf_dir"]))]
            self.run("bf16 import", command, self.lane_dir / "lane.log")

        self.run(
            "bf16 lalamo copy",
            [sys.executable, str(self.scripts["copy"]), "--source", str(raw), "--dest", str(target)],
            self.lane_dir / "lane.log",
        )
        return target

    def eval_corpora(self) -> dict[str, Path]:
        corpora = self.spec.get("eval", {}).get("corpora", {})
        if not corpora:
            raise SystemExit("spec.eval.corpora is empty")
        resolved = {}
        for lang, path in corpora.items():
            target = self.resolve(path)
            assert target is not None
            resolved[lang] = target
        return resolved

    def condition_settings(self, condition: dict[str, Any]) -> dict[str, Any]:
        settings = dict(DEFAULT_CONDITION)
        settings.update(self.spec.get("condition_defaults", {}))
        settings.update({key: value for key, value in condition.items() if key not in ("name", "calibration_corpus")})
        return settings

    def existing_result(self, name: str) -> dict[str, Any] | None:
        path = self.lane_dir / name / "result.json"
        if not path.exists():
            return None
        try:
            payload = json.loads(path.read_text(encoding="utf-8"))
        except json.JSONDecodeError:
            return None
        if payload.get("status") != "complete":
            return None
        return payload

    def evaluate(self, name: str, candidate: Path, bf16: Path) -> dict[str, Any]:
        out = self.lane_dir / name
        base = read_json(out / "calibration.json") or {}
        summary: dict[str, Any] = {
            "name": name,
            "calibration": {
                "corpus": base.get("corpus"),
                "samples": base.get("samples"),
                "max_tokens": base.get("max_tokens"),
                "output_block": base.get("output_block"),
                "damping": base.get("damping"),
                "calib_dtype": base.get("calib_dtype"),
                "raw_output": base.get("raw_output"),
                "ja_ratio": base.get("ja_ratio"),
                "overlap_checked": base.get("overlap_checked"),
            },
            "ppl": {},
        }
        for lang, corpus in self.eval_corpora().items():
            json_out = out / f"ppl_{lang}.json"
            self.run(
                f"{name} eval {lang}",
                [
                    sys.executable,
                    str(self.scripts["eval"]),
                    "--bf16-dir",
                    str(bf16),
                    "--candidate-dir",
                    str(candidate),
                    "--corpus",
                    str(corpus),
                    "--max-sequences",
                    str(self.spec.get("eval", {}).get("max_sequences", DEFAULT_EVAL["max_sequences"])),
                    "--max-tokens",
                    str(self.spec.get("eval", {}).get("max_tokens", DEFAULT_EVAL["max_tokens"])),
                    "--dtype",
                    str(self.eval_dtype),
                    "--min-tokens",
                    str(self.spec.get("eval", {}).get("min_tokens", DEFAULT_EVAL["min_tokens"])),
                    "--json-out",
                    str(json_out),
                ],
                out / "lane.log",
            )
            payload = read_json(json_out) or {}
            summary["ppl"][lang] = {
                key: payload.get(key)
                for key in (
                    "chunks",
                    "tokens",
                    "bf16_ppl",
                    "candidate_ppl",
                    "delta_nll_per_token",
                    "config_hash",
                )
            }
        return summary

    def run_condition(self, condition: dict[str, Any], bf16: Path) -> dict[str, Any]:
        name = condition["name"]
        out = self.lane_dir / name
        if not self.dry_run:
            out.mkdir(parents=True, exist_ok=True)
        settings = self.condition_settings(condition)
        if self.triton_off and str(settings.get("calib_dtype")) == "bfloat16":
            print(f"{name}: BF16 calibration is unsupported on this GPU; using float32", flush=True)
            settings["calib_dtype"] = "float32"
        is_rtn = bool(condition.get("rtn"))
        corpus = self.resolve(condition.get("calibration_corpus")) if not is_rtn else None
        if not is_rtn and corpus is None:
            raise SystemExit(f"{name}: calibration_corpus is required unless rtn=true")

        existing = self.existing_result(name)
        if existing is not None:
            print(f"skip {name}: result.json already complete", flush=True)
            return existing

        skip_convert = (not is_rtn) and (bool(condition.get("skip_convert")) or (
            settings.get("raw_output") and bool(self.spec.get("merge")) and not condition.get("force_convert")
        ))
        calib_npz = out / "calibration.npz"
        if is_rtn:
            print(f"{name}: RTN (no calibration)", flush=True)
        elif not calib_npz.exists():
            command = [
                sys.executable,
                str(self.scripts["calibrate"]),
                "--model-dir",
                str(bf16),
                "--corpus",
                str(corpus),
                "--output",
                str(calib_npz),
                "--json-out",
                str(out / "calibration.json"),
                "--samples",
                str(settings["samples"]),
                "--max-tokens",
                str(settings["max_tokens"]),
                "--output-block",
                str(settings["output_block"]),
                "--output-block-limit",
                str(settings["output_block_limit"]),
                "--damping",
                str(settings["damping"]),
            ]
            for eval_corpus in self.eval_corpora().values():
                command += ["--eval-corpus", str(eval_corpus)]
            if settings.get("calib_dtype"):
                command += ["--calib-dtype", str(settings["calib_dtype"])]
            if settings.get("seed") is not None:
                command += ["--seed", str(settings["seed"])]
            if settings.get("raw_output"):
                command.append("--raw-output")
            if self.spec.get("convert", {}).get("parallel"):
                command += ["--parallel", str(self.spec["convert"]["parallel"])]
            self.run(f"{name} calibration", command, out / "lane.log")

        if skip_convert:
            summary = {
                "name": name,
                "status": "complete",
                "skipped": "convert" if not condition.get("force_convert") else None,
                "calibration": {
                    "corpus": str(corpus),
                    "samples": settings["samples"],
                    "max_tokens": settings["max_tokens"],
                    "output_block": settings["output_block"],
                    "damping": settings["damping"],
                    "raw_output": settings["raw_output"],
                },
                "ppl": {},
                "finished": time.strftime("%Y-%m-%dT%H:%M:%S"),
                "spec": str(self.spec_path),
            }
            if not self.dry_run:
                (out / "result.json").write_text(
                    json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
                )
            return summary

        int4 = self.work / f"int4-{self.lane}-{name}"
        int4_eval = self.work / f"int4-{self.lane}-{name}-eval"
        convert_command = [
            sys.executable,
            str(self.scripts["convert"]),
            "--load-from",
            str(bf16),
            "--output-dir",
            str(int4),
        ]
        if not is_rtn:
            convert_command += [
                "--preconditioners",
                str(calib_npz),
                "--calibration-json",
                str(out / "calibration.json"),
            ]
        convert_settings = dict(self.spec.get("convert", {}))
        convert_settings.update(condition.get("convert") or {})
        for key in ("bits", "group_size", "block_size", "parallel", "embedding_bits", "symmetric_bits"):
            if key in convert_settings:
                convert_command += [f"--{key.replace('_', '-')}", str(convert_settings[key])]
        if convert_settings.get("quantize_embedding"):
            convert_command.append("--quantize-embedding")
        if convert_settings.get("layer_filter"):
            convert_command += ["--layer-filter", str(convert_settings["layer_filter"])]
        if convert_settings.get("layer_bits_json"):
            settings_path = self.resolve(convert_settings["layer_bits_json"])
            assert settings_path is not None
            convert_command += ["--layer-bits-json", str(settings_path)]
        if condition.get("layer_bits_json"):
            bits_path = self.resolve(condition["layer_bits_json"])
            assert bits_path is not None
            convert_command += ["--layer-bits-json", str(bits_path)]
        self.run(f"{name} convert", convert_command, out / "lane.log")
        self.run(
            f"{name} eval copy",
            [sys.executable, str(self.scripts["copy"]), "--source", str(int4), "--dest", str(int4_eval)],
            out / "lane.log",
        )

        summary = self.evaluate(name, int4_eval, bf16)
        summary["status"] = "complete"
        summary["env"] = self.env_provenance()
        summary["eval_dtype"] = self.eval_dtype
        summary["finished"] = time.strftime("%Y-%m-%dT%H:%M:%S")
        summary["spec"] = str(self.spec_path)
        if not self.dry_run:
            (out / "result.json").write_text(
                json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
            )

        if not self.dry_run:
            shutil.rmtree(int4, ignore_errors=True)
            shutil.rmtree(int4_eval, ignore_errors=True)
            calib_npz.unlink(missing_ok=True)
        return summary

    def run_merge(self, bf16: Path) -> list[dict[str, Any]]:
        merge = self.spec.get("merge")
        if not merge:
            return []
        en_raw = self.lane_dir / merge["en"] / "calibration.npz"
        ja_raw = self.lane_dir / merge["ja"] / "calibration.npz"
        summaries = []
        for ratio in merge.get("ratios", [0.5]):
            label = f"{float(ratio) * 100:.0f}" if float(ratio) <= 1 else str(ratio)
            name = merge.get("name_template", "balanced-{ratio}").format(ratio=label)
            out = self.lane_dir / name
            if not self.dry_run:
                out.mkdir(parents=True, exist_ok=True)
            existing = self.existing_result(name)
            if existing is not None:
                print(f"skip {name}: result.json already complete", flush=True)
                summaries.append(existing)
                continue
            merged = out / "calibration.npz"
            self.run(
                f"{name} merge",
                [
                    sys.executable,
                    str(self.scripts["merge"]),
                    "--en",
                    str(en_raw),
                    "--ja",
                    str(ja_raw),
                    "--ja-ratio",
                    str(ratio),
                    "--damping",
                    str(merge.get("damping", 1e-3)),
                    "--output",
                    str(merged),
                    "--json-out",
                    str(out / "calibration.json"),
                    "--en-json",
                    str(self.lane_dir / merge["en"] / "calibration.json"),
                    "--ja-json",
                    str(self.lane_dir / merge["ja"] / "calibration.json"),
                ],
                out / "lane.log",
            )
            int4 = self.work / f"int4-{self.lane}-{name}"
            int4_eval = self.work / f"int4-{self.lane}-{name}-eval"
            convert_command = [
                sys.executable,
                str(self.scripts["convert"]),
                "--load-from",
                str(bf16),
                "--output-dir",
                str(int4),
                "--preconditioners",
                str(merged),
                "--calibration-json",
                str(out / "calibration.json"),
            ]
            for key in ("bits", "group_size", "block_size", "parallel", "embedding_bits", "symmetric_bits"):
                if key in self.spec.get("convert", {}):
                    convert_command += [f"--{key.replace('_', '-')}", str(self.spec["convert"][key])]
            if self.spec.get("convert", {}).get("quantize_embedding"):
                convert_command.append("--quantize-embedding")
            self.run(f"{name} convert", convert_command, out / "lane.log")
            self.run(
                f"{name} eval copy",
                [sys.executable, str(self.scripts["copy"]), "--source", str(int4), "--dest", str(int4_eval)],
                out / "lane.log",
            )
            summary = self.evaluate(name, int4_eval, bf16)
            summary["status"] = "complete"
            summary["env"] = self.env_provenance()
            summary["eval_dtype"] = self.eval_dtype
            summary["ja_ratio"] = ratio
            summary["finished"] = time.strftime("%Y-%m-%dT%H:%M:%S")
            summary["spec"] = str(self.spec_path)
            if not self.dry_run:
                (out / "result.json").write_text(
                    json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
                )
            if not self.dry_run:
                shutil.rmtree(int4, ignore_errors=True)
                shutil.rmtree(int4_eval, ignore_errors=True)
                merged.unlink(missing_ok=True)
            summaries.append(summary)
        return summaries

    # ---------- validation ----------

    def validate(self, summaries: list[dict[str, Any]]) -> list[str]:
        problems = []
        expected_chunks = self.spec.get("eval", {}).get("max_sequences", DEFAULT_EVAL["max_sequences"])
        baseline: dict[str, float] = {}
        for summary in summaries:
            name = summary.get("name")
            for lang, ppl in (summary.get("ppl") or {}).items():
                if ppl.get("chunks") != expected_chunks:
                    problems.append(f"{name}/{lang}: chunks={ppl.get('chunks')} (expected {expected_chunks})")
                value = ppl.get("bf16_ppl")
                if value is None:
                    problems.append(f"{name}/{lang}: missing bf16_ppl")
                    continue
                if lang not in baseline:
                    baseline[lang] = float(value)
                elif abs(baseline[lang] - float(value)) > 0.05:
                    problems.append(
                        f"{name}/{lang}: bf16_ppl drift {float(value):.2f} vs {baseline[lang]:.2f}"
                    )
        return problems

    def write_manifest(self, summaries: list[dict[str, Any]], problems: list[str]) -> Path:
        manifest = {
            "preflight": self.preflight,
            "lane": self.lane,
            "spec": str(self.spec_path),
            "model": self.spec.get("model"),
            "eval": self.spec.get("eval"),
            "env": self.env_provenance(),
            "environment_fingerprint": fingerprint(),
            "eval_dtype": self.eval_dtype,
            "results": summaries,
            "problems": problems,
            "updated": time.strftime("%Y-%m-%dT%H:%M:%S"),
        }
        path = self.lane_dir / "manifest.json"
        if self.dry_run:
            print(json.dumps(manifest, indent=2, ensure_ascii=False)[:2000])
            return path
        self.lane_dir.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        return path

    def upload(self, repo: str) -> None:
        if self.dry_run:
            print(f"[dry-run] would upload {self.lane_dir} to {repo}")
            return
        subprocess.run(
            ["hf", "upload", repo, str(self.lane_dir), self.lane, "--repo-type", "dataset"],
            check=False,
        )

    def pull(self, repo: str) -> None:
        """Restore finished conditions of this lane from the results repo.

        Kaggle wipes /kaggle/working between sessions, so without this a lane
        that died on condition 4 restarted from condition 1 and paid for the
        same calibration twice.
        """
        if self.dry_run:
            print(f"[dry-run] would pull {self.lane} from {repo}")
            return
        target = self.work / "out"
        target.mkdir(parents=True, exist_ok=True)
        subprocess.run(
            [
                "hf", "download", repo, "--repo-type", "dataset",
                "--include", f"{self.lane}/*", "--local-dir", str(target),
            ],
            check=False,
        )


def read_json(path: Path) -> dict[str, Any] | None:
    if not path.exists():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return None


def run_conditions(runner, conditions, bf16, after_each=None, fail_fast: bool = False):
    """Run every condition even if one dies; return (summaries, failures).

    A single OOM condition used to abort the lane, so the four conditions after
    it never ran and nothing was uploaded. Failures are recorded instead.
    """
    summaries = []
    failures = []
    for condition in conditions:
        name = condition.get("name", "?")
        try:
            summaries.append(runner.run_condition(condition, bf16))
        except (SystemExit, Exception) as error:
            failures.append(f"{name}: {error}")
            print(f"CONDITION FAILED {name}: {error}", flush=True)
            summaries.append({"name": name, "status": "failed", "error": str(error)})
            if fail_fast:
                raise
        if after_each is not None:
            after_each()
    return summaries, failures


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--spec", type=Path, required=True)
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--hf-results", default=None, help="upload <lane_dir> to this HF dataset repo")
    parser.add_argument(
        "--fail-fast",
        action="store_true",
        help="stop at the first failing condition instead of recording it and continuing",
    )
    parser.add_argument("--skip-merge", action="store_true")
    parser.add_argument("--work", default=None, help="override spec.paths.work")
    parser.add_argument("--jax-platform", choices=("cpu", "gpu"), default=None, help="override spec.paths.jax_platform")
    parser.add_argument("--eval-dtype", choices=("bfloat16", "float32"), default=None, help="override the eval model dtype")
    parser.add_argument("--parallel", choices=("tensor", "replicated"), default=None, help="override convert/calibration sharding")
    parser.add_argument(
        "--shard",
        default=None,
        help="run only part of the condition list, e.g. 0/3. Merges are not allowed with sharding.",
    )
    parser.add_argument(
        "--exclude",
        action="append",
        default=[],
        metavar="SUBSTR",
        help="drop conditions whose name contains SUBSTR (repeatable); e.g. --exclude q512",
    )
    args = parser.parse_args()

    spec = json.loads(args.spec.read_text(encoding="utf-8"))
    conditions = spec.get("conditions", [])
    if not conditions and not spec.get("merge"):
        raise SystemExit("spec has no conditions")

    if args.exclude:
        before = len(conditions)
        conditions = [
            condition
            for condition in conditions
            if not any(pattern in condition.get("name", "") for pattern in args.exclude)
        ]
        print(f"excluded {before - len(conditions)} conditions matching {args.exclude}", flush=True)
        if not conditions:
            raise SystemExit(f"--exclude {args.exclude} removed every condition")
        spec["conditions"] = conditions

    if args.shard:
        if spec.get("merge"):
            raise SystemExit("--shard cannot be combined with spec.merge")
        try:
            index_text, count_text = args.shard.split("/")
            index, count = int(index_text), int(count_text)
        except ValueError:
            raise SystemExit("--shard must look like 0/3")
        if count <= 0 or not 0 <= index < count:
            raise SystemExit("--shard index out of range")
        conditions = [condition for position, condition in enumerate(conditions) if position % count == index]
        if not conditions:
            raise SystemExit(f"shard {args.shard} has no conditions")
        spec["conditions"] = conditions
        spec["lane"] = f"{spec['lane']}-shard{index + 1}of{count}"

    if args.jax_platform:
        spec.setdefault("paths", {})["jax_platform"] = args.jax_platform
    if args.eval_dtype:
        spec.setdefault("eval", {})["dtype"] = args.eval_dtype
    if args.parallel:
        spec.setdefault("convert", {})["parallel"] = args.parallel

    runner = Runner(spec, args.spec, dry_run=args.dry_run)
    if args.work:
        runner.work = Path(args.work).expanduser()
        runner.lane_dir = runner.work / "out" / runner.lane
    if not args.dry_run:
        runner.lane_dir.mkdir(parents=True, exist_ok=True)

    runner.preflight = runner.run_preflight()
    bf16 = runner.ensure_bf16()
    if args.hf_results and not args.dry_run:
        runner.pull(args.hf_results)

    def after_each() -> None:
        # Upload as soon as a condition finishes: a dead session otherwise took
        # every completed condition with it.
        if args.hf_results:
            runner.upload(args.hf_results)

    summaries, failures = run_conditions(
        runner, conditions, bf16, after_each=after_each, fail_fast=args.fail_fast
    )
    if not args.skip_merge:
        summaries.extend(runner.run_merge(bf16))

    completed = [summary for summary in summaries if summary.get("status") == "complete"]
    problems = [] if args.dry_run else runner.validate(completed)
    problems.extend(failures)
    manifest = runner.write_manifest(summaries, problems)
    print(f"\nmanifest: {manifest}")
    if args.hf_results:
        runner.upload(args.hf_results)
    if problems:
        print("VALIDATION PROBLEMS:")
        for problem in problems:
            print(f"  - {problem}")
        raise SystemExit(1)

    print("LANE COMPLETE", flush=True)


if __name__ == "__main__":
    main()