From 7defa464e5af7eb59cbfb469fa03a9d7e5419a63 Mon Sep 17 00:00:00 2001 From: dev0Guy <97923827+dev0Guy@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:09:36 +0200 Subject: [PATCH 1/3] Add DeepRM Packer policy packer: among pairs that fit now, max sum_r free[r][now] * peak[r] (unnormalized, current tick only), as DeepRM's get_packer_action; uses PairCache. Hand-worked scenario (differs from tetris), added to the cache-vs-fresh-scan property test, registered, in paper eval, CI smoke run and docs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 +- docs/guide.md | 3 ++- docs/python.md | 2 +- paper/evaluate.py | 2 +- readme.md | 2 +- src/adapters.zig | 1 + src/adapters/policies/packer.zig | 43 ++++++++++++++++++++++++++++++++ src/app/registry.zig | 2 ++ tests/scenario_test.zig | 41 +++++++++++++++++++++++++++++- 9 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 src/adapters/policies/packer.zig diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1122ad3..e02c00a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,7 @@ jobs: - name: Build CLI and smoke-run every policy and arrival process run: | zig build -Doptimize=ReleaseFast - for p in fifo fifo_strict sjf best_fit tetris tetris_srpt random; do + for p in fifo fifo_strict sjf best_fit tetris tetris_srpt packer random; do for j in poisson mmpp pareto selfsimilar batch; do ./zig-out/bin/sim --machines deeprm:n=2 --jobs $j:n=200 --res 2 --ticks 30 \ --policy $p --reward slowdown --observe trace:path=/tmp/t.jsonl > /dev/null 2>&1 diff --git a/docs/guide.md b/docs/guide.md index b2744f6..2fe327b 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -37,7 +37,7 @@ Always use ReleaseFast for real measurements; Debug is ~10–50× slower. |---|---|---| | `--machines ` | machine capacities + job profiles | `random` | | `--jobs ` | arrival process | `poisson` | -| `--policy ` | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt[:weight=w]`, `random` | `fifo` | +| `--policy ` | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt[:weight=w]`, `packer`, `random` | `fifo` | | `--observe ` | `viz`, `metrics`, `log` (repeatable) | none | | `--res`, `--ticks`, `--pool` | resources, horizon, waiting slots | 10, 100, 128 | | `--reward ` | `neg_in_system`, `neg_waiting`, `slowdown`, `zero` | `neg_in_system` | @@ -86,6 +86,7 @@ Arrivals and profiles are independent: any `--jobs` works with any `--machines`. | `best_fit` | (job, machine) leaving least free capacity at tick 0 | tight packing now | | `tetris` | (job, machine) with the largest Σ_r Σ_t demand·free / cap² over the job's duration (Grandl et al. 2014) | multi-resource packing across time | | `tetris_srpt` | `tetris` alignment − weight · ε · duration, ε = mean(alignment)/mean(duration) over the candidates (the paper's combination) | packing *and* completion time | +| `packer` | DeepRM's Packer: max Σ_r free[r][now] · demand[r] over the pairs that fit; no normalization, current tick only | packing (DeepRM baseline) | | `random` | random legal placement | sanity baseline | Pure `tetris` favours large jobs (they score highest), so it packs well but diff --git a/docs/python.md b/docs/python.md index 16f84ed..84cda34 100644 --- a/docs/python.md +++ b/docs/python.md @@ -106,7 +106,7 @@ and is treated as *wait* (`info["illegal"] = True`). Use ### Baselines at native speed ```python -env.run_policy("sjf", seed=1000) # fifo | fifo_strict | sjf | best_fit | tetris | tetris_srpt[:weight=2] | random +env.run_policy("sjf", seed=1000) # fifo | fifo_strict | sjf | best_fit | tetris | tetris_srpt[:weight=2] | packer | random ``` runs a whole episode inside Zig with a built-in heuristic and returns the diff --git a/paper/evaluate.py b/paper/evaluate.py index 5da7ca4..db32d59 100644 --- a/paper/evaluate.py +++ b/paper/evaluate.py @@ -41,7 +41,7 @@ train_seed_range) from sched_env import SchedEnv -BUILTIN = ["fifo", "sjf", "best_fit", "tetris", "tetris_srpt", "random"] +BUILTIN = ["fifo", "sjf", "best_fit", "tetris", "tetris_srpt", "packer", "random"] def read_trace(path: Path) -> tuple[dict, dict]: diff --git a/readme.md b/readme.md index 02219f5..1af4fda 100644 --- a/readme.md +++ b/readme.md @@ -69,7 +69,7 @@ zig build run -- --machines deeprm:n=2 --res 2 --ticks 30 --policy sjf |---|---| | Machines / profiles | `random`, `deeprm` | | Job arrivals | `poisson`, `mmpp` (bursty), `pareto` (heavy-tailed), `selfsimilar`, `batch` | -| Policies | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt`, `random` | +| Policies | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt`, `packer`, `random` | | Rewards | `neg_in_system` (default), `neg_waiting`, `slowdown` (DeepRM), `zero` | | Observers | `viz`, `metrics`, `log`, `trace` (JSON Lines for offline replay) | diff --git a/src/adapters.zig b/src/adapters.zig index 43856ff..e7add19 100644 --- a/src/adapters.zig +++ b/src/adapters.zig @@ -7,6 +7,7 @@ pub const policies = struct { pub const RandomPolicy = @import("adapters/policies/random.zig").RandomPolicy; pub const Tetris = @import("adapters/policies/tetris.zig").Tetris; pub const TetrisSrpt = @import("adapters/policies/tetris.zig").TetrisSrpt; + pub const Packer = @import("adapters/policies/packer.zig").Packer; }; pub const arrivals = struct { diff --git a/src/adapters/policies/packer.zig b/src/adapters/policies/packer.zig new file mode 100644 index 0000000..e776951 --- /dev/null +++ b/src/adapters/policies/packer.zig @@ -0,0 +1,43 @@ +//! Packer, the packing baseline of DeepRM (Mao et al., HotNets'16; the +//! `get_packer_action` agent of the reference code): among the (job, +//! machine) pairs that fit now, pick the one with the largest dot product of +//! the machine's free capacity at the current tick and the job's demand +//! vector: +//! +//! score = Σ_r free[r][now] · peak[r] +//! +//! Unlike `tetris` there is no normalization by capacity and only the current +//! tick of the machine is looked at (the fit check still covers the job's +//! whole duration). The demand vector is the job's per-resource peak, which +//! is DeepRM's constant `res_vec` for constant-demand jobs. Ties: first +//! machine, then oldest job (DeepRM: lowest slot index). With one machine +//! this is exactly DeepRM's Packer. +//! +//! Scores are cached across decisions (`PairCache`). +const model = @import("../../model.zig"); +const PairCache = @import("pair_cache.zig").PairCache; + +fn score(_: void, st: *const model.State, s: usize, m: usize) f32 { + const peak = st.jobs.peakOf(s); + const mach = st.machines.get(m); + var acc: f32 = 0; + for (0..st.machines.layout.n_res) |r| { + acc += @as(f32, @floatFromInt(mach.resource(r)[0])) * @as(f32, @floatFromInt(peak[r])); + } + return acc; +} + +pub const Packer = struct { + pub const name = "packer"; + + cache: PairCache = .{}, + + pub fn deinit(self: *Packer) void { + self.cache.deinit(); + } + + pub fn decide(self: *Packer, st: *const model.State) model.Action { + self.cache.update(st, score, {}) catch @panic("packer: out of memory"); + return self.cache.pick(st, PairCache.noPen, {}); + } +}; diff --git a/src/app/registry.zig b/src/app/registry.zig index f1df637..43f4c86 100644 --- a/src/app/registry.zig +++ b/src/app/registry.zig @@ -255,6 +255,7 @@ pub const policy_types = .{ A.policies.RandomPolicy, A.policies.Tetris, A.policies.TetrisSrpt, + A.policies.Packer, }; pub fn hasPolicy(name: []const u8) bool { @@ -349,6 +350,7 @@ pub const list_text = \\ tetris (job, machine) pair whose demand best aligns with free capacity over time \\ tetris_srpt weight=1.5 tetris alignment minus weight x shortest-job term (Grandl et al.) \\ 0 = pure tetris (packing, makespan), ~2 = close to sjf (slowdown) + \\ packer DeepRM's Packer: max free-now . demand (unnormalized, current tick only) \\ \\Rewards (--reward), per elapsed tick: \\ neg_in_system -(waiting + running) (default) diff --git a/tests/scenario_test.zig b/tests/scenario_test.zig index 29ed48c..61ab192 100644 --- a/tests/scenario_test.zig +++ b/tests/scenario_test.zig @@ -449,6 +449,45 @@ test "scenario: tetris_srpt trades packing for short jobs via its weight" { try testing.expect(w.decide(&st2) == .wait); } +test "scenario: packer scores free-now x demand, unnormalized (DeepRM)" { + // m0 cap (20, 20), m1 cap (10, 10), both empty. job (2, 2) x 2 ticks. + // packer: m0 = 20·2 + 20·2 = 80, m1 = 10·2 + 10·2 = 40 → m0 + // tetris (normalized by cap²): m0 = 2·(2·20·2)/400 = 0.4, m1 = 2·(2·10·2)/100 = 0.8 → m1 + var sim = Sim{ .script = .{ .caps = &.{ 20, 20, 10, 10 }, .n_res = 2, .jobs = &.{ + .{ .dur = 2, .demand = &.{ 2, 2 } }, + } } }; + try sim.start(cfg1(2, 8)); + defer sim.deinit(); + const st = sim.eng.state(); + var p = A.policies.Packer{}; + defer p.deinit(); + try testing.expectEqual(@as(u32, 0), p.decide(&st).place.machine); + var t = A.policies.Tetris{}; + defer t.deinit(); + try testing.expectEqual(@as(u32, 1), t.decide(&st).place.machine); + + // job choice, one machine cap (10, 10): A (6, 1) → 10·6 + 10·1 = 70, + // B (3, 3) → 60, C (1, 1) → 20: A first; then free (4, 9): B (3,3) → 39, + // C (1,1) → 13: B; then free (1, 6): C → 7; then nothing waits. + var sim2 = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 2, .jobs = &.{ + .{ .dur = 3, .demand = &.{ 3, 3 } }, + .{ .dur = 3, .demand = &.{ 1, 1 } }, + .{ .dur = 3, .demand = &.{ 6, 1 } }, + } } }; + try sim2.start(cfg1(2, 8)); + defer sim2.deinit(); + var p2 = A.policies.Packer{}; + defer p2.deinit(); + for ([_]u32{ 2, 0, 1 }) |want| { + const s2 = sim2.eng.state(); + const a = p2.decide(&s2); + try testing.expectEqual(sim2.slotOf(want), a.place.slot); + _ = try sim2.place(want, 0); + } + const s3 = sim2.eng.state(); + try testing.expect(p2.decide(&s3) == .wait); +} + test "scenario: several placements in one tick, time does not move" { var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ .{ .dur = 2, .demand = &.{3} }, @@ -785,7 +824,7 @@ test "property: engine matches the naive reference on random workloads" { test "property: cached pair scores give the same decision as a fresh scan" { // A long-lived policy (incremental cache) against a fresh copy at every // step (full rescan), over many placements per tick and time advances. - inline for (.{ A.policies.BestFit, A.policies.Tetris, A.policies.TetrisSrpt }) |P| { + inline for (.{ A.policies.BestFit, A.policies.Tetris, A.policies.TetrisSrpt, A.policies.Packer }) |P| { for (0..4) |seed| { var arr = A.arrivals.Poisson{ .total = 400, .rate = 4 }; var gen = A.generators.RandomProfiles{ .n_machines = 6, .varying = true }; From cd9a29cb6528c793a06868f7d7331f959b8a52e4 Mon Sep 17 00:00:00 2001 From: dev0Guy <97923827+dev0Guy@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:53 +0200 Subject: [PATCH 2/3] Address review: global change counter, exact packer scores, real wait test - Machines epoch/stamp now come from one process-wide counter, so a PairCache policy reused with another engine can't match stale scores (regression test: same Packer on a second engine with swapped machines). - packer sums the dot product in u64 before converting to f32. - packer wait assertion now has a job left that does not fit. Co-Authored-By: Claude Opus 5.5 --- src/adapters/policies/packer.zig | 10 +++++++--- src/model/machines.zig | 12 +++++++----- tests/scenario_test.zig | 17 +++++++++++++++-- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/adapters/policies/packer.zig b/src/adapters/policies/packer.zig index e776951..da5cb2a 100644 --- a/src/adapters/policies/packer.zig +++ b/src/adapters/policies/packer.zig @@ -13,6 +13,10 @@ //! machine, then oldest job (DeepRM: lowest slot index). With one machine //! this is exactly DeepRM's Packer. //! +//! The dot product is summed exactly in integers; it is stored as f32 by +//! `PairCache`, which is exact up to 2^24 (e.g. capacities up to ~2000 on +//! 2 resources), so ties are real ties for realistic capacities. +//! //! Scores are cached across decisions (`PairCache`). const model = @import("../../model.zig"); const PairCache = @import("pair_cache.zig").PairCache; @@ -20,11 +24,11 @@ const PairCache = @import("pair_cache.zig").PairCache; fn score(_: void, st: *const model.State, s: usize, m: usize) f32 { const peak = st.jobs.peakOf(s); const mach = st.machines.get(m); - var acc: f32 = 0; + var acc: u64 = 0; for (0..st.machines.layout.n_res) |r| { - acc += @as(f32, @floatFromInt(mach.resource(r)[0])) * @as(f32, @floatFromInt(peak[r])); + acc += @as(u64, mach.resource(r)[0]) * @as(u64, peak[r]); } - return acc; + return @floatFromInt(acc); } pub const Packer = struct { diff --git a/src/model/machines.zig b/src/model/machines.zig index 5d09662..a706443 100644 --- a/src/model/machines.zig +++ b/src/model/machines.zig @@ -129,10 +129,11 @@ pub const Machines = struct { /// adapters/policies/pair_cache.zig). `epoch` changes whenever every /// machine may have changed (reset, time advance); `stamp[m]` changes /// when machine m alone changed (`touch`, called by the engine on every - /// placement). Both come from one counter that never repeats. + /// placement). Both come from one process-wide counter that never + /// repeats, so a cache reused with another engine (or after a reset) + /// can never mistake its old values for current ones. epoch: u64 = 0, stamp: []u64, - clock: u64 = 0, /// `caps` is flat [n_machines][n_res]. pub fn init(a: std.mem.Allocator, layout: Layout, n_machines: usize, caps: []const Elem) !Machines { @@ -159,9 +160,10 @@ pub const Machines = struct { a.free(self.stamp); } - fn tick(self: *Machines) u64 { - self.clock += 1; - return self.clock; + var clock = std.atomic.Value(u64).init(0); + + fn tick(_: *Machines) u64 { + return clock.fetchAdd(1, .monotonic) + 1; } /// Record that machine m changed (a job was placed on it). diff --git a/tests/scenario_test.zig b/tests/scenario_test.zig index 61ab192..e322a33 100644 --- a/tests/scenario_test.zig +++ b/tests/scenario_test.zig @@ -466,13 +466,25 @@ test "scenario: packer scores free-now x demand, unnormalized (DeepRM)" { defer t.deinit(); try testing.expectEqual(@as(u32, 1), t.decide(&st).place.machine); + // the same policy reused on another engine with the same shape but the + // machines swapped must not reuse the first engine's cached scores + var swapped = Sim{ .script = .{ .caps = &.{ 10, 10, 20, 20 }, .n_res = 2, .jobs = &.{ + .{ .dur = 2, .demand = &.{ 2, 2 } }, + } } }; + try swapped.start(cfg1(2, 8)); + defer swapped.deinit(); + const sw = swapped.eng.state(); + try testing.expectEqual(@as(u32, 1), p.decide(&sw).place.machine); + // job choice, one machine cap (10, 10): A (6, 1) → 10·6 + 10·1 = 70, - // B (3, 3) → 60, C (1, 1) → 20: A first; then free (4, 9): B (3,3) → 39, - // C (1,1) → 13: B; then free (1, 6): C → 7; then nothing waits. + // B (3, 3) → 60, C and D (1, 1) → 20: A first; then free (4, 9): + // B → 39, C, D → 13: B; then free (1, 6): C, D → 7, tie → older C; + // then free (0, 5): D does not fit → wait, D still waiting. var sim2 = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 2, .jobs = &.{ .{ .dur = 3, .demand = &.{ 3, 3 } }, .{ .dur = 3, .demand = &.{ 1, 1 } }, .{ .dur = 3, .demand = &.{ 6, 1 } }, + .{ .arrival = 0, .dur = 3, .demand = &.{ 1, 1 } }, } } }; try sim2.start(cfg1(2, 8)); defer sim2.deinit(); @@ -485,6 +497,7 @@ test "scenario: packer scores free-now x demand, unnormalized (DeepRM)" { _ = try sim2.place(want, 0); } const s3 = sim2.eng.state(); + try testing.expect(s3.jobs.isValid(sim2.slotOf(3))); try testing.expect(p2.decide(&s3) == .wait); } From 4d123d8cd6502968b9835f587aa15113cb2bb592 Mon Sep 17 00:00:00 2001 From: dev0Guy <97923827+dev0Guy@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:30:54 +0200 Subject: [PATCH 3/3] paper: cap training episodes at 1000 ticks so self-play can't hang A policy that keeps choosing wait never ended the episode, and MCTS replay made each step slower, so training stalled after ~8 iterations. Co-Authored-By: Claude Opus 5.5 --- paper/ptrmcts.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/paper/ptrmcts.py b/paper/ptrmcts.py index 85d5f1c..9d58923 100644 --- a/paper/ptrmcts.py +++ b/paper/ptrmcts.py @@ -60,6 +60,10 @@ n_ticks=20, max_jobs=N_JOBS, reward="slowdown", + # Hard episode limit. Without it a policy that keeps choosing "wait" never + # ends the episode (and MCTS replay makes each step slower): training + # would hang. A normal episode of 80 jobs ends in ~100-200 ticks. + max_ticks=1000, ) # Seed ranges: training and evaluation never share a workload.