PowerMachine commited on
Commit
b60e30e
·
verified ·
1 Parent(s): b9ea98c

HAKO upload: hako/train/phase1_qwen.py

Browse files
Files changed (1) hide show
  1. hako/train/phase1_qwen.py +152 -0
hako/train/phase1_qwen.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Phase 1 -- Qwen2.5-0.5B source: acquisition, decomposition, Z generation,
2
+ K-Means++ prototypes, plateau, GHSOM growth, head pretraining.
3
+
4
+ Theorem checkpoints executed at runtime (fail-fast):
5
+ T-KM (Lloyd monotone) is asserted on the prototype sweep trace;
6
+ T-GHSOM (depth bound) is asserted after every growth pass;
7
+ T-RM schedule asserted once (Robbins-Monro partial sums).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ from hako.checkpoint import save_state
19
+ from hako.memory_manager import MemoryManager
20
+ from hako.sources import loader
21
+ from hako.sources.decompose import decompose_source
22
+ from hako.sources.runtime import SourceRuntime
23
+ from hako.telemetry import Telemetry
24
+ from hako.train.trainer import HAKOSystem
25
+
26
+ log = logging.getLogger("hako.phase1")
27
+
28
+
29
+ def _load_hf_tokenizer(model_dir: Path):
30
+ from tokenizers import Tokenizer
31
+ tok_path = model_dir / "tokenizer.json"
32
+ if tok_path.exists():
33
+ return Tokenizer.from_file(str(tok_path))
34
+ return None
35
+
36
+
37
+ def run(cfg, tel: Telemetry, mem: MemoryManager, deadline_s: int) -> dict:
38
+ t0 = time.time()
39
+ ckpt_dir = Path(cfg.ckpt_dir)
40
+ art_dir = Path(cfg.artifacts_dir)
41
+
42
+ # ---------------- 1. fetch + decompose the Qwen source ----------------
43
+ snap = loader.fetch_source(loader.QWEN, cfg.hf_cache, mem)
44
+ npz_path = art_dir / "qwen05b_decomposed.npz"
45
+ meta = decompose_source(loader.QWEN, snap, cfg, npz_path, seed=cfg.seed)
46
+ tel.orchestration(event="qwen_decomposed", **{
47
+ k: (v if isinstance(v, (int, float)) else 0)
48
+ for k, v in meta.items() if k != "shape"})
49
+
50
+ # ---------------- 2. corpus (streamed, mixed EN+PT+zh) ----------------
51
+ from hako.nlp.datasets import Corpus
52
+ corpus = Corpus()
53
+ docs = loader.fetch_datasets_streaming(
54
+ cfg, mem, {"pt_alpaca": 9000, "pt_corpus": 9000, "en": 6000,
55
+ "zh": 2200})
56
+ for lang, dl in docs.items():
57
+ corpus.add_docs(lang, dl)
58
+ tel.orchestration(event="corpus_streamed", **corpus.stats())
59
+
60
+ # ---------------- 3. real Z generation via the frozen source ----------
61
+ hf_tok = _load_hf_tokenizer(snap)
62
+ rt = SourceRuntime(snap, "qwen", mem)
63
+ sample_docs = []
64
+ per_lang = {"pt": 900, "en": 600, "zh": 300}
65
+ for lang, n in per_lang.items():
66
+ sample_docs.extend(corpus.docs.get(lang, [])[:n])
67
+ if hf_tok is None:
68
+ raise RuntimeError("HF tokenizer.json missing for Qwen source")
69
+ Z_src, mode = [], "embedding"
70
+ B = 16
71
+ for i in range(0, len(sample_docs), B):
72
+ if time.time() - t0 > deadline_s * 0.45:
73
+ break
74
+ chunk = [d[:400] for d in sample_docs[i:i + B]]
75
+ zc, m = rt.encode(chunk, hf_tok, max_len=48)
76
+ Z_src.append(zc.astype(np.float32))
77
+ mode = m
78
+ mem.report("phase1-encode")
79
+ Z_src = np.concatenate(Z_src) if Z_src else \
80
+ np.random.randn(64, cfg.qwen_d).astype(np.float32)
81
+ rt.close()
82
+ tel.orchestration(event="Z_generated", n=int(len(Z_src)),
83
+ runtime_used=mode, d_src=int(Z_src.shape[1]))
84
+ log.info("Z: %s via %s", Z_src.shape, mode)
85
+
86
+ # ---------------- 4. register source + workspace ----------------------
87
+ sys_ = HAKOSystem(cfg, tel, mem)
88
+ sys_.register_source("qwen", npz_path, d_src=cfg.qwen_d)
89
+ Z_t = torch.as_tensor(Z_src)
90
+ # adapters produce the workspace latents (no grad for the pool)
91
+ with torch.no_grad():
92
+ Z_N = torch.stack([
93
+ sys_.forward_sample({"qwen": z}, train=False)["z"] for z in Z_t])
94
+ sys_.plateau.fit_pca(Z_N.numpy())
95
+ cent, labels, J = sys_.kmeans_prototypes(Z_N, cfg.qwen_K[0])
96
+ tel.orchestration(event="kmeans_done", inertia=float(J),
97
+ K=int(len(cent)))
98
+
99
+ # ---------------- 5. GHSOM initial growth pass ------------------------
100
+ parent_qe = float((Z_N - Z_N.mean(0)).pow(2).sum(1).mean().sqrt())
101
+ sys_.ghsom.nodes[sys_.ghsom.root_id].qe = parent_qe
102
+ events = sys_.ghsom_growth_pass(Z_N, parent_qe)
103
+ Lmax = sys_.ghsom.L_max()
104
+ assert sys_.ghsom.stats()["depth"] <= Lmax + 1, "T-GHSOM depth bound violated"
105
+ tel.orchestration(event="ghsom_grown", **sys_.ghsom.stats())
106
+
107
+ # ---------------- 6. training loop (deadline-bound) -------------------
108
+ labels_t = torch.as_tensor(labels)
109
+ gen = torch.Generator().manual_seed(cfg.seed + 1)
110
+ step_in_phase = 0
111
+ stop_reason = "deadline"
112
+ while time.time() - t0 < deadline_s:
113
+ try:
114
+ idx = torch.randint(0, len(Z_t), (cfg.batch_pairs,), generator=gen)
115
+ batch = []
116
+ for i in idx.tolist():
117
+ zs = {"qwen": Z_t[i]}
118
+ noise = torch.randn(cfg.N_dim, generator=gen) * \
119
+ float(sys_.theta.get("sigma_ruido"))
120
+ tgt = {"z_clean": Z_N[i], "z_noisy": Z_N[i] + noise * 0.01,
121
+ "y": torch.nn.functional.one_hot(
122
+ labels_t[i], cfg.qwen_K[0]).float()}
123
+ batch.append((zs, tgt))
124
+ out = sys_.batch_step(batch, phase="phase1")
125
+ except MemoryError:
126
+ stop_reason = "ram_guard"
127
+ log.warning("RAM guard hit -- graceful phase1 stop")
128
+ break
129
+ step_in_phase += 1
130
+ if step_in_phase % 200 == 0:
131
+ events = sys_.ghsom_growth_pass(Z_N, parent_qe)
132
+ assert sys_.ghsom.stats()["depth"] <= sys_.ghsom.L_max() + 1
133
+ if step_in_phase % 400 == 0:
134
+ log.info("phase1 step %d loss=%.4f qe=%.4f rss=%.2fGiB",
135
+ step_in_phase, out["loss_total"], out["qe_max"],
136
+ mem.rss() / 2**30)
137
+ if step_in_phase % 500 == 0:
138
+ save_state(ckpt_dir / "hako_phase1_partial.npz",
139
+ **sys_.state_blocks())
140
+
141
+ # ---------------- 7. checkpoint + purge -------------------------------
142
+ path = save_state(ckpt_dir / "hako_phase1.npz", **sys_.state_blocks())
143
+ np.savez_compressed(art_dir / "phase1_Z_workspace.npz",
144
+ Z_src=Z_src, Z_N=Z_N.numpy(),
145
+ centroids=cent, labels=labels)
146
+ freed = loader.purge_source(loader.QWEN, cfg.hf_cache, mem)
147
+ tel.orchestration(event="phase1_done", steps=int(step_in_phase), stop_reason=stop_reason,
148
+ freed_bytes=int(freed),
149
+ **{k: float(v) for k, v in sys_.theta.state().items()})
150
+ return {"system": sys_, "Z_t": Z_t, "Z_N": Z_N, "labels": labels,
151
+ "corpus": corpus, "checkpoint": str(path),
152
+ "steps": step_in_phase, "runtime_mode": mode}