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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Always use ReleaseFast for real measurements; Debug is ~10–50× slower.
|---|---|---|
| `--machines <spec>` | machine capacities + job profiles | `random` |
| `--jobs <spec>` | arrival process | `poisson` |
| `--policy <spec>` | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt[:weight=w]`, `random` | `fifo` |
| `--policy <spec>` | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt[:weight=w]`, `packer`, `random` | `fifo` |
| `--observe <spec>` | `viz`, `metrics`, `log` (repeatable) | none |
| `--res`, `--ticks`, `--pool` | resources, horizon, waiting slots | 10, 100, 128 |
| `--reward <spec>` | `neg_in_system`, `neg_waiting`, `slowdown`, `zero` | `neg_in_system` |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/python.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion paper/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
4 changes: 4 additions & 0 deletions paper/ptrmcts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |

Expand Down
1 change: 1 addition & 0 deletions src/adapters.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
47 changes: 47 additions & 0 deletions src/adapters/policies/packer.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! 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.
//!
//! 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;

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: u64 = 0;
for (0..st.machines.layout.n_res) |r| {
acc += @as(u64, mach.resource(r)[0]) * @as(u64, peak[r]);
}
return @floatFromInt(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");
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
return self.cache.pick(st, PairCache.noPen, {});
}
};
2 changes: 2 additions & 0 deletions src/app/registry.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 7 additions & 5 deletions src/model/machines.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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).
Expand Down
54 changes: 53 additions & 1 deletion tests/scenario_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,58 @@ 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);

// 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 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();
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(s3.jobs.isValid(sim2.slotOf(3)));
try testing.expect(p2.decide(&s3) == .wait);
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}

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} },
Expand Down Expand Up @@ -785,7 +837,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 };
Expand Down
Loading