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 @@ -27,3 +27,4 @@ python/out/
*.zip
bench/compare.png
paper/out/
data/psplib/
21 changes: 20 additions & 1 deletion paper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Outputs go to `paper/out/`, which git ignores: `ptr.pt` holds the weights, the c
- 80 Poisson jobs at 0.8 per tick;
- 2 resources;
- a 20-tick horizon;
- a pool of 10 waiting slots;
- a waiting pool with one slot per job (80), so it is never full: no job is rejected and the model always sees every waiting job;
- the DeepRM slowdown reward.

Its sum over an episode is minus the total slowdown.
Expand Down Expand Up @@ -76,6 +76,25 @@ Use `--episodes` that is a multiple of the worker count. Bigger `--batch` /
`--updates` / `--d-model` use the GPU more; more `--episodes` / `--sims` use
the CPU cores more.

## PSPLIB workload

Job profiles can come from PSPLIB RCPSP instances (Kolisch & Sprecher 1997)
instead of DeepRM. Download a set (e.g. j30.sm) from the PSPLIB site and
unpack it, then:

python paper/train.py --psplib data/psplib/j30 ...
python paper/evaluate.py paper/out/ptr.pt ... # uses the env stored in the checkpoint

Every activity with duration > 0 becomes a job template: its duration and
constant demand on the 4 renewable resources, divided by the instance's
availability and scaled to capacity 100 (so instances can be mixed). Each
job draws a template with the episode seed; precedence relations are
ignored. Arrivals stay `poisson:n=80,rate=0.8`. PSPLIB activities are larger
than DeepRM jobs, so lower the rate if the queue grows without bound.

From the CLI: `sim --machines psplib:path=data/psplib/j30,n=2 --res 4 ...`
(`order=sequential` takes activities in file order).

