Repository navigation
Pointer network + MCTS experiments; fix seed-dependent workloads - #2
Merged
Merged
Conversation
paper/: pointer network with AlphaZero-style MCTS (replay-based state restore), training script (behaviour cloning + self-play) and a seeded evaluation against the built-in heuristics that checks every policy sees the same workload and that runs are byte-identical. Engine fix: a job rejected for a full pool now still draws its profile (into a scratch grid), so the generator's random stream - and every later job - no longer depends on the policy. Tests: same seed reproduces an episode on fresh/reused engines for all arrivals x generators; profiles are policy-independent under pool rejections; Python binding seed test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reviewer's GuideAPIAdd the shared pointer-network and MCTS module used by training and evaluation.
Uses of the APIAdd seeded policy evaluation with workload, determinism, and training-seed checks.
ImplementationGenerate profiles for jobs rejected by a full pool so later workload generation remains independent of policy decisions.
ConfigurationIgnore generated paper experiment outputs.
DocumentationDocument the experiment setup, reproducibility safeguards, seed fix, and preliminary results.
TestsTest that seeded episodes reproduce across environments and resets in the Python binding.
Test seed reproducibility across arrival and generator combinations and verify profiles are drawn on pool-full rejection.
Other changesFiles not grouped.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 12 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="paper/evaluate.py" line_range="115" />
<code_context>
+
+ policies = {name: (lambda e, o, s, p, n=name: e.policy_action(n)) for name in args.policies.split(",") if name}
+ if args.checkpoint:
+ ck = torch.load(args.checkpoint, map_location=device)
+ net = PointerNet.for_env(env, d=ck["d_model"]).to(device)
+ net.load_state_dict(ck["model"])
</code_context>
<issue_to_address>
**Loading checkpoints executes attacker code**
When an attacker supplies a crafted checkpoint and persuades a user to evaluate it, `torch.load` deserializes the checkpoint before any validation, so a malicious checkpoint executes arbitrary code with the evaluator's privileges when the user runs the evaluation script.
Load checkpoints using a restricted weights-only format or a non-executable tensor format, and validate the loaded structure before use.
</issue_to_address>
### Comment 2
<location path="paper/ptrmcts.py" line_range="158" />
<code_context>
+ if lib.sim_reset(h, seed) != 0:
+ raise RuntimeError("sim_reset failed")
+ for a in actions:
+ lib.sim_step(h, a, C.byref(self._res))
+ if expect is not None and self.fingerprint() != expect:
+ raise RuntimeError(f"replay diverged (seed {seed}): {self.fingerprint()} != {expect}. "
</code_context>
<issue_to_address>
**Replay continues after step errors**
When an engine step returns an error during replay or simulation, `Replayer.restore` and `Replayer.step` ignore `sim_step`'s return code, so replay continues with a state that did not advance and stale `_res` values, corrupting MCTS visit counts returned to training or evaluation.
Check every `sim_step` return code and stop replay or search immediately when a step fails.
Also at `paper/ptrmcts.py:165`.
</issue_to_address>
### Comment 3
<location path="paper/ptrmcts.py" line_range="151" />
<code_context>
+ def fingerprint(self) -> tuple:
+ self.env._lib.sim_stats(self.env._h, C.byref(self._st))
+ s = self._st
+ return (s.now, s.arrived, s.placed, s.rejected, s.waiting, round(s.total_reward, 4))
+
+ def restore(self, seed: int, actions: list[int], expect: tuple | None = None) -> None:
</code_context>
<issue_to_address>
**Divergent replay states pass validation**
When a replay has different job profiles or machine state but matching aggregate statistics and rounded reward, `Replayer.fingerprint` checks only summary values, so `restore` accepts the divergent state and MCTS chooses actions from the wrong state.
Include the restored job and machine state in the fingerprint comparison.
Also at `paper/ptrmcts.py:158-159`, `paper/ptrmcts.py:266`.
</issue_to_address>
### Comment 4
<location path="paper/ptrmcts.py" line_range="212" />
<code_context>
+ 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:
</code_context>
<issue_to_address>
**Search uses a different environment**
When MCTS is used with an environment that differs from `ENV_KW` and its configuration is not repeated in the constructor, `Replayer` builds its engine from default `ENV_KW` when no overrides are supplied, so MCTS searches transitions from that default rather than the caller's custom environment. The returned visit counts then do not represent the caller's state or workload.
Require the environment configuration when constructing MCTS, or pass in an environment/replayer tied to the caller's configuration and validate compatibility.
</issue_to_address>
### Comment 5
<location path="src/engine/engine.zig" line_range="273" />
<code_context>
+ // 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| if (e == error.OutOfMemory) return e;
self.reject(meta.id, .pool_full);
continue;
</code_context>
<issue_to_address>
**Generator failures go unnoticed**
When the pool is full and `generator.job` returns a non-`OutOfMemory` error, `pullArrivals` returns only `OutOfMemory` and silently discards other generator errors, then records the job as `pool_full`. A failed profile read or invalid input therefore looks like a successful rejection and the episode continues with a potentially shifted workload; no error is logged or exposed.
Propagate or explicitly report generator errors on the pool-full path instead of silently swallowing them.
</issue_to_address>
### Comment 6
<location path="paper/ptrmcts.py" line_range="53" />
<code_context>
+)
+
+# Seed ranges: training and evaluation never share a workload.
+EVAL_SEED_START = 10**12 # training uses seed·10⁶ + episode
+
+
</code_context>
<issue_to_address>
**Training and evaluation reuse workloads**
When the caller-selected training and evaluation seed ranges intersect, `next_seed` and the fixed `EVAL_SEED_START` allow overlapping ranges, so evaluation reuses workloads seen during training despite the documented separation.
Validate the generated ranges and reject overlapping training and evaluation seeds.
Also at `paper/train.py:125`, `paper/evaluate.py:99`.
</issue_to_address>
### Comment 7
<location path="paper/evaluate.py" line_range="49" />
<code_context>
+ 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)) # demand not recorded
+ elif e["type"] == "place":
+ places.append(e)
</code_context>
<issue_to_address>
**Different workloads pass the fairness check**
When a job is rejected by one policy run but admitted in another, `read_trace` records no demand for rejected jobs, and `same_workload` skips demand comparison unless both runs recorded one, so differing profiles pass as identical and evaluation reports an unchecked workload match.
Record rejected jobs' demands in the trace and compare every job's demand in `same_workload`, including rejected jobs.
Also at `paper/evaluate.py:72-73`, `paper/README.md:67-68`.
</issue_to_address>
### Comment 8
<location path="paper/train.py" line_range="94" />
<code_context>
+ 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)")
</code_context>
<issue_to_address>
**Zero simulations abort training**
When training is invoked with `--sims 0`, `MCTS.search` returns zero visit counts, so `choose` normalizes them into NaN probabilities and `rng.choice` raises instead of training.
Reject `--sims 0` during argument validation or provide a defined fallback for zero visit counts.
Also at `paper/train.py:164`.
</issue_to_address>
### Comment 9
<location path="paper/train.py" line_range="179" />
<code_context>
+ log.append(rec)
+ print(json.dumps(rec))
+ torch.save({"model": net.state_dict(), "d_model": args.d_model, "env": ENV_KW,
+ "args": vars(args), "log": log}, out)
+ print("saved", out)
+
</code_context>
<issue_to_address>
**Failed writes destroy completed artifacts**
When a checkpoint or evaluation write fails partway through, `torch.save` and `write_text` write directly to their destinations, so an interruption or I/O error leaves a partial artifact and destroys the previous complete file.
Write each artifact to a temporary file and replace the destination only after the write completes.
Also at `paper/evaluate.py:163`.
</issue_to_address>
### Comment 10
<location path="paper/evaluate.py" line_range="59" />
<code_context>
+ 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),
+ "rejected": sum(1 for v in work.values() if v[1] is None)}
+ return m, work
</code_context>
<issue_to_address>
**Rejected jobs disappear from summary**
When a policy rejects jobs, for example because the waiting pool is full, the `unplaced` count subtracts placements only from admitted jobs, excluding rejected jobs, while the printed summary omits the separate `rejected` metric. Runs with pool-full rejections therefore understate how many jobs were not placed in the main comparison table.
Include rejected jobs in the reported unplaced total or add a rejected-job column to the printed summary.
Also at `paper/evaluate.py:149`.
</issue_to_address>
### Comment 11
<location path="tests/scenario_test.zig" line_range="867" />
<code_context>
self.jobs.deinit(self.gpa);
+ self.gpa.free(self.scratch);
self.running.deinit(self.gpa);
}
</code_context>
<issue_to_address>
**Different-seed check passes on identical workloads**
When the arrival and profile generators stop using the reset seed but the engine still reports that seed in `episode_started`, the `same seed gives the same episode` test still passes its different-seed assertion: `EventHash` hashes every event, including `episode_started.seed` at lines 817–820, so this assertion sees different hashes even when the arrival and profile generators ignore their seeds and produce identical workloads.
Compare a workload-only hash of job IDs, arrival ticks, and demand grids for the different-seed assertion, excluding the episode seed and policy-dependent events.
</issue_to_address>
### Comment 12
<location path="src/engine/engine.zig" line_range="273" />
<code_context>
+ // 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| if (e == error.OutOfMemory) return e;
self.reject(meta.id, .pool_full);
continue;
</code_context>
<issue_to_address>
**Changed rejection path lacks hand-worked coverage**
When the pool-full path's new profile draw is treated as an engine-semantics change, `pullArrivals` now draws a profile for pool-full jobs, but the added test compares randomized workloads across policies rather than checking a hand-worked expected case for this behavior, leaving the required semantic regression case missing.
Add a deterministic hand-worked scenario in `tests/scenario_test.zig` that verifies the effect of drawing a profile for a pool-full rejection.
Also at `tests/scenario_test.zig:897`.
</issue_to_address>…l case - engine: a generator error on the pool-full path is reported as invalid_profile (as on the admitted path) instead of being dropped - tests: hand-worked scenario for drawing a pool-full job's profile; the different-seed assertion compares a workload-only hash - paper: torch.load(weights_only=True) + checkpoint validation; sim_step return codes checked; full-state replay fingerprint; MCTS takes the env config explicitly; train/eval seed overlap rejected; --sims >= 1; atomic writes; workload check against a reference run that admits every job; rejected column in the summary Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
train.py(BC warm start + self-play),evaluate.py(seeded comparison vs. built-in heuristics; checks identical workloads across policies and byte-identical repeated runs).Results (10 seeds, short run)
sjf 1.73 · ptr 1.73 · ptr+MCTS 1.73 · tetris_srpt 1.77 · fifo 2.66 (avg slowdown). See paper/README.md.
Note: results for configs with pool-full rejections change (42/112 reference lines).
🤖 Generated with Claude Code
Summary by Sourcery
Add reproducible pointer-network and MCTS scheduling experiments while making seeded workloads independent of policy decisions.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: