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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
"""Training jobs: on-policy distillation (opd), GRPO (grpo), SFT (sft) and loop fixing (loopfix).



A job is a sequence of rounds; a round is a fixed list of phases (PHASES). Each finished phase

commits its output and the next phase's name to the job repo in one commit, so a session that

dies at any point resumes at the first unfinished phase, on any account. Prompts for a round are

a pure function of (seed, epoch, cursor) in the state, so a re-run picks the same problems.

"""

from __future__ import annotations

import hashlib
import json
import math
import random
import shutil
import time
from pathlib import Path
from typing import Any

from .config import profile
from .context import JobContext, PhaseTimeout
from .io import read_jsonl, write_jsonl
from .losses import group_advantages
from .modeling import TOKENIZER_FILES
from .phases import (
    gen_spec,
    load_problems,
    materialize,
    prompt_ids,
    run_generation,
    run_scoring,
    run_training,
)
from .types import Problem, Sample

PHASES = {
    "opd": ["generate", "score", "train"],
    "grpo": ["generate", "grade", "train"],
    "sft": ["train"],
    "loopfix": ["generate", "train"],
}
COMMIT_MARGIN = 15 * 60
DEFAULT_PHASE_SECONDS = 20 * 60


def take_prompts(n_pool: int, seed: int, epoch: int, cursor: int, k: int) -> tuple[list[int], int, int]:
    """k pool indices from a seeded per-epoch permutation; returns them and the advanced (epoch, cursor)."""
    out: list[int] = []
    while len(out) < k:
        perm = list(range(n_pool))
        random.Random(seed * 1_000_003 + epoch).shuffle(perm)
        take = perm[cursor:cursor + (k - len(out))]
        out += take
        cursor += len(take)
        if cursor >= n_pool:
            epoch, cursor = epoch + 1, 0
    return out, epoch, cursor


def lr_at(optim: dict[str, Any], step: int) -> float:
    lr = float(optim.get("lr", 5e-5))
    warmup = int(optim.get("warmup_rounds", 0))
    return lr * min(1.0, (step + 1) / warmup) if warmup else lr


def stop_reason(metrics: list[dict[str, Any]], rules: dict[str, Any]) -> str | None:
    patience = int(rules.get("patience", 3))
    recent = metrics[-patience:]
    if len(recent) < patience:
        return None
    if "min_entropy" in rules and all(m.get("entropy", 1.0) < rules["min_entropy"] for m in recent):
        return f"entropy below {rules['min_entropy']} for {patience} rounds"
    if "max_truncation" in rules and all(m.get("trunc_rate", 0.0) > rules["max_truncation"] for m in recent):
        return f"truncation above {rules['max_truncation']} for {patience} rounds"
    return None


