Skip to content

Pointer network + MCTS experiments; fix seed-dependent workloads - #2

Merged
dev0Guy merged 2 commits into
mainfrom
paper-ptr-mcts
Nov 25, 2026
Merged

dev0Guy merged 2 commits into
mainfrom
paper-ptr-mcts

Conversation

@dev0Guy

@dev0Guy dev0Guy commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • paper/: pointer network + AlphaZero-style MCTS, 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).
  • Engine fix: jobs rejected for a full pool now still draw their profile, so a seed fixes the whole workload regardless of policy. Previously later jobs' demands depended on the policy.
  • Tests: Zig seed-reproducibility across arrivals × generators, policy-independent profiles under pool rejection, Python binding seed test.

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:

  • Add pointer-network scheduling experiments with AlphaZero-style MCTS training and evaluation against built-in policies.

Bug Fixes:

  • Ensure jobs rejected because the waiting pool is full still consume profile-generation randomness, making seeded workloads independent of scheduling policy.

Enhancements:

  • Add reproducible seeded evaluation checks for identical workloads, deterministic traces, and disjoint training and evaluation seeds.
  • Add atomic experiment outputs and state-replay validation for MCTS simulations.

Documentation:

  • Document the pointer-network and MCTS experiment setup, environment, training process, evaluation safeguards, and preliminary results.

Tests:

  • Add Zig and Python coverage for seed reproducibility across arrival and generator combinations and policy-independent job profiles under pool rejection.

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>
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the shared pointer-network and MCTS module used by training and evaluation.

  • paper/ptrmcts.py L1-314

Uses of the API

Add seeded policy evaluation with workload, determinism, and training-seed checks.

  • paper/evaluate.py L1-202

Implementation

Generate profiles for jobs rejected by a full pool so later workload generation remains independent of policy decisions.

  • src/engine/engine.zig L64-67, L269-280 (+3 small edits)

Configuration

Ignore generated paper experiment outputs.

  • .gitignore L29

Documentation

Document the experiment setup, reproducibility safeguards, seed fix, and preliminary results.

  • paper/README.md L1-108

Tests

Test that seeded episodes reproduce across environments and resets in the Python binding.

  • python/tests/test_env.py L139-167

Test seed reproducibility across arrival and generator combinations and verify profiles are drawn on pool-full rejection.

  • tests/scenario_test.zig L810-974

Other changes

Files not grouped.

  • paper/train.py L1-184

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread paper/evaluate.py Resolved
Comment thread paper/ptrmcts.py Resolved
Comment thread paper/ptrmcts.py Resolved
Comment thread paper/ptrmcts.py Resolved
Comment thread src/engine/engine.zig Resolved
Comment thread paper/train.py Resolved
Comment thread paper/train.py Resolved
Comment thread paper/evaluate.py Resolved
Comment thread tests/scenario_test.zig Resolved
Comment thread src/engine/engine.zig Resolved
…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>
@dev0Guy
dev0Guy merged commit 19457e1 into main Nov 25, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant