"""Parent-side helpers that turn one unit of GPU work into subprocesses, one per GPU. Every phase subprocess runs without HF_TOKEN in its environment: models are downloaded by the parent first, and nothing a subprocess writes is trusted to be secret-free (see drop_secrets). """ from __future__ import annotations import json import os import re import shutil import sys from pathlib import Path from typing import Any from .config import ModelRef, profile from .context import JobContext, PhaseFailed, secret_values from .generate import READY_MARKER, GenSpec from .io import read_json, read_jsonl, write_json, write_jsonl from .types import Problem, Sample # Tried in order until vLLM's engine starts on this GPU; the first that works is remembered # for the session. T4 (sm75) has no FlashAttention, and which fallback a vLLM release picks # differs between versions. VLLM_ENV_OPTIONS: list[dict[str, str]] = [ {}, {"VLLM_ATTENTION_BACKEND": "TRITON_ATTN"}, {"VLLM_ATTENTION_BACKEND": "FLEX_ATTENTION"}, {"VLLM_USE_V1": "0", "VLLM_ATTENTION_BACKEND": "XFORMERS"}, ] def slug(text: str) -> str: return re.sub(r"[^A-Za-z0-9._-]+", "_", text)[-120:] def hf_download(ref: ModelRef, patterns: list[str] | None = None) -> Path: from huggingface_hub import snapshot_download path = snapshot_download(ref.repo, revision=ref.revision, allow_patterns=patterns, token=os.environ.get("HF_TOKEN") or None) return Path(path) def materialize(ctx: JobContext, ref_text: str, trust_remote_code: bool = False) -> Path: """A local directory with a plain (merged) model for `ref_text`.""" ref = ModelRef.parse(ref_text) if ref.is_local: path = Path(ref.repo) / (ref.subfolder or "") else: root = hf_download(ref, [f"{ref.subfolder}/**"] if ref.subfolder else None) path = root / (ref.subfolder or "") if not (path / "adapter_config.json").exists(): return path base_ref = json.loads((path / "base.json").read_text())["base"] base_dir = materialize(ctx, base_ref, trust_remote_code) out = ctx.session.work / "models" / slug(ref_text) if not (out / "config.json").exists(): cmd = [sys.executable, "-m", "pocket_math.train", "--merge-only", "--base", str(base_dir), "--adapter", str(path), "--out", str(out)] + (["--trust-remote-code"] if trust_remote_code else []) ctx.run(cmd, f"merge-{slug(ref_text)[-40:]}", timeout=1800, secret_free=True) return out def prompt_ids(tokenizer, prof: dict[str, Any], problem: str, tool_note: str | None = None) -> list[int]: user = prof["user_template"].format(problem=problem) if tool_note: user = f"{user}\n\n{tool_note}" messages = ([{"role": "system", "content": prof["system"]}] if prof.get("system") else []) + \ [{"role": "user", "content": user}] text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) return tokenizer(text, add_special_tokens=False).input_ids def gen_spec(model_dir: Path, prof_name: str, cfg: dict[str, Any], seed: int, eval_mode: bool) -> GenSpec: """Sampling settings: the model card's for evaluation, plain policy sampling (T=1, top-p=1) for training, so the sampled distribution is the policy the losses assume.""" prof = profile(prof_name) sampling = dict(prof["eval_sampling"]) if eval_mode else {"temperature": 1.0, "top_p": 1.0, "top_k": -1} sampling.update(cfg.get("sampling") or {}) max_new = int(cfg.get("max_new_tokens") or prof["max_new_tokens"]) vllm = cfg.get("vllm") or {} return GenSpec(model_dir=str(model_dir), max_new_tokens=max_new, n=int(cfg.get("n", 1)), temperature=float(sampling["temperature"]), top_p=float(sampling["top_p"]), top_k=int(sampling.get("top_k", -1)), stop_token_ids=list(prof["stop_token_ids"]), seed=seed, backend=cfg.get("backend", "vllm"), max_model_len=vllm.get("max_model_len"), gpu_memory_utilization=float(vllm.get("gpu_memory_utilization", 0.90)), enforce_eager=bool(vllm.get("enforce_eager", False)), tool=bool(cfg.get("tool", False)), max_tool_calls=int(cfg.get("max_tool_calls", 8)), trust_remote_code=bool(prof.get("trust_remote_code", False))) def _shards(n_items: int, n: int) -> list[list[int]]: return [list(range(i, n_items, n)) for i in range(n)] def drop_secrets(samples: list[Sample], log) -> list[Sample]: secrets = secret_values() kept = [s for s in samples if not any(v in s.text for v in secrets)] if len(kept) != len(samples): log(f"dropped {len(samples) - len(kept)} samples whose text contained a secret value") return kept def run_generation(ctx: JobContext, spec: GenSpec, items: list[tuple[str, list[int]]], name: str, timeout: float) -> list[Sample]: gpus = ctx.session.n_gpus n = max(1, gpus) if spec.backend == "vllm" else 1 root = ctx.work / "gen" / name shutil.rmtree(root, ignore_errors=True) shards = [s for s in _shards(len(items), n) if s] procs = [] for i, idx in enumerate(shards): d = root / str(i) write_jsonl(d / "prompts.jsonl", ({"uid": items[j][0], "prompt_ids": items[j][1]} for j in idx)) write_json(d / "spec.json", {**spec.__dict__, "seed": spec.seed + 7919 * i}) python = ctx.session.gen_python if spec.backend == "vllm" else sys.executable cmd = [python, "-m", "pocket_math.generate", "--spec", str(d / "spec.json"), "--inp", str(d / "prompts.jsonl"), "--out", str(d / "out.jsonl.gz")] procs.append((cmd, {"CUDA_VISIBLE_DEVICES": str(i)} if gpus else {})) remembered = ctx.session.work / "vllm_env.json" options = [read_json(remembered)] if remembered.exists() else VLLM_ENV_OPTIONS if spec.backend != "vllm": options = [{}] for k, opt in enumerate(options): for i in range(len(shards)): (root / str(i) / READY_MARKER).unlink(missing_ok=True) try: ctx.run_many([(cmd, {**env, **opt}) for cmd, env in procs], name, timeout, secret_free=True) if spec.backend == "vllm": write_json(remembered, opt) break except PhaseFailed as e: engine_started = any((root / str(i) / READY_MARKER).exists() for i in range(len(shards))) if engine_started or k == len(options) - 1: raise ctx.log(f"vLLM did not start with {opt or 'defaults'} ({str(e).splitlines()[0]}); trying the next option") samples = [Sample.from_json(r) for i in range(len(shards)) for r in read_jsonl(root / str(i) / "out.jsonl.gz")] return drop_secrets(samples, ctx.log) def run_scoring(ctx: JobContext, model_dir: Path, rows: list[dict[str, Any]], name: str, timeout: float, trust_remote_code: bool = False, chunk: int = 2048) -> dict[int, list[float]]: gpus = ctx.session.n_gpus n = max(1, gpus) order = sorted(range(len(rows)), key=lambda i: -len(rows[i]["response_ids"])) loads, buckets = [0] * n, [[] for _ in range(n)] for i in order: b = loads.index(min(loads)) buckets[b].append(i) loads[b] += len(rows[i]["prompt_ids"]) + len(rows[i]["response_ids"]) root = ctx.work / "score" / name shutil.rmtree(root, ignore_errors=True) procs = [] for b, idx in enumerate(buckets): if not idx: continue d = root / str(b) write_jsonl(d / "rows.jsonl.gz", (rows[i] for i in idx)) write_json(d / "spec.json", {"model_dir": str(model_dir), "trust_remote_code": trust_remote_code, "chunk": chunk, "dtype": "fp16"}) cmd = [sys.executable, "-m", "pocket_math.score", "--spec", str(d / "spec.json"), "--inp", str(d / "rows.jsonl.gz"), "--out", str(d / "out.jsonl.gz")] procs.append((cmd, {"CUDA_VISIBLE_DEVICES": str(b)} if gpus else {})) ctx.run_many(procs, name, timeout, secret_free=True) out: dict[int, list[float]] = {} for b, idx in enumerate(buckets): if idx: for r in read_jsonl(root / str(b) / "out.jsonl.gz"): out[r["idx"]] = r["logprobs"] return out def run_training(ctx: JobContext, spec: dict[str, Any], name: str, timeout: float) -> dict[str, Any]: d = ctx.work / "train" / name d.mkdir(parents=True, exist_ok=True) spec = {**spec, "metrics_out": str(d / "metrics.json")} write_json(d / "spec.json", spec) n = ctx.session.n_gpus if n > 1: cmd = [sys.executable, "-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={n}", "-m", "pocket_math.train", "--spec", str(d / "spec.json")] else: cmd = [sys.executable, "-m", "pocket_math.train", "--spec", str(d / "spec.json")] ctx.run(cmd, name, timeout, secret_free=True) return read_json(d / "metrics.json") def load_problems(ctx: JobContext, source: Any) -> list[Problem]: """Problems from "repo:path/in/repo.jsonl" on a dataset repo, a local path, a list of inline {problem, answer} dicts, or a list of sources, each a string or {source, repeat}. `repeat` lists a source's problems that many times, so a small source is drawn more often.""" if isinstance(source, list) and source and all(isinstance(s, str) or "source" in s for s in source): out: list[Problem] = [] for s in source: spec = {"source": s} if isinstance(s, str) else s out += load_problems(ctx, spec["source"]) * int(spec.get("repeat", 1)) return out if isinstance(source, list): return [Problem(uid=str(p.get("uid", f"inline/{i}")), source=p.get("source", "inline"), problem=p["problem"], answer=str(p["answer"]), year=p.get("year"), meta=p.get("meta") or {}) for i, p in enumerate(source)] if Path(str(source)).exists(): return [Problem.from_json(r) for r in read_jsonl(source)] repo, _, path = str(source).partition(":") from huggingface_hub import hf_hub_download local = hf_hub_download(repo, path, repo_type="dataset", token=os.environ.get("HF_TOKEN") or None) return [Problem.from_json(r) for r in read_jsonl(local)]