"""Sampling answers. Runs as its own process (one per GPU), inside the vLLM venv on Kaggle. python -m pocket_math.generate --spec spec.json --inp prompts.jsonl --out samples.jsonl.gz Two backends share one interface: vLLM (Kaggle) and Hugging Face generate (CPU tests and fallback). The Python-tool loop sits above the backend: when an answer stops at , the code inside the last block runs in the sandbox and its output is appended before generation continues. Tool output tokens get loss_mask 0. """ from __future__ import annotations import argparse import hashlib import json import math import os import re import sys from dataclasses import dataclass, field from pathlib import Path from typing import Any, Protocol from .io import read_jsonl, write_jsonl from .types import Sample TOOL_OPEN, TOOL_CLOSE = "", "" READY_MARKER = "ENGINE_READY" def request_seeds(base: int, keys: list[str]) -> list[int]: """One sampling seed per request, hashed from the base seed and the request's key. vLLM gives the k-th sample of an n-sample request the seed `seed + k` (vllm 0.10.1.1, sequence.py and v1/engine/parallel_sampling.py). Seeds of the form base + prompt index therefore made neighbouring prompts, and the same problem in consecutive rounds, share most of their random streams: grpo-smoke's two rounds trained on the same kept group. Hashed seeds keep the streams apart. They stay below 2**31 - 64, so seed + k fits any backend. """ out = [] for key in keys: digest = hashlib.blake2b(f"{base}|{key}".encode(), digest_size=8).digest() out.append(int.from_bytes(digest, "little") % (2 ** 31 - 64)) return out def occurrence_keys(uids: list[str]) -> list[str]: """uid#0, uid#1, ... so a prompt listed twice gets two different seeds.""" seen: dict[str, int] = {} keys = [] for u in uids: keys.append(f"{u}#{seen.get(u, 0)}") seen[u] = seen.get(u, 0) + 1 return keys @dataclass class Completion: token_ids: list[int] logprobs: list[float] finish: str stop_token: int | None = None @dataclass class GenSpec: model_dir: str max_new_tokens: int n: int = 1 temperature: float = 1.0 top_p: float = 1.0 top_k: int = -1 stop_token_ids: list[int] = field(default_factory=list) seed: int = 0 backend: str = "vllm" max_model_len: int | None = None gpu_memory_utilization: float = 0.90 enforce_eager: bool = False tool: bool = False max_tool_calls: int = 8 tool_timeout: float = 10.0 trust_remote_code: bool = False @staticmethod def from_json(d: dict[str, Any]) -> GenSpec: known = GenSpec.__dataclass_fields__ return GenSpec(**{k: v for k, v in d.items() if k in known}) class Backend(Protocol): def complete(self, prompts: list[list[int]], n: int, max_tokens: list[int], spec: GenSpec, stop_ids: list[int], seeds: list[int]) -> list[list[Completion]]: ... def vllm_engine_args(spec: GenSpec) -> dict[str, Any]: """Engine arguments for vLLM 0.10 on a Kaggle T4. Chunked prefill and prefix caching both stay off. Either one sends prefill through vLLM's Triton prefix-attention kernel, which fails to compile on a T4 (sm_75) with "Unsupported conversion from f16 to f16". vLLM turns chunked prefill on by itself above a 32k context, so every 40k eval crashed (DECISIONS D-025). Samples of one prompt share its blocks through n=k anyway, so prefix caching saved little. """ return {"model": spec.model_dir, "dtype": "half", "seed": spec.seed, "max_model_len": spec.max_model_len or (spec.max_new_tokens + 4096), "gpu_memory_utilization": spec.gpu_memory_utilization, "enable_chunked_prefill": False, "enable_prefix_caching": False, "enforce_eager": spec.enforce_eager, "trust_remote_code": spec.trust_remote_code} class VllmBackend: def __init__(self, spec: GenSpec, ready_dir: Path | None = None): from vllm import LLM self.llm = LLM(**vllm_engine_args(spec)) if ready_dir is not None: (ready_dir / READY_MARKER).write_text("ok") def complete(self, prompts, n, max_tokens, spec, stop_ids, seeds): from vllm import SamplingParams from vllm.inputs import TokensPrompt params = [SamplingParams(n=n, temperature=spec.temperature, top_p=spec.top_p, top_k=spec.top_k, max_tokens=m, logprobs=0, stop_token_ids=stop_ids, seed=sd, skip_special_tokens=False) for m, sd in zip(max_tokens, seeds, strict=True)] outs = self.llm.generate([TokensPrompt(prompt_token_ids=p) for p in prompts], params, use_tqdm=False) result = [] for out in outs: comps = [] for c in out.outputs: ids = list(c.token_ids) lps = [_sampled_lp(c.logprobs, i, t) for i, t in enumerate(ids)] stop_tok = c.stop_reason if isinstance(c.stop_reason, int) else None if stop_tok is not None and (not ids or ids[-1] != stop_tok): ids.append(stop_tok) lps.append(math.nan) comps.append(Completion(ids, lps, "length" if c.finish_reason == "length" else "stop", stop_tok)) result.append(comps) return result def _sampled_lp(logprobs, i: int, tok: int) -> float: if not logprobs or i >= len(logprobs) or logprobs[i] is None: return math.nan entry = logprobs[i].get(tok) if hasattr(logprobs[i], "get") else None return float(entry.logprob) if entry is not None else math.nan class HfBackend: """Slow reference backend: Hugging Face generate, one prompt at a time.""" def __init__(self, spec: GenSpec, ready_dir: Path | None = None): import torch from .modeling import load_model, pick_dtype self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model = load_model(spec.model_dir, pick_dtype("fp16", self.device), self.device, spec.trust_remote_code).eval() if ready_dir is not None: (ready_dir / READY_MARKER).write_text("ok") def complete(self, prompts, n, max_tokens, spec, stop_ids, seeds): import torch result = [] for prompt, m, sd in zip(prompts, max_tokens, seeds, strict=True): torch.manual_seed(sd) ids = torch.tensor([prompt] * n, device=self.device) sampling = ({"do_sample": True, "temperature": spec.temperature, "top_p": spec.top_p, "top_k": 0} if spec.temperature > 0 else {"do_sample": False}) out = self.model.generate(ids, attention_mask=torch.ones_like(ids), **sampling, max_new_tokens=m, eos_token_id=stop_ids or None, pad_token_id=stop_ids[0] if stop_ids else 0, output_scores=True, return_dict_in_generate=True) scores = self.model.compute_transition_scores(out.sequences, out.scores, normalize_logits=True) comps = [] for row, sc in zip(out.sequences, scores, strict=True): gen = row[len(prompt):].tolist() lps = sc.tolist() cut = next((j + 1 for j, t in enumerate(gen) if t in stop_ids), None) if cut is not None: comps.append(Completion(gen[:cut], lps[:cut], "stop", gen[cut - 1])) else: comps.append(Completion(gen, lps, "length" if len(gen) >= m else "stop", None)) result.append(comps) return result def make_backend(spec: GenSpec, ready_dir: Path | None = None) -> Backend: return VllmBackend(spec, ready_dir) if spec.backend == "vllm" else HfBackend(spec, ready_dir) @dataclass class _Partial: uid: str prompt: list[int] key: str = "" resp: list[int] = field(default_factory=list) lps: list[float] = field(default_factory=list) mask: list[int] = field(default_factory=list) calls: int = 0 def last_tool_code(text: str) -> str | None: start = text.rfind(TOOL_OPEN) if start < 0: return None end = text.find(TOOL_CLOSE, start) body = text[start + len(TOOL_OPEN): end if end >= 0 else len(text)] fenced = re.search(r"```(?:python)?\n(.*?)```", body, re.S) return (fenced.group(1) if fenced else body).strip() or None def generate_samples(backend: Backend, items: list[tuple[str, list[int]]], spec: GenSpec, tokenizer) -> list[Sample]: """n samples per prompt, running the tool loop when spec.tool is on.""" stop_ids = list(spec.stop_token_ids) tool_close = tokenizer.convert_tokens_to_ids(TOOL_CLOSE) if spec.tool else None keys = occurrence_keys([uid for uid, _ in items]) first = backend.complete([p for _, p in items], spec.n, [spec.max_new_tokens] * len(items), spec, stop_ids + ([tool_close] if spec.tool else []), request_seeds(spec.seed, keys)) active: list[tuple[_Partial, Completion]] = [] for (uid, prompt), key, comps in zip(items, keys, first, strict=True): for k, c in enumerate(comps): active.append((_Partial(uid, prompt, f"{key}/{k}"), c)) done: list[Sample] = [] while active: pending: list[_Partial] = [] for part, c in active: part.resp += c.token_ids part.lps += c.logprobs part.mask += [1] * len(c.token_ids) budget = spec.max_new_tokens - len(part.resp) wants_tool = spec.tool and c.stop_token == tool_close and part.calls < spec.max_tool_calls if wants_tool and budget > 64: from .sandbox import format_tool_output, run_python code = last_tool_code(tokenizer.decode(part.resp, skip_special_tokens=False)) result_text = format_tool_output(run_python(code, timeout=spec.tool_timeout)) if code else \ "```output\nError: no code found in the tool call\n```\n" out_ids = tokenizer("\n" + result_text, add_special_tokens=False).input_ids[: budget - 32] part.resp += out_ids part.lps += [math.nan] * len(out_ids) part.mask += [0] * len(out_ids) part.calls += 1 pending.append(part) continue finish = "length" if c.finish == "length" or budget <= 0 else "stop" done.append(Sample(uid=part.uid, prompt_ids=part.prompt, response_ids=part.resp, sampler_logprobs=part.lps, finish=finish, text=tokenizer.decode(part.resp, skip_special_tokens=False), loss_mask=part.mask if 0 in part.mask else None)) if not pending: break budgets = [spec.max_new_tokens - len(p.resp) for p in pending] stops = stop_ids + ([tool_close] if any(p.calls < spec.max_tool_calls for p in pending) else []) nxt = backend.complete([p.prompt + p.resp for p in pending], 1, budgets, spec, stops, request_seeds(spec.seed, [f"{p.key}/call{p.calls}" for p in pending])) active = [(p, comps[0]) for p, comps in zip(pending, nxt, strict=True)] order = {uid: i for i, (uid, _) in enumerate(items)} done.sort(key=lambda s: order[s.uid]) return done def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser() p.add_argument("--spec", required=True) p.add_argument("--inp", required=True, help="JSONL rows with uid and prompt_ids") p.add_argument("--out", required=True) a = p.parse_args(argv) spec = GenSpec.from_json(json.loads(Path(a.spec).read_text())) items = [(r["uid"], r["prompt_ids"]) for r in read_jsonl(a.inp)] from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(spec.model_dir, trust_remote_code=spec.trust_remote_code) out_dir = Path(a.out).parent backend = make_backend(spec, ready_dir=out_dir) samples = generate_samples(backend, items, spec, tokenizer) n = write_jsonl(a.out, (s.to_json() for s in samples)) toks = sum(len(s.response_ids) for s in samples) print(json.dumps({"samples": n, "response_tokens": toks}), flush=True) return 0 if __name__ == "__main__": os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") sys.exit(main())