## 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:
Expand Down
14 changes: 10 additions & 4 deletions paper/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

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.
admitted jobs left unplaced, and episodes cut off at --max-ticks.
Writes paper/out/eval.json and prints a mean ± std table.
"""

Expand Down Expand Up @@ -65,7 +65,8 @@ def read_trace(path: Path) -> tuple[dict, dict]:
"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)}
"rejected": sum(1 for v in work.values() if v[1] is None),
"truncated": int(bool(done and done.get("truncated")))}
return m, work


Expand Down Expand Up @@ -119,6 +120,8 @@ def main():
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("--max-ticks", type=int, default=2000,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Invalid caps break evaluation

When the effective max_ticks value is zero or negative, SchedEnv resets an already-finished engine for a zero cap, so run fails on its first step; for a negative cap, sim_create treats the value as no cap and a wait-only policy never ends, so evaluation fails or hangs.

Validate the effective cap from the CLI and checkpoint as positive before constructing SchedEnv.

Also at paper/evaluate.py:149.

Prompt for AI agents
In `paper/evaluate.py` at line 123:

**Invalid caps break evaluation**

When the effective `max_ticks` value is zero or negative, `SchedEnv` resets an already-finished engine for a zero cap, so `run` fails on its first `step`; for a negative cap, `sim_create` treats the value as no cap and a wait-only policy never ends, so evaluation fails or hangs.

Validate the effective cap from the CLI and checkpoint as positive before constructing `SchedEnv`.

Also at `paper/evaluate.py:149`.

help="end (truncate) an episode after this many ticks; counted in the 'truncated' column")
ap.add_argument("--device", default="cpu")
ap.add_argument("--out", default="paper/out/eval.json")
args = ap.parse_args()
Expand All @@ -140,7 +143,10 @@ def main():
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_kw = dict(ck["env"] if ck else ENV_KW)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Checkpoint paths trigger local reads

When a user evaluates an untrusted checkpoint whose environment selects a FIFO or a directory with a large number of .sm/.mm files, evaluation passes checkpoint-controlled env["machines"] to SchedEnv, and the PSPLIB generator reads the resulting path as the current user. A checkpoint pointing to a FIFO or a directory with many matching files can hang or exhaust the evaluation process, so users see a stuck or terminated run.

Validate checkpoint environment specs before constructing the environment, and restrict PSPLIB inputs to explicitly trusted regular files or bounded directories.

Also at src/app/registry.zig:97.

Prompt for AI agents
In `paper/evaluate.py` at line 146:

**Checkpoint paths trigger local reads**

When a user evaluates an untrusted checkpoint whose environment selects a FIFO or a directory with a large number of `.sm`/`.mm` files, evaluation passes checkpoint-controlled `env["machines"]` to `SchedEnv`, and the PSPLIB generator reads the resulting path as the current user. A checkpoint pointing to a FIFO or a directory with many matching files can hang or exhaust the evaluation process, so users see a stuck or terminated run.

Validate checkpoint environment specs before constructing the environment, and restrict PSPLIB inputs to explicitly trusted regular files or bounded directories.

Also at `src/app/registry.zig:97`.

# a policy that keeps choosing "wait" would otherwise never end the episode;
# every job has arrived long before this, so the cap does not change the workload
env_kw["max_ticks"] = env_kw.get("max_ticks") or args.max_ticks

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Paper changes lack regression tests

When the paper tick-cap and pool-size changes are merged without dedicated tests, the new evaluation tick-cap and reporting path, and the 80-slot paper pool configuration, can regress without any test failing; existing truncation coverage exercises engine behavior, not these paper changes.

Add paper-level tests for capped evaluation and truncated reporting, and for admitting all jobs with the configured pool.

Also at paper/ptrmcts.py:61.

Prompt for AI agents
In `paper/evaluate.py` at line 149:

**Paper changes lack regression tests**

When the paper tick-cap and pool-size changes are merged without dedicated tests, the new evaluation tick-cap and reporting path, and the 80-slot paper pool configuration, can regress without any test failing; existing truncation coverage exercises engine behavior, not these paper changes.

Add paper-level tests for capped evaluation and truncated reporting, and for admitting all jobs with the configured pool.

Also at `paper/ptrmcts.py:61`.

From CLAUDE.md L29-31:

- Every behavior change needs a test; integration tests in tests/. Engine
  semantics: add a hand-worked case to tests/scenario_test.zig; the
  `property:` test there checks against a naive reference simulator.

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}
Expand Down Expand Up @@ -176,7 +182,7 @@ def main():
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"]
cols = ["slowdown", "wait", "makespan", "reward", "rejected", "unplaced", "truncated", "sec"]
print(f"{'policy':<14}" + "".join(f"{c:>18}" for c in cols))
summary = {}
for name, rows in results.items():
Expand Down
21 changes: 19 additions & 2 deletions paper/ptrmcts.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,16 @@
from sched_env import _lib # noqa: E402

# Environment used in the paper experiments. Small enough for MCTS on a CPU.
# The waiting pool has one slot per job in the episode, so it can never be
# full: no job is rejected and the model always sees every waiting job (the
# pointer network handles any number of jobs; empty slots are masked).
N_JOBS = 80
ENV_KW = dict(
machines="deeprm:n=1",
jobs="poisson:n=80,rate=0.8",
jobs=f"poisson:n={N_JOBS},rate=0.8",
n_res=2,
n_ticks=20,
max_jobs=10,
max_jobs=N_JOBS,
reward="slowdown",
)

Expand Down Expand Up @@ -87,6 +91,19 @@ def atomic_write(path, write) -> None:
raise


def env_config(psplib: str | None = None) -> dict:
"""ENV_KW, or with job profiles from PSPLIB instances (a .sm file or a
directory of them): 4 renewable resources, demand / availability x 100."""
if not psplib:
return dict(ENV_KW)
path = os.path.abspath(psplib)
if not os.path.exists(path):
raise FileNotFoundError(path)
if "," in path or "=" in path:
raise ValueError(f"PSPLIB path must not contain ',' or '=': {path}")
return {**ENV_KW, "machines": f"psplib:path={path},n=1", "n_res": 4}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · PSPLIB training rejects valid instances

When the selected instance, or an instance in the selected directory, has fewer than four renewable resources, --psplib sets n_res to 4, so Psplib.machine rejects the request when the instance provides fewer renewable resources and SchedEnv construction fails before training starts.

Set n_res to a value supported by the selected PSPLIB instance instead of always fixing it at 4.

Prompt for AI agents
In `paper/ptrmcts.py` at line 104:

**PSPLIB training rejects valid instances**

When the selected instance, or an instance in the selected directory, has fewer than four renewable resources, `--psplib` sets `n_res` to 4, so `Psplib.machine` rejects the request when the instance provides fewer renewable resources and `SchedEnv` construction fails before training starts.

Set `n_res` to a value supported by the selected PSPLIB instance instead of always fixing it at 4.



def make_env(**overrides) -> SchedEnv:
return SchedEnv(**{**ENV_KW, **overrides})

Expand Down
22 changes: 13 additions & 9 deletions paper/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
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
from ptrmcts import MCTS, PointerNet, atomic_write, collate, env_config, featurize, fingerprint, train_seed_range
from sched_env import SchedEnv


def discounted(rewards: list[float], gamma: float, scale: float) -> list[float]:
Expand Down Expand Up @@ -86,10 +87,10 @@ def train_step(net, opt, batch, device, value_coef):
_W: dict = {}


def _worker_init(d_model: int, threads: int):
def _worker_init(env_kw: dict, d_model: int, threads: int):
torch.set_num_threads(threads)
env = make_env()
_W["env"] = env
env = SchedEnv(**env_kw)
_W["env"], _W["env_kw"] = env, env_kw
_W["net"] = PointerNet.for_env(env, d=d_model).eval()


Expand All @@ -101,7 +102,7 @@ def self_play_episode(job):
_W["net"].load_state_dict(state)
env, net = _W["env"], _W["net"]
rng = np.random.default_rng([a["seed"], seed])
mcts = MCTS(net, ENV_KW, "cpu", sims=a["sims"], gamma=a["gamma"], reward_scale=a["reward_scale"], rng=rng)
mcts = MCTS(net, _W["env_kw"], "cpu", sims=a["sims"], gamma=a["gamma"], reward_scale=a["reward_scale"], rng=rng)

def choose(obs, mask, prefix, expect, step):
counts = mcts.search(seed, prefix, expect, noise=True)
Expand Down Expand Up @@ -143,6 +144,8 @@ def main():
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("--psplib", default=None,
help="take job profiles from PSPLIB instances (.sm file or directory) instead of DeepRM")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--workers", type=int, default=1,
help="parallel self-play processes (0 = all cores but one); results do not depend on it")
Expand All @@ -159,7 +162,8 @@ def main():
rng = np.random.default_rng(args.seed)
device = torch.device(args.device)

env = make_env()
env_kw = env_config(args.psplib)
env = SchedEnv(**env_kw)
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)
Expand Down Expand Up @@ -194,9 +198,9 @@ def teacher(obs, mask, prefix, expect, step):
# 2-3. self-play + training ------------------------------------------------
cpus = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2)
workers = args.workers or max(1, cpus - 1) # affinity: only the CPUs SLURM/taskset gave us
pool = (mp.get_context("spawn").Pool(workers, _worker_init, (args.d_model, 1)) if workers > 1 else None)
pool = (mp.get_context("spawn").Pool(workers, _worker_init, (env_kw, args.d_model, 1)) if workers > 1 else None)
if pool is None:
_worker_init(args.d_model, torch.get_num_threads())
_worker_init(env_kw, args.d_model, torch.get_num_threads())
print(f"self-play: {workers} worker(s), training on {device}")
for it in range(args.iters):
t0 = time.time()
Expand All @@ -214,7 +218,7 @@ def teacher(obs, mask, prefix, expect, step):
"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}
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))
if pool:
pool.close()
Expand Down
2 changes: 2 additions & 0 deletions src/adapters.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub const arrivals = struct {
pub const generators = struct {
pub const RandomProfiles = @import("adapters/generators/random_profiles.zig").RandomProfiles;
pub const DeepRM = @import("adapters/generators/deeprm.zig").DeepRM;
pub const psplib = @import("adapters/generators/psplib.zig");
pub const Psplib = psplib.Psplib;
};

pub const rewards = struct {
Expand Down
Loading
Loading