diff --git a/.gitignore b/.gitignore index e21bff4..59a962b 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ __pycache__/ python/out/ *.zip bench/compare.png +paper/out/ diff --git a/paper/README.md b/paper/README.md new file mode 100644 index 0000000..c2d2197 --- /dev/null +++ b/paper/README.md @@ -0,0 +1,108 @@ +# Paper experiments: pointer network + MCTS + +| File | What | +|---|---| +| `ptrmcts.py` | Environment config, pointer network, MCTS, replay-based state restore | +| `train.py` | Behaviour-cloning warm start, then AlphaZero-style MCTS self-play | +| `evaluate.py` | Seeded evaluation of the learned policy and every built-in heuristic | + +```bash +zig build lib +pip install torch numpy gymnasium +export PYTHONPATH=python:paper +python paper/train.py --iters 15 --episodes 2 --sims 24 --out paper/out/ptr.pt +python paper/evaluate.py paper/out/ptr.pt --episodes 10 --sims 24 +``` + +Outputs go to `paper/out/`, which git ignores: `ptr.pt` holds the weights, the config and the training log, and `eval.json` holds the per-seed results. + +## Environment + +`ENV_KW` in `ptrmcts.py` defines the environment: +- 1 DeepRM machine; +- 80 Poisson jobs at 0.8 per tick; +- 2 resources; +- a 20-tick horizon; +- a pool of 10 waiting slots; +- the DeepRM slowdown reward. + +Its sum over an episode is minus the total slowdown. + +## Model + +The network sees the waiting jobs and the machines as one set: +- each job carries its demand grid, its wait time and a valid flag; +- each machine carries its free-capacity grid. + +A transformer encoder and a glimpse produce a context vector q. As in a pointer network, the output points at input elements: +- a pointer score for each job, `vᵀ tanh(W1 h_j + W2 q)`; +- plus a bilinear job–machine score, giving one logit per (job, machine) pair; +- a wait logit; +- a value head on q. + +Illegal actions are masked out. The action order matches `SchedEnv`. + +## Search + +MCTS is PUCT in the AlphaZero style: +- the network gives the prior and evaluates leaves; +- Q values are min-max normalized (as in MuZero); +- Dirichlet noise is added at the root during training. + +The engine cannot be cloned. Each simulation therefore restores the root state with `reset(seed)` and replays the actions taken so far. Every restore checks that the replayed state matches the recorded one, so this relies on, and continuously verifies, that the engine is deterministic for a given seed. + +## Training + +1. Imitate `tetris_srpt` for 40 episodes. +2. Repeat: + - play self-play episodes, sampling from the visit distribution π for the first 30 moves and choosing greedily after that; + - train on `CE(π) + 0.5·Huber(value, discounted return / 10)`. + +All randomness is seeded from `--seed`. Training episode e uses seed `seed·10⁶ + e`. + +## Evaluation and seeds + +Every policy runs on the same seeds: `10¹²`, `10¹² + 1`, … These never overlap with training seeds. Two things are checked, not assumed: + +- **Same workload for every policy.** For each seed, a reference run with a pool large enough to admit every job records the full workload. Every policy's run, recorded with the trace observer, must have the same jobs at the same ticks. Every job it admitted must have the reference duration and demand, including jobs that another policy rejected for a full pool. +- **Deterministic engine.** The first policy runs twice per seed, and the two trace files must be byte-identical. + +- **No seed overlap.** The training seeds stored in the checkpoint must not overlap the evaluation seeds. + +If any check fails, the script exits with an error. + +Other safeguards: +- Checkpoints are loaded with `weights_only=True`, so loading one cannot run code. +- Outputs are written atomically. +- During search, every replay is checked against a hash of the full state: each machine's free capacity, plus each waiting job's grid, duration and arrival tick. + +## Seed bug found and fixed + +The first evaluation failed the workload check. When the waiting pool was full, the engine rejected a job without generating its profile. The generator's random stream then shifted, so later jobs got different demands depending on the policy. Policies were not being compared on the same workload whenever jobs were rejected for a full pool. + +The engine now always draws the profile, writing it into a scratch grid, before rejecting the job. Two Zig tests cover this: +- one checks that the same seed reproduces an episode on fresh or reused engines, for every arrival process × generator; +- one checks that a job's profile does not depend on the policy when the pool rejects jobs. + +`python/tests/test_env.py` checks the same through the Python binding. + +## First results + +10 seeds, after 15 short iterations (about 4 minutes on an M1 Pro CPU): + +| policy | slowdown | wait | reward | +|---|---|---|---| +| fifo | 2.66 ± 0.86 | 3.31 | −208 | +| sjf | 1.73 ± 0.32 | 2.15 | −138 | +| best_fit | 2.75 ± 0.91 | 3.33 | −212 | +| tetris | 3.85 ± 1.41 | 4.22 | −283 | +| tetris_srpt | 1.77 ± 0.38 | 2.27 | −141 | +| random | 2.69 ± 1.13 | 3.18 | −210 | +| ptr (greedy) | 1.73 ± 0.31 | 2.31 | −137 | +| ptr + MCTS (24 sims) | 1.73 ± 0.32 | 2.20 | −137 | + +These results are preliminary: +- **Short run.** It is far too short to beat SJF. The network has mostly learned its `tetris_srpt` teacher, and is already slightly better than it. +- **For the paper,** use more iterations and simulations, and 100 or more evaluation seeds. + +The model was trained before the seed fix, but evaluated after it. diff --git a/paper/evaluate.py b/paper/evaluate.py new file mode 100644 index 0000000..3ad708f --- /dev/null +++ b/paper/evaluate.py @@ -0,0 +1,202 @@ +"""Evaluate the pointer network (greedy and with MCTS) against the built-in +heuristics on the *same* seeded workloads. + + PYTHONPATH=python:paper python paper/evaluate.py paper/out/ptr.pt --episodes 20 --sims 32 + +Fairness / reproducibility + * Every policy runs on seeds EVAL_SEED_START + 0..N-1 (disjoint from the + training seeds). The seed fixes the arrival process and every job's + demand profile, so all policies see the same workload. + * This is checked, not assumed: for every seed a reference run with a + pool large enough to admit every job records the full workload (job id + -> arrival tick, duration, demand grid). Each policy's run is recorded + with the trace observer and must have the same jobs at the same ticks, + and every job it admitted must have the reference profile -- including + jobs another policy rejected for a full pool. + * Training and evaluation seeds must not overlap (checked from the + checkpoint's training arguments). + * Engine determinism is checked too: the first policy is run twice per + seed and the two trace files must be byte-identical. + +Metrics per episode (from the trace): average slowdown (wait + dur) / dur, +average wait, makespan, total reward, jobs rejected (full pool, impossible) +and admitted jobs left unplaced. +Writes paper/out/eval.json and prints a mean ± std table. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import tempfile +import time +from pathlib import Path + +import numpy as np +import torch + +from ptrmcts import (ENV_KW, EVAL_SEED_START, MCTS, PointerNet, act_greedy, atomic_write, fingerprint, + train_seed_range) +from sched_env import SchedEnv + +BUILTIN = ["fifo", "sjf", "best_fit", "tetris", "tetris_srpt", "random"] + + +def read_trace(path: Path) -> tuple[dict, dict]: + """-> (metrics, workload) of the single episode in `path`.""" + work: dict[int, tuple] = {} + places = [] + done = None + for line in path.read_text().splitlines(): + e = json.loads(line) + if e["type"] == "arrive": + work[e["id"]] = (e["t"], e["dur"], json.dumps(e["demand"])) + elif e["type"] == "reject": + work.setdefault(e["id"], (e["t"], None, None, e["reason"])) # profile not in the trace + elif e["type"] == "place": + places.append(e) + elif e["type"] == "done": + done = e + sd = [(p["t"] - p["arrival"] + p["dur"]) / p["dur"] for p in places] + wait = [p["t"] - p["arrival"] for p in places] + m = {"slowdown": float(np.mean(sd)) if sd else float("nan"), + "wait": float(np.mean(wait)) if wait else float("nan"), + "makespan": done["makespan"] if done else None, + "unplaced": sum(1 for v in work.values() if v[1] is not None) - len(places), # admitted, never placed + "rejected": sum(1 for v in work.values() if v[1] is None)} + return m, work + + +def same_workload(ref: dict, run: dict) -> bool: + """`run` has exactly the reference jobs at the same ticks, and every job + it admitted has the reference duration and demand. (`ref` admitted every + job, so this also covers jobs this or another policy rejected.)""" + if ref.keys() != run.keys(): + return False + for k, v in run.items(): + if v[0] != ref[k][0]: + return False + if v[1] is not None and v[1:3] != ref[k][1:3]: + return False + return True + + +def reference_workload(env_kw: dict, seed: int, path: Path) -> dict: + """Full workload of `seed`: a run with a pool big enough to admit every job.""" + env = SchedEnv(**{**env_kw, "max_jobs": 1024}) + _, work = run(env, seed, lambda e, o, s, p: e.policy_action("fifo"), path) + env.close() + full = [k for k, v in work.items() if v[1] is None and v[3] == "pool_full"] + if full: + raise SystemExit(f"reference run for seed {seed} still rejected {len(full)} jobs for a full pool") + return work + + +def run(env, seed, policy, trace: Path) -> dict: + """One episode with `policy(env, obs, seed, prefix) -> action`; returns metrics.""" + env.start_trace(str(trace)) + obs, _ = env.reset(seed=seed) + total, prefix, done = 0.0, [], False + t0 = time.time() + while not done: + a = policy(env, obs, seed, prefix) + obs, r, term, trunc, info = env.step(a) + total += r + prefix.append(a) + done = term or trunc + env.stop_trace() + m, work = read_trace(trace) + m.update(reward=total, sec=time.time() - t0, illegal=info["stats"]["illegal"]) + return m, work + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("checkpoint", nargs="?", help="model from train.py (omit: heuristics only)") + ap.add_argument("--episodes", type=int, default=20) + ap.add_argument("--seed-start", type=int, default=EVAL_SEED_START) + ap.add_argument("--sims", type=int, default=32, help="MCTS simulations per move (0 = skip ptr+mcts)") + ap.add_argument("--policies", default=",".join(BUILTIN)) + ap.add_argument("--device", default="cpu") + ap.add_argument("--out", default="paper/out/eval.json") + args = ap.parse_args() + + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + device = torch.device(args.device) + seeds = [args.seed_start + i for i in range(args.episodes)] + ck = None + if args.checkpoint: + # weights_only: plain tensors/containers only, no arbitrary code on load + ck = torch.load(args.checkpoint, map_location=device, weights_only=True) + missing = {"model", "d_model", "env", "args"} - set(ck) + if missing: + raise SystemExit(f"{args.checkpoint}: not a train.py checkpoint (missing {sorted(missing)})") + tr = ck["args"] + used = train_seed_range(tr["seed"], tr["bc_episodes"] + tr["iters"] * tr["episodes"]) + overlap = [s for s in seeds if s in used] + if overlap: + raise SystemExit(f"evaluation seeds {overlap[0]}.. were used in training ({used.start}..{used.stop - 1})") + env_kw = ck["env"] if ck else ENV_KW + env = SchedEnv(**env_kw) + + policies = {name: (lambda e, o, s, p, n=name: e.policy_action(n)) for name in args.policies.split(",") if name} + if ck: + net = PointerNet.for_env(env, d=ck["d_model"]).to(device) + net.load_state_dict(ck["model"]) + net.eval() + policies["ptr"] = lambda e, o, s, p: act_greedy(net, o, e.action_masks(), device) + if args.sims: + mcts = MCTS(net, env_kw, device, sims=args.sims, gamma=tr["gamma"], reward_scale=tr["reward_scale"]) + policies[f"ptr+mcts{args.sims}"] = ( + lambda e, o, s, p: int(np.argmax(mcts.search(s, p, fingerprint(e), noise=False)))) + + results = {name: [] for name in policies} + checks = {"workload_mismatch": [], "nondeterministic": []} + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + for seed in seeds: + ref_work = reference_workload(env_kw, seed, tmp / "ref.jsonl") + for k, (name, pol) in enumerate(policies.items()): + m, work = run(env, seed, pol, tmp / f"{k}.jsonl") + results[name].append({"seed": seed, **m}) + if not same_workload(ref_work, work): + checks["workload_mismatch"].append((seed, name)) + if k == 0: + # determinism: same policy, same seed, again -> identical trace bytes + run(env, seed, pol, tmp / "again.jsonl") + h = [hashlib.sha256((tmp / f).read_bytes()).hexdigest() for f in (f"{k}.jsonl", "again.jsonl")] + if h[0] != h[1]: + checks["nondeterministic"].append(seed) + print(f"seed {seed}: " + " ".join(f"{n} {results[n][-1]['slowdown']:.2f}" for n in policies)) + + print(f"\n{len(seeds)} seeds from {args.seed_start}; same workload for every policy: " + f"{'yes' if not checks['workload_mismatch'] else 'NO ' + str(checks['workload_mismatch'])}; " + f"engine deterministic: {'yes' if not checks['nondeterministic'] else 'NO ' + str(checks['nondeterministic'])}\n") + cols = ["slowdown", "wait", "makespan", "reward", "rejected", "unplaced", "sec"] + print(f"{'policy':<14}" + "".join(f"{c:>18}" for c in cols)) + summary = {} + for name, rows in results.items(): + summary[name] = {} + line = f"{name:<14}" + for c in cols: + x = np.array([r[c] for r in rows], dtype=float) + summary[name][c] = {"mean": float(np.nanmean(x)), "std": float(np.nanstd(x))} + line += f"{np.nanmean(x):>11.2f} ±{np.nanstd(x):>5.2f}" + print(line) + + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + text = json.dumps({"seeds": seeds, "env": env_kw, "checks": checks, "summary": summary, + "episodes": results, "checkpoint": args.checkpoint}, indent=1) + atomic_write(out, lambda p: Path(p).write_text(text)) + print("\nsaved", out) + if checks["workload_mismatch"] or checks["nondeterministic"]: + raise SystemExit("seed checks FAILED") + + +if __name__ == "__main__": + main() diff --git a/paper/ptrmcts.py b/paper/ptrmcts.py new file mode 100644 index 0000000..2b9f523 --- /dev/null +++ b/paper/ptrmcts.py @@ -0,0 +1,314 @@ +"""Pointer network + Monte Carlo tree search for the scheduling simulator. + +Shared by paper/train.py and paper/evaluate.py. + +Model (`PointerNet`) + Waiting jobs and machines are encoded as one set with a transformer + encoder (jobs carry their demand grid, wait time and a valid flag; + machines their free-capacity grid). A glimpse over the set gives a + context vector q. Like a pointer network (Vinyals et al., 2015), the + output points at input elements instead of a fixed vocabulary: + + job pointer u_j = vᵀ tanh(W1 h_j + W2 q) + pair logit l_jm = u_j + ⟨W3 h_j, W4 h_m⟩ / √d + wait logit l_w = wᵀ q + + so the action space (max_jobs·n_machines + 1, same order as SchedEnv) + is scored by attention and illegal actions are masked out. A value head + on q estimates the (scaled, discounted) return for MCTS. + +Search (`MCTS`) + AlphaZero-style PUCT with the network as prior and leaf evaluator. + The engine has no clone(), so every simulation restores the root by + replaying it: reset(seed) + the episode's actions so far. This only + works because the Zig engine is deterministic for a given seed; every + restore checks that the replayed state matches the recorded one. +""" + +from __future__ import annotations + +import ctypes as C +import hashlib +import math +import os +import tempfile +from dataclasses import dataclass, field + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from sched_env import SchedEnv +from sched_env import _lib + +# Environment used in the paper experiments. Small enough for MCTS on a CPU. +ENV_KW = dict( + machines="deeprm:n=1", + jobs="poisson:n=80,rate=0.8", + n_res=2, + n_ticks=20, + max_jobs=10, + reward="slowdown", +) + +# Seed ranges: training and evaluation never share a workload. +EVAL_SEED_START = 10**12 # training uses seed·10⁶ + episode +TRAIN_SEED_BLOCK = 10**6 # episodes per --seed value + + +def train_seed_range(seed: int, n_episodes: int) -> range: + """Seeds a training run with `--seed seed` uses (must stay below EVAL_SEED_START).""" + if n_episodes > TRAIN_SEED_BLOCK: + raise ValueError(f"at most {TRAIN_SEED_BLOCK} training episodes per --seed") + r = range(seed * TRAIN_SEED_BLOCK, seed * TRAIN_SEED_BLOCK + n_episodes) + if r.stop > EVAL_SEED_START: + raise ValueError(f"training seeds {r.start}..{r.stop - 1} would reach the evaluation seeds") + return r + + +def atomic_write(path, write) -> None: + """write(tmp_path) then rename over `path`: a failed write never + destroys the previous complete file.""" + path = os.fspath(path) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", suffix=".tmp") + os.close(fd) + try: + write(tmp) + os.replace(tmp, path) + except BaseException: + os.unlink(tmp) + raise + + +def make_env(**overrides) -> SchedEnv: + return SchedEnv(**{**ENV_KW, **overrides}) + + +# ----------------------------------------------------------------------------- features + + +def featurize(obs: dict) -> dict[str, np.ndarray]: + """SchedEnv observation -> per-element feature arrays (unbatched).""" + jobs = obs["jobs"].reshape(obs["jobs"].shape[0], -1) + jobs = np.concatenate([jobs, obs["wait"][:, None], obs["valid"][:, None]], axis=1) + mach = obs["machines"].reshape(obs["machines"].shape[0], -1) + return {"jobs": jobs.astype(np.float32), "mach": mach.astype(np.float32), + "valid": obs["valid"] > 0} + + +def collate(feats: list[dict], masks: list[np.ndarray], device) -> tuple: + j = torch.as_tensor(np.stack([f["jobs"] for f in feats]), device=device) + m = torch.as_tensor(np.stack([f["mach"] for f in feats]), device=device) + v = torch.as_tensor(np.stack([f["valid"] for f in feats]), device=device) + a = torch.as_tensor(np.stack(masks), device=device) + return j, m, v, a + + +# ----------------------------------------------------------------------------- model + + +class PointerNet(nn.Module): + def __init__(self, job_dim: int, mach_dim: int, d: int = 128, heads: int = 4, layers: int = 2): + super().__init__() + self.d = d + self.job_in = nn.Sequential(nn.Linear(job_dim, d), nn.ReLU(), nn.Linear(d, d)) + self.mach_in = nn.Sequential(nn.Linear(mach_dim, d), nn.ReLU(), nn.Linear(d, d)) + self.type_emb = nn.Parameter(torch.zeros(2, d)) # job / machine + layer = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True) + self.enc = nn.TransformerEncoder(layer, layers) + self.glimpse = nn.MultiheadAttention(d, heads, batch_first=True) + self.q0 = nn.Parameter(torch.randn(1, 1, d) * 0.02) + # pointer + self.W1 = nn.Linear(d, d, bias=False) + self.W2 = nn.Linear(d, d) + self.v = nn.Linear(d, 1, bias=False) + self.W3 = nn.Linear(d, d, bias=False) + self.W4 = nn.Linear(d, d, bias=False) + self.wait = nn.Linear(d, 1) + self.value = nn.Sequential(nn.Linear(d, d), nn.ReLU(), nn.Linear(d, 1)) + + def forward(self, jobs, mach, valid, mask): + """jobs (B,J,Fj), mach (B,M,Fm), valid (B,J) bool, mask (B,J·M+1) bool + -> logits (B,J·M+1) with illegal = -inf, value (B,)""" + B, J, _ = jobs.shape + M = mach.shape[1] + x = torch.cat([self.job_in(jobs) + self.type_emb[0], self.mach_in(mach) + self.type_emb[1]], 1) + pad = torch.cat([~valid, torch.zeros(B, M, dtype=torch.bool, device=jobs.device)], 1) + h = self.enc(x, src_key_padding_mask=pad) + q, _ = self.glimpse(self.q0.expand(B, 1, self.d), h, h, key_padding_mask=pad) + q = q[:, 0] + hj, hm = h[:, :J], h[:, J:] + u = self.v(torch.tanh(self.W1(hj) + self.W2(q)[:, None])).squeeze(-1) # (B,J) + pair = torch.einsum("bjd,bmd->bjm", self.W3(hj), self.W4(hm)) / math.sqrt(self.d) + logits = torch.cat([(u[:, :, None] + pair).reshape(B, J * M), self.wait(q)], 1) + logits = logits.masked_fill(~mask, float("-inf")) + return logits, self.value(q).squeeze(-1) + + @classmethod + def for_env(cls, env: SchedEnv, **kw) -> "PointerNet": + d = env.dims + return cls(d.n_res * d.n_ticks + 2, d.n_res * d.n_ticks, **kw) + + +@torch.no_grad() +def evaluate_net(net: PointerNet, obs: dict, mask: np.ndarray, device) -> tuple[np.ndarray, float]: + """Prior probabilities over actions and value for one state.""" + logits, v = net(*collate([featurize(obs)], [mask], device)) + return torch.softmax(logits[0], 0).cpu().numpy(), float(v[0]) + + +# ----------------------------------------------------------------------------- replay + + +class Replayer: + """Restores an episode state by reset(seed) + replaying actions. + + Uses its own engine handle (so the caller's env is untouched) and raw + ctypes steps (no observation copies) for speed. + """ + + def __init__(self, env_kw: dict): + self.env = SchedEnv(**env_kw) + self._res = _lib.SimStep() + self._st = _lib.SimStats() + + def fingerprint(self) -> tuple: + return fingerprint(self.env) + + def restore(self, seed: int, actions: list[int], expect: tuple | None = None) -> None: + lib, h = self.env._lib, self.env._h + if lib.sim_reset(h, seed) != 0: + raise RuntimeError("sim_reset failed") + for a in actions: + if lib.sim_step(h, a, C.byref(self._res)) != 0: + raise RuntimeError(f"replay failed: step after the episode ended (seed {seed})") + if expect is not None and self.fingerprint() != expect: + raise RuntimeError(f"replay diverged (seed {seed}): {self.fingerprint()} != {expect}. " + "The engine is not deterministic for this seed.") + + def step(self, a: int) -> tuple[float, bool]: + if self.env._lib.sim_step(self.env._h, a, C.byref(self._res)) != 0: + raise RuntimeError("search stepped past the end of the episode") + r = self._res + return float(r.reward), bool(r.terminated or r.truncated) + + +# ----------------------------------------------------------------------------- MCTS + + +@dataclass +class Node: + prior: float + reward: float = 0.0 # reward of the transition into this node + terminal: bool = False + n: int = 0 + w: float = 0.0 + children: dict[int, "Node"] = field(default_factory=dict) + + @property + def expanded(self) -> bool: + return bool(self.children) or self.terminal + + def q(self) -> float: + return self.w / self.n if self.n else 0.0 + + +class MinMax: + def __init__(self): + self.lo, self.hi = math.inf, -math.inf + + def update(self, x: float): + self.lo, self.hi = min(self.lo, x), max(self.hi, x) + + def norm(self, x: float) -> float: + return (x - self.lo) / (self.hi - self.lo) if self.hi > self.lo else 0.5 + + +class MCTS: + """PUCT search. Rewards are divided by `reward_scale`; Q values are + min-max normalized inside the tree (MuZero), so the scale only matters + for the value head's targets.""" + + def __init__(self, net: PointerNet, env_kw: dict, device="cpu", sims: int = 32, c_puct: float = 1.5, + gamma: float = 0.98, reward_scale: float = 10.0, dirichlet: float = 0.3, + noise_frac: float = 0.25, rng: np.random.Generator | None = None): + """`env_kw`: the exact SchedEnv config of the episodes searched (required: + the search replays them on its own engine).""" + if sims < 1: + raise ValueError("MCTS needs sims >= 1") + self.net, self.device = net, device + self.sims, self.c, self.gamma, self.scale = sims, c_puct, gamma, reward_scale + self.dirichlet, self.noise_frac = dirichlet, noise_frac + self.rng = rng or np.random.default_rng(0) + self.rp = Replayer(env_kw) + + def _expand(self, node: Node) -> float: + env = self.rp.env + obs, mask = env._obs(), env.action_masks() + p, v = evaluate_net(self.net, obs, mask, self.device) + for a in np.flatnonzero(mask): + node.children[int(a)] = Node(prior=float(p[a])) + return v + + def _select(self, node: Node, mm: MinMax) -> tuple[int, Node]: + sq = math.sqrt(max(1, node.n)) + best, best_s = None, -math.inf + for a, ch in node.children.items(): + q = mm.norm(ch.reward / self.scale + self.gamma * ch.q()) if ch.n else 0.0 + s = q + self.c * ch.prior * sq / (1 + ch.n) + if s > best_s: + best, best_s = (a, ch), s + return best + + def search(self, seed: int, prefix: list[int], expect: tuple, noise: bool) -> np.ndarray: + """Visit counts over actions at the state reached by `prefix`.""" + root = Node(prior=1.0) + mm = MinMax() + self.rp.restore(seed, prefix, expect) + self._expand(root) + if noise and len(root.children) > 1: + eta = self.rng.dirichlet([self.dirichlet] * len(root.children)) + for e, ch in zip(eta, root.children.values()): + ch.prior = (1 - self.noise_frac) * ch.prior + self.noise_frac * e + for _ in range(self.sims): + self.rp.restore(seed, prefix) + node, path = root, [root] + while node.expanded and not node.terminal: + a, node = self._select(node, mm) + r, done = self.rp.step(a) + node.reward, node.terminal = r, done + path.append(node) + g = 0.0 if node.terminal else self._expand(node) + for nd in reversed(path): + nd.n += 1 + nd.w += g + if nd is not root: + mm.update(nd.reward / self.scale + self.gamma * nd.q()) + g = nd.reward / self.scale + self.gamma * g + counts = np.zeros(self.rp.env.dims.n_actions, dtype=np.float32) + for a, ch in root.children.items(): + counts[a] = ch.n + return counts + + +# ----------------------------------------------------------------------------- episodes + + +def fingerprint(env: SchedEnv) -> tuple: + """Full-state fingerprint: counters plus a hash of every machine's free + capacity and, for each waiting slot, its job grid, duration and arrival.""" + s = env.stats() + r = env.raw() + h = hashlib.blake2b(digest_size=16) + v = r["valid"] + h.update(np.ascontiguousarray(r["free"]).tobytes()) + h.update(v.tobytes()) + for k in ("jobs", "duration", "arrival"): # empty slots hold stale data: skip them + h.update(np.ascontiguousarray(r[k][v]).tobytes()) + return (s["now"], s["arrived"], s["placed"], s["rejected"], s["waiting"], s["total_reward"], h.hexdigest()) + + +def act_greedy(net, obs, mask, device) -> int: + p, _ = evaluate_net(net, obs, mask, device) + return int(np.argmax(p)) diff --git a/paper/train.py b/paper/train.py new file mode 100644 index 0000000..4bf3f7c --- /dev/null +++ b/paper/train.py @@ -0,0 +1,184 @@ +"""Train the pointer network with MCTS self-play (AlphaZero style). + + zig build lib + PYTHONPATH=python:paper python paper/train.py --iters 20 --out paper/out/ptr.pt + +1. (optional) Behaviour cloning warm start: imitate a built-in heuristic + (default tetris_srpt) so search starts from a sensible prior. +2. Self-play: each step runs MCTS from the current state; the visit + distribution π is the policy target, the discounted (scaled) return the + value target. Actions are sampled from π for the first `--explore-steps` + steps of an episode, greedy afterwards. +3. Train on a replay buffer with CE(π, net) + value_coef · Huber(v, G). + +Every episode uses its own training seed (seed·10⁶ + 0, 1, 2, ...); +evaluation seeds (paper/evaluate.py) are disjoint, and both scripts check it. All randomness (torch, numpy, engine) is +seeded from --seed, so a run is reproducible on the same machine. +""" + +from __future__ import annotations + +import argparse +import collections +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +from ptrmcts import ENV_KW, MCTS, PointerNet, atomic_write, collate, featurize, fingerprint, make_env, train_seed_range + + +def discounted(rewards: list[float], gamma: float, scale: float) -> list[float]: + g, out = 0.0, [] + for r in reversed(rewards): + g = r / scale + gamma * g + out.append(g) + return out[::-1] + + +def run_episode(env, seed, choose, gamma, scale): + """Play one episode; `choose(obs, mask, prefix, expect, step)` -> (action, π).""" + obs, _ = env.reset(seed=seed) + samples, rewards, prefix = [], [], [] + done = False + while not done: + mask = env.action_masks() + a, pi = choose(obs, mask, prefix, fingerprint(env), len(prefix)) + samples.append((featurize(obs), mask, pi)) + obs, r, term, trunc, info = env.step(a) + rewards.append(r) + prefix.append(a) + done = term or trunc + rets = discounted(rewards, gamma, scale) + return [(f, m, p, g) for (f, m, p), g in zip(samples, rets)], info["stats"], sum(rewards) + + +def train_step(net, opt, batch, device, value_coef): + feats, masks, pis, rets = zip(*batch) + j, m, v, a = collate(list(feats), list(masks), device) + pi = torch.as_tensor(np.stack(pis), device=device) + g = torch.as_tensor(np.asarray(rets, dtype=np.float32), device=device) + logits, val = net(j, m, v, a) + logp = torch.log_softmax(logits, 1).masked_fill(~a, 0.0) + pl = -(pi * logp).sum(1).mean() + vl = F.smooth_l1_loss(val, g) + loss = pl + value_coef * vl + opt.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0) + opt.step() + return pl.item(), vl.item() + + +def fit(net, opt, buffer, args, device, rng): + if len(buffer) < args.batch: + return float("nan"), float("nan") + data = list(buffer) + pls, vls = [], [] + for _ in range(args.updates): + idx = rng.choice(len(data), args.batch, replace=False) + pl, vl = train_step(net, opt, [data[i] for i in idx], device, args.value_coef) + pls.append(pl) + vls.append(vl) + return float(np.mean(pls)), float(np.mean(vls)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--iters", type=int, default=20, help="self-play / train iterations") + ap.add_argument("--episodes", type=int, default=4, help="self-play episodes per iteration") + ap.add_argument("--sims", type=int, default=32, help="MCTS simulations per move") + ap.add_argument("--explore-steps", type=int, default=30, help="sample from π for the first N moves") + ap.add_argument("--bc-teacher", default="tetris_srpt", help="built-in policy to imitate first ('' = none)") + ap.add_argument("--bc-episodes", type=int, default=40) + ap.add_argument("--bc-epochs", type=int, default=5) + ap.add_argument("--updates", type=int, default=50, help="gradient steps per iteration") + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--buffer", type=int, default=20_000) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--value-coef", type=float, default=0.5) + ap.add_argument("--gamma", type=float, default=0.98) + ap.add_argument("--reward-scale", type=float, default=10.0) + ap.add_argument("--d-model", type=int, default=128) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--device", default="cpu") + ap.add_argument("--out", default="paper/out/ptr.pt") + args = ap.parse_args() + if args.sims < 1: + ap.error("--sims must be >= 1") + seeds = iter(train_seed_range(args.seed, args.bc_episodes + args.iters * args.episodes)) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + rng = np.random.default_rng(args.seed) + device = torch.device(args.device) + + env = make_env() + net = PointerNet.for_env(env, d=args.d_model).to(device) + opt = torch.optim.Adam(net.parameters(), lr=args.lr) + buffer = collections.deque(maxlen=args.buffer) + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + log = [] + + # 1. behaviour cloning ------------------------------------------------------ + if args.bc_teacher and args.bc_episodes: + n_act = env.dims.n_actions + + def teacher(obs, mask, prefix, expect, step): + a = env.policy_action(args.bc_teacher) + pi = np.zeros(n_act, dtype=np.float32) + pi[a] = 1 + return a, pi + + data = [] + for _ in range(args.bc_episodes): + d, _, _ = run_episode(env, next(seeds), teacher, args.gamma, args.reward_scale) + data += d + for ep in range(args.bc_epochs): + perm = rng.permutation(len(data)) + pls, vls = [], [] + for i in range(0, len(perm) - args.batch + 1, args.batch): + pl, vl = train_step(net, opt, [data[k] for k in perm[i:i + args.batch]], device, args.value_coef) + pls.append(pl) + vls.append(vl) + print(f"bc epoch {ep}: policy loss {np.mean(pls):.3f} value loss {np.mean(vls):.3f} ({len(data)} samples)") + buffer.extend(data) + + # 2-3. self-play + training ------------------------------------------------ + mcts = MCTS(net, ENV_KW, device, sims=args.sims, gamma=args.gamma, reward_scale=args.reward_scale, rng=rng) + for it in range(args.iters): + t0 = time.time() + net.eval() + rets, slow = [], [] + for _ in range(args.episodes): + seed = next(seeds) + + def choose(obs, mask, prefix, expect, step, seed=seed): + counts = mcts.search(seed, prefix, expect, noise=True) + pi = counts / counts.sum() + a = int(rng.choice(len(pi), p=pi)) if step < args.explore_steps else int(np.argmax(counts)) + return a, pi + + d, stats, ret = run_episode(env, seed, choose, args.gamma, args.reward_scale) + buffer.extend(d) + rets.append(ret) + slow.append(-ret / max(1, stats["placed"])) + net.train() + pl, vl = fit(net, opt, buffer, args, device, rng) + rec = {"iter": it, "return": float(np.mean(rets)), "slowdown_per_job": float(np.mean(slow)), + "policy_loss": pl, "value_loss": vl, "buffer": len(buffer), "sec": round(time.time() - t0, 1)} + log.append(rec) + print(json.dumps(rec)) + ck = {"model": net.state_dict(), "d_model": args.d_model, "env": ENV_KW, "args": vars(args), "log": log} + atomic_write(out, lambda p: torch.save(ck, p)) + print("saved", out) + + +if __name__ == "__main__": + main() diff --git a/python/tests/test_env.py b/python/tests/test_env.py index 8de9756..8076224 100644 --- a/python/tests/test_env.py +++ b/python/tests/test_env.py @@ -136,3 +136,32 @@ def test_trace_replay_matches_live_run(tmp_path): assert abs(s["avg_wait"] - want["avg_wait"]) < 1e-9 animate(eps[1], eps[1].frames[:4], str(tmp_path / "r.gif"), fps=10) + + +def test_seed_reproduces_episode_across_envs_and_resets(): + """Same seed -> identical observations and rewards, whether on a fresh + env or after other episodes; different seeds -> different workloads.""" + + def rollout(env, seed): + obs, _ = env.reset(seed=seed) + rng = np.random.default_rng(123) # same action choices + frames, done = [], False + while not done: + frames.append(np.concatenate([obs[k].ravel() for k in sorted(obs)])) + a = int(rng.choice(np.flatnonzero(env.action_masks()))) + obs, r, term, trunc, _ = env.step(a) + frames.append(np.array([r], dtype=np.float32)) + done = term or trunc + return np.concatenate(frames) + + for jobs in ["poisson:n=40,rate=0.8", "mmpp:n=40", "pareto:n=40", "selfsimilar:n=40"]: + for machines in ["deeprm:n=2", "random:n=3,varying=1"]: + kw = {**KW, "jobs": jobs, "machines": machines} + a, b = SchedEnv(**kw), SchedEnv(**kw) + x = rollout(a, 5) + rollout(b, 9) + y = rollout(b, 5) # after a different episode + assert np.array_equal(x, y), (jobs, machines) + assert not np.array_equal(x, rollout(a, 9)) + a.close() + b.close() diff --git a/src/engine/engine.zig b/src/engine/engine.zig index 5672a6c..aabd1e4 100644 --- a/src/engine/engine.zig +++ b/src/engine/engine.zig @@ -61,6 +61,10 @@ pub const Engine = struct { layout: Layout, machines: Machines, jobs: Jobs, + /// One job grid that a job rejected for a full pool is generated into, + /// so the generator draws the same random numbers whatever the policy + /// did (a seed fixes the whole workload). + scratch: []align(grid.simd.CACHE) Elem, arrivals: ports.ArrivalSource, generator: ports.UsageGenerator, observers: ports.ObserverList = .{}, @@ -89,7 +93,9 @@ pub const Engine = struct { var machines = try Machines.init(gpa, layout, n_m, caps); errdefer machines.deinit(gpa); - const jobs = try Jobs.init(gpa, layout, cfg.max_jobs); + var jobs = try Jobs.init(gpa, layout, cfg.max_jobs); + errdefer jobs.deinit(gpa); + const scratch = try gpa.alignedAlloc(Elem, grid.simd.ALIGN, layout.block); return .{ .gpa = gpa, @@ -97,6 +103,7 @@ pub const Engine = struct { .layout = layout, .machines = machines, .jobs = jobs, + .scratch = scratch, .arrivals = arrivals, .generator = generator, }; @@ -105,6 +112,7 @@ pub const Engine = struct { pub fn deinit(self: *Engine) void { self.machines.deinit(self.gpa); self.jobs.deinit(self.gpa); + self.gpa.free(self.scratch); self.running.deinit(self.gpa); } @@ -258,6 +266,18 @@ pub const Engine = struct { fn pullArrivals(self: *Engine) !void { while (try self.arrivals.next(self.now)) |meta| { const slot = self.jobs.acquire() orelse { + // still draw its profile: keeps the generator's random + // stream, and so every later job, independent of the policy + const g = grid.Usage.fromPool(self.scratch, self.layout, 0); + g.clear(); + _ = self.generator.job(meta, g) catch |e| switch (e) { + error.OutOfMemory => return e, + else => { + // same report as on the admitted path + self.reject(meta.id, .invalid_profile); + continue; + }, + }; self.reject(meta.id, .pool_full); continue; }; diff --git a/tests/scenario_test.zig b/tests/scenario_test.zig index 7c6cab3..29ed48c 100644 --- a/tests/scenario_test.zig +++ b/tests/scenario_test.zig @@ -807,3 +807,168 @@ test "property: cached pair scores give the same decision as a fresh scan" { } } } + +// ------------------------------------------------------------------ seeds + +/// `h`: every event plus the demand grid of each arriving job. +/// `work`: the workload only (arriving jobs: id, tick, duration, demand), +/// without the episode seed or anything the policy decides. +const EventHash = struct { + h: std.hash.Wyhash = .init(0), + work: std.hash.Wyhash = .init(0), + + pub fn onEvent(self: *EventHash, ev: sched.Event, st: *const sched.State) void { + if (ev == .job_arrived) { + const e = ev.job_arrived; + std.hash.autoHash(&self.work, e.id); + std.hash.autoHash(&self.work, e.tick); + std.hash.autoHash(&self.work, st.jobs.duration[e.slot]); + for (0..st.jobs.layout.n_res) |r| self.work.update(std.mem.sliceAsBytes(st.jobs.get(e.slot).row(r))); + } + self.h.update(@tagName(ev)); + switch (ev) { + inline else => |e| std.hash.autoHash(&self.h, e), + } + if (ev == .job_arrived) { + const s = ev.job_arrived.slot; + const job = st.jobs.get(s); + self.h.update(std.mem.asBytes(&st.jobs.duration[s])); + for (0..st.jobs.layout.n_res) |r| self.h.update(std.mem.sliceAsBytes(job.row(r))); + } + } +}; + +const RunHash = struct { all: u64, work: u64 }; + +fn seededRun(comptime Arr: type, comptime Gen: type, arr0: Arr, seeds: []const u64, out: []RunHash) !void { + var arr = arr0; + var gen = Gen{ .n_machines = 3 }; + var eng = try sched.Engine.init(testing.allocator, .{ .n_res = 2, .n_ticks = 20, .max_jobs = 12 }, .init(&arr), .init(&gen)); + defer eng.deinit(); + var hash = EventHash{}; + try eng.addObserver(.init(&hash)); + for (seeds, out) |seed, *o| { + hash = .{}; + try eng.reset(seed); + var p = A.policies.RandomPolicy{}; + sched.ports.policy.resetIfAny(A.policies.RandomPolicy, &p, seed); + _ = try eng.run(&p, 100_000); + o.* = .{ .all = hash.h.final(), .work = hash.work.final() }; + } +} + +test "property: same seed gives the same episode, on fresh or reused engines" { + // Run A: seed 5 on a fresh engine. Run B: seeds 9 then 5 on another + // engine, so seed 5 follows a different episode. Both seed-5 episodes + // must produce the identical event stream (and job grids); seed 9 not. + inline for (.{ A.generators.RandomProfiles, A.generators.DeepRM }) |G| { + const arrivals = .{ + A.arrivals.Poisson{ .total = 150, .rate = 1.5 }, + A.arrivals.Mmpp{ .total = 150, .rate = 1.5 }, + A.arrivals.ParetoArrivals{ .total = 150, .rate = 1.5 }, + A.arrivals.SelfSimilar{ .total = 150, .rate = 1.5 }, + }; + inline for (arrivals) |arr| { + var a: [1]RunHash = undefined; + var b: [3]RunHash = undefined; + try seededRun(@TypeOf(arr), G, arr, &.{5}, &a); + try seededRun(@TypeOf(arr), G, arr, &.{ 9, 5, 9 }, &b); + try testing.expectEqual(a[0], b[1]); + try testing.expectEqual(b[0], b[2]); + // different seed -> different workload (not just a different seed field) + try testing.expect(a[0].work != b[0].work); + } + } +} + +/// job id -> hash of its demand grid, for every admitted job. +const Demands = struct { + map: std.AutoHashMapUnmanaged(u32, u64) = .empty, + + pub fn onEvent(self: *Demands, ev: sched.Event, st: *const sched.State) void { + if (ev != .job_arrived) return; + const s = ev.job_arrived.slot; + var h = std.hash.Wyhash.init(st.jobs.duration[s]); + for (0..st.jobs.layout.n_res) |r| h.update(std.mem.sliceAsBytes(st.jobs.get(s).row(r))); + self.map.put(testing.allocator, ev.job_arrived.id, h.final()) catch unreachable; + } +}; + +fn demandsWith(comptime P: type, d: *Demands) !usize { + var arr = A.arrivals.Poisson{ .total = 300, .rate = 2 }; + var gen = A.generators.RandomProfiles{ .n_machines = 1 }; + // tiny pool: many pool_full rejections, which differ per policy + var eng = try sched.Engine.init(testing.allocator, .{ .n_res = 2, .n_ticks = 20, .max_jobs = 3 }, .init(&arr), .init(&gen)); + defer eng.deinit(); + try eng.addObserver(.init(d)); + try eng.reset(11); + var p = P{}; + defer sched.ports.policy.deinitIfAny(P, &p); + return (try eng.run(&p, 100_000)).rejected; +} + +test "property: a seed fixes every job's profile, even when the pool rejects jobs" { + var a = Demands{}; + defer a.map.deinit(testing.allocator); + var b = Demands{}; + defer b.map.deinit(testing.allocator); + const ra = try demandsWith(A.policies.FifoStrict, &a); + const rb = try demandsWith(A.policies.ShortestFirst, &b); + try testing.expect(ra > 0 and rb > 0 and ra != rb); // the policies did reject differently + var common: usize = 0; + var it = a.map.iterator(); + while (it.next()) |e| if (b.map.get(e.key_ptr.*)) |h| { + try testing.expectEqual(e.value_ptr.*, h); + common += 1; + }; + try testing.expect(common > 10); +} + +/// Generator whose n-th call (from reset) returns a 1-tick job of demand n. +const Counting = struct { + calls: Elem = 0, + pub fn reset(self: *Counting, seed: u64) void { + _ = seed; + self.calls = 0; + } + pub fn machineCount(_: *Counting) usize { + return 1; + } + pub fn machine(_: *Counting, _: usize, cap: []Elem) sched.ports.usage_generator.Error!void { + @memset(cap, 10); + } + pub fn job(self: *Counting, _: sched.JobMeta, out: sched.Usage) sched.ports.usage_generator.Error!u16 { + self.calls += 1; + out.resourceMut(0)[0] = self.calls; + return 1; + } +}; + +test "scenario: a job rejected for a full pool still draws its profile" { + // Pool of 1. Jobs 0 and 1 arrive at t=0, job 2 at t=1. + // t=0: job 0 admitted (draw 1), job 1 pool_full (draw 2) + // wait (job 0 never placed: still holds the slot) + // t=1: job 2 pool_full (draw 3) + // Place job 0 at t=1, then job 3 arrives at t=2 and is admitted with + // draw 4. Before the fix, rejected jobs drew nothing and job 3 got 2. + var metas = [_]sched.JobMeta{ + .{ .id = 0, .arrival = 0 }, .{ .id = 1, .arrival = 0 }, + .{ .id = 2, .arrival = 1 }, .{ .id = 3, .arrival = 2 }, + }; + var arr = A.arrivals.Fixed{ .items = &metas }; + var gen = Counting{}; + var rec = Recorder{}; + defer rec.deinit(); + var eng = try sched.Engine.init(testing.allocator, .{ .n_res = 1, .n_ticks = 4, .max_jobs = 1, .skip_empty = false }, .init(&arr), .init(&gen)); + defer eng.deinit(); + try eng.addObserver(.init(&rec)); + try eng.reset(0); + try testing.expectEqual(@as(Elem, 1), eng.jobs.get(0).row(0)[0]); + _ = try eng.step(.wait); + _ = try eng.step(.{ .place = .{ .slot = 0, .machine = 0 } }); + _ = try eng.step(.wait); + try testing.expectEqual(@as(u32, 3), eng.jobs.id[0]); + try testing.expectEqual(@as(Elem, 4), eng.jobs.get(0).row(0)[0]); + try testing.expectEqual(@as(usize, 2), rec.rejected.items.len); + for (rec.rejected.items) |r| try testing.expectEqual(sched.model.RejectReason.pool_full, r); +}