"""Token-quota stratified sampler (round 1's ``stratified_cycle`` did not stratify). For every component c of ``configs/macjev/quotas.json`` an epoch receives ``min(tokens_per_epoch_c, max_repeat_c * available_tokens_c)`` tokens of c's rows (quota mode) or ``passes * available_tokens_c`` (passes mode). Rows are drawn from a per-component stream of fresh permutations, so a fractional quota walks through *different* rows in successive epochs instead of re-drawing the same prefix. The exact deficit against the quota is reported. Micro-batches are formed inside length buckets (length-sorted windows, budget = rows x longest row in padded tokens), shuffled across buckets and grouped into optimizer steps of ~``step_tokens`` real tokens (whole micro-batches, the boundary nearest to the target). A fraction ``js_frac`` of choice rows is planned as a two-view pair (second random option order) whose cost is included in the budget. The whole plan is a deterministic function of (rows, config, seed), so resuming needs only (epoch, step) and option orders are re-derived from (seed, epoch, step, micro-batch). Quota streams (2026-09-24, 25.6K context): a component with ``length_split`` in quotas.json (long -> long_le8k / long_gt8k) is drawn as one stream per length part (``macjev.pool.quota_streams``), each with its own quota and max_repeat; rows keep their component. A bucket with ``max_seqs`` holds at most that many views per micro-batch (buckets above 8192: one sequence, so JS pairs there run as one view). """ from __future__ import annotations import hashlib import json import math from collections import defaultdict from dataclasses import dataclass from typing import Sequence import numpy as np from ..pool import quota_streams, stream_of from .data import bucket_label, row_len def _rng(*key) -> np.random.Generator: h = hashlib.sha256(json.dumps(key).encode()).digest() return np.random.default_rng(int.from_bytes(h[:8], "little")) @dataclass class EpochPlan: epoch: int entry_row: np.ndarray # int32 row indices, grouped by micro-batch entry_pair: np.ndarray # bool: planned as a two-view pair mb_offsets: np.ndarray # len n_mb + 1, into entries step_offsets: np.ndarray # len n_steps + 1, into micro-batches step_tokens: np.ndarray # real tokens (both views) per step step_rows: np.ndarray # rows (not views) per step report: dict @property def n_steps(self) -> int: return len(self.step_offsets) - 1 def step_microbatches(self, step: int) -> list[list[tuple[int, bool]]]: out = [] for mb in range(self.step_offsets[step], self.step_offsets[step + 1]): a, b = self.mb_offsets[mb], self.mb_offsets[mb + 1] out.append([(int(r), bool(p)) for r, p in zip(self.entry_row[a:b], self.entry_pair[a:b])]) return out class QuotaSampler: def __init__(self, rows: Sequence[dict], readout: str, *, seed: int, buckets: Sequence[dict], step_tokens: int, quota_mode: str = "quotas", quotas: dict | None = None, passes: float = 1.0, scale_to_tokens: float | None = None, js_frac: float = 0.1, megabatch: int = 32): self.rows, self.readout, self.seed = rows, readout, seed self.bounds = [int(b["max_len"]) for b in buckets] self.budgets = [int(b["tokens"]) for b in buckets] self.max_seqs = [int(b["max_seqs"]) if b.get("max_seqs") is not None else None for b in buckets] self.step_tokens, self.js_frac, self.megabatch = int(step_tokens), float(js_frac), int(megabatch) self.lengths = np.array([row_len(r, readout) for r in rows], dtype=np.int64) if len(rows) == 0: raise ValueError("no training rows") if self.lengths.max() > self.bounds[-1]: raise ValueError(f"row of {self.lengths.max()} tokens exceeds the largest bucket {self.bounds[-1]}") self.is_choice = np.array([r["qtype"] == "choice" and len(r["names"]) >= 2 for r in rows]) self.mode = quota_mode self.components = self._components(quotas, passes, scale_to_tokens) self._cursor = {c: (0, 0) for c in self.components} # (cycle, position) into the permutation stream self._plans: dict[int, EpochPlan] = {} # ------------------------------------------------------------------ quotas def _components(self, quotas: dict | None, passes: float, scale: float | None) -> dict: by_comp: dict[str, list[int]] = defaultdict(list) for i, r in enumerate(self.rows): by_comp[r.get("component") or r["category"]].append(i) comps = {} if self.mode == "quotas": if quotas is None: raise ValueError("quota_mode=quotas needs configs/macjev/quotas.json") spec = quota_streams(quotas) unquoted = sorted(set(by_comp) - set(quotas["components"])) if unquoted: raise ValueError(f"rows belong to components without a quota: {unquoted}") by_stream: dict[str, list[int]] = defaultdict(list) for comp, idx in by_comp.items(): for i in idx: st = stream_of(spec, comp, int(self.lengths[i])) if st is None: raise ValueError(f"row {self.rows[i].get('id')} ({comp}, {self.lengths[i]} tokens) fits no " "length_split part of its component") by_stream[st].append(i) for name, s in spec.items(): idx = np.array(by_stream.get(name, []), dtype=np.int64) comps[name] = {"rows": idx, "tokens_per_epoch": float(s["tokens_per_epoch"]), "max_repeat": float(s["max_repeat"]), "component": s["component"], "categories": list(s["categories"])} if s["max_tokens"] is not None: comps[name]["length_range"] = [s["min_tokens"], s["max_tokens"]] present = sum(c["tokens_per_epoch"] for c in comps.values() if len(c["rows"])) factor = (float(scale) / present) if scale else 1.0 for c in comps.values(): c["quota"] = c["tokens_per_epoch"] * factor else: for name, idx in by_comp.items(): idx = np.array(idx, dtype=np.int64) comps[name] = {"rows": idx, "tokens_per_epoch": None, "max_repeat": float(passes), "categories": sorted({self.rows[i]["category"] for i in idx})} comps[name]["quota"] = float(passes) * float(self.lengths[idx].sum()) if scale: total = sum(c["quota"] for c in comps.values()) for c in comps.values(): c["quota"] *= float(scale) / total c["max_repeat"] = math.inf # the requested total wins over the pass count for name, c in comps.items(): avail = float(self.lengths[c["rows"]].sum()) if len(c["rows"]) else 0.0 c["available_tokens"] = avail c["target"] = min(c["quota"], c["max_repeat"] * avail) return comps def _draw(self, name: str, target: float) -> tuple[list[int], float]: """Take rows from the component's permutation stream until ``target`` tokens are reached.""" comp = self.components[name] idx = comp["rows"] if len(idx) == 0 or target <= 0: return [], 0.0 cycle, pos = self._cursor[name] perm = _rng(self.seed, "perm", name, cycle).permutation(len(idx)) taken, tokens = [], 0.0 while tokens < target: if pos >= len(idx): cycle, pos = cycle + 1, 0 perm = _rng(self.seed, "perm", name, cycle).permutation(len(idx)) i = int(idx[perm[pos]]) n = float(self.lengths[i]) # stop before overshooting by more than half a row if tokens + n - target > n / 2 and taken: break taken.append(i) tokens += n pos += 1 self._cursor[name] = (cycle, pos) return taken, tokens # ------------------------------------------------------------------ plans def plan(self, epoch: int) -> EpochPlan: for e in range(len(self._plans), epoch + 1): self._plans[e] = self._build(e) return self._plans[epoch] def _build(self, epoch: int) -> EpochPlan: entries: list[int] = [] report = {"epoch": epoch, "components": {}} for name in sorted(self.components): c = self.components[name] taken, tokens = self._draw(name, c["target"]) entries += taken uniq = len(set(taken)) report["components"][name] = { "component": c.get("component", name), "quota_tokens": c["quota"], "available_tokens": c["available_tokens"], "max_repeat": c["max_repeat"], "target_tokens": c["target"], "planned_tokens": tokens, "rows_available": int(len(c["rows"])), "rows_planned": len(taken), "unique_rows": uniq, "repeat_factor": (tokens / c["available_tokens"]) if c["available_tokens"] else 0.0, "deficit_tokens": max(0.0, c["quota"] - tokens), "capped_by_max_repeat": c["quota"] > c["max_repeat"] * c["available_tokens"]} if c.get("length_range"): report["components"][name]["length_range"] = list(c["length_range"]) rng = _rng(self.seed, "epoch", epoch) rows = np.array(entries, dtype=np.int64) pair = (rng.random(len(rows)) < self.js_frac) & self.is_choice[rows] bucket = np.searchsorted(self.bounds, self.lengths[rows]) mbs: list[np.ndarray] = [] for bi, (bound, budget, max_seqs) in enumerate(zip(self.bounds, self.budgets, self.max_seqs)): members = np.nonzero(bucket == bi)[0] if not len(members): continue members = members[rng.permutation(len(members))] window_tokens = self.megabatch * budget start = 0 while start < len(members): acc, end = 0, start while end < len(members) and acc < window_tokens: acc += int(self.lengths[rows[members[end]]]) * (2 if pair[members[end]] else 1) end += 1 win = members[start:end] win = win[np.argsort(-self.lengths[rows[win]], kind="stable")] cur: list[int] = [] cur_views, longest = 0, 0 for e in win: ln = int(self.lengths[rows[e]]) if pair[e] and (2 * ln > budget or (max_seqs is not None and max_seqs < 2)): pair[e] = False # a pair that alone exceeds the budget runs as one view views = 2 if pair[e] else 1 if cur and ((cur_views + views) * max(longest, ln) > budget or (max_seqs is not None and cur_views + views > max_seqs)): mbs.append(np.array(cur)) cur, cur_views, longest = [], 0, 0 cur.append(e) cur_views += views longest = max(longest, ln) if cur: mbs.append(np.array(cur)) start = end cost = self.lengths[rows] * np.where(pair, 2, 1) order = rng.permutation(len(mbs)) if mbs else np.zeros(0, dtype=np.int64) mbs = [mbs[i] for i in order] entry_row, entry_pair, mb_off = [], [], [0] step_off, step_tok, step_rows = [0], [], [] acc_tok, acc_rows = 0, 0 for m, members in enumerate(mbs): c_mb = int(cost[members].sum()) # nearest grouping (audit 2026-09-24): close the open step before this micro-batch when that lands # closer to step_tokens than adding it. Closing only at ">= step_tokens" made every H100 step 3 # micro-batches of ~62.6k = ~188k real tokens (+43% vs the plan's ~128k/step) because two are ~125k. if acc_rows and acc_tok + c_mb - self.step_tokens > self.step_tokens - acc_tok: step_off.append(m) step_tok.append(acc_tok) step_rows.append(acc_rows) acc_tok, acc_rows = 0, 0 entry_row.append(rows[members]) entry_pair.append(pair[members]) mb_off.append(mb_off[-1] + len(members)) acc_tok += c_mb acc_rows += len(members) if acc_tok >= self.step_tokens or m == len(mbs) - 1: step_off.append(m + 1) step_tok.append(acc_tok) step_rows.append(acc_rows) acc_tok, acc_rows = 0, 0 report["steps"] = len(step_tok) report["micro_batches"] = len(mbs) report["views"] = int(len(rows) + pair.sum()) report["pairs"] = int(pair.sum()) report["tokens"] = int(sum(step_tok)) return EpochPlan(epoch, np.concatenate(entry_row).astype(np.int32) if entry_row else np.zeros(0, np.int32), np.concatenate(entry_pair) if entry_pair else np.zeros(0, bool), np.array(mb_off), np.array(step_off), np.array(step_tok, dtype=np.int64), np.array(step_rows, dtype=np.int64), report) # ------------------------------------------------------------------ schedule horizon def horizon(self, epochs: float, max_tokens: int | None = None, max_steps: int | None = None) -> dict: """Total optimizer steps for the LR schedule: ``epochs`` (fractional last epoch allowed), capped.""" steps, tokens, per_epoch = 0, 0, [] full = math.ceil(epochs) for e in range(full): p = self.plan(e) n = p.n_steps if e < full - 1 or float(epochs).is_integer() else int(round(p.n_steps * (epochs - e))) per_epoch.append(n) for s in range(n): if (max_tokens is not None and tokens >= max_tokens) or (max_steps is not None and steps >= max_steps): break tokens += int(p.step_tokens[s]) steps += 1 return {"total_steps": steps, "total_tokens": tokens, "steps_per_epoch": per_epoch} def orders(self, epoch: int, step: int, mb: int, entries: list[tuple[int, bool]]) -> list[tuple[list[int], list[int] | None]]: """Random option orders for choice rows (score/noul keep canonical order).""" rng = _rng(self.seed, "order", epoch, step, mb) out = [] for r, paired in entries: k = len(self.rows[r]["names"]) if self.rows[r]["qtype"] != "choice": out.append((list(range(k)), None)) continue first = rng.permutation(k).tolist() second = None if paired: second = rng.permutation(k).tolist() if k > 1: tries = 0 while second == first and tries < 8: second = rng.permutation(k).tolist() tries += 1 out.append((first, second)) return out def quota_report(self) -> dict: return {name: {k: (v if not isinstance(v, np.ndarray) else int(len(v))) for k, v in c.items()} for name, c in self.components.items()} class Exposure: """Counts of *consumed* views/tokens per component/source/category/qtype/lang/length bucket.""" AXES = ("component", "source", "category", "qtype", "lang", "length") def __init__(self): self.counts = {a: {} for a in self.AXES} self.total = {"views": 0, "rows": 0, "tokens": 0} def add(self, row: dict, n_tokens: int, views: int) -> None: keys = {"component": row.get("component") or row["category"], "source": row["source"], "category": row["category"], "qtype": row["qtype"], "lang": row.get("lang", "?"), "length": bucket_label(n_tokens)} for axis, key in keys.items(): d = self.counts[axis].setdefault(key, {"views": 0, "rows": 0, "tokens": 0}) d["views"] += views d["rows"] += 1 d["tokens"] += n_tokens * views self.total["views"] += views self.total["rows"] += 1 self.total["tokens"] += n_tokens * views def state(self) -> dict: return {"counts": self.counts, "total": self.total} def load(self, state: dict) -> None: self.counts, self.total = state["counts"], state["total"] def report(self) -> dict: out = {"total": self.total} tot = max(1, self.total["tokens"]) for axis, d in self.counts.items(): out[axis] = {k: dict(v, token_share=v["tokens"] / tot) for k, v in sorted(d.items())} return out