class TrainingJob:
    def __init__(self, ctx: JobContext):
        self.ctx = ctx
        self.cfg = ctx.config
        self.kind = self.cfg["kind"]
        self.phases = PHASES[self.kind]
        self.prof = profile(self.cfg["profile"])
        self.ckpt = ctx.repo_dir / "ckpt"
        self.policy = ctx.work / "policy"
        self.round_dir = ctx.repo_dir / "round"
        self._next_cursor: dict[str, int] = {}

    @property
    def state(self) -> dict[str, Any]:
        return self.ctx.state

    def run(self) -> str:
        ctx, cfg = self.ctx, self.cfg
        ctx.fetch(["ckpt/**", "round/**", "metrics.jsonl"])
        self.student_dir = materialize(ctx, cfg["student"], bool(self.prof.get("trust_remote_code")))
        from .modeling import load_tokenizer

        self.tok = load_tokenizer(self.student_dir)
        if self.kind in ("opd", "grpo", "loopfix"):
            self.pool = load_problems(ctx, cfg["pool"])
            self.pool = self._filter_pool(self.pool)
            self.by_uid = {p.uid: p for p in self.pool}
        if self.kind == "opd":
            tprof = profile(cfg["teacher_profile"])
            self.teacher_dir = materialize(ctx, cfg["teacher"], bool(tprof.get("trust_remote_code")))
            self.teacher_tok = load_tokenizer(self.teacher_dir, bool(tprof.get("trust_remote_code")))
            self.tprof = tprof
        if self.kind == "sft":
            self.sft_rows = self._load_sft()
        total = int(cfg["rounds"])
        while self.state.get("round", 0) < total and not self.state.get("stopped"):
            r = self.state.get("round", 0)
            phase = self.state.get("phase", self.phases[0])
            for name in self.phases[self.phases.index(phase):]:
                est = self.state.get("phase_secs", {}).get(name, DEFAULT_PHASE_SECONDS)
                ctx.require_time(est * 1.25 + COMMIT_MARGIN, f"round {r} {name}")
                t0 = time.time()
                try:
                    getattr(self, f"phase_{name}")(r, timeout=max(3 * est, 1800))
                except PhaseTimeout as e:
                    grown = {**self.state.get("phase_secs", {}), name: 2 * max(est, e.elapsed)}
                    ctx.commit({}, f"round {r} {name} timed out; estimate raised", state={"phase_secs": grown})
                    raise
                ctx.log(f"round {r} {name} took {(time.time() - t0) / 60:.1f} min")
        if self.state.get("final_committed"):
            return "done"
        self.finalize()
        return "done"

    def _filter_pool(self, pool: list[Problem]) -> list[Problem]:
        unjudged = [p for p in pool if p.meta.get("judge")]
        if unjudged:
            self.ctx.log(f"left out {len(unjudged)} pool problems that look like dev problems (awaiting a judge)")
            pool = [p for p in pool if not p.meta.get("judge")]
        f = self.cfg.get("pool_filter") or {}
        excluded = set(f.get("exclude_sources") or ())
        if excluded:
            pool = [p for p in pool if p.source not in excluded]
        lo, hi = f.get("min_pass"), f.get("max_pass")
        if lo is None and hi is None:
            return pool
        out = [p for p in pool if "pass_rate" not in p.meta or
               ((lo is None or p.meta["pass_rate"] >= lo) and (hi is None or p.meta["pass_rate"] <= hi))]
        self.ctx.log(f"pool filter kept {len(out)}/{len(pool)} problems")
        return out

    def _phase_done(self, name: str, secs: float, files: dict[str, Any], extra: dict[str, Any] | None = None) -> None:
        phase_secs = dict(self.state.get("phase_secs", {}))
        old = phase_secs.get(name)
        phase_secs[name] = secs if old is None else 0.5 * old + 0.5 * secs
        nxt = self.phases[(self.phases.index(name) + 1) % len(self.phases)]
        update = {"phase": nxt, "phase_secs": phase_secs, **(extra or {})}
        self.ctx.commit(files, f"round {self.state.get('round', 0)} {name}", state=update)

    def _policy_dir(self, r: int) -> Path:
        if r == 0 and not (self.ckpt / "adapter_config.json").exists():
            return self.student_dir
        marker = self.policy / "ROUND"
        if marker.exists() and marker.read_text().strip() == str(r):
            return self.policy
        import sys

        cmd = [sys.executable, "-m", "pocket_math.train", "--merge-only", "--base", str(self.student_dir),
               "--adapter", str(self.ckpt), "--out", str(self.policy)]
        self.ctx.run(cmd, f"merge-r{r}", timeout=1800, secret_free=True)
        marker.write_text(str(r))
        return self.policy

    def _gen_cfg(self, n: int, max_new: int | None = None) -> dict[str, Any]:
        cfg = self.cfg
        return {"n": n, "max_new_tokens": max_new or cfg["max_new_tokens"], "sampling": cfg.get("sampling"),
                "backend": cfg.get("backend", "vllm"), "vllm": cfg.get("vllm"), "tool": cfg.get("tool", False)}

    def _round_seed(self, r: int) -> int:
        return int(self.cfg.get("seed", 0)) * 1_000_003 + r

    def phase_generate(self, r: int, timeout: float) -> None:
        t0 = time.time()
        cfg = self.cfg
        k = int(cfg["prompts_per_round"])
        if self.kind == "grpo":
            k = math.ceil(k * float(cfg.get("oversample", 1.0)))
        idx, epoch, cursor = take_prompts(len(self.pool), int(cfg.get("seed", 0)), self.state.get("epoch", 0),
                                          self.state.get("cursor", 0), k)
        probs = [self.pool[i] for i in idx]
        items = [(p.uid, prompt_ids(self.tok, self.prof, p.problem)) for p in probs]
        spec = gen_spec(self._policy_dir(r), cfg["profile"], self._gen_cfg(int(cfg["samples_per_prompt"])),
                        self._round_seed(r), eval_mode=False)
        samples = run_generation(self.ctx, spec, items, f"gen-r{r}", timeout)
        if self.kind == "loopfix":
            samples = self._loop_pairs(r, samples, spec, timeout)
            out = self.round_dir / "pairs.jsonl.gz"
            write_jsonl(out, samples)
            self._phase_done("generate", time.time() - t0, {"round/pairs.jsonl.gz": out},
                             {"epoch": epoch, "cursor": cursor})
            return
        out = self.round_dir / "samples.jsonl.gz"
        write_jsonl(out, (s.to_json() for s in samples))
        files: dict[str, Any] = {"round/samples.jsonl.gz": out}
        every = int(cfg.get("milestone_every", 20))
        if every and r % every == 0:
            files[f"rollouts/r{r:04d}.jsonl.gz"] = out
        self._phase_done("generate", time.time() - t0, files, {"epoch": epoch, "cursor": cursor})

    def phase_score(self, r: int, timeout: float) -> None:
        t0 = time.time()
        samples = [Sample.from_json(x) for x in read_jsonl(self.round_dir / "samples.jsonl.gz")]
        cache: dict[str, list[int]] = {}
        rows = []
        for i, s in enumerate(samples):
            if s.uid not in cache:
                cache[s.uid] = prompt_ids(self.teacher_tok, self.tprof, self.by_uid[s.uid].problem)
            rows.append({"idx": i, "prompt_ids": cache[s.uid], "response_ids": s.response_ids})
        scores = run_scoring(self.ctx, self.teacher_dir, rows, f"score-r{r}", timeout,
                             bool(self.tprof.get("trust_remote_code")), int(self.cfg.get("score_chunk", 2048)))
        for i, s in enumerate(samples):
            s.teacher_logprobs = scores[i]
        out = self.round_dir / "scored.jsonl.gz"
        write_jsonl(out, (s.to_json() for s in samples))
        self._phase_done("score", time.time() - t0, {"round/scored.jsonl.gz": out})

    def phase_grade(self, r: int, timeout: float) -> None:
        from .grading import grade_many

        t0 = time.time()
        samples = [Sample.from_json(x) for x in read_jsonl(self.round_dir / "samples.jsonl.gz")]
        correct = grade_many([(s.text, self.by_uid[s.uid].answer) for s in samples])
        for s, ok in zip(samples, correct, strict=True):
            s.reward = 1.0 if ok and not s.truncated else 0.0
        by_uid: dict[str, list[Sample]] = {}
        for s in samples:
            by_uid.setdefault(s.uid, []).append(s)
        mixed = [u for u, g in by_uid.items() if len({x.reward for x in g}) > 1]
        keep = set(mixed[: int(self.cfg["prompts_per_round"])])
        kept = [s for s in samples if s.uid in keep]
        stats = {"reward_mean": sum(s.reward or 0.0 for s in samples) / max(len(samples), 1),
                 "trunc_rate": sum(s.truncated for s in samples) / max(len(samples), 1),
                 "groups": len(by_uid), "groups_kept": len(keep),
                 "zero_var_frac": 1 - len(mixed) / max(len(by_uid), 1)}
        out = self.round_dir / "scored.jsonl.gz"
        write_jsonl(out, (s.to_json() for s in kept))
        self._phase_done("grade", time.time() - t0, {"round/scored.jsonl.gz": out}, {"grade_stats": stats})

    def phase_train(self, r: int, timeout: float) -> None:
        t0 = time.time()
        cfg = self.cfg
        d = self.ctx.work / "train" / f"r{r}"
        shutil.rmtree(d, ignore_errors=True)
        rows, gen_stats = self._train_rows(r)
        if not rows:
            self.ctx.log(f"round {r}: no trainable data (every group had equal rewards); skipping the update")
            row = {"round": r, "skipped": True, **gen_stats, **(self.state.get("grade_stats") or {})}
            self._advance(r, time.time() - t0, row, {})
            return
        write_jsonl(d / "data.jsonl.gz", rows)
        optim = cfg.get("optim", {})
        spec = {
            "kind": {"sft": "sft", "loopfix": "dpo"}.get(self.kind, "pg"),
            "base_dir": str(self.student_dir), "data": str(d / "data.jsonl.gz"),
            "adapter_in": str(self.ckpt) if (self.ckpt / "adapter_config.json").exists() else None,
            "optim_in": str(self.ckpt / "optimizer.pt"), "adapter_out": str(d / "adapter"),
            "optim_out": str(d / "optimizer.pt"), "merge_out": None if self.kind == "sft" else str(d / "policy"),
            "lora": cfg.get("lora", {}), "loss": cfg.get("loss", {}), "lr": lr_at(optim, r),
            "betas": optim.get("betas", [0.9, 0.999]), "weight_decay": optim.get("weight_decay", 0.0),
            "grad_clip": optim.get("grad_clip", 1.0), "minibatches": cfg.get("train", {}).get("minibatches", 1),
            "chunk": cfg.get("train", {}).get("chunk", 1024), "seed": self._round_seed(r), "step": r,
            "max_seq_tokens": cfg.get("train", {}).get("max_seq_tokens"),
            "dpo_beta": cfg.get("dpo_beta", 0.1), "trust_remote_code": bool(self.prof.get("trust_remote_code")),
            "base_info": {"base": cfg["student"], "profile": cfg["profile"], "job": self.ctx.job_id, "round": r + 1},
        }
        metrics = run_training(self.ctx, spec, f"train-r{r}", timeout)
        shutil.rmtree(self.ckpt, ignore_errors=True)
        shutil.copytree(d / "adapter", self.ckpt)
        shutil.copyfile(d / "optimizer.pt", self.ckpt / "optimizer.pt")
        if spec["merge_out"]:
            shutil.rmtree(self.policy, ignore_errors=True)
            shutil.move(str(d / "policy"), str(self.policy))
            (self.policy / "ROUND").write_text(str(r + 1))
        files = {f"ckpt/{p.name}": p for p in self.ckpt.iterdir() if p.is_file()}
        every = int(cfg.get("milestone_every", 20))
        if every and (r + 1) % every == 0:
            for p in self.ckpt.iterdir():
                if p.is_file() and p.name != "optimizer.pt":
                    files[f"milestones/r{r + 1:04d}/{p.name}"] = p
        row = {"round": r, "lr": spec["lr"], **gen_stats, **metrics, **(self.state.get("grade_stats") or {})}
        self._advance(r, time.time() - t0, row, files)

    def _advance(self, r: int, secs: float, row: dict[str, Any], files: dict[str, Any]) -> None:
        metrics_path = self.ctx.metric(row)
        history = [json.loads(x) for x in metrics_path.read_text().splitlines() if x.strip()]
        reason = stop_reason([h for h in history if "round" in h], self.cfg.get("stop_rules") or {})
        phase_secs = dict(self.state.get("phase_secs", {}))
        phase_secs["train"] = secs if "train" not in phase_secs else 0.5 * phase_secs["train"] + 0.5 * secs
        update: dict[str, Any] = {"round": r + 1, "phase": self.phases[0], "phase_secs": phase_secs,
                                  "grade_stats": None, **self._next_cursor}
        if reason:
            update["stopped"] = reason
            self.ctx.log(f"stop rule fired: {reason}")
        self.ctx.commit({**files, "metrics.jsonl": metrics_path}, f"round {r} train", state=update)
        squash = int(self.cfg.get("squash_every", 10))
        if squash and (r + 1) % squash == 0:
            self.ctx.handle.squash()

    def _train_rows(self, r: int) -> tuple[list[dict[str, Any]], dict[str, Any]]:
        if self.kind == "sft":
            k = int(self.cfg["examples_per_round"])
            idx, epoch, cursor = take_prompts(len(self.sft_rows), int(self.cfg.get("seed", 0)),
                                              self.state.get("epoch", 0), self.state.get("cursor", 0), k)
            self._next_cursor = {"epoch": epoch, "cursor": cursor}
            return [self.sft_rows[i] for i in idx], {"examples": len(idx)}
        if self.kind == "loopfix":
            pairs = list(read_jsonl(self.round_dir / "pairs.jsonl.gz"))
            return pairs, {"pairs": len(pairs)}
        name = "scored.jsonl.gz"
        samples = [Sample.from_json(x) for x in read_jsonl(self.round_dir / name)]
        if self.kind == "grpo":
            advs = group_advantages([s.reward or 0.0 for s in samples], [s.uid for s in samples],
                                    std_norm=bool(self.cfg.get("std_norm", True)))
        else:
            advs = [None] * len(samples)
        rows = [{"prompt_ids": s.prompt_ids, "response_ids": s.response_ids, "loss_mask": s.loss_mask,
                 "sampler_logprobs": [None if (isinstance(x, float) and math.isnan(x)) else x
                                      for x in s.sampler_logprobs],
                 "teacher_logprobs": s.teacher_logprobs, "seq_adv": a} for s, a in zip(samples, advs, strict=True)]
        lens = [len(s.response_ids) for s in samples] or [0]
        # A digest of the exact training tokens, so two rounds that look alike can be told apart.
        digest = hashlib.sha256(json.dumps([[s.uid, s.response_ids] for s in samples]).encode()).hexdigest()
        stats = {"samples": len(samples), "mean_len": sum(lens) / len(lens), "max_len": max(lens),
                 "trunc_rate": sum(s.truncated for s in samples) / max(len(samples), 1), "data_sha": digest[:16]}
        return rows, stats

    def _load_sft(self) -> list[dict[str, Any]]:
        from .sft_data import sft_rows

        return sft_rows(self.ctx, self.cfg["data"], self.tok, self.prof, int(self.cfg.get("max_seq_len", 16384)))

    def _loop_pairs(self, r: int, samples: list[Sample], spec, timeout: float) -> list[dict[str, Any]]:
        from .loops import loop_onset, repeated_fraction

        cont_len = int(self.cfg.get("pair_tokens", 256))
        looping = []
        for s in samples:
            onset = loop_onset(s.response_ids) if s.truncated else None
            if onset is not None and onset > 0:
                looping.append((s, onset))
        if not looping:
            return []
        items = [(f"{s.uid}#{i}", s.prompt_ids + s.response_ids[:onset]) for i, (s, onset) in enumerate(looping)]
        longest = max(len(p) for _, p in items)
        spec2 = type(spec)(**{**spec.__dict__, "n": int(self.cfg.get("resamples", 4)), "max_new_tokens": cont_len,
                              "seed": spec.seed + 17, "max_model_len": longest + cont_len + 64})
        conts = run_generation(self.ctx, spec2, items, f"gen-r{r}-resample", timeout)
        by_item: dict[str, list[Sample]] = {}
        for c in conts:
            by_item.setdefault(c.uid, []).append(c)
        pairs = []
        for i, (s, onset) in enumerate(looping):
            rejected = s.response_ids[onset:onset + cont_len]
            clean = [c for c in by_item.get(f"{s.uid}#{i}", [])
                     if c.response_ids[:32] != rejected[:32] and repeated_fraction(c.response_ids) < 0.2]
            if clean:
                pairs.append({"prompt_ids": s.prompt_ids + s.response_ids[:onset],
                              "chosen_ids": clean[0].response_ids, "rejected_ids": rejected})
        self.ctx.log(f"loop pairs: {len(looping)} looping answers, {len(pairs)} pairs")
        return pairs

    def finalize(self) -> None:
        ctx = self.ctx
        ctx.require_time(COMMIT_MARGIN + 600, "final merge and upload")
        r = self.state.get("round", 0)
        final = ctx.work / "final"
        shutil.rmtree(final, ignore_errors=True)
        source = self._policy_dir(r) if self.kind != "sft" else None
        if source is None or source == self.student_dir:
            import sys

            cmd = [sys.executable, "-m", "pocket_math.train", "--merge-only", "--base", str(self.student_dir),
                   "--adapter", str(self.ckpt), "--out", str(final)]
            ctx.run(cmd, "merge-final", timeout=1800, secret_free=True)
        else:
            shutil.copytree(source, final, ignore=shutil.ignore_patterns("ROUND"))
        for name in TOKENIZER_FILES:
            if (self.student_dir / name).exists() and not (final / name).exists():
                shutil.copyfile(self.student_dir / name, final / name)
        info = {"base": self.cfg["student"], "profile": self.cfg["profile"], "job": ctx.job_id, "rounds": r,
                "stopped": self.state.get("stopped")}
        files: dict[str, Any] = {f"final/{p.name}": p for p in final.iterdir() if p.is_file()}
        files["final/provenance.json"] = info
        ctx.commit(files, "final model", state={"final_committed": True})


def run(ctx: JobContext) -> str:
    return TrainingJob(ctx).run()