Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ __pycache__/
python/out/
*.zip
bench/compare.png
paper/out/
108 changes: 108 additions & 0 deletions paper/README.md
Original file line number Diff line number Diff line change
@@ -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.
202 changes: 202 additions & 0 deletions paper/evaluate.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading