yamahei21 commited on
Commit
bd72529
·
verified ·
1 Parent(s): 3bf7abb

Add build_kit and bootstrap helpers

Browse files
Files changed (2) hide show
  1. scripts/bootstrap_kaggle.py +71 -0
  2. scripts/build_kit.py +178 -0
scripts/bootstrap_kaggle.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Prepare a Kaggle/Colab session for a uzu lane.
3
+
4
+ Robustness notes:
5
+ - ``hf download --include`` behaviour differs between huggingface_hub versions
6
+ (some accept a single value only). The kit is ~5 MB, so this script downloads
7
+ the whole dataset and avoids ``--include`` entirely.
8
+ - The kit is rebuilt from a fixed manifest (``scripts/build_kit.py``), so a
9
+ missing script cannot silently slip in.
10
+
11
+ Usage:
12
+ python scripts/bootstrap_kaggle.py # install deps + fetch kit
13
+ python scripts/bootstrap_kaggle.py --no-install # kit only
14
+ python scripts/bootstrap_kaggle.py --dry-run
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ KIT_REPO = "yamahei21/uzu-quant-kit"
25
+ LALAMO = "git+https://github.com/trymirai/lalamo@e401e17761f2fcd337b0cf20218d67d656e6ecba"
26
+ PACKAGES = [LALAMO, "jax[cuda12]", "huggingface_hub", "tokenizers"]
27
+
28
+
29
+ def run(command: list[str], dry_run: bool) -> None:
30
+ print("$ " + " ".join(command), flush=True)
31
+ if dry_run:
32
+ return
33
+ subprocess.run(command, check=True)
34
+
35
+
36
+ def main() -> None:
37
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
38
+ parser.add_argument("--work", default="/kaggle/working")
39
+ parser.add_argument("--no-install", action="store_true", help="skip pip install")
40
+ parser.add_argument("--dry-run", action="store_true")
41
+ args = parser.parse_args()
42
+
43
+ work = Path(args.work)
44
+ kit = work / "kit"
45
+
46
+ if not args.no_install:
47
+ run([sys.executable, "-m", "pip", "install", "-q", *PACKAGES], args.dry_run)
48
+
49
+ run(
50
+ [
51
+ "hf",
52
+ "download",
53
+ KIT_REPO,
54
+ "--repo-type",
55
+ "dataset",
56
+ "--local-dir",
57
+ str(kit),
58
+ ],
59
+ args.dry_run,
60
+ )
61
+
62
+ print(
63
+ "\nnext:\n"
64
+ f" python {kit}/scripts/run_lane.py --spec {kit}/lanes/clean-suite-08b.json "
65
+ f"--hf-results <user>/uzu-results --work {work}",
66
+ flush=True,
67
+ )
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
scripts/build_kit.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble or check the public quantization kit (scripts + corpora).
3
+
4
+ The Kaggle/HF kit is a copy of a fixed file list. Copying by hand is how
5
+ ``rewrite_lalamo_hybrid_spec.py`` went missing even though
6
+ ``rht_int4_convert.py`` imports it lazily. This script is the single source of
7
+ truth for what goes in, so the kit can be rebuilt and verified.
8
+
9
+ Usage:
10
+ python scripts/build_kit.py --output /tmp/uzu-kit
11
+ python scripts/build_kit.py --check /tmp/uzu-kit
12
+ python scripts/build_kit.py --list
13
+
14
+ A kit is valid when:
15
+ - every file in KIT_FILES exists
16
+ - every ``import <local_module>`` / ``from <local_module> import`` inside the
17
+ kit resolves to a file in the kit
18
+ - every script compiles
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import ast
25
+ import json
26
+ import shutil
27
+ from pathlib import Path
28
+
29
+ ROOT = Path(__file__).resolve().parents[1]
30
+
31
+ KIT_SCRIPTS = [
32
+ # pipeline
33
+ "rht_int4_convert.py",
34
+ "rewrite_lalamo_hybrid_spec.py",
35
+ "normalize_lalamo_config.py",
36
+ "make_lalamo_eval_copy.py",
37
+ "yaqa_calibration.py",
38
+ "merge_language_hessians.py",
39
+ "merge_calibration_groups.py",
40
+ "eval_quantized.py",
41
+ "qad_finetune.py",
42
+ "compute_bpc.py",
43
+ "run_lane.py",
44
+ # guards / audits
45
+ "corpus_guard.py",
46
+ "dedup_lines.py",
47
+ "dedup_calibration.py",
48
+ "check_experiment.py",
49
+ # sharding
50
+ "tiny_sharding_probe.py",
51
+ # operator tooling
52
+ "build_kit.py",
53
+ "bootstrap_kaggle.py",
54
+ ]
55
+
56
+ KIT_DATA = [
57
+ "calibration_en_wikitext2_dedup.txt",
58
+ "calibration_ja_wikipedia_dedup.txt",
59
+ "calibration_mixed_en_ja_dedup.txt",
60
+ "calibration_mixed_ja35_en65_dedup.txt",
61
+ "calibration_mixed_ja65_en35_dedup.txt",
62
+ "eval_en_wikitext2_dedup.txt",
63
+ "eval_ja_wikipedia_dedup.txt",
64
+ ]
65
+
66
+ KIT_LANES = ["README.md", "clean-suite-08b.json", "balanced-h-08b.json"]
67
+
68
+ KIT_TESTS = [
69
+ "test_experiment_guards.py",
70
+ "test_compute_bpc.py",
71
+ "test_run_lane.py",
72
+ "test_tiny_sharding.py",
73
+ ]
74
+
75
+ DATA_ROOT = ROOT / "experiments" / "qwen35-0.8b" / "data"
76
+
77
+
78
+ def build(output: Path) -> list[str]:
79
+ copied: list[str] = []
80
+ layout = {
81
+ "scripts": [(ROOT / "scripts" / name, name) for name in KIT_SCRIPTS],
82
+ "data": [(DATA_ROOT / name, name) for name in KIT_DATA],
83
+ "lanes": [(ROOT / "lanes" / name, name) for name in KIT_LANES],
84
+ "tests": [(ROOT / "tests" / name, name) for name in KIT_TESTS],
85
+ "configs": [(ROOT / "experiments" / model / "config.json", f"{model}.json") for model in ("qwen35-0.8b", "qwen35-4b", "qwen35-9b")],
86
+ }
87
+ for subdir, entries in layout.items():
88
+ target_dir = output / subdir
89
+ target_dir.mkdir(parents=True, exist_ok=True)
90
+ for source, name in entries:
91
+ if not source.exists():
92
+ raise SystemExit(f"missing source: {source}")
93
+ shutil.copy2(source, target_dir / name)
94
+ copied.append(f"{subdir}/{name}")
95
+ return copied
96
+
97
+
98
+ def local_modules(scripts: list[Path]) -> dict[str, set[str]]:
99
+ """Map module name -> places where it is imported, for kit-local modules."""
100
+ available = {path.stem for path in scripts}
101
+ imported: dict[str, set[str]] = {}
102
+ for path in scripts:
103
+ tree = ast.parse(path.read_text(encoding="utf-8"))
104
+ for node in ast.walk(tree):
105
+ names: list[str] = []
106
+ if isinstance(node, ast.Import):
107
+ names = [alias.name.split(".")[0] for alias in node.names]
108
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
109
+ names = [node.module.split(".")[0]]
110
+ for name in names:
111
+ if name in available and name != path.stem:
112
+ imported.setdefault(name, set()).add(path.name)
113
+ return imported
114
+
115
+
116
+ def check(kit: Path) -> list[str]:
117
+ problems: list[str] = []
118
+ for subdir, names in (
119
+ ("scripts", KIT_SCRIPTS),
120
+ ("data", KIT_DATA),
121
+ ("lanes", KIT_LANES),
122
+ ("tests", KIT_TESTS),
123
+ ):
124
+ for name in names:
125
+ if not (kit / subdir / name).exists():
126
+ problems.append(f"missing {subdir}/{name}")
127
+
128
+ scripts = sorted((kit / "scripts").glob("*.py"))
129
+ if not scripts:
130
+ return problems + ["no scripts in kit"]
131
+ for path in scripts:
132
+ try:
133
+ compile(path.read_text(encoding="utf-8"), str(path), "exec")
134
+ except SyntaxError as error:
135
+ problems.append(f"syntax error in {path.name}: {error}")
136
+
137
+ for module, importers in local_modules(scripts).items():
138
+ if not (kit / "scripts" / f"{module}.py").exists():
139
+ problems.append(
140
+ f"missing scripts/{module}.py imported by {', '.join(sorted(importers))}"
141
+ )
142
+ return problems
143
+
144
+
145
+ def main() -> None:
146
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
147
+ parser.add_argument("--output", type=Path, default=None, help="build the kit here")
148
+ parser.add_argument("--check", type=Path, default=None, help="verify an existing kit")
149
+ parser.add_argument("--list", action="store_true", help="print the manifest as JSON")
150
+ args = parser.parse_args()
151
+
152
+ if args.list:
153
+ print(
154
+ json.dumps(
155
+ {"scripts": KIT_SCRIPTS, "data": KIT_DATA, "lanes": KIT_LANES, "tests": KIT_TESTS},
156
+ indent=2,
157
+ )
158
+ )
159
+ return
160
+ if args.output:
161
+ copied = build(args.output)
162
+ print(f"wrote {len(copied)} files to {args.output}")
163
+ problems = check(args.output)
164
+ elif args.check:
165
+ problems = check(args.check)
166
+ else:
167
+ parser.error("pass --output, --check, or --list")
168
+
169
+ if problems:
170
+ print("KIT INVALID")
171
+ for problem in problems:
172
+ print(f" - {problem}")
173
+ raise SystemExit(1)
174
+ print("KIT OK")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()