diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1122ad3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,68 @@ +name: CI + +on: + push: + branches: [main, setup] + pull_request: + workflow_dispatch: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # x86-64 (AVX2, 16 u16 lanes) and arm64 (NEON, 8 lanes): both SIMD widths + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - uses: mlugg/setup-zig@v2 + with: + version: 0.17.0 + + - name: Zig tests (unit, integration, scenarios, C ABI) + run: zig build test --summary all + + - name: Zig tests with a fixed SIMD width (lanes = 32) + run: zig build test -Dlanes=32 + + - 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 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 + done + done + + - name: Build libsched + run: zig build lib + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + + - name: Install Python test dependencies + # SB3 / PyTorch are only needed for the training example, not the tests. + run: pip install "numpy>=1.26" "gymnasium>=1.0" "matplotlib>=3.8" "pillow>=10" pytest + + - name: Python tests + env: + PYTHONPATH: python + MPLBACKEND: Agg + run: pytest -q python/tests + + - name: Replay smoke test + env: + PYTHONPATH: python + MPLBACKEND: Agg + run: python python/examples/replay.py /tmp/t.jsonl --list diff --git a/.gitignore b/.gitignore index d04daab..e21bff4 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,14 @@ zig-out/ /debug/ /build/ /build-*/ -/docgen_tmp/ \ No newline at end of file +/docgen_tmp/ +# Python +__pycache__/ +*.pyc +.venv/ +.pytest_cache/ + +# generated outputs +python/out/ +*.zip +bench/compare.png diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..45f1a50 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,31 @@ +# Project notes for Claude Code + +SIMD job-to-machine scheduling simulator in **Zig 0.17**, for a thesis +comparing scheduling policies (later RL via Gymnasium). + +- Commands: `zig build test`, `zig build run -- --help`, `zig build bench`, + `zig build example`, `zig build lib` (libsched for Python), + `PYTHONPATH=python pytest python/tests`. Benchmarks always build ReleaseFast. +- Python binding: src/app/capi.zig (C ABI) ↔ python/sched_env/_lib.py (ctypes + structs must match field-for-field). Docs: docs/python.md. +- Architecture: hexagonal, layers grid → model → ports → engine → adapters → + app; each imports only layers before it. See docs/architecture.md. +- Grid cells are `grid.Elem` (u16); never hard-code i32/u16 elsewhere. +- Machines are a sliding window (`Machines.head`, `ring` layout): access ticks + only via `Machine` methods (`resource`, `freeNow`, `canPlace`), never + `free.row(r)[t]` directly. Everything past head + n_ticks must stay = cap. +- `Jobs.blocked` is a per-tick "fits on no machine" memo: valid only because + capacity never grows within a tick; the engine clears it on tick advance. + Pair-scanning policies should use `rules.knownBlocked/markBlocked`, or + `PairCache` (adapters/policies/pair_cache.zig), which caches scores across + decisions using `Machines.epoch`/`stamp`. Anything that changes a machine + outside time advance must call `Machines.touch(m)` (the engine does on place). + Policies with caches have `deinit`; callers use `ports.policy.deinitIfAny`. +- Invariants: job padding = 0, machine padding = capacity, `t + dur <= + n_ticks`, never subtract below 0 (check `canPlace` first). +- Ports: Policy, Observer, UsageGenerator, ArrivalSource, Reward. +- New adapters: implement the port, export in src/adapters.zig, register in + src/app/registry.zig (+ help text). +- 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. diff --git a/bench/.gitkeep b/bench/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/bench/compare.py b/bench/compare.py new file mode 100644 index 0000000..a79184a --- /dev/null +++ b/bench/compare.py @@ -0,0 +1,130 @@ +"""CPU (Zig SIMD) vs GPU comparison of the fit-mask workload. + +Runs both sides on the same sizes and prints one table: + envs | Zig CPU µs | µs | speedup vs Zig +and the crossover: the smallest batch at which a GPU backend beats Zig. +With matplotlib installed it also saves bench/compare.png. + +Run from the project root (THREADS=8 to choose the thread count): + pip install mlx # Apple GPU (or: pip install torch) + python3 bench/compare.py +""" + +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(__file__)) +import fitmask_gpu as g # noqa: E402 + + +def run_zig(): + """Build and run the Zig benchmark in CSV mode → + ({envs: µs, 1 thread}, {envs: µs, N threads}, N).""" + zig = os.environ.get("ZIG", "zig") + cmd = [zig, "build", "fitmask", "--", "--csv"] + if os.environ.get("THREADS"): + cmd += ["--threads", os.environ["THREADS"]] + proc = subprocess.run(cmd, capture_output=True, text=True) + one, many, n = {}, {}, 1 + for line in (proc.stdout + proc.stderr).splitlines(): + if line.startswith("CSV,"): + _, envs, us1, usn, threads = line.split(",") + one[int(envs)] = float(us1) + many[int(envs)] = float(usn) + n = int(threads) + if not one: + sys.exit("zig benchmark failed:\n" + proc.stderr) + return one, many, n + + +def run_python(backend): + """Run one Python backend → {envs: µs}, checked against numpy.""" + import time + import numpy as np + + name, prep, run, to_np, _ = backend + out = {} + for n_env in g.ENVS: + jobs, free = g.make_data(n_env) + ref = g.numpy_backend()[2](jobs, free) + dj, df = prep(jobs, free) + run(dj, df) # warm-up + best = float("inf") + for _ in range(g.REPS): + t0 = time.perf_counter() + res = run(dj, df) + best = min(best, time.perf_counter() - t0) + if not np.array_equal(to_np(res), ref): + sys.exit(f"{name}: WRONG result at envs={n_env}") + out[n_env] = best * 1e6 + return out + + +def main(): + print("running Zig CPU benchmark …") + one, many, n = run_zig() + results = {"zig cpu": one, f"zig cpu x{n}": many} + for b in g.available_backends(): + print(f"running {b[0]} …") + results[b[0]] = run_python(b) + + names = list(results) + zig = results["zig cpu"] + + # ---- table: time per batch and speedup relative to Zig ---- + print() + head = f"{'envs':>6} | " + " | ".join(f"{n:>18}" for n in names) + print("time per batch (µs), speedup vs Zig in brackets (>1 = faster than Zig)") + print(head) + print("-" * len(head)) + for e in g.ENVS: + cells = [] + for n in names: + us = results[n][e] + cells.append(f"{us:>9.1f}" + (" " if n == "zig cpu" else f" ({zig[e]/us:>5.2f}x)")) + print(f"{e:>6} | " + " | ".join(f"{c:>18}" for c in cells)) + + # ---- crossover ---- + print() + for n in names[2:]: + wins = [e for e in g.ENVS if results[n][e] < zig[e]] + if wins: + print(f"{n}: faster than 1-thread Zig from {wins[0]} envs " + f"(at {g.ENVS[-1]} envs: {zig[g.ENVS[-1]] / results[n][g.ENVS[-1]]:.1f}x)") + else: + print(f"{n}: never faster than 1-thread Zig up to {g.ENVS[-1]} envs") + + best_cpu = {e: min(one[e], many[e]) for e in g.ENVS} + for n in names[2:]: + wins = [e for e in g.ENVS if results[n][e] < best_cpu[e]] + print(f"{n}: " + (f"faster than the best Zig CPU result from {wins[0]} envs" if wins + else f"never faster than the best Zig CPU result up to {g.ENVS[-1]} envs")) + + # ---- plot ---- + try: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + except ImportError: + print("\n(pip install matplotlib for bench/compare.png)") + return + tests = {e: e * g.J * g.M for e in g.ENVS} + fig, ax = plt.subplots(figsize=(7, 4.5)) + for n in names: + ax.plot(g.ENVS, [tests[e] / (results[n][e] * 1e-6) for e in g.ENVS], marker="o", label=n) + ax.set_xscale("log", base=2) + ax.set_yscale("log") + ax.set_xlabel("environments per batch") + ax.set_ylabel("fit tests per second") + ax.set_title(f"Fit mask: CPU vs GPU (J={g.J}, M={g.M}, R={g.R}, T={g.T})") + ax.grid(True, which="both", alpha=0.3) + ax.legend() + path = os.path.join(os.path.dirname(__file__), "compare.png") + fig.tight_layout() + fig.savefig(path, dpi=150) + print(f"\nplot saved to {path}") + + +if __name__ == "__main__": + main() diff --git a/bench/engine_bench.zig b/bench/engine_bench.zig new file mode 100644 index 0000000..0f70f2b --- /dev/null +++ b/bench/engine_bench.zig @@ -0,0 +1,47 @@ +//! Engine benchmark: full episodes with each policy, no observers. +//! Reports episodes/s, steps/s and placements/s. +const std = @import("std"); +const sched = @import("sched"); +const A = sched.adapters; + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const io = init.io; + + std.debug.print( + "engine bench L = {d} Elem = {s} (500 jobs, 4 machines, 10 res, 100 ticks, best of 5)\n\n", + .{ sched.grid.simd.L, @typeName(sched.Elem) }, + ); + std.debug.print("{s:>12} | {s:>10} | {s:>12} | {s:>14} | {s:>9} | {s:>8}\n", .{ "policy", "µs/episode", "steps/s", "placements/s", "makespan", "avg wait" }); + std.debug.print("{s:->12}-+-{s:->10}-+-{s:->12}-+-{s:->14}-+-{s:->9}-+-{s:->8}\n", .{ "", "", "", "", "", "" }); + + inline for (.{ A.policies.FifoBackfill, A.policies.FifoStrict, A.policies.ShortestFirst, A.policies.BestFit, A.policies.RandomPolicy, A.policies.Tetris }) |P| { + var arr = A.arrivals.Poisson{ .total = 500, .rate = 1.0 }; + var gen = A.generators.RandomProfiles{}; + var eng = try sched.Engine.init(gpa, .{}, .init(&arr), .init(&gen)); + defer eng.deinit(); + var zero = A.rewards.Zero{}; + eng.setReward(.init(&zero)); + + var best: i64 = std.math.maxInt(i64); + var stats: sched.Stats = undefined; + for (0..5) |_| { + try eng.reset(42); + var p = P{}; + defer sched.ports.policy.deinitIfAny(P, &p); + sched.ports.policy.resetIfAny(P, &p, 42); + const t0 = std.Io.Timestamp.now(io, .awake); + stats = try eng.run(&p, 100_000_000); + best = @min(best, t0.durationTo(std.Io.Timestamp.now(io, .awake)).toMicroseconds()); + } + const sec = @as(f64, @floatFromInt(@max(best, 1))) / 1e6; + std.debug.print("{s:>12} | {d:>10} | {d:>12.0} | {d:>14.0} | {d:>9} | {d:>8.2}\n", .{ + P.name, + @as(u64, @intCast(best)), + @as(f64, @floatFromInt(stats.steps)) / sec, + @as(f64, @floatFromInt(stats.placed)) / sec, + @as(u64, @intCast(stats.makespan)), + stats.avgWait(), + }); + } +} diff --git a/bench/fitmask_bench.zig b/bench/fitmask_bench.zig new file mode 100644 index 0000000..acef6ee --- /dev/null +++ b/bench/fitmask_bench.zig @@ -0,0 +1,155 @@ +//! Fit-mask benchmark, CPU side of the CPU-vs-GPU comparison. +//! +//! Workload (the same one bench/fitmask_gpu.py runs on the GPU): +//! for every env e, job j, machine m: +//! mask[e][j][m] = all(job[e][j][r][k] <= free[e][m][r][k]) +//! for every resource r and tick k < duration +//! This is the action mask an RL agent needs every step. +//! +//! Output: fit tests per second for growing numbers of environments. +//! Run: zig build fitmask (ReleaseFast) +//! zig build fitmask -- --threads 8 (default: all CPUs) +//! zig build fitmask -- --csv (machine-readable, used by bench/compare.py) + +const std = @import("std"); +const sched = @import("sched"); +const grid = sched.grid; +const Elem = grid.Elem; +const Usage = grid.Usage; + +// Same sizes as fitmask_gpu.py +const J = 64; // job slots per env +const M = 4; // machines per env +const R = 10; // resources +const T = 100; // ticks +const envs_list = [_]usize{ 1, 4, 16, 64, 256, 1024 }; + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + var csv = false; + var n_threads: usize = std.Thread.getCpuCount() catch 1; + var ai: usize = 1; + while (ai < args.len) : (ai += 1) { + if (std.mem.eql(u8, args[ai], "--csv")) csv = true; + if (std.mem.eql(u8, args[ai], "--threads") and ai + 1 < args.len) { + ai += 1; + n_threads = try std.fmt.parseInt(usize, args[ai], 10); + } + } + n_threads = @max(1, n_threads); + + const layout = try grid.Layout.init(R, T, grid.simd.padding); + const max_e = envs_list[envs_list.len - 1]; + + const machines = try gpa.alignedAlloc(Elem, grid.simd.ALIGN, max_e * M * layout.block); + defer gpa.free(machines); + const jobs = try gpa.alignedAlloc(Elem, grid.simd.ALIGN, max_e * J * layout.block); + defer gpa.free(jobs); + const dur = try gpa.alloc(u16, max_e * J); + defer gpa.free(dur); + const mask = try gpa.alloc(bool, max_e * J * M); + defer gpa.free(mask); + + // Random data: machines partly used (free in [20, 100]), jobs with + // duration 1..20 and demand 0..30 → a realistic mix of fits / no-fits. + var prng = std.Random.DefaultPrng.init(42); + const rnd = prng.random(); + @memset(machines, 0); + @memset(jobs, 0); + for (0..max_e * M) |i| { + const u = Usage.fromPool(machines, layout, i); + for (0..R) |r| for (u.row(r)) |*v| { + v.* = rnd.intRangeAtMost(Elem, 20, 100); + }; + } + for (0..max_e * J) |i| { + const d = rnd.intRangeAtMost(u16, 1, 20); + dur[i] = d; + const u = Usage.fromPool(jobs, layout, i); + for (0..R) |r| @memset(u.resourceMut(r)[0..d], rnd.intRangeAtMost(Elem, 0, 30)); + } + + if (!csv) std.debug.print( + "fit-mask bench (CPU) L = {d} x {s} J={d} M={d} R={d} T={d} threads = {d}\n\n", + .{ grid.simd.L, @typeName(Elem), J, M, R, T, n_threads }, + ); + if (!csv) std.debug.print("{s:>6} | {s:>12} | {s:>14} | {s:>12} | {s:>14} | {s:>8} | {s:>7}\n", .{ "envs", "1 thread µs", "tests / s", "N threads µs", "tests / s", "speedup", "fits %" }); + if (!csv) std.debug.print("{s:->6}-+-{s:->12}-+-{s:->14}-+-{s:->12}-+-{s:->14}-+-{s:->8}-+-{s:->7}\n", .{ "", "", "", "", "", "", "" }); + + const data = Data{ .machines = machines, .jobs = jobs, .dur = dur, .mask = mask, .layout = layout }; + + for (envs_list) |n_env| { + const t1 = try bestOf(io, data, n_env, 1); + const tn = try bestOf(io, data, n_env, n_threads); + + var fits: usize = 0; + for (mask[0 .. n_env * J * M]) |b| fits += @intFromBool(b); + const tests: f64 = @floatFromInt(n_env * J * M); + if (csv) { + std.debug.print("CSV,{d},{d},{d},{d}\n", .{ n_env, t1 * 1e6, tn * 1e6, n_threads }); + continue; + } + std.debug.print("{d:>6} | {d:>12.1} | {e:>14.3} | {d:>12.1} | {e:>14.3} | {d:>7.2}x | {d:>6.1}%\n", .{ + n_env, t1 * 1e6, tests / t1, tn * 1e6, tests / tn, t1 / tn, + 100 * @as(f64, @floatFromInt(fits)) / tests, + }); + } + if (!csv) std.debug.print("\nCompare with: python3 bench/fitmask_gpu.py\n", .{}); +} + +const Data = struct { + machines: []align(grid.simd.CACHE) Elem, + jobs: []align(grid.simd.CACHE) Elem, + dur: []const u16, + mask: []bool, + layout: grid.Layout, +}; + +/// Best-of-7 seconds for one batch of `n_env` envs on `n_threads` threads. +fn bestOf(io: std.Io, d: Data, n_env: usize, n_threads: usize) !f64 { + var best: i96 = std.math.maxInt(i96); + for (0..7) |_| { + const t0 = std.Io.Timestamp.now(io, .awake); + try computeMaskThreaded(d, n_env, n_threads); + std.mem.doNotOptimizeAway(d.mask.ptr); + best = @min(best, t0.durationTo(std.Io.Timestamp.now(io, .awake)).nanoseconds); + } + return @as(f64, @floatFromInt(best)) / 1e9; +} + +/// Split the envs into contiguous chunks, one per thread. Each thread +/// reads and writes only its own envs (no locks, no shared writes except +/// at chunk edges of `mask`). The calling thread does the last chunk. +/// Threads are spawned per batch, so small batches pay the spawn cost +/// (~10–50 µs); a persistent worker pool would remove it. +fn computeMaskThreaded(d: Data, n_env: usize, n_threads: usize) !void { + const n = @min(n_threads, n_env); + if (n <= 1) return computeMask(d, 0, n_env); + + var threads: [256]std.Thread = undefined; + const per = (n_env + n - 1) / n; + var spawned: usize = 0; + var begin: usize = 0; + while (begin + per < n_env and spawned < threads.len) : (begin += per) { + threads[spawned] = try std.Thread.spawn(.{}, computeMask, .{ d, begin, begin + per }); + spawned += 1; + } + computeMask(d, begin, n_env); + for (threads[0..spawned]) |t| t.join(); +} + +/// mask for envs [env_begin, env_end). +noinline fn computeMask(d: Data, env_begin: usize, env_end: usize) void { + for (env_begin..env_end) |e| { + for (0..J) |j| { + const job = Usage.fromPool(d.jobs, d.layout, e * J + j); + const du = d.dur[e * J + j]; + for (0..M) |m| { + const mach = Usage.fromPool(d.machines, d.layout, e * M + m); + d.mask[(e * J + j) * M + m] = mach.covers(job, 0, du); + } + } + } +} diff --git a/bench/fitmask_gpu.py b/bench/fitmask_gpu.py new file mode 100644 index 0000000..2a79320 --- /dev/null +++ b/bench/fitmask_gpu.py @@ -0,0 +1,145 @@ +"""Fit-mask benchmark, GPU side of the CPU-vs-GPU comparison. + +Same workload and sizes as bench/fitmask_bench.zig: + mask[e, j, m] = all(job[e, j, r, k] <= free[e, m, r, k]) for all r, k + +Backends, whichever are installed: + numpy CPU reference (vectorized), also used to check correctness + mlx Apple GPU (pip install mlx) ← use this on a Mac + torch-mps Apple GPU via PyTorch (pip install torch) + torch-cuda NVIDIA GPU via PyTorch + +Run: python3 bench/fitmask_gpu.py +Every GPU result is checked against numpy before its time is reported. +GPU timings synchronize before stopping the clock and include no host copies +(data is uploaded once), i.e. the "data stays on the GPU" scenario. +""" + +import time +import numpy as np + +J, M, R, T = 64, 4, 10, 100 +ENVS = [1, 4, 16, 64, 256, 1024] +REPS = 7 + + +def make_data(n_env, seed=42): + rng = np.random.default_rng(seed) + free = rng.integers(20, 101, size=(n_env, M, R, T), dtype=np.uint16) + dur = rng.integers(1, 21, size=(n_env, J)) + demand = rng.integers(0, 31, size=(n_env, J, R, 1), dtype=np.uint16) + ticks = np.arange(T)[None, None, None, :] + jobs = np.where(ticks < dur[:, :, None, None], demand, 0).astype(np.uint16) + return jobs, free + + +def chunks(n_env, max_cells=64_000_000): + """Split envs so the (E, J, M, R, T) comparison fits in memory.""" + per_env = J * M * R * T + step = max(1, max_cells // per_env) + return [(i, min(n_env, i + step)) for i in range(0, n_env, step)] + + +# ---------------------------------------------------------------- backends + +def numpy_backend(): + def prep(jobs, free): + return jobs, free + + def run(jobs, free): + out = [] + for a, b in chunks(jobs.shape[0]): + ok = jobs[a:b, :, None] <= free[a:b, None, :] # (E, J, M, R, T) + out.append(ok.all(axis=(-1, -2))) + return np.concatenate(out) + + return "numpy (CPU)", prep, run, lambda x: x, lambda: None + + +def mlx_backend(): + import mlx.core as mx + + def prep(jobs, free): + j, f = mx.array(jobs), mx.array(free) + mx.eval(j, f) + return j, f + + def run(jobs, free): + outs = [] + for a, b in chunks(jobs.shape[0]): + ok = jobs[a:b, :, None] <= free[a:b, None, :] + outs.append(mx.all(ok, axis=(-1, -2))) + out = mx.concatenate(outs) + mx.eval(out) + return out + + return "mlx (Apple GPU)", prep, run, lambda x: np.array(x), lambda: None + + +def torch_backend(device): + import torch + + if device == "mps" and not torch.backends.mps.is_available(): + raise ImportError + if device == "cuda" and not torch.cuda.is_available(): + raise ImportError + sync = torch.mps.synchronize if device == "mps" else torch.cuda.synchronize + + def prep(jobs, free): + # torch has limited uint16 support; int32 is safe for comparisons + j = torch.from_numpy(jobs.astype(np.int32)).to(device) + f = torch.from_numpy(free.astype(np.int32)).to(device) + sync() + return j, f + + def run(jobs, free): + outs = [] + for a, b in chunks(jobs.shape[0]): + ok = jobs[a:b, :, None] <= free[a:b, None, :] + outs.append(ok.flatten(-2).all(dim=-1)) + out = torch.cat(outs) + sync() + return out + + return f"torch-{device}", prep, run, lambda x: x.cpu().numpy(), sync + + +def available_backends(): + found = [numpy_backend()] + for make in (mlx_backend, lambda: torch_backend("mps"), lambda: torch_backend("cuda")): + try: + found.append(make()) + except Exception: + pass + return found + + +# ---------------------------------------------------------------- bench + +def bench(backend): + name, prep, run, to_np, _ = backend + print(f"\n{name}") + print(f"{'envs':>6} | {'µs / batch':>12} | {'fit tests / s':>14} | {'check':>6}") + print(f"{'-'*6}-+-{'-'*12}-+-{'-'*14}-+-{'-'*6}") + for n_env in ENVS: + jobs, free = make_data(n_env) + ref = numpy_backend()[2](jobs, free) + dj, df = prep(jobs, free) + run(dj, df) # warm-up (kernel compilation, allocation) + best = float("inf") + for _ in range(REPS): + t0 = time.perf_counter() + out = run(dj, df) + best = min(best, time.perf_counter() - t0) + ok = np.array_equal(to_np(out), ref) + tests = n_env * J * M + print(f"{n_env:>6} | {best*1e6:>12.1f} | {tests/best:>14.3e} | {'ok' if ok else 'WRONG':>6}") + + +if __name__ == "__main__": + print(f"fit-mask bench J={J} M={M} R={R} T={T}") + backs = available_backends() + if len(backs) == 1: + print("(no GPU backend found: pip install mlx or pip install torch)") + for b in backs: + bench(b) diff --git a/bench/simd_bench.zig b/bench/simd_bench.zig new file mode 100644 index 0000000..d154049 --- /dev/null +++ b/bench/simd_bench.zig @@ -0,0 +1,155 @@ +//! Benchmarks for grid/simd.zig. +//! +//! 1. SIMD vs scalar for the two hot kernels (compare = fit test, sub = place). +//! 2. Working-set sweep 4 KiB … 256 MiB: throughput drops at each cache +//! level (L1 → L2 → L3 → RAM), which shows how much caching matters. +//! 3. Aligned vs unaligned vector loads (machine reads at offset t). +//! +//! Run: zig build bench (always ReleaseFast) +//! zig build bench -Dlanes=4 (compare vector widths) + +const std = @import("std"); +const simd = @import("sched").grid.simd; +const Elem = simd.Elem; + +const L = simd.L; +const V = simd.V; + +// ------------------------------------------------------------------ +// kernels (noinline so they can be found in the disassembly by name) +// ------------------------------------------------------------------ + +/// SIMD fit test: all need[i] <= have[i] ? +noinline fn coversSimd(need: []const Elem, have: []const Elem) bool { + var i: usize = 0; + while (i < need.len) : (i += L) + if (@reduce(.Or, simd.load(need, i) > simd.load(have, i))) return false; + return true; +} + +/// Scalar fit test. The early exit per element keeps LLVM from +/// auto-vectorizing it, so it is a fair scalar baseline. +noinline fn coversScalar(need: []const Elem, have: []const Elem) bool { + for (need, have) |n, h| if (n > h) return false; + return true; +} + +/// SIMD place: have[i] -= need[i] +noinline fn subSimd(have: []Elem, need: []const Elem) void { + var i: usize = 0; + while (i < need.len) : (i += L) simd.store(have, i, simd.load(have, i) - simd.load(need, i)); +} + +/// Same as subSimd but every vector load/store is shifted by one element +/// (4 bytes), so loads are unaligned and every L-th one splits a cache line. +noinline fn subSimdUnaligned(have: []Elem, need: []const Elem) void { + var i: usize = 0; + const n = need.len - L; // room for the +1 shift + while (i < n) : (i += L) simd.store(have, i + 1, simd.load(have, i + 1) - simd.load(need, i + 1)); +} + +// ------------------------------------------------------------------ +// timing +// ------------------------------------------------------------------ + +var io: std.Io = undefined; + +fn nowNs() i96 { + return std.Io.Timestamp.now(io, .awake).toNanoseconds(); +} + +const Kernel = enum { covers_simd, covers_scalar, sub_simd, sub_unaligned }; + +/// Best-of-5 nanoseconds per element for `k` over arrays of `n` elements. +fn measure(k: Kernel, need: []Elem, have: []Elem) f64 { + const n = need.len; + // Repeat so each sample touches ~256 MiB of data in total. + const reps: usize = @max(1, (256 << 20) / (n * 2 * @sizeOf(Elem))); + var best: f64 = std.math.inf(f64); + for (0..5) |_| { + const t0 = nowNs(); + for (0..reps) |_| { + switch (k) { + .covers_simd => std.mem.doNotOptimizeAway(coversSimd(need, have)), + .covers_scalar => std.mem.doNotOptimizeAway(coversScalar(need, have)), + .sub_simd => subSimd(have, need), + .sub_unaligned => subSimdUnaligned(have, need), + } + std.mem.doNotOptimizeAway(have.ptr); + } + const dt: f64 = @floatFromInt(nowNs() - t0); + best = @min(best, dt / @as(f64, @floatFromInt(reps * n))); + } + return best; +} + +fn gbps(ns_per_elem: f64, bytes_per_elem: f64) f64 { + return bytes_per_elem / ns_per_elem; // bytes/ns == GB/s +} + +pub fn main(init: std.process.Init) !void { + io = init.io; + const gpa = init.gpa; + + std.debug.print( + \\simd bench Elem = {s} L = {d} lanes ({d}-bit vectors) CACHE = {d} B + \\ + \\ + , .{ @typeName(Elem), L, L * @bitSizeOf(Elem), simd.CACHE }); + + const sizes_kib = [_]usize{ 4, 16, 32, 64, 256, 1024, 4096, 16384, 65536, 262144 }; + const max_n = sizes_kib[sizes_kib.len - 1] * 1024 / @sizeOf(Elem) / 2; // two arrays share the size + + const need_all = try gpa.alignedAlloc(Elem, simd.ALIGN, max_n); + defer gpa.free(need_all); + const have_all = try gpa.alignedAlloc(Elem, simd.ALIGN, max_n); + defer gpa.free(have_all); + // need = 0, have = max → the fit test never exits early (full scan), + // and sub never underflows across many repetitions. + @memset(need_all, 0); + @memset(have_all, std.math.maxInt(Elem)); + + std.debug.print("working set = both arrays together; ns/elem (lower is better), GB/s (higher is better)\n\n", .{}); + std.debug.print("{s:>10} | {s:>22} | {s:>22} | {s:>8} | {s:>22} | {s:>22}\n", .{ + "set", "covers SIMD", "covers scalar", "speedup", "sub SIMD aligned", "sub SIMD unaligned", + }); + std.debug.print("{s:->10}-+-{s:->22}-+-{s:->22}-+-{s:->8}-+-{s:->22}-+-{s:->22}\n", .{ "", "", "", "", "", "" }); + + for (sizes_kib) |kib| { + const n = std.mem.alignForward(usize, kib * 1024 / @sizeOf(Elem) / 2, L); + const need = need_all[0..n]; + const have = have_all[0..n]; + + const cs = measure(.covers_simd, need, have); + const cr = measure(.covers_scalar, need, have); + const ss = measure(.sub_simd, need, have); + const su = measure(.sub_unaligned, need, have); + + var label: [16]u8 = undefined; + const lbl = if (kib >= 1024) + try std.fmt.bufPrint(&label, "{d} MiB", .{kib / 1024}) + else + try std.fmt.bufPrint(&label, "{d} KiB", .{kib}); + + std.debug.print("{s:>10} | {d:>8.3} ns {d:>7.1} GB/s | {d:>8.3} ns {d:>7.1} GB/s | {d:>7.1}x | {d:>8.3} ns {d:>7.1} GB/s | {d:>8.3} ns {d:>7.1} GB/s\n", .{ + lbl, + cs, gbps(cs, 2 * @sizeOf(Elem)), + cr, gbps(cr, 2 * @sizeOf(Elem)), + cr / cs, + ss, gbps(ss, 3 * @sizeOf(Elem)), // 2 loads + 1 store + su, gbps(su, 3 * @sizeOf(Elem)), + }); + } + + std.debug.print( + \\ + \\How to read it: + \\ * speedup = scalar / SIMD for the fit test; close to L in L1, smaller + \\ once memory bandwidth is the limit. + \\ * rows where GB/s drops sharply mark cache boundaries (L1 → L2 → L3 → RAM). + \\ Your simulator's hot data (one machine ≈ 5 KiB, metadata ≈ 25 KiB) sits + \\ in the first rows; the 2.5 MiB job pool around the 4 MiB row. + \\ * aligned vs unaligned: the cost of machine reads at an arbitrary tick t. + \\ + , .{}); +} diff --git a/build.zig b/build.zig index 7177add..399981b 100644 --- a/build.zig +++ b/build.zig @@ -1,154 +1,130 @@ const std = @import("std"); -// Although this function looks imperative, it does not perform the build -// directly and instead it mutates the build graph (`b`) that will be then -// executed by an external runner. The functions in `std.Build` implement a DSL -// for defining build steps and express dependencies between them, allowing the -// build runner to parallelize the build automatically (and the cache system to -// know when a step doesn't need to be re-run). pub fn build(b: *std.Build) void { - // Standard target options allow the person running `zig build` to choose - // what target to build for. Here we do not override the defaults, which - // means any target is allowed, and the default is native. Other options - // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); - // Standard optimization options allow the person running `zig build` to select - // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not - // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); - // It's also possible to define more custom flags to toggle optional features - // of this build script using `b.option()`. All defined flags (including - // target and optimize options) will be listed when running `zig build --help` - // in this directory. - // This creates a module, which represents a collection of source files alongside - // some compilation options, such as optimization mode and linked system libraries. - // Zig modules are the preferred way of making Zig code available to consumers. - // addModule defines a module that we intend to make available for importing - // to our consumers. We must give it a name because a Zig package can expose - // multiple modules and consumers will need to be able to specify which - // module they want to access. - const mod = b.addModule("JobSchedulingSimulator", .{ - // The root source file is the "entry point" of this module. Users of - // this module will only be able to access public declarations contained - // in this file, which means that if you have declarations that you - // intend to expose to consumers that were defined in other files part - // of this module, you will have to make sure to re-export them from - // the root file. - .root_source_file = b.path("src/root.zig"), - // Later on we'll use this module as the root module of a test executable - // which requires us to specify a target. - .target = target, - }); + // ---- build options (0 = auto / default) ---- + const options = b.addOptions(); + options.addOption(usize, "cache_line", b.option(usize, "cache-line", "CPU cache line in bytes (0 = auto)") orelse 0); + options.addOption(usize, "lanes", b.option(usize, "lanes", "CPU SIMD lanes (0 = auto)") orelse 0); + options.addOption(usize, "gpu_warp", b.option(usize, "gpu-warp", "GPU threads per warp (0 = 32)") orelse 0); + options.addOption(usize, "gpu_align", b.option(usize, "gpu-align", "GPU grid alignment in bytes (0 = 256)") orelse 0); + + const lib = libModule(b, target, optimize, options); + const lib_fast = libModule(b, target, .ReleaseFast, options); - // Here we define an executable. An executable needs to have a root module - // which needs to expose a `main` function. While we could add a main function - // to the module defined above, it's sometimes preferable to split business - // logic and the CLI into two separate modules. - // - // If your goal is to create a Zig library for others to use, consider if - // it might benefit from also exposing a CLI tool. A parser library for a - // data serialization format could also bundle a CLI syntax checker, for example. - // - // If instead your goal is to create an executable, consider if users might - // be interested in also being able to embed the core functionality of your - // program in their own executable in order to avoid the overhead involved in - // subprocessing your CLI tool. - // - // If neither case applies to you, feel free to delete the declaration you - // don't need and to put everything under a single module. + // ---- simulator: zig build run -- ---- const exe = b.addExecutable(.{ - .name = "JobSchedulingSimulator", + .name = "sim", .root_module = b.createModule(.{ - // b.createModule defines a new module just like b.addModule but, - // unlike b.addModule, it does not expose the module to consumers of - // this package, which is why in this case we don't have to give it a name. - .root_source_file = b.path("src/main.zig"), - // Target and optimization levels must be explicitly wired in when - // defining an executable or library (in the root module), and you - // can also hardcode a specific target for an executable or library - // definition if desireable (e.g. firmware for embedded devices). + .root_source_file = b.path("src/app/main.zig"), .target = target, .optimize = optimize, - // List of modules available for import in source files part of the - // root module. - .imports = &.{ - // Here "JobSchedulingSimulator" is the name you will use in your source code to - // import this module (e.g. `@import("JobSchedulingSimulator")`). The name is - // repeated because you are allowed to rename your imports, which - // can be extremely useful in case of collisions (which can happen - // importing modules from different packages). - .{ .name = "JobSchedulingSimulator", .module = mod }, - }, + .imports = &.{.{ .name = "sched", .module = lib }}, }), }); - - // This declares intent for the executable to be installed into the - // install prefix when running `zig build` (i.e. when executing the default - // step). By default the install prefix is `zig-out/` but can be overridden - // by passing `--prefix` or `-p`. b.installArtifact(exe); + const run = b.addRunArtifact(exe); + run.addPassthruArgs(); // zig build run -- + b.step("run", "Run the simulator (args after --)").dependOn(&run.step); - // This creates a top level step. Top level steps have a name and can be - // invoked by name when running `zig build` (e.g. `zig build run`). - // This will evaluate the `run` step rather than the default step. - // For a top level step to actually do something, it must depend on other - // steps (e.g. a Run step, as we will see in a moment). - const run_step = b.step("run", "Run the app"); - - // This creates a RunArtifact step in the build graph. A RunArtifact step - // invokes an executable compiled by Zig. Steps will only be executed by the - // runner if invoked directly by the user (in the case of top level steps) - // or if another step depends on it, so it's up to you to define when and - // how this Run step will be executed. In our case we want to run it when - // the user runs `zig build run`, so we create a dependency link. - const run_cmd = b.addRunArtifact(exe); - run_step.dependOn(&run_cmd.step); - - // By making the run step depend on the default step, it will be run from the - // installation directory rather than directly from within the cache directory. - run_cmd.step.dependOn(b.getInstallStep()); - - // This allows the user to pass arguments to the application in the build - // command itself, like this: `zig build run -- arg1 arg2 etc` - run_cmd.addPassthruArgs(); + // ---- tests: zig build test ---- + const test_step = b.step("test", "Run unit and integration tests"); + const unit = b.addTest(.{ .root_module = lib }); + test_step.dependOn(&b.addRunArtifact(unit).step); + const app_tests = b.addTest(.{ .root_module = exe.root_module }); + test_step.dependOn(&b.addRunArtifact(app_tests).step); + const integ = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("tests/engine_test.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "sched", .module = lib }}, + }) }); + test_step.dependOn(&b.addRunArtifact(integ).step); + const scen = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("tests/scenario_test.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "sched", .module = lib }}, + }) }); + test_step.dependOn(&b.addRunArtifact(scen).step); - // Creates an executable that will run `test` blocks from the provided module. - // Here `mod` needs to define a target, which is why earlier we made sure to - // set the releative field. - const mod_tests = b.addTest(.{ - .root_module = mod, + // ---- C ABI shared library for Python: zig build lib ---- + // Default ReleaseFast (RL needs speed); override with -Doptimize. + const capi_mod = b.createModule(.{ + .root_source_file = b.path("src/app/capi.zig"), + .target = target, + .optimize = if (optimize == .debug) .fast else optimize, + .imports = &.{.{ .name = "sched", .module = if (optimize == .debug) lib_fast else lib }}, }); + const capi = b.addLibrary(.{ .linkage = .dynamic, .name = "sched", .root_module = capi_mod }); + const capi_install = b.addInstallArtifact(capi, .{}); + b.step("lib", "Build libsched (C ABI for Python) into zig-out/lib").dependOn(&capi_install.step); + const capi_tests = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("src/app/capi.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "sched", .module = lib }}, + }) }); + test_step.dependOn(&b.addRunArtifact(capi_tests).step); - // A run step that will run the test executable. - const run_mod_tests = b.addRunArtifact(mod_tests); + // ---- benchmarks: zig build bench (always ReleaseFast) ---- + const bench_step = b.step("bench", "Run benchmarks (ReleaseFast)"); + for ([_][]const u8{ "simd_bench", "engine_bench" }) |name| { + const exe_b = b.addExecutable(.{ + .name = name, + .root_module = b.createModule(.{ + .root_source_file = b.path(b.fmt("bench/{s}.zig", .{name})), + .target = target, + .optimize = .ReleaseFast, + .imports = &.{.{ .name = "sched", .module = lib_fast }}, + }), + }); + b.installArtifact(exe_b); + bench_step.dependOn(&b.addRunArtifact(exe_b).step); + } - // Creates an executable that will run `test` blocks from the executable's - // root module. Note that test executables only test one module at a time, - // hence why we have to create two separate ones. - const exe_tests = b.addTest(.{ - .root_module = exe.root_module, + // ---- CPU side of the CPU-vs-GPU comparison: zig build fitmask ---- + const fm = b.addExecutable(.{ + .name = "fitmask_bench", + .root_module = b.createModule(.{ + .root_source_file = b.path("bench/fitmask_bench.zig"), + .target = target, + .optimize = .ReleaseFast, + .imports = &.{.{ .name = "sched", .module = lib_fast }}, + }), }); + b.installArtifact(fm); + const fm_run = b.addRunArtifact(fm); + fm_run.addPassthruArgs(); + b.step("fitmask", "CPU fit-mask benchmark (compare with bench/compare.py)").dependOn(&fm_run.step); - // A run step that will run the second test executable. - const run_exe_tests = b.addRunArtifact(exe_tests); - - // A top level step for running all tests. dependOn can be called multiple - // times and since the two run steps do not depend on one another, this will - // make the two of them run in parallel. - const test_step = b.step("test", "Run tests"); - test_step.dependOn(&run_mod_tests.step); - test_step.dependOn(&run_exe_tests.step); + // ---- examples: zig build example ---- + const ex = b.addExecutable(.{ + .name = "custom_policy", + .root_module = b.createModule(.{ + .root_source_file = b.path("examples/custom_policy.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "sched", .module = lib }}, + }), + }); + b.installArtifact(ex); + b.step("example", "Run examples/custom_policy.zig").dependOn(&b.addRunArtifact(ex).step); +} - // Just like flags, top level steps are also listed in the `--help` menu. - // - // The Zig build system is entirely implemented in userland, which means - // that it cannot hook into private compiler APIs. All compilation work - // orchestrated by the build system will result in other Zig compiler - // subcommands being invoked with the right flags defined. You can observe - // these invocations when one fails (or you pass a flag to increase - // verbosity) to validate assumptions and diagnose problems. - // - // Lastly, the Zig build system is relatively simple and self-contained, - // and reading its source code will allow you to master it. +fn libModule( + b: *std.Build, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + options: *std.Build.Step.Options, +) *std.Build.Module { + const m = b.createModule(.{ + .root_source_file = b.path("src/root.zig"), + .target = target, + .optimize = optimize, + }); + m.addOptions("build_options", options); + return m; } diff --git a/build.zig.zon b/build.zig.zon index 7e1be77..2043a47 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,79 +1,8 @@ .{ - // This is the default name used by packages depending on this one. For - // example, when a user runs `zig fetch --save `, this field is used - // as the key in the `dependencies` table. Although the user can choose a - // different name, most users will stick with this provided value. - // - // It is redundant to include "zig" in this name because it is already - // within the Zig package namespace. - .name = .JobSchedulingSimulator, - // This is a [Semantic Version](https://semver.org/). - // In a future version of Zig it will be used for package deduplication. - .version = "0.0.0", - // Together with name, this represents a globally unique package - // identifier. This field is generated by the Zig toolchain when the - // package is first created, and then *never changes*. This allows - // unambiguous detection of one package being an updated version of - // another. - // - // When forking a Zig project, this id should be regenerated (delete the - // field and run `zig build`) if the upstream project is still maintained. - // Otherwise, the fork is *hostile*, attempting to take control over the - // original project's identity. Thus it is recommended to leave the comment - // on the following line intact, so that it shows up in code reviews that - // modify the field. - .fingerprint = 0x4aa0a080552fa291, // Changing this has security and trust implications. - // Tracks the earliest Zig version that the package considers to be a - // supported use case. + .name = .sched, + .version = "0.1.0", + .fingerprint = 0x455295d4ad304230, .minimum_zig_version = "0.17.0", - // This field is optional. - // Each dependency must either provide a `url` and `hash`, or a `path`. - // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. - // Once all dependencies are fetched, `zig build` no longer requires - // internet connectivity. - .dependencies = .{ - // See `zig fetch --save ` for a command-line interface for adding dependencies. - //.example = .{ - // // When updating this field to a new URL, be sure to delete the corresponding - // // `hash`, otherwise you are communicating that you expect to find the old hash at - // // the new URL. If the contents of a URL change this will result in a hash mismatch - // // which will prevent zig from using it. - // .url = "https://example.com/foo.tar.gz", - // - // // This is computed from the file contents of the directory of files that is - // // obtained after fetching `url` and applying the inclusion rules given by - // // `paths`. - // // - // // This field is the source of truth; packages do not come from a `url`; they - // // come from a `hash`. `url` is just one of many possible mirrors for how to - // // obtain a package matching this `hash`. - // .hash = "...", - // - // // When this is provided, the package is found in a directory relative to the - // // build root. In this case the package's hash is irrelevant and therefore not - // // computed. This field and `url` are mutually exclusive. - // .path = "foo", - // - // // When this is set to `true`, a package is declared to be lazily - // // fetched. This makes the dependency only get fetched if it is - // // actually used. - // .lazy = false, - //}, - }, - // Specifies the set of files and directories that are included in this package. - // Only files and directories listed here are included in the `hash` that - // is computed for this package. Only files listed here will remain on disk - // when using the zig package manager. As a rule of thumb, one should list - // files required for compilation plus any license(s). - // Paths are relative to the build root. Use the empty string (`""`) to refer to - // the build root itself. - // A directory listed here means that all files within, recursively, are included. - .paths = .{ - "build.zig", - "build.zig.zon", - "src", - // For example... - //"LICENSE", - //"README.md", - }, + .dependencies = .{}, + .paths = .{ "build.zig", "build.zig.zon", "src", "bench", "tests", "examples", "README.md", "LICENSE" }, } diff --git a/docs/architecture.md b/docs/architecture.md index e69de29..815cff3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -0,0 +1,90 @@ +# Architecture + +Hexagonal ("ports and adapters"): the core holds only the simulation rules; +everything that varies between experiments plugs in through ports. + +``` + driving side: app/main.zig (CLI) tests bench capi (C ABI → Gymnasium) + │ reset(seed) / step(action) / state() + ▼ + ┌───────────────────────────── core ─────────────────────────────┐ + │ grid Layout · Usage · SIMD (no domain knowledge) │ + │ model Machines · Jobs · State/Action/Event │ + │ engine rules · Engine (validate, place, advance, arrivals) │ + └──────┬──────────────────┬───────────────────┬──────────────────┘ + │ ArrivalSource │ UsageGenerator │ Policy │ Observer + ▼ ▼ ▼ ▼ + poisson, batch random, deeprm fifo, sjf, … viz, metrics, log +``` + +## Layers and dependency rule + +Each layer imports only layers above it in this list: + +1. **grid** — `[resource][tick]` grids of `Elem` (u16), padding rules for CPU, + GPU and unified memory, SIMD operations (`Usage`). No jobs or machines. +2. **model** — `Machines` (free capacity, fit test, sliding-window time), `Jobs` + (slot pool, metadata, bitmask), and the plain types `State`, `Action`, + `Event`, `JobMeta`. +3. **ports** — the four interfaces below. +4. **engine** — `rules` (legality, default reward, action encoding/masks) and + `Engine` (applies actions, enforces rules, emits events). +5. **adapters** — implementations of the ports. +6. **app** — composition root: parses the command line, builds adapters by + name (registry), wires them into the engine. + +## Ports + +| Port | Question | Called | Mechanism | +|---|---|---|---| +| `ArrivalSource` | which jobs arrive, when? | every tick | runtime (vtable) | +| `UsageGenerator` | machine capacities; a job's profile | init; per arrival | runtime (vtable) | +| `Policy` | what to do now? | every decision | comptime (inlined) or runtime | +| `Observer` | something happened | every event | runtime, list of up to 8 | +| `Reward` | how good was this tick? | every elapsed tick | runtime (vtable), optional | + +Arrival time and profile are separate ports, so any arrival process combines +with any profile distribution. + +Policies are chosen at run time by name, but each runs in its own +comptime-specialized loop (`registry.runPolicy`), so `decide` is inlined. + +## Step semantics + +One `step(action)`: + +- `.place{slot, machine}` — must be legal (`rules.isLegal`): slot holds a + waiting job, the job fits on the machine now. The profile is subtracted + from the machine starting at tick 0; `job_placed` is emitted. +- `.wait` — time advances one tick: the machine window slides one tick, finished jobs + leave, new arrivals enter the pool, `tick_advanced` is emitted, the tick + reward is returned. With `skip_empty`, empty periods are fast-forwarded. +- illegal action — `illegal_action` is emitted, the penalty is added, and it + is treated as `.wait`. + +Several placements can happen in the same tick (repeated `.place` steps). +The episode terminates when all jobs arrived, none wait and none run; it is +truncated at `max_ticks`. + +Rewards come from the `Reward` port (`engine.setReward`): `neg_in_system` += −(waiting + running) (the default when none is set), `neg_waiting` = +−waiting, `slowdown` = −Σ 1/T_j over jobs in system (DeepRM), `zero`. + +## Adding an adapter + +1. Write a type implementing the port's methods in `src/adapters//`. +2. Export it in `src/adapters.zig`. +3. Add one entry in `src/app/registry.zig` (and the help text there). + +The engine and the other adapters do not change. + +## Gymnasium + +`src/app/capi.zig` is a second driving adapter next to the CLI: it exports a +C ABI (`sim_create/reset/step/action_mask/...`), built as `libsched` by +`zig build lib`. The Python `gymnasium.Env` in `python/sched_env` loads it +with ctypes, reads the job and machine pools through zero-copy NumPy views +(strides hide the padding), uses `Discrete(max_jobs·n_machines + 1)` actions +(`rules.encode/decode`) and `rules.actionMask` for masking. Adapters are +built by name through the same registry as the CLI. See +[python.md](python.md). diff --git a/docs/data-layout.md b/docs/data-layout.md index e69de29..28823ff 100644 --- a/docs/data-layout.md +++ b/docs/data-layout.md @@ -0,0 +1,127 @@ +# Data layout + +## Grids + +Every job and every machine is a grid of `Elem` (`u16`): + +``` +row r (resource r): tick 0 … tick n_ticks-1 | padding | ← stride elements +``` + +- **Ticks innermost.** Consecutive ticks are consecutive in memory, so one + SIMD instruction compares or subtracts `L` ticks. +- **Job grid** = requirement profile relative to the job's start. + **Machine grid** = *free* capacity, tick 0 = now. The fit test is + `job[r][k] <= free[r][t+k]`; placing is `free -= job`. +- **Padding.** `stride` is a multiple of the vector width with at least one + vector of slack, so loops process whole vectors with no tail and offset + reads stay inside the row. Job padding is 0; machine padding is full + capacity, so neither changes any result. +- **Alignment.** Each grid starts on a cache line (CPU) or a 256-byte + boundary (GPU / unified), so grids stored back to back stay aligned. + +`Layout.init(n_res, n_ticks, padding)` computes `stride` and `block` from a +`Padding` rule: `grid.simd.padding` (CPU), `grid.simd_gpu.padding` (GPU +only), or `grid.simd_gpu.unified_padding` (shared CPU+GPU memory). + +## Pools + +``` +machines.buf: [machine][res][m_stride] one allocation, aligned (sliding window, see Time) +jobs.buf: [slot][res][stride] one allocation, aligned (= observation) +``` + +Job metadata is struct-of-arrays (`duration[]`, `arrival[]`, `id[]`, +`peak[]`) so scans read only what they need. Live slots are a bitmask; the +iterator uses count-trailing-zeros to skip 64 empty slots per step. Removing +a job clears its bit and zeroes its grid; nothing moves. + +## Time + +Machine rows are a **sliding window**. Each row stores `n_ticks + slack` +ticks (`Machines.ring`, slack = max(n_ticks, 4 vectors)); the horizon +[now, now + n_ticks) starts at the shared offset `Machines.head`: + +``` +row r: | stale … | head: tick 0 … tick n_ticks-1 | cap cap … cap | padding | +``` + +- **Advance k ticks** = `head += k`. Nothing is copied: every slot at or + after `head + n_ticks` is always full capacity (placements never write + past the horizon), so the ticks that become visible are already right. +- **Compaction.** When `head + n_ticks` would pass `n_ticks + slack`, each + row's live window is copied back to index 0 and the rest refilled with + capacity, and `head = 0`. That happens once every `slack` ticks, so the + cost per tick is O(machines × resources) amortized instead of + O(machines × resources × n_ticks) for a shift. +- **Contiguous windows.** Unlike a wrap-around ring, the horizon is never + split, so the SIMD fit test and `subAt` work on `row[head + t ..]` + unchanged. The price is 2× machine memory. + +Running jobs live inside the machine grids, so they age as the window moves; +waiting jobs are relative to their own start and are never touched. +Always access machine ticks through `Machine` (`resource(r)`, `freeNow`, +`canPlace`, …), which add `head`; never index `free.row(r)` directly. + +On the 300-machine × 4-resource × 1000-tick FIFO workload this took an +episode from ~415 ms (shifting 2.4 MB every tick) to ~6 ms; the small +engine benchmark (4 machines, 100 ticks) became ~2× faster. + +## Fast paths + +- **Quick reject** (`Machine.mayFit`): peak above capacity, or first tick + above free capacity now — no grid scan. +- **SIMD fit test** (`Usage.covers`): `L` ticks per compare, early exit. +- **Arrival-ordered list** (`Jobs.byArrival`, `Jobs.oldest`): waiting jobs + are also linked in (arrival, slot) order, so `oldest()` is O(1) and FIFO + stops at the first job that fits instead of scanning the whole pool. +- **"Fits nowhere" memo** (`Jobs.blocked`, `rules.firstMachine`, + `rules.knownBlocked/markBlocked`): one bit per job meaning "fits on no + machine this tick". Free capacity only shrinks within a tick, so the bit + stays valid until the engine clears it when time advances. A hit skips a + scan over every machine. + +Measured on an M1 Pro (ms per episode, 4 resources, 100 ticks, identical +results before and after): + +| machines / pool | fifo | fifo_strict | sjf | best_fit | tetris_srpt | +|---|---|---|---|---|---| +| 4 / 128 | 2.4 → 1.6 | 0.5 → 0.3 | 2.8 → 2.7 | 4.5 → 4.6 | 9.2 → 9.0 | +| 32 / 128 | 31.6 → 12.3 | 3.4 → 2.3 | 28.0 → 21.1 | 172 → 132 | 263 → 199 | +| 300 / 128 | 95 → 24 | 16 → 13 | 69 → 33 | 2196 → 2107 | 6828 → 6514 | +| 300 / 1024 | 1683 → 141 | 36 → 15 | 1118 → 218 | 22698 → 21968 | — | + +- **Incremental pair scores** (`PairCache`, used by `best_fit`, `tetris`, + `tetris_srpt`): scores of every (job, machine) pair are kept across + decisions. Within a tick a placement changes one machine, so only that + machine's column is recomputed (and a job's row rescanned only if its best + machine got worse). `Machines.epoch` (reset, time advance) forces a full + rebuild; `Machines.stamp[m]` (bumped by `touch` on placement) marks + changed columns. Decisions are bit-identical to a full scan (same score + function, same tie-breaking; checked by a property test). + +Incremental scoring (ms per episode, same setup, identical results): + +| machines / pool | best_fit | tetris | tetris_srpt | +|---|---|---|---| +| 4 / 128 | 4.3 → 5.7 | 4.2 → 5.4 | 7.5 → 6.6 | +| 32 / 128 | 112 → 61 | 81 → 50 | 176 → 83 | +| 300 / 128 | 1810 → 159 | 2860 → 210 | 6056 → 1055 | + +On tiny clusters the bookkeeping costs more than it saves (~30 %). +`tetris_srpt` still sums every cached alignment per decision for its ε +(kept in full-scan order so rounding matches). + +Tried and rejected: a per-(job, machine) fit cache. The fit test is only a +quick reject plus a few SIMD compares, about as cheap as a scattered cache +lookup, and every miss adds a write — it made FIFO ~2× slower and best_fit +only ~5–10 % faster, so it was removed. + +## Sizes (10 resources, 100 ticks, u16) + +| Data | Size | +|---|---| +| one grid (L = 16, stride 128) | 2.5 KiB | +| 4 machines (2× for the sliding-window slack) | 20 KiB | +| 128 job slots | 320 KiB | +| metadata (128 slots) | ~5 KiB | diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 0000000..b2744f6 --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,273 @@ +# User guide + +How to run experiments, read the results, and extend the simulator. +For the internals see [architecture.md](architecture.md) and +[data-layout.md](data-layout.md); for reinforcement learning see +[python.md](python.md). + +## 1. The model in one page + +- **Machines** have `n_res` resources (CPU, memory, …), each with a capacity. + A machine is a `[resource][tick]` grid of *free* capacity over a sliding + horizon of `n_ticks` ticks; tick 0 is "now". +- **Jobs** arrive over time and wait in a pool of `max_jobs` slots. Each job + is a `[resource][tick]` grid of *demand* relative to its start, with a + duration `1 ≤ dur ≤ n_ticks`. Demand may vary over the job's lifetime. +- A job **fits** on a machine if its demand is ≤ the machine's free capacity + on every resource and every tick of its duration. Placing it subtracts its + grid from the machine's. +- A **policy** is asked, repeatedly, what to do: *place job s on machine m + now*, or *wait*. Waiting advances time one tick: the machine horizon slides + one tick (finished work disappears, a fresh empty tick enters at the end), new jobs + arrive. +- The **reward** is paid per elapsed tick by a `Reward` adapter (see + Rewards below); the default is −(waiting + running jobs). +- An episode **terminates** when all jobs have arrived, been placed and + finished, and is **truncated** at `--max-ticks`. + +## 2. Running experiments from the command line + +```bash +zig build run -Doptimize=ReleaseFast -- [options] +``` + +Always use ReleaseFast for real measurements; Debug is ~10–50× slower. + +| Option | Meaning | Default | +|---|---|---| +| `--machines ` | machine capacities + job profiles | `random` | +| `--jobs ` | arrival process | `poisson` | +| `--policy ` | `fifo`, `fifo_strict`, `sjf`, `best_fit`, `tetris`, `tetris_srpt[:weight=w]`, `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` | +| `--max-ticks ` | truncate episodes | never | +| `--seed`, `--episodes` | first seed; episode *i* uses `seed + i` | 42, 1 | +| `--list` | every adapter with its options | | + +A *spec* is `name:key=value,key=value`. Values can be integers, floats, +booleans (`1/0/yes/no`), ranges `lo-hi` and lists `a/b/c`. Unknown keys are +errors, so typos are caught. + +### Workloads + +| Spec | Options | Description | +|---|---|---| +| `random` | `n=4 caps=100/80/60/40 dur=1-20 demand=0-30 varying=0` | machine *i* gets `caps[i % len]` on every resource; uniform duration and demand; `varying=1` changes demand at random points during a job | +| `deeprm` | `n=1 cap=100 short=3 long=10-15 short_prob=0.8` | DeepRM workload: identical machines, 80 % short jobs, one dominant resource per job (25–50 % of cap), others 5–10 % | +| `poisson` | `n=500 rate=1.0` | `n` jobs, exponential gaps, `rate` jobs per tick on average | +| `mmpp` | `n=500 rate=1.0 ratio=10 calm=40 burst=10` | bursty: alternates calm/burst states (geometric lengths, means in ticks); burst rate = `ratio` × calm rate; long-run mean = `rate` | +| `pareto` | `n=500 rate=1.0 alpha=1.5` | heavy-tailed gaps, Pareto(α) with mean 1/rate; infinite variance for α ≤ 2 | +| `selfsimilar` | `n=500 rate=1.0 sources=8 alpha=1.4 period=50` | superposition of Pareto ON/OFF sources (Willinger et al. 1997): long-range dependent, Hurst H = (3−α)/2 | +| `batch` | `n=200` | all jobs at tick 0 | + +How bursty they are (index of dispersion = variance/mean of the number of +arrivals in a window, rate 1, from the unit test): + +| Window (ticks) | 1 | 10 | 100 | 1000 | +|---|---|---|---|---| +| `poisson` | 1.0 | 1.0 | 1.0 | 0.9 | +| `mmpp` | 2.7 | 12 | 23 | 19 — bursty, short-range (levels off) | +| `pareto` α=1.3 | 1.3 | 5.7 | 26 | 100 | +| `selfsimilar` | 1.1 | 2.1 | 6.4 | 24 — keeps growing (≈ m^(2H−1), H ≈ 0.8) | + +All have the same mean rate, so differences between policies under them +come from burstiness alone. + +Arrivals and profiles are independent: any `--jobs` works with any `--machines`. + +### Policies + +| Name | Picks | Optimizes | +|---|---|---| +| `fifo` | oldest job that fits now, first machine (backfill) | fairness, simple | +| `fifo_strict` | only the oldest job; waits if it does not fit | no starvation | +| `sjf` | shortest job that fits now | mean wait / slowdown | +| `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 | +| `random` | random legal placement | sanity baseline | + +Pure `tetris` favours large jobs (they score highest), so it packs well but +has the worst slowdown of the set; `tetris_srpt` adds the paper's +shortest-remaining-time term. Its `weight` (default 1.5) moves it along the +trade-off between the two — e.g. on a batch of 500 jobs, 4 heterogeneous +machines, 4 resources, time-varying demand (5 seeds): + +| policy | makespan | slowdown / job | utilization | +|---|---|---|---| +| `sjf` | 895 | **17.3** | 68.5 % | +| `tetris` (= weight 0) | **852** | 54.9 | **72.1 %** | +| `tetris_srpt:weight=1` | 845 | 49.4 | 72.9 % | +| `tetris_srpt:weight=1.25` | 856 | 39.8 | 71.9 % | +| `tetris_srpt` (1.5) | 872 | 23.2 | 70.4 % | +| `tetris_srpt:weight=2` | 887 | 18.1 | 69.3 % | + +With online arrivals and the DeepRM workload (one dominant resource, +constant demand) packing gains little and the best slowdown is at weight ≈ 2, +where it behaves like `sjf`. + +Policy options: any numeric field of a policy struct can be set in its spec +(`--policy tetris_srpt:weight=2`; also from Python `run_policy` / +`policy_action`). Unknown options are errors. + +### Rewards + +Reward is a port (`ports.Reward`): one call per elapsed tick, with the +waiting jobs and the running jobs (id, machine, start, duration). + +| Spec | Per tick | Summed over an episode | +|---|---|---| +| `neg_in_system` (default) | −(waiting + running) | −Σ (wait + duration): mean time in system | +| `neg_waiting` | −waiting | −Σ wait | +| `slowdown:min_dur=1` | −Σ 1/max(T_j, min_dur) over jobs in system | −Σ (wait + T_j)/T_j: total slowdown (DeepRM, Mao et al. 2016); `min_dur > 1` gives bounded slowdown | +| `zero` | 0 | heuristics / benchmarks | + +Write your own by implementing `tick(ctx) f32` (see +[src/ports/reward.zig](../src/ports/reward.zig)) and setting it with +`engine.setReward(.init(&r))`. + +### Observers + +| Spec | Output | +|---|---| +| `viz:delay=80,per_resource=0,on_place=0,jobs=20,cols=100,color=1` | animated terminal view of machines and the waiting pool | +| `metrics` | wait percentiles, utilization, jobs per machine at episode end | +| `log:ticks=0` | one line per event on stderr | +| `trace:path=trace.jsonl,ticks=1` | every event plus each job's demand profile, as JSON Lines — download it and replay / visualize offline (see [python.md](python.md#recording-and-replay)) | + +### Example: compare policies + +```bash +for p in fifo sjf best_fit random; do + zig build run -Doptimize=ReleaseFast -- --machines deeprm:n=2 \ + --jobs poisson:n=2000,rate=1.2 --res 2 --ticks 30 \ + --policy $p --episodes 10 +done +``` + +Each episode prints `placed`, `makespan`, `avg wait`, `util`, `reward`, +`steps` and wall time. Use the same `--seed` for every policy so they see +identical workloads. + +### Reading the numbers + +| Metric | Meaning | +|---|---| +| `placed / arrived` | jobs started / jobs admitted to the pool | +| `rejected` | jobs dropped: pool full, impossible on every machine, or invalid profile | +| `avg wait`, `max wait` | ticks between arrival and start | +| `makespan` | tick when the last job finishes | +| `util` | mean over ticks of used/capacity at tick 0, averaged over machines and resources | +| `reward` | sum of per-tick rewards (plus illegal-action penalties) | + +If `rejected > 0` with reason *pool full*, increase `--pool`. + +## 3. Writing a policy in Zig + +A policy is any type with `decide`: + +```zig +const sched = @import("sched"); +const rules = sched.engine.rules; + +const LongestFirst = struct { + pub const name = "longest"; // needed only for the registry + pub fn decide(self: *LongestFirst, st: *const sched.State) sched.Action { + _ = self; + var best: ?usize = null; + var best_m: usize = 0; + var it = st.jobs.iter(); // waiting jobs, by slot + while (it.next()) |s| { + if (best) |b| if (st.jobs.duration[s] <= st.jobs.duration[b]) continue; + best_m = rules.firstMachine(st, s) orelse continue; + best = s; + } + const s = best orelse return .wait; + return .{ .place = .{ .slot = @intCast(s), .machine = @intCast(best_m) } }; + } +}; +``` + +Useful queries on `State`: + +| Query | Returns | +|---|---| +| `st.now` | current tick | +| `st.jobs.iter()`, `st.jobs.count`, `st.jobs.oldest()` | waiting jobs | +| `st.jobs.duration[s]`, `arrival[s]`, `id[s]`, `peakOf(s)` | job metadata | +| `st.jobs.get(s)` | the job's demand grid (`Usage`) | +| `st.machines.n`, `st.machines.get(m)` | machines | +| `machine.freeNow(r)`, `.cap`, `.earliestFit(job, dur)`, `.utilizationNow()` | machine queries | +| `rules.fitsNow(st, s, m)`, `rules.firstMachine(st, s)` | legality, same test the engine uses | + +Return `.wait` when you want time to move. Never mutate the state. + +Run it directly (see [examples/custom_policy.zig](../examples/custom_policy.zig), +`zig build example`): + +```zig +var eng = try sched.Engine.init(gpa, .{ .n_res = 2, .n_ticks = 30 }, .init(&arrivals), .init(&profiles)); +defer eng.deinit(); +try eng.reset(1); +var p = LongestFirst{}; +const stats = try eng.run(&p, 10_000_000); +std.debug.print("avg wait {d:.2}\n", .{stats.avgWait()}); +``` + +To make it available as `--policy longest` (and from Python's +`run_policy`): put it in `src/adapters/policies/`, export it in +`src/adapters.zig`, add it to `policy_types` and `list_text` in +`src/app/registry.zig`, and add a test. + +## 4. Other adapters + +The same three steps (implement, export, register) apply to every port. +Contracts are documented at the top of each port file: + +| Port | File | Implement | +|---|---|---| +| `ArrivalSource` | [src/ports/arrival_source.zig](../src/ports/arrival_source.zig) | `next(now) ?JobMeta`, `done()`, optional `reset(seed)` | +| `UsageGenerator` | [src/ports/usage_generator.zig](../src/ports/usage_generator.zig) | `machineCount()`, `machine(i, cap)`, `job(meta, out) u16`, optional `reset(seed)` | +| `Observer` | [src/ports/observer.zig](../src/ports/observer.zig) | `onEvent(event, state)` | +| `Policy` | [src/ports/policy.zig](../src/ports/policy.zig) | `decide(state) Action`, optional `reset(seed)` | +| `Reward` | [src/ports/reward.zig](../src/ports/reward.zig) | `tick(ctx) f32`, optional `reset(seed)` | + +Rules that keep experiments valid: + +- Be deterministic for a given seed. +- Arrival times are non-decreasing and never in the future. +- Generators write only ticks `[0, dur)` of the job grid and return `dur`. +- Observers never change state or results. + +## 5. Reinforcement learning + +Build `libsched` and use the Gymnasium environment — see +[python.md](python.md) for setup, observation/action spaces and a +Stable-Baselines3 `MaskablePPO` example. + +## 6. Testing and benchmarks + +What the tests cover: + +| File | What it proves | +|---|---| +| `src/**` (unit tests) | grids, SIMD ops, sliding window vs a hand-shifted reference, ports, adapters | +| [tests/scenario_test.zig](../tests/scenario_test.zig) | hand-worked scenarios with exact expected placements, waits, makespan and reward: blocking, multi-machine, exact fit, time-varying profiles, per-resource limits, horizon-length jobs, backfill vs strict FIFO, SJF, best_fit, illegal actions, action masks, admission (pool full / impossible / invalid), truncation, `skip_empty`, reward kinds, reset | +| same file, `property:` test | 20 random episodes with random (sometimes illegal) actions, checked at every step against a naive reference simulator: free capacity at every tick, legality of every (job, machine), per-step reward, makespan | +| [tests/engine_test.zig](../tests/engine_test.zig) | whole episodes with every policy: invariants after every event, each job placed once, determinism | +| `python/tests` | Gymnasium `check_env`, masks, stepping built-in policies, zero-copy views, visualizer | + +To add a scenario, script the jobs and capacities, work out the expected +result by hand in a comment, and assert it (see the helpers `Script`, +`Recorder` and `Sim` at the top of `scenario_test.zig`). + +```bash +zig build test # unit, integration (tests/), C ABI +PYTHONPATH=python pytest python/tests +zig build bench # SIMD + engine throughput (ReleaseFast) +zig build fitmask # CPU side of bench/compare.py (CPU vs GPU) +``` + +Build options `-Dlanes`, `-Dcache-line`, `-Dgpu-warp`, `-Dgpu-align` change +SIMD width and padding; results must not depend on them. diff --git a/docs/python.md b/docs/python.md new file mode 100644 index 0000000..16f84ed --- /dev/null +++ b/docs/python.md @@ -0,0 +1,291 @@ +# Python, Gymnasium and Stable-Baselines3 + +The Zig engine is exposed to Python through a small C ABI +([src/app/capi.zig](../src/app/capi.zig)) compiled into a shared library +`libsched`. A pure-Python package, [`python/sched_env`](../python/sched_env), +loads it with `ctypes` and wraps it as a `gymnasium.Env`. No compiler is +needed on the Python side and no data is copied for the grids. + +``` + Python Zig (libsched) + ─────────────────────────────── ───────────────────────────────── + SB3 / MaskablePPO + │ step(a) / action_masks() + sched_env.SchedEnv (gymnasium.Env) ──ctypes──► sim_step / sim_action_mask + │ obs = NumPy views ◄──── zero-copy ───── machine pool, job pool + Engine + registry adapters +``` + +## 1. Build the library + +```bash +zig build lib # → zig-out/lib/libsched.dylib (.so on Linux, .dll on Windows) +``` + +`zig build lib` builds ReleaseFast unless you pass another `-Doptimize`. +The Python package finds the library in `zig-out/lib` automatically; to use +one elsewhere set `SCHED_LIB=/path/to/libsched.dylib`. + +## 2. Install the Python dependencies + +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install -r python/requirements.txt # numpy, gymnasium, stable-baselines3, sb3-contrib +export PYTHONPATH=$PWD/python +``` + +## 3. Use the environment + +```python +from sched_env import SchedEnv + +env = SchedEnv( + machines="deeprm:n=1", # same spec as sim --machines + jobs="poisson:n=60,rate=0.7", # same spec as sim --jobs + n_res=2, n_ticks=20, max_jobs=10, + reward="neg_in_system", # | neg_waiting | slowdown | zero (same as --reward) + max_ticks=2000, # truncation (None = never) +) +obs, info = env.reset(seed=0) +mask = env.action_masks() # bool[n_actions] +obs, reward, terminated, truncated, info = env.step(env.action_space.n - 1) # wait +``` + +Or through the registry: `gymnasium.make("Sched-v0", machines=..., ...)`. + +Any adapter listed by `zig build run -- --list` works in `machines=` / +`jobs=`; a bad spec raises `ValueError` and prints the reason on stderr. + +### Constructor arguments + +| Argument | Meaning | Default | +|---|---|---| +| `machines` | usage-generator spec (`random:…`, `deeprm:…`) | `deeprm:n=2` | +| `jobs` | arrival spec (`poisson:…`, `batch:…`) | `poisson:n=100,rate=0.5` | +| `n_res` | resources per machine | 2 | +| `n_ticks` | horizon of every grid (also max job duration) | 20 | +| `max_jobs` | waiting-pool slots (observation & action size) | 10 | +| `reward` | reward spec: `neg_in_system`, `neg_waiting`, `slowdown[:min_dur=k]`, `zero` | `neg_in_system` | +| `max_ticks` | truncate the episode at this tick | `None` | +| `illegal_penalty` | reward added for an illegal action | -1.0 | +| `skip_empty` | fast-forward time while the pool is empty | `True` | +| `drop_impossible` | drop jobs no machine can ever run | `True` | + +### Observation — `Dict`, all `float32` in [0, 1] + +| Key | Shape | Content | +|---|---|---| +| `machines` | `(n_machines, n_res, n_ticks)` | free capacity / max capacity, tick 0 = now | +| `jobs` | `(max_jobs, n_res, n_ticks)` | demand profile / max capacity, 0 for empty slots | +| `valid` | `(max_jobs,)` | 1 if the slot holds a waiting job | +| `wait` | `(max_jobs,)` | ticks waited / n_ticks, clipped to 1 | + +This is the DeepRM "image" representation: a job fits on a machine iff its +`jobs[s]` grid is ≤ `machines[m]` everywhere on `[0, duration)`. + +### Action — `Discrete(max_jobs · n_machines + 1)` + +| Index | Meaning | +|---|---| +| `a < max_jobs·n_machines` | place job in slot `a // n_machines` on machine `a % n_machines`, now | +| `a == max_jobs·n_machines` | wait: time advances one tick, finished jobs leave, new jobs arrive | + +Several placements can happen in one tick; only *wait* moves time, and the +per-tick reward is paid on *wait*. An illegal action gets `illegal_penalty` +and is treated as *wait* (`info["illegal"] = True`). Use +`env.action_masks()` to avoid illegal actions altogether. + +### Episode end + +`terminated` when every job has arrived, been placed and finished; +`truncated` at `max_ticks`. The final `info["stats"]` holds `avg_wait`, +`max_wait`, `makespan`, `avg_util`, `placed`, `arrived`, `rejected`, +`illegal`, `total_reward`, … + +### Baselines at native speed + +```python +env.run_policy("sjf", seed=1000) # fifo | fifo_strict | sjf | best_fit | tetris | tetris_srpt[:weight=2] | random +``` + +runs a whole episode inside Zig with a built-in heuristic and returns the +same stats dict — use the same seeds as your agent's evaluation episodes for +a fair comparison. + +### Stepping a built-in policy + +`env.policy_action("sjf")` returns the action a built-in Zig policy would +take in the current state, so you can step heuristics from Python (stepping +SJF this way reproduces `run_policy("sjf", seed)` exactly). `env.raw()` +returns the unnormalized state and `env.capacity()` the machine capacities. + +### Visualization + +```bash +PYTHONPATH=python python python/examples/visualize.py --policy sjf --out sjf.gif +PYTHONPATH=python python python/examples/visualize.py --policy fifo # live window +PYTHONPATH=python python python/examples/visualize.py --model ppo_sched.zip --out ppo.gif +``` + +One frame per tick, at the start of the tick (after arrivals, before +placements): + +- **machines**: used / capacity heatmap per machine, resource × ticks ahead + (column 0 = now); +- **waiting pool**: one row per resource of each slot (`slot s / r0, r1, …`), + demand over the job's duration, with how long it has waited; +- **time series**: waiting jobs, jobs placed that tick, utilization. + +From code: `frames = sched_env.viz.record(env, "sjf", seed=0)` then +`sched_env.viz.animate(env, frames, "out.gif")`. `record` also accepts a +callable `(env, obs) -> action`, e.g. a trained model. + +### Recording and replay + +The `trace` observer writes everything needed to rebuild an episode — +machine capacities, every arrival with its full demand profile, every +placement, rejection, illegal action and tick — to a JSON Lines file. The +file is self-contained: copy or download it and replay it anywhere with +Python, without the simulator or `libsched`. + +```bash +# record (command line): one file, all episodes +zig build run -- --machines deeprm:n=1 --jobs poisson:n=60,rate=0.8 --res 2 --ticks 20 \ + --pool 10 --policy sjf --episodes 3 --observe trace:path=run.jsonl + +# replay +PYTHONPATH=python python python/examples/replay.py run.jsonl --list +PYTHONPATH=python python python/examples/replay.py run.jsonl --episode 1 --out ep1.gif +PYTHONPATH=python python python/examples/replay.py run.jsonl --from-tick 40 --to-tick 80 # live window +``` + +From Python (e.g. to record a trained agent): + +```python +env.start_trace("ppo.jsonl") # before reset: whole episodes +obs, _ = env.reset(seed=0) +... # step with any policy or model +env.stop_trace() + +from sched_env.replay import load_trace +from sched_env.viz import animate +ep = load_trace("ppo.jsonl")[0] +print(ep.stats) # placed, arrived, avg_wait, max_wait, makespan, avg_util, ... +print(ep.placements[:3]) # raw place events (id, machine, t, arrival, dur) +animate(ep, ep.frames, "ppo.gif") +``` + +`load_trace` rebuilds one frame per tick (machine usage, waiting pool, waits) +— identical to a live `viz.record` run (checked by a test). Format: one +JSON object per line, `type` ∈ `episode`, `arrive`, `reject`, `place`, +`illegal`, `tick`, `done`; documented at the top of +[src/adapters/observers/trace.zig](../src/adapters/observers/trace.zig). +Size: roughly 100 bytes per event plus the demand profiles (a 60-job, +3-episode run ≈ 35 KB); `ticks=0` drops tick lines but then replay cannot +rebuild frames. + +## 4. Train with Stable-Baselines3 + +Use `MaskablePPO` from `sb3-contrib` (plain PPO works too, but wastes most of +its exploration on illegal actions): + +```python +from sb3_contrib import MaskablePPO +from sb3_contrib.common.wrappers import ActionMasker +from stable_baselines3.common.env_util import make_vec_env +from sched_env import SchedEnv + +KW = dict(machines="deeprm:n=1", jobs="poisson:n=60,rate=0.7", + n_res=2, n_ticks=20, max_jobs=10, max_ticks=2000) + +def make(): + return ActionMasker(SchedEnv(**KW), lambda e: e.action_masks()) + +venv = make_vec_env(make, n_envs=8, seed=0) +model = MaskablePPO("MultiInputPolicy", venv, n_steps=256, batch_size=256, verbose=1) +model.learn(total_timesteps=100_000) + +env = SchedEnv(**KW) +obs, _ = env.reset(seed=1000) +done = False +while not done: + a, _ = model.predict(obs, action_masks=env.action_masks(), deterministic=True) + obs, r, term, trunc, info = env.step(a) + done = term or trunc +print(info["stats"]["avg_wait"], env.run_policy("sjf", 1000)["avg_wait"]) +``` + +The full script, including a comparison against every heuristic on 20 +seeds, is [python/examples/train_sb3.py](../python/examples/train_sb3.py): + +```bash +PYTHONPATH=python python python/examples/train_sb3.py --steps 100000 +PYTHONPATH=python python python/examples/train_sb3.py --device mps # Apple GPU (cuda for NVIDIA) +``` + +`--device` only moves the neural network; the simulator always runs on the +CPU. For this small policy the GPU is often no faster than the CPU. + +Sample output after 100k steps (8 envs, ≈4 400 env steps/s on an M-series +laptop, almost all of it in PyTorch): + +``` +ppo avg_wait 2.06 makespan 98.6 reward -356.1 +fifo avg_wait 2.07 makespan 98.5 reward -355.0 +sjf avg_wait 1.49 makespan 99.9 reward -322.4 +best_fit avg_wait 2.06 makespan 99.0 reward -354.8 +random avg_wait 2.12 makespan 98.2 reward -357.9 +``` + +100k steps only reaches FIFO level; train longer (1–10 M steps) to approach +or beat SJF. + +### Tips + +- **Load matters.** With few jobs or many machines every policy is optimal + and the comparison is meaningless; raise `rate` or lower `n` until + `fifo` and `sjf` differ. +- **Keep the action space small.** It is `max_jobs·n_machines + 1`; DeepRM + used 10 visible slots. Jobs beyond `max_jobs` are rejected (`rejected` + in stats) — increase it if that happens. +- **Flat observations.** For `MlpPolicy` instead of `MultiInputPolicy`, wrap + with `gymnasium.wrappers.FlattenObservation`. +- **Seeds.** `reset(seed=s)` makes arrivals and profiles reproducible. + +## 5. Tests + +```bash +zig build test # includes the C ABI test +PYTHONPATH=python pytest python/tests # gymnasium check_env + episodes +``` + +## C ABI reference + +All functions are in [src/app/capi.zig](../src/app/capi.zig); the ctypes +declarations mirror them in [python/sched_env/_lib.py](../python/sched_env/_lib.py). + +| Function | Purpose | +|---|---| +| `sim_create(*SimConfig) → handle` | build generator, arrivals and engine; NULL on error | +| `sim_destroy(h)` | free everything | +| `sim_reset(h, seed) → int` | start an episode | +| `sim_step(h, action, *SimStep) → int` | one action; -1 if no episode is running | +| `sim_action_mask(h, u8*)` | `n_actions` bytes, 1 = legal | +| `sim_slot_valid(h, u8*)` | `max_jobs` bytes, 1 = waiting job | +| `sim_dims(h, *SimDims)` | sizes, job `stride`/`block`, machine `m_stride`/`m_block`, `max_cap` | +| `sim_jobs_ptr` | zero-copy job pool `[slot][res][stride]` (u16) | +| `sim_machines_ptr`, `sim_machine_head` | machine pool `[machine][res][m_stride]`; tick 0 is at `head` (moves with time) | +| `sim_capacity_ptr` | `[n_machines][n_res]` capacities | +| `sim_duration_ptr / sim_arrival_ptr` | per-slot metadata | +| `sim_now(h)`, `sim_stats(h, *SimStats)` | clock and episode statistics | +| `sim_trace_open(h, path)`, `sim_trace_close(h)` | record events to a JSON Lines trace | +| `sim_run_policy(h, name, seed, *SimStats)` | full episode with a built-in policy | + +Pointers stay valid until `sim_destroy` and always reflect the current state. +Each job grid occupies `block` elements, each row `stride` elements, and only the +first `n_ticks` of a row are real. Machine rows are a sliding window +(`m_stride`, `m_block`, offset `sim_machine_head()`), so a machine view must be +rebuilt after every step — `SchedEnv` does this (see [data-layout.md](data-layout.md)); +`_lib.grid_view` builds a strided NumPy view that hides the padding. One +handle is not thread-safe; use one per environment (SB3's vector envs do). diff --git a/examples/.gitkeep b/examples/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/custom_policy.zig b/examples/custom_policy.zig new file mode 100644 index 0000000..2315364 --- /dev/null +++ b/examples/custom_policy.zig @@ -0,0 +1,50 @@ +//! Example: write your own policy and run it against a built-in one on the +//! same workload. A policy is any type with +//! pub fn decide(self: *Self, state: *const sched.State) sched.Action +const std = @import("std"); +const sched = @import("sched"); +const A = sched.adapters; +const rules = sched.engine.rules; + +/// "Largest first": among jobs that fit now, the one with the biggest total +/// peak demand (pack big jobs early, fill gaps with small ones later). +const LargestFirst = struct { + pub fn decide(self: *LargestFirst, st: *const sched.State) sched.Action { + _ = self; + var best: ?usize = null; + var best_m: usize = 0; + var best_size: u32 = 0; + var it = st.jobs.iter(); + while (it.next()) |s| { + var size: u32 = 0; + for (st.jobs.peakOf(s)) |p| size += p; + if (best != null and size <= best_size) continue; + const m = rules.firstMachine(st, s) orelse continue; + best = s; + best_m = m; + best_size = size; + } + const s = best orelse return .wait; + return .{ .place = .{ .slot = @intCast(s), .machine = @intCast(best_m) } }; + } +}; + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + + var arr = A.arrivals.Poisson{ .total = 1000, .rate = 0.7 }; + var gen = A.generators.DeepRM{ .n_machines = 2 }; + var eng = try sched.Engine.init(gpa, .{ .n_res = 10, .n_ticks = 30 }, .init(&arr), .init(&gen)); + defer eng.deinit(); + + try eng.reset(1); + var mine = LargestFirst{}; + const a = try eng.run(&mine, 10_000_000); + + try eng.reset(1); + var fifo = A.policies.FifoBackfill{}; + const b = try eng.run(&fifo, 10_000_000); + + std.debug.print("largest_first makespan {d:>4} avg wait {d:>6.2}\n", .{ @as(u64, @intCast(a.makespan)), a.avgWait() }); + std.debug.print("fifo makespan {d:>4} avg wait {d:>6.2}\n", .{ @as(u64, @intCast(b.makespan)), b.avgWait() }); +} diff --git a/python/examples/replay.py b/python/examples/replay.py new file mode 100644 index 0000000..c582363 --- /dev/null +++ b/python/examples/replay.py @@ -0,0 +1,51 @@ +"""Replay a recorded trace as an animation — no simulator needed. + +Record (command line): + zig build run -- --machines deeprm:n=1 --jobs poisson:n=60,rate=0.8 --res 2 --ticks 20 \\ + --pool 10 --policy sjf --observe trace:path=run.jsonl +Record (Python): + env.start_trace("run.jsonl"); env.reset(seed=0); ...steps...; env.stop_trace() + +Replay: + PYTHONPATH=python python python/examples/replay.py run.jsonl --out run.gif + PYTHONPATH=python python python/examples/replay.py run.jsonl --episode 1 # live window + PYTHONPATH=python python python/examples/replay.py run.jsonl --list +""" + +import argparse + +from sched_env.replay import load_trace +from sched_env.viz import animate + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("trace") + ap.add_argument("--episode", type=int, default=0) + ap.add_argument("--out", help=".gif or .mp4 (default: live window)") + ap.add_argument("--fps", type=int, default=6) + ap.add_argument("--from-tick", type=int, default=0) + ap.add_argument("--to-tick", type=int) + ap.add_argument("--list", action="store_true", help="summarize the episodes and exit") + a = ap.parse_args() + + episodes = load_trace(a.trace) + if a.list or not episodes: + for i, ep in enumerate(episodes): + s = ep.stats + print(f"episode {i}: seed {ep.seed}, {len(ep.frames)} ticks, placed {s['placed']}/{s['arrived']}, " + f"rejected {s['rejected']}, avg wait {s['avg_wait']:.2f}, makespan {s['makespan']}" + + (" (truncated)" if ep.truncated else "")) + return + ep = episodes[a.episode] + frames = [f for f in ep.frames if f.now >= a.from_tick and (a.to_tick is None or f.now <= a.to_tick)] + s = ep.stats + print(f"episode {a.episode} (seed {ep.seed}): {len(frames)} frames, placed {s['placed']}/{s['arrived']}, " + f"avg wait {s['avg_wait']:.2f}, makespan {s['makespan']}") + animate(ep, frames, a.out, fps=a.fps, title=f"{a.trace} #{a.episode}") + if a.out: + print("saved", a.out) + + +if __name__ == "__main__": + main() diff --git a/python/examples/train_sb3.py b/python/examples/train_sb3.py new file mode 100644 index 0000000..9cc96d3 --- /dev/null +++ b/python/examples/train_sb3.py @@ -0,0 +1,79 @@ +"""Train MaskablePPO (sb3-contrib) on the Zig simulator and compare it with +the built-in heuristics on the same seeds. + + zig build lib + pip install -r python/requirements.txt + PYTHONPATH=python python python/examples/train_sb3.py --steps 100000 +""" + +import argparse + +import numpy as np +from sb3_contrib import MaskablePPO +from sb3_contrib.common.wrappers import ActionMasker +from stable_baselines3.common.env_util import make_vec_env + +from sched_env import SchedEnv + +ENV_KW = dict( + machines="deeprm:n=1", + jobs="poisson:n=60,rate=0.7", # loaded enough that policies differ + n_res=2, + n_ticks=20, + max_jobs=10, + reward="neg_in_system", + max_ticks=2000, +) + + +def make(): + # ActionMasker lets MaskablePPO find the mask through any wrappers. + return ActionMasker(SchedEnv(**ENV_KW), lambda e: e.action_masks()) + + +def evaluate(model, seeds): + env = SchedEnv(**ENV_KW) + out = [] + for s in seeds: + obs, _ = env.reset(seed=s) + done = False + while not done: + a, _ = model.predict(obs, action_masks=env.action_masks(), deterministic=True) + obs, _, term, trunc, info = env.step(a) + done = term or trunc + out.append(info["stats"]) + env.close() + return out + + +def summary(name, stats): + w = np.mean([s["avg_wait"] for s in stats]) + r = np.mean([s["total_reward"] for s in stats]) + m = np.mean([s["makespan"] for s in stats]) + print(f"{name:12s} avg_wait {w:7.2f} makespan {m:7.1f} reward {r:9.1f}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--steps", type=int, default=100_000) + ap.add_argument("--envs", type=int, default=8) + ap.add_argument("--save", default="ppo_sched") + ap.add_argument("--device", default="auto", + help="torch device for the network: auto | cpu | cuda | mps") + args = ap.parse_args() + + venv = make_vec_env(make, n_envs=args.envs, seed=0) + model = MaskablePPO("MultiInputPolicy", venv, n_steps=256, batch_size=256, + gamma=0.99, verbose=1, seed=0, device=args.device) + model.learn(total_timesteps=args.steps) + model.save(args.save) + + seeds = list(range(1000, 1020)) + summary("ppo", evaluate(model, seeds)) + base = SchedEnv(**ENV_KW) + for p in ("fifo", "sjf", "best_fit", "random"): + summary(p, [base.run_policy(p, s) for s in seeds]) + + +if __name__ == "__main__": + main() diff --git a/python/examples/visualize.py b/python/examples/visualize.py new file mode 100644 index 0000000..02b136e --- /dev/null +++ b/python/examples/visualize.py @@ -0,0 +1,49 @@ +"""Visualize one episode of a built-in policy (or a trained SB3 model). + + zig build lib + PYTHONPATH=python python python/examples/visualize.py --policy sjf --out sjf.gif + PYTHONPATH=python python python/examples/visualize.py --policy fifo # live window + PYTHONPATH=python python python/examples/visualize.py --model ppo_sched.zip --out ppo.gif +""" + +import argparse + +from sched_env import SchedEnv +from sched_env.viz import animate, record + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--policy", default="sjf", help="fifo | fifo_strict | sjf | best_fit | random") + ap.add_argument("--model", help="MaskablePPO .zip to visualize instead of --policy") + ap.add_argument("--machines", default="deeprm:n=1") + ap.add_argument("--jobs", default="poisson:n=60,rate=0.8") + ap.add_argument("--res", type=int, default=2) + ap.add_argument("--ticks", type=int, default=20) + ap.add_argument("--pool", type=int, default=10) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--fps", type=int, default=6) + ap.add_argument("--out", help=".gif or .mp4 (default: live window)") + a = ap.parse_args() + + env = SchedEnv(machines=a.machines, jobs=a.jobs, n_res=a.res, n_ticks=a.ticks, + max_jobs=a.pool, max_ticks=5000) + if a.model: + from sb3_contrib import MaskablePPO + model = MaskablePPO.load(a.model) + policy = lambda e, o: model.predict(o, action_masks=e.action_masks(), deterministic=True)[0] + name = "ppo" + else: + policy, name = a.policy, a.policy + + frames = record(env, policy, seed=a.seed) + s = frames[-1].stats + print(f"{name}: {len(frames)} ticks, placed {s['placed']}/{s['arrived']}, " + f"avg wait {s['avg_wait']:.2f}, makespan {s['makespan']}, util {s['avg_util']:.1%}") + animate(env, frames, a.out, fps=a.fps, title=name) + if a.out: + print("saved", a.out) + + +if __name__ == "__main__": + main() diff --git a/python/requirements.txt b/python/requirements.txt new file mode 100644 index 0000000..efa61a7 --- /dev/null +++ b/python/requirements.txt @@ -0,0 +1,6 @@ +numpy>=1.26 +gymnasium>=1.0 +stable-baselines3>=2.3 +sb3-contrib>=2.3 +matplotlib>=3.8 +pillow>=10 diff --git a/python/sched_env/__init__.py b/python/sched_env/__init__.py new file mode 100644 index 0000000..fb409c1 --- /dev/null +++ b/python/sched_env/__init__.py @@ -0,0 +1,9 @@ +"""Gymnasium wrapper around the Zig scheduling simulator (libsched).""" + +import gymnasium as gym + +from .env import SchedEnv + +gym.register(id="Sched-v0", entry_point="sched_env.env:SchedEnv") + +__all__ = ["SchedEnv"] diff --git a/python/sched_env/_lib.py b/python/sched_env/_lib.py new file mode 100644 index 0000000..dfefb46 --- /dev/null +++ b/python/sched_env/_lib.py @@ -0,0 +1,110 @@ +"""ctypes bindings for libsched (src/app/capi.zig). Build it with `zig build lib`.""" + +from __future__ import annotations + +import ctypes as C +import os +import sys +from pathlib import Path + +import numpy as np + + +class SimConfig(C.Structure): + _fields_ = [ + ("machines", C.c_char_p), + ("jobs", C.c_char_p), + ("n_res", C.c_uint32), + ("n_ticks", C.c_uint32), + ("max_jobs", C.c_uint32), + ("reward", C.c_char_p), + ("max_ticks", C.c_int64), + ("illegal_penalty", C.c_float), + ("skip_empty", C.c_uint8), + ("drop_impossible", C.c_uint8), + ] + + +class SimDims(C.Structure): + _fields_ = [(n, C.c_uint32) for n in + ("n_machines", "n_res", "n_ticks", "max_jobs", "n_actions", "stride", "block", "max_cap", + "m_stride", "m_block")] + + +class SimStep(C.Structure): + _fields_ = [ + ("reward", C.c_float), + ("terminated", C.c_uint8), + ("truncated", C.c_uint8), + ("placed", C.c_uint8), + ("illegal", C.c_uint8), + ] + + +class SimStats(C.Structure): + _fields_ = [ + ("now", C.c_int64), ("arrived", C.c_uint64), ("placed", C.c_uint64), + ("rejected", C.c_uint64), ("illegal", C.c_uint64), ("steps", C.c_uint64), + ("waiting", C.c_uint64), ("makespan", C.c_int64), ("avg_wait", C.c_double), + ("max_wait", C.c_int64), ("avg_util", C.c_double), ("total_reward", C.c_double), + ] + + def to_dict(self) -> dict: + return {name: getattr(self, name) for name, _ in self._fields_} + + + +def _find_lib() -> Path: + if env := os.environ.get("SCHED_LIB"): + return Path(env) + name = {"darwin": "libsched.dylib", "win32": "sched.dll"}.get(sys.platform, "libsched.so") + root = Path(__file__).resolve().parents[2] # repo root + for p in (root / "zig-out" / "lib" / name, root / "zig-out" / "bin" / name): + if p.exists(): + return p + raise FileNotFoundError(f"{name} not found; run `zig build lib` in {root} or set SCHED_LIB") + + +def load() -> C.CDLL: + lib = C.CDLL(str(_find_lib())) + P = C.c_void_p + u16p = C.POINTER(C.c_uint16) + sig = { + "sim_create": ([C.POINTER(SimConfig)], P), + "sim_destroy": ([P], None), + "sim_reset": ([P, C.c_uint64], C.c_int), + "sim_dims": ([P, C.POINTER(SimDims)], None), + "sim_step": ([P, C.c_uint32, C.POINTER(SimStep)], C.c_int), + "sim_action_mask": ([P, C.c_void_p], None), + "sim_slot_valid": ([P, C.c_void_p], None), + "sim_machines_ptr": ([P], u16p), + "sim_machine_head": ([P], C.c_uint32), + "sim_capacity_ptr": ([P], u16p), + "sim_jobs_ptr": ([P], u16p), + "sim_duration_ptr": ([P], u16p), + "sim_arrival_ptr": ([P], C.POINTER(C.c_int64)), + "sim_now": ([P], C.c_int64), + "sim_trace_open": ([P, C.c_char_p], C.c_int), + "sim_trace_close": ([P], C.c_int), + "sim_stats": ([P, C.POINTER(SimStats)], None), + "sim_policy_action": ([P, C.c_char_p], C.c_int64), + "sim_run_policy": ([P, C.c_char_p, C.c_uint64, C.POINTER(SimStats)], C.c_int), + } + for name, (args, res) in sig.items(): + f = getattr(lib, name) + f.argtypes, f.restype = args, res + return lib + + +def grid_view(ptr, n_grids: int, d: SimDims, *, block=None, stride=None, offset=0) -> np.ndarray: + """Zero-copy (n_grids, n_res, n_ticks) uint16 view; strides skip the padding. + + Job pool: defaults. Machine pool: block=d.m_block, stride=d.m_stride, + offset=sim_machine_head (the view is only valid until time advances).""" + block = d.block if block is None else block + stride = d.stride if stride is None else stride + flat = np.ctypeslib.as_array(ptr, shape=(n_grids * block,)) + e = flat.itemsize + return np.lib.stride_tricks.as_strided( + flat[offset:], shape=(n_grids, d.n_res, d.n_ticks), + strides=(block * e, stride * e, e), writeable=False) diff --git a/python/sched_env/env.py b/python/sched_env/env.py new file mode 100644 index 0000000..414c92e --- /dev/null +++ b/python/sched_env/env.py @@ -0,0 +1,177 @@ +"""Gymnasium environment backed by the Zig engine.""" + +from __future__ import annotations + +import ctypes as C +from typing import Any + +import gymnasium as gym +import numpy as np +from gymnasium import spaces + +from . import _lib + + +class SchedEnv(gym.Env): + """Job-to-machine scheduling. + + Observation (Dict, float32, everything in [0, 1]): + machines (n_machines, n_res, n_ticks) free capacity / max_cap + jobs (max_jobs, n_res, n_ticks) demand / max_cap (0 = empty slot) + valid (max_jobs,) 1 if the slot holds a waiting job + wait (max_jobs,) ticks waited / n_ticks, clipped to 1 + + Action: Discrete(max_jobs * n_machines + 1) + a < max_jobs*n_machines -> place job slot a // n_machines on machine a % n_machines + a == max_jobs*n_machines -> wait (advance time one tick) + + `action_masks()` returns the legal actions (used by sb3_contrib MaskablePPO). + Illegal actions are penalized (`illegal_penalty`) and treated as wait. + """ + + metadata = {"render_modes": ["ansi"]} + + def __init__( + self, + machines: str = "deeprm:n=2", + jobs: str = "poisson:n=100,rate=0.5", + n_res: int = 2, + n_ticks: int = 20, + max_jobs: int = 10, + reward: str = "neg_in_system", + max_ticks: int | None = None, + illegal_penalty: float = -1.0, + skip_empty: bool = True, + drop_impossible: bool = True, + render_mode: str | None = None, + ): + self._lib = _lib.load() + self._spec = (machines.encode(), jobs.encode(), reward.encode()) # keep bytes alive + cfg = _lib.SimConfig( + self._spec[0], self._spec[1], n_res, n_ticks, max_jobs, self._spec[2], + -1 if max_ticks is None else max_ticks, illegal_penalty, int(skip_empty), int(drop_impossible)) + self._h = self._lib.sim_create(C.byref(cfg)) + if not self._h: + raise ValueError("sim_create failed (see stderr for the reason)") + + d = _lib.SimDims() + self._lib.sim_dims(self._h, C.byref(d)) + self.dims = d + self.render_mode = render_mode + + # zero-copy views into engine memory (always current) + self._mptr = self._lib.sim_machines_ptr(self._h) + self._jobs = _lib.grid_view(self._lib.sim_jobs_ptr(self._h), d.max_jobs, d) + self._arrival = np.ctypeslib.as_array(self._lib.sim_arrival_ptr(self._h), shape=(d.max_jobs,)) + self._valid = np.zeros(d.max_jobs, dtype=np.uint8) + self._mask = np.zeros(d.n_actions, dtype=np.uint8) + self._res = _lib.SimStep() + self._scale = 1.0 / max(1, d.max_cap) + + self.action_space = spaces.Discrete(d.n_actions) + self.observation_space = spaces.Dict({ + "machines": spaces.Box(0, 1, (d.n_machines, d.n_res, d.n_ticks), np.float32), + "jobs": spaces.Box(0, 1, (d.max_jobs, d.n_res, d.n_ticks), np.float32), + "valid": spaces.Box(0, 1, (d.max_jobs,), np.float32), + "wait": spaces.Box(0, 1, (d.max_jobs,), np.float32), + }) + + # ------------------------------------------------------------------ gym API + + def reset(self, *, seed: int | None = None, options: dict | None = None): + super().reset(seed=seed) + s = int(self.np_random.integers(0, 2**63)) if seed is None else seed + if self._lib.sim_reset(self._h, s) != 0: + raise RuntimeError("sim_reset failed") + return self._obs(), {} + + def step(self, action): + rc = self._lib.sim_step(self._h, int(action), C.byref(self._res)) + if rc != 0: + raise RuntimeError("step() after the episode ended; call reset()") + r = self._res + info = {"illegal": bool(r.illegal), "placed": bool(r.placed)} + if r.terminated or r.truncated: + info["stats"] = self.stats() + return self._obs(), float(r.reward), bool(r.terminated), bool(r.truncated), info + + def action_masks(self) -> np.ndarray: + self._lib.sim_action_mask(self._h, self._mask.ctypes.data) + return self._mask.astype(bool) + + def render(self): + s = self.stats() + return f"t={s['now']} waiting={s['waiting']} placed={s['placed']}/{s['arrived']}" + + def close(self): + if getattr(self, "_h", None): + self._lib.sim_destroy(self._h) + self._h = None + + def __del__(self): + self.close() + + # ------------------------------------------------------------------ extras + + def stats(self) -> dict[str, Any]: + st = _lib.SimStats() + self._lib.sim_stats(self._h, C.byref(st)) + return st.to_dict() + + def run_policy(self, name: str, seed: int) -> dict[str, Any]: + """Run a whole episode with a built-in Zig policy (fifo, sjf, best_fit, ...).""" + st = _lib.SimStats() + if self._lib.sim_run_policy(self._h, name.encode(), seed, C.byref(st)) != 0: + raise ValueError(f"unknown policy {name!r}") + return st.to_dict() + + @property + def _machines(self) -> np.ndarray: + """Zero-copy view of the machine horizon (rebuilt: the window head moves).""" + d = self.dims + return _lib.grid_view(self._mptr, d.n_machines, d, block=d.m_block, stride=d.m_stride, + offset=self._lib.sim_machine_head(self._h)) + + def start_trace(self, path: str) -> None: + """Write every following event to a JSON Lines trace (replay with + sched_env.replay). Call before reset() to capture whole episodes.""" + if self._lib.sim_trace_open(self._h, str(path).encode()) != 0: + raise OSError(f"cannot create trace file {path!r}") + + def stop_trace(self) -> None: + """Flush and close the trace file.""" + if self._lib.sim_trace_close(self._h) != 0: + raise OSError("writing the trace failed") + + def policy_action(self, name: str) -> int: + """Action a built-in Zig policy would take now (step it yourself).""" + a = self._lib.sim_policy_action(self._h, name.encode()) + if a < 0: + raise ValueError(f"unknown policy {name!r}") + return int(a) + + def capacity(self) -> np.ndarray: + """(n_machines, n_res) capacities.""" + d = self.dims + return np.ctypeslib.as_array(self._lib.sim_capacity_ptr(self._h), + shape=(d.n_machines * d.n_res,)).reshape(d.n_machines, d.n_res).copy() + + def raw(self) -> dict[str, np.ndarray]: + """Unnormalized current state (copies): free, jobs, duration, arrival, valid, now.""" + self._lib.sim_slot_valid(self._h, self._valid.ctypes.data) + dur = np.ctypeslib.as_array(self._lib.sim_duration_ptr(self._h), shape=(self.dims.max_jobs,)) + return {"free": self._machines.copy(), "jobs": self._jobs.copy(), "duration": dur.copy(), + "arrival": self._arrival.copy(), "valid": self._valid.astype(bool), + "now": self._lib.sim_now(self._h)} + + def _obs(self) -> dict[str, np.ndarray]: + self._lib.sim_slot_valid(self._h, self._valid.ctypes.data) + now = self._lib.sim_now(self._h) + valid = self._valid.astype(np.float32) + wait = np.clip((now - self._arrival) / self.dims.n_ticks, 0, 1).astype(np.float32) * valid + return { + "machines": self._machines.astype(np.float32) * self._scale, + "jobs": self._jobs.astype(np.float32) * self._scale, + "valid": valid, + "wait": wait, + } diff --git a/python/sched_env/replay.py b/python/sched_env/replay.py new file mode 100644 index 0000000..c16c2f9 --- /dev/null +++ b/python/sched_env/replay.py @@ -0,0 +1,164 @@ +"""Replay a trace file written by the `trace` observer — no simulator needed. + +Record: + zig build run -- --observe trace:path=run.jsonl ... (command line) + env.start_trace("run.jsonl"); env.reset(seed=0); ...; env.stop_trace() (Python) + +Replay: + from sched_env.replay import load_trace + from sched_env.viz import animate + episodes = load_trace("run.jsonl") + ep = episodes[0] + print(ep.stats) # placed, arrived, avg_wait, makespan, ... + animate(ep, ep.frames, "run.gif") # same visualization as a live run + +Each episode is rebuilt event by event into one Frame per tick (state at the +start of the tick, after arrivals), identical to what sched_env.viz.record +captures live with skip_empty=False. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +from .viz import Frame + + +@dataclass +class _Job: + id: int + slot: int + arrival: int + demand: np.ndarray # (n_res, dur) + + +@dataclass +class Episode: + seed: int + caps: np.ndarray # (n_machines, n_res) + dims: SimpleNamespace # n_machines, n_res, n_ticks, max_jobs, max_cap + frames: list[Frame] = field(default_factory=list) + placements: list[dict] = field(default_factory=list) # every "place" event + rejected: list[dict] = field(default_factory=list) + stats: dict = field(default_factory=dict) + truncated: bool = False + + +class _Rebuild: + """Mutable state while reading one episode.""" + + def __init__(self, ep: Episode): + self.ep = ep + self.now = 0 + self.waiting: dict[int, _Job] = {} # slot -> job + self.running: list[tuple[int, int, np.ndarray]] = [] # (machine, start, demand) + self.arrived = self.placed = self.illegal = 0 + self.total_wait = 0 + self.max_wait = 0 + self.makespan = 0 + self.util_sum = 0.0 + self.placed_now = 0 + self.started = False # first frame (tick 0) taken? + + def stats(self) -> dict: + n = max(1, len(self.ep.frames)) + return { + "now": self.now, "arrived": self.arrived, "placed": self.placed, + "rejected": len(self.ep.rejected), "illegal": self.illegal, + "waiting": len(self.waiting), "makespan": self.makespan, + "avg_wait": self.total_wait / self.placed if self.placed else 0.0, + "max_wait": self.max_wait, "avg_util": self.util_sum / n, + } + + def snapshot(self) -> None: + d = self.ep.dims + nm, nr, nt = d.n_machines, d.n_res, d.n_ticks + self.running = [r for r in self.running if r[1] + r[2].shape[1] > self.now] + used = np.zeros((nm, nr, nt), dtype=np.float32) + for m, start, dem in self.running: + off = self.now - start # ticks already run + k = min(nt, dem.shape[1] - off) + used[m, :, :k] += dem[:, off:off + k] + used /= np.maximum(self.ep.caps, 1)[:, :, None] + pool = np.full((d.max_jobs, nr, nt), np.nan, dtype=np.float32) + wait = np.full(d.max_jobs, -1) + for s, j in self.waiting.items(): + pool[s, :, :j.demand.shape[1]] = j.demand / max(1, d.max_cap) + wait[s] = self.now - j.arrival + self.util_sum += float(used[:, :, 0].mean()) + self.ep.frames.append(Frame(self.now, used, pool.reshape(-1, nt), wait, 0, {})) + self.ep.frames[-1].stats = self.stats() + + def flush_placed(self) -> None: + if self.ep.frames: + self.ep.frames[-1].placed_now += self.placed_now + self.ep.frames[-1].stats = {**self.stats(), "now": self.ep.frames[-1].now, + "waiting": self.ep.frames[-1].stats["waiting"]} + self.placed_now = 0 + + def event(self, e: dict) -> None: + ty = e["type"] + if ty in ("arrive", "reject"): + if ty == "arrive": + dem = np.asarray(e["demand"], dtype=np.float32).reshape(self.ep.dims.n_res, e["dur"]) + self.waiting[e["slot"]] = _Job(e["id"], e["slot"], e["t"], dem) + self.arrived += 1 + else: + self.ep.rejected.append(e) + return + if not self.started: # arrivals at tick 0 are in: that is frame 0 + self.started = True + self.snapshot() + if ty == "place": + j = self.waiting.pop(e["slot"]) + self.running.append((e["machine"], e["t"], j.demand)) + w = e["t"] - e["arrival"] + self.placed += 1 + self.placed_now += 1 + self.total_wait += w + self.max_wait = max(self.max_wait, w) + self.makespan = max(self.makespan, e["t"] + e["dur"]) + self.ep.placements.append(e) + elif ty == "illegal": + self.illegal += 1 + elif ty == "tick": + self.flush_placed() + self.now = e["t"] + self.snapshot() + elif ty == "done": + self.flush_placed() + self.now = e["t"] + self.ep.truncated = bool(e["truncated"]) + self.ep.stats = self.stats() + + +def load_trace(path: str | Path) -> list[Episode]: + """Read every episode of a trace file.""" + episodes: list[Episode] = [] + rb: _Rebuild | None = None + with open(path) as f: + for line in f: + if not line.strip(): + continue + e = json.loads(line) + if e["type"] == "episode": + if e.get("v", 1) != 1: + raise ValueError(f"unsupported trace version {e.get('v')}") + caps = np.asarray(e["caps"], dtype=np.int64) + dims = SimpleNamespace(n_machines=caps.shape[0], n_res=e["n_res"], n_ticks=e["n_ticks"], + max_jobs=e["max_jobs"], max_cap=int(caps.max())) + episodes.append(Episode(e["seed"], caps, dims)) + rb = _Rebuild(episodes[-1]) + elif rb is None: + raise ValueError("trace does not start with an episode line") + else: + rb.event(e) + for ep in episodes: # episode cut short (file not closed / truncated write) + if not ep.stats and ep.frames: + ep.stats = ep.frames[-1].stats + return episodes diff --git a/python/sched_env/viz.py b/python/sched_env/viz.py new file mode 100644 index 0000000..9e0e28d --- /dev/null +++ b/python/sched_env/viz.py @@ -0,0 +1,178 @@ +"""Matplotlib visualization of a scheduling episode. + + from sched_env import SchedEnv + from sched_env.viz import record, animate + env = SchedEnv(machines="deeprm:n=2", jobs="poisson:n=60,rate=1.0") + frames = record(env, policy="sjf", seed=0) # or policy=callable(env, obs) -> action + animate(env, frames, "sjf.gif") # or path=None for a live window + +One frame per tick, taken at the start of the tick (after arrivals, before +the policy's placements), annotated with how many jobs it then placed: + * one heatmap per machine: used capacity [resource × future tick], 0 = now + * the waiting pool: each slot's demand per resource over its duration + * time series: waiting jobs, jobs placed this tick, utilization now +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Callable + +import numpy as np + +from .env import SchedEnv + + +@dataclass +class Frame: + now: int + used: np.ndarray # (n_machines, n_res, n_ticks) used / capacity in [0, 1] + pool: np.ndarray # (max_jobs * n_res, n_ticks) demand / max_cap, row = slot*n_res + r; NaN = empty + wait: np.ndarray # (max_jobs,) ticks waited, -1 for empty + placed_now: int + stats: dict = field(default_factory=dict) + + +def _frame(env: SchedEnv, cap: np.ndarray, placed_now: int) -> Frame: + r = env.raw() + c = np.maximum(cap, 1)[:, :, None].astype(np.float32) + used = (cap[:, :, None] - r["free"]) / c + pool = r["jobs"].astype(np.float32) / max(1, env.dims.max_cap) # (slots, res, ticks) + pool[~r["valid"]] = np.nan + for s in np.flatnonzero(r["valid"]): + pool[s, :, r["duration"][s]:] = np.nan + pool = pool.reshape(-1, pool.shape[-1]) + wait = np.where(r["valid"], r["now"] - r["arrival"], -1) + return Frame(r["now"], used, pool, wait, placed_now, env.stats()) + + +def record(env: SchedEnv, policy: str | Callable = "sjf", seed: int = 0, + max_frames: int = 5000) -> list[Frame]: + """Run one episode and capture a frame per tick. + + policy: a built-in Zig policy name (fifo, fifo_strict, sjf, best_fit, + random) or a callable (env, obs) -> action, e.g. a trained SB3 model: + lambda e, o: model.predict(o, action_masks=e.action_masks(), deterministic=True)[0] + """ + cap = env.capacity() + obs, _ = env.reset(seed=seed) + wait_a = env.action_space.n - 1 + frames, done = [_frame(env, cap, 0)], False + while not done and len(frames) < max_frames: + a = env.policy_action(policy) if isinstance(policy, str) else int(policy(env, obs)) + obs, _, term, trunc, info = env.step(a) + done = term or trunc + if a == wait_a or done: # a new tick starts + frames.append(_frame(env, cap, 0)) + else: + frames[-1].placed_now += int(info["placed"]) + return frames + + +def animate(env: SchedEnv, frames: list[Frame], path: str | None = None, + fps: int = 6, title: str = ""): + """Animate frames. path ending in .gif / .mp4 saves; None shows a window.""" + import matplotlib.pyplot as plt + from matplotlib import animation + + d = env.dims + nm = d.n_machines + nr = d.n_res + pool_h = 1.3 * max(1.0, d.max_jobs * nr / 20) + fig = plt.figure(figsize=(3.2 * max(nm, 2) + 4, 6.2 + pool_h), constrained_layout=True) + gs = fig.add_gridspec(3, max(nm, 2), height_ratios=[1.1, pool_h, 1]) + + cmap = plt.get_cmap("viridis").copy() + cmap.set_bad("#eeeeee") + mach_im = [] + for m in range(nm): + ax = fig.add_subplot(gs[0, m]) + im = ax.imshow(frames[0].used[m], vmin=0, vmax=1, cmap="magma_r", aspect="auto", + interpolation="nearest") + ax.set_title(f"machine {m}: used / cap") + ax.set_xlabel("ticks ahead") + ax.set_ylabel("resource") + ax.set_yticks(range(d.n_res)) + mach_im.append(im) + fig.colorbar(mach_im[-1], ax=fig.axes[:nm], shrink=0.8) + + axp = fig.add_subplot(gs[1, :]) + pool_im = axp.imshow(frames[0].pool, vmin=0, vmax=1, cmap=cmap, aspect="auto", + interpolation="nearest") + axp.set_title("waiting pool: demand / max cap per resource over the job's duration, grey = empty") + axp.set_xlabel("job tick") + axp.set_ylabel("slot / resource") + axp.set_yticks([s * nr + (nr - 1) / 2 for s in range(d.max_jobs)], + [f"slot {s}" for s in range(d.max_jobs)]) + axp.set_yticks(range(d.max_jobs * nr), [f"r{r}" for _ in range(d.max_jobs) for r in range(nr)], + minor=True) + axp.tick_params(axis="y", which="major", pad=18, length=0) + axp.tick_params(axis="y", which="minor", labelsize=6, length=2) + for s in range(1, d.max_jobs): + axp.axhline(s * nr - 0.5, color="white", lw=2) + fig.colorbar(pool_im, ax=axp, shrink=0.8) + wait_txt = [axp.text(d.n_ticks - 0.5, s * nr + (nr - 1) / 2, "", ha="right", va="center", + fontsize=7, color="k") for s in range(d.max_jobs)] + + axt = fig.add_subplot(gs[2, :]) + t = np.array([f.now for f in frames]) + waiting = np.array([f.stats["waiting"] for f in frames]) + placed = np.array([f.placed_now for f in frames]) + util = np.array([f.used[:, :, 0].mean() for f in frames]) + axt.plot(t, waiting, color="tab:red", lw=1, alpha=.35) + axt.bar(t, placed, color="tab:green", alpha=.35, width=1.0) + (lw,) = axt.plot([], [], color="tab:red", lw=2, label="waiting") + (lp,) = axt.plot([], [], color="tab:green", lw=0, marker="|", ms=10, label="placed this tick") + axt.set_xlabel("tick") + axt.xaxis.get_major_locator().set_params(integer=True) + axt.yaxis.get_major_locator().set_params(integer=True) + axt.set_ylabel("jobs") + axu = axt.twinx() + axu.plot(t, util, color="tab:blue", lw=1, alpha=.35) + (lu,) = axu.plot([], [], color="tab:blue", lw=2, label="utilization") + axu.set_ylim(0, 1.05) + axu.set_ylabel("utilization now") + cursor = axt.axvline(t[0], color="k", lw=1) + axt.legend(handles=[lw, lp, lu], loc="upper right", fontsize=8) + head = fig.suptitle("") + + def update(i): + f = frames[i] + for m, im in enumerate(mach_im): + im.set_data(f.used[m]) + pool_im.set_data(f.pool) + for s, txt in enumerate(wait_txt): + txt.set_text(f"wait {f.wait[s]}" if f.wait[s] >= 0 else "") + lw.set_data(t[: i + 1], waiting[: i + 1]) + lp.set_data(t[: i + 1], placed[: i + 1]) + lu.set_data(t[: i + 1], util[: i + 1]) + cursor.set_xdata([f.now, f.now]) + s = f.stats + head.set_text(f"{title} tick {f.now} placed {s['placed']}/{s['arrived']} " + f"waiting {s['waiting']} avg wait {s['avg_wait']:.2f}") + return [*mach_im, pool_im, lw, lp, lu, cursor, head, *wait_txt] + + anim = animation.FuncAnimation(fig, update, frames=len(frames), interval=1000 / fps, blit=False) + if path is None: + plt.show() + elif path.endswith(".gif"): + anim.save(path, writer=animation.PillowWriter(fps=fps)) + else: + anim.save(path, fps=fps) + return anim + + +def snapshot(env: SchedEnv, frame: Frame, path: str, title: str = ""): + """Save a single frame as a PNG.""" + import matplotlib.pyplot as plt + d = env.dims + fig, axes = plt.subplots(1, d.n_machines + 1, figsize=(3.2 * (d.n_machines + 1), 3), + constrained_layout=True) + for m in range(d.n_machines): + axes[m].imshow(frame.used[m], vmin=0, vmax=1, cmap="magma_r", aspect="auto") + axes[m].set_title(f"machine {m}") + axes[-1].imshow(frame.pool, vmin=0, vmax=1, aspect="auto") + axes[-1].set_title("waiting pool") + fig.suptitle(f"{title} tick {frame.now}") + fig.savefig(path) + plt.close(fig) diff --git a/python/tests/test_env.py b/python/tests/test_env.py new file mode 100644 index 0000000..8de9756 --- /dev/null +++ b/python/tests/test_env.py @@ -0,0 +1,138 @@ +"""Smoke tests for the Python binding: PYTHONPATH=python pytest python/tests""" + +import numpy as np +from gymnasium.utils.env_checker import check_env + +from sched_env import SchedEnv + +KW = dict(machines="deeprm:n=2", jobs="poisson:n=30,rate=0.5", n_res=2, n_ticks=20, max_jobs=8) + + +def test_check_env(): + env = SchedEnv(**KW) + check_env(env, skip_render_check=True) + env.close() + + +def test_masked_episode_places_every_job(): + env = SchedEnv(**KW) + obs, _ = env.reset(seed=1) + assert env.observation_space.contains(obs) + done = False + while not done: + mask = env.action_masks() + assert mask[-1] # wait is always legal + a = int(np.flatnonzero(mask)[0]) + obs, r, term, trunc, info = env.step(a) + assert not info["illegal"] + done = term or trunc + assert info["stats"]["placed"] == info["stats"]["arrived"] + env.close() + + +def test_builtin_policy_and_determinism(): + env = SchedEnv(**KW) + a = env.run_policy("sjf", 7) + b = env.run_policy("sjf", 7) + assert a == b and a["placed"] == a["arrived"] + env.close() + + +def test_policy_action_matches_run_policy(): + env = SchedEnv(**KW) + want = env.run_policy("sjf", 3) + env.reset(seed=3) + done = False + while not done: + _, _, term, trunc, info = env.step(env.policy_action("sjf")) + done = term or trunc + assert info["stats"]["avg_wait"] == want["avg_wait"] + assert info["stats"]["makespan"] == want["makespan"] + env.close() + + +def test_viz_record_and_render(tmp_path): + import matplotlib + matplotlib.use("Agg") + from sched_env.viz import animate, record + + env = SchedEnv(**KW) + frames = record(env, "sjf", seed=0) + assert len(frames) > 1 + assert sum(f.placed_now for f in frames) == frames[-1].stats["placed"] + assert all(0 <= f.used.min() and f.used.max() <= 1 for f in frames) + animate(env, frames[:5], str(tmp_path / "a.gif"), fps=10) + assert (tmp_path / "a.gif").stat().st_size > 0 + env.close() + + +def test_machine_view_follows_sliding_window(): + # long episode → the window compacts several times + env = SchedEnv(**{**KW, "jobs": "poisson:n=150,rate=0.4"}) + cap = env.capacity() + obs, _ = env.reset(seed=2) + done, ticks = False, 0 + while not done: + free = env.raw()["free"] + assert (free <= cap[:, :, None]).all() + a = env.policy_action("fifo") + ticks += a == env.action_space.n - 1 + obs, _, term, trunc, _ = env.step(a) + done = term or trunc + assert ticks > 5 * KW["n_ticks"] + assert np.allclose(obs["machines"], cap[:, :, None] / env.dims.max_cap) # all jobs finished → empty + env.close() + + +def test_reward_specs_and_new_adapters(): + # slowdown reward sums to minus the total slowdown of finished jobs + env = SchedEnv(**{**KW, "reward": "slowdown"}) + env.reset(seed=4) + total, done = 0.0, False + while not done: + _, r, term, trunc, info = env.step(env.policy_action("tetris")) + total += r + done = term or trunc + assert total < 0 and info["stats"]["placed"] == info["stats"]["arrived"] + env.close() + for jobs in ("mmpp:n=50,rate=0.5", "pareto:n=50,rate=0.5,alpha=1.3", "selfsimilar:n=50,rate=0.5"): + e = SchedEnv(**{**KW, "jobs": jobs}) + st = e.run_policy("tetris", 1) + assert st["placed"] == st["arrived"] > 0 + e.close() + import pytest + with pytest.raises(ValueError): + SchedEnv(**{**KW, "reward": "nope"}) + + +def test_trace_replay_matches_live_run(tmp_path): + import matplotlib + matplotlib.use("Agg") + from sched_env.replay import load_trace + from sched_env.viz import animate, record + + kw = {**KW, "jobs": "mmpp:n=40,rate=0.8", "skip_empty": False} + env = SchedEnv(**kw) + path = tmp_path / "run.jsonl" + env.start_trace(str(path)) + live = record(env, "sjf", seed=5) # episode 1 + record(env, "fifo", seed=6) # episode 2 in the same file + env.stop_trace() + env.close() + + eps = load_trace(path) + assert [e.seed for e in eps] == [5, 6] + rep = eps[0].frames + assert len(rep) == len(live) + for a, b in zip(live, rep): + assert a.now == b.now + np.testing.assert_allclose(a.used, b.used, atol=1e-6) + np.testing.assert_allclose(a.pool, b.pool, atol=1e-6) # NaN where empty, both sides + assert (a.wait == b.wait).all() + assert a.placed_now == b.placed_now + s, want = eps[0].stats, live[-1].stats + for k in ("placed", "arrived", "makespan", "max_wait"): + assert s[k] == want[k], k + assert abs(s["avg_wait"] - want["avg_wait"]) < 1e-9 + animate(eps[1], eps[1].frames[:4], str(tmp_path / "r.gif"), fps=10) + diff --git a/readme.md b/readme.md index e69de29..02219f5 100644 --- a/readme.md +++ b/readme.md @@ -0,0 +1,108 @@ +# sched + +A SIMD job-to-machine scheduling simulator in Zig, built for comparing +scheduling policies (heuristics now, reinforcement learning via Gymnasium +later). + +Jobs and machines are `[resource][tick]` grids. Placing a job subtracts its +profile from a machine's free capacity; the fit test is a SIMD comparison of +two rows. When nothing can be placed, time advances: machine grids shift one +tick left. + +Requires **Zig 0.17**. + +## Quick start + +```bash +zig build test # unit + integration tests +zig build run -- --observe viz # animated terminal view +zig build run -Doptimize=ReleaseFast -- --observe metrics +zig build bench # SIMD + engine benchmarks +zig build example # custom policy example +zig build lib # libsched for Python / Gymnasium +``` + +## Python / Stable-Baselines3 + +```bash +zig build lib +pip install -r python/requirements.txt +PYTHONPATH=python python python/examples/train_sb3.py --steps 100000 +PYTHONPATH=python python python/examples/visualize.py --policy sjf --out sjf.gif +``` + +```python +from sched_env import SchedEnv +env = SchedEnv(machines="deeprm:n=1", jobs="poisson:n=60,rate=0.7", + n_res=2, n_ticks=20, max_jobs=10) +obs, _ = env.reset(seed=0) +obs, reward, terminated, truncated, info = env.step(env.action_space.n - 1) # wait +``` + +Dict observation (machine and job grids, zero-copy from Zig), +`Discrete(max_jobs·n_machines + 1)` actions, `env.action_masks()` for +`MaskablePPO`. Details in [docs/python.md](docs/python.md). + +## Command line + +``` +sim [options] + --machines usage generator (default random) + --jobs arrival source (default poisson) + --policy scheduling policy (default fifo) + --observe observer, repeatable (viz, metrics, log) + --res --ticks --pool --seed --episodes + --reward neg_in_system|neg_waiting|slowdown|zero --max-ticks + --list all adapters and their options +``` + +A spec is `name:key=value,key=value`, for example: + +```bash +zig build run -- --machines random:n=8,caps=100/50,dur=1-10,varying=1 \ + --jobs poisson:n=1000,rate=1.5 --policy best_fit \ + --observe viz:delay=30,per_resource=1 --observe metrics +zig build run -- --machines deeprm:n=2 --res 2 --ticks 30 --policy sjf +``` + +| Kind | Adapters | +|---|---| +| 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` | +| Rewards | `neg_in_system` (default), `neg_waiting`, `slowdown` (DeepRM), `zero` | +| Observers | `viz`, `metrics`, `log`, `trace` (JSON Lines for offline replay) | + +## Build options + +| Option | Meaning | Default | +|---|---|---| +| `-Dlanes=` | CPU SIMD lanes | target CPU | +| `-Dcache-line=` | CPU cache line | target arch | +| `-Dgpu-warp=` | GPU threads per warp (padding rule) | 32 | +| `-Dgpu-align=` | GPU grid alignment | 256 | + +## Layout + +``` +src/ + root.zig library API (module "sched") + grid/ aligned grids, SIMD, CPU/GPU padding rules + model/ machines, jobs, State / Action / Event + ports/ Policy, Observer, UsageGenerator, ArrivalSource + engine/ rules (legality, default reward, action encoding) and the step loop + adapters/ policies, arrivals, generators, observers + app/ command line, registry, main, capi (C ABI for Python) +tests/ integration tests +bench/ simd_bench, engine_bench +examples/ custom_policy +python/ sched_env (Gymnasium env), examples/train_sb3.py, tests +docs/ guide, python, architecture, data-layout +``` + +## Documentation + +- [docs/guide.md](docs/guide.md) — model, command line, metrics, writing policies and adapters +- [docs/python.md](docs/python.md) — Python binding, Gymnasium env, Stable-Baselines3 +- [docs/architecture.md](docs/architecture.md) — layers, ports, step semantics +- [docs/data-layout.md](docs/data-layout.md) — grids, padding, SIMD diff --git a/src/adapters.zig b/src/adapters.zig new file mode 100644 index 0000000..af8d816 --- /dev/null +++ b/src/adapters.zig @@ -0,0 +1,50 @@ +//! Adapters: concrete implementations of the ports. +pub const policies = struct { + pub const FifoBackfill = @import("adapters/policies/fifo_backfill.zig").FifoBackfill; + pub const FifoStrict = @import("adapters/policies/fifo_strict.zig").FifoStrict; + pub const ShortestFirst = @import("adapters/policies/sjf.zig").ShortestFirst; + pub const BestFit = @import("adapters/policies/best_fit.zig").BestFit; + 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 arrivals = struct { + pub const Fixed = @import("adapters/arrivals/fixed.zig").Fixed; + pub const Poisson = @import("adapters/arrivals/poisson.zig").Poisson; + pub const Mmpp = @import("adapters/arrivals/mmpp.zig").Mmpp; + pub const ParetoArrivals = @import("adapters/arrivals/pareto.zig").ParetoArrivals; + pub const SelfSimilar = @import("adapters/arrivals/self_similar.zig").SelfSimilar; +}; + +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 rewards = struct { + pub const NegInSystem = @import("adapters/rewards/basic.zig").NegInSystem; + pub const NegWaiting = @import("adapters/rewards/basic.zig").NegWaiting; + pub const Zero = @import("adapters/rewards/basic.zig").Zero; + pub const Slowdown = @import("adapters/rewards/slowdown.zig").Slowdown; +}; + +pub const observers = struct { + pub const TerminalViz = @import("adapters/observers/terminal_viz.zig").TerminalViz; + pub const VizOptions = @import("adapters/observers/terminal_viz.zig").Options; + pub const Metrics = @import("adapters/observers/metrics.zig").Metrics; + pub const EventLog = @import("adapters/observers/event_log.zig").EventLog; + pub const Trace = @import("adapters/observers/trace.zig").Trace; +}; + +test { + _ = @import("adapters/arrivals/poisson.zig"); + _ = @import("adapters/arrivals/sample.zig"); + _ = @import("adapters/observers/trace.zig"); + _ = @import("adapters/arrivals/burst_test.zig"); + @import("std").testing.refAllDecls(rewards); + @import("std").testing.refAllDecls(policies); + @import("std").testing.refAllDecls(arrivals); + @import("std").testing.refAllDecls(generators); + @import("std").testing.refAllDecls(observers); +} diff --git a/src/adapters/.gitkeep b/src/adapters/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/adapters/arrivals/burst_test.zig b/src/adapters/arrivals/burst_test.zig new file mode 100644 index 0000000..3bd8926 --- /dev/null +++ b/src/adapters/arrivals/burst_test.zig @@ -0,0 +1,94 @@ +//! Statistical checks for the arrival sources: mean rate, determinism, +//! and burstiness (index of dispersion = Var/Mean of counts per window; +//! Poisson ≈ 1, bursty sources ≫ 1, self-similar keeps growing with the +//! window size). +const std = @import("std"); +const Poisson = @import("poisson.zig").Poisson; +const Mmpp = @import("mmpp.zig").Mmpp; +const ParetoArrivals = @import("pareto.zig").ParetoArrivals; +const SelfSimilar = @import("self_similar.zig").SelfSimilar; + +const N = 60_000; +const RATE = 1.0; + +/// Counts per tick for one run; returns the number of ticks used. +fn counts(src: anytype, seed: u64, out: []u32) !usize { + src.reset(seed); + @memset(out, 0); + var now: i64 = 0; + var last: i64 = -1; + while (!src.done()) : (now += 1) { + while (try src.next(now)) |m| { + try std.testing.expect(m.arrival <= now and m.arrival >= last); + last = m.arrival; + out[@intCast(m.arrival)] += 1; + } + } + return @intCast(now); +} + +fn dispersion(c: []const u32, window: usize) f64 { + const n = c.len / window; + var sum: f64 = 0; + var sq: f64 = 0; + for (0..n) |w| { + var x: f64 = 0; + for (c[w * window ..][0..window]) |v| x += @floatFromInt(v); + sum += x; + sq += x * x; + } + const mean = sum / @as(f64, @floatFromInt(n)); + return (sq / @as(f64, @floatFromInt(n)) - mean * mean) / mean; +} + +const Result = struct { rate: f64, d1: f64, d10: f64, d100: f64, d1000: f64 }; + +fn measure(src: anytype) !Result { + const buf = try std.testing.allocator.alloc(u32, 4 * N); + defer std.testing.allocator.free(buf); + const ticks = try counts(src, 7, buf); + // determinism + const buf2 = try std.testing.allocator.alloc(u32, 4 * N); + defer std.testing.allocator.free(buf2); + _ = try counts(src, 7, buf2); + try std.testing.expectEqualSlices(u32, buf, buf2); + const c = buf[0..ticks]; + return .{ + .rate = @as(f64, @floatFromInt(N)) / @as(f64, @floatFromInt(ticks)), + .d1 = dispersion(c, 1), + .d10 = dispersion(c, 10), + .d100 = dispersion(c, 100), + .d1000 = dispersion(c, 1000), + }; +} + +test "arrivals: mean rate, determinism and burstiness" { + var p = Poisson{ .total = N, .rate = RATE }; + var m = Mmpp{ .total = N, .rate = RATE }; + var h = ParetoArrivals{ .total = N, .rate = RATE, .alpha = 1.3 }; + var s = SelfSimilar{ .total = N, .rate = RATE }; + const rp = try measure(&p); + const rm = try measure(&m); + const rh = try measure(&h); + const rs = try measure(&s); + + // every source honours the mean rate (heavy tails converge slowly) + try std.testing.expectApproxEqRel(RATE, rp.rate, 0.05); + try std.testing.expectApproxEqRel(RATE, rm.rate, 0.15); + try std.testing.expectApproxEqRel(RATE, rh.rate, 0.25); + try std.testing.expectApproxEqRel(RATE, rs.rate, 0.15); + + // Poisson: dispersion ≈ 1 at every time scale + try std.testing.expectApproxEqAbs(@as(f64, 1), rp.d1, 0.1); + try std.testing.expect(rp.d1000 < 1.5); + // MMPP: bursty, but short-range — dispersion grows, then levels off + try std.testing.expect(rm.d10 > 3); + try std.testing.expect(rm.d1000 < 2 * rm.d100); + // heavy-tailed gaps: bursty and still growing at long scales + try std.testing.expect(rh.d1000 > 2 * rh.d100); + // self-similar: dispersion keeps growing with the window (long-range + // dependence; d(m) ~ m^(2H-1), H = 0.8 for alpha = 1.4) + try std.testing.expect(rs.d10 < rs.d100 and rs.d100 < rs.d1000); + try std.testing.expect(rs.d1000 > 2 * rs.d100); + try std.testing.expect(rs.d1000 > 10); +} diff --git a/src/adapters/arrivals/fixed.zig b/src/adapters/arrivals/fixed.zig new file mode 100644 index 0000000..92acbf7 --- /dev/null +++ b/src/adapters/arrivals/fixed.zig @@ -0,0 +1,24 @@ +//! Fixed: a hard-coded list of jobs (sorted by arrival). For tests and +//! reproducing specific scenarios. +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").arrival_source.Error; + +pub const Fixed = struct { + items: []const model.JobMeta, + i: usize = 0, + + pub fn next(self: *Fixed, now: i64) Error!?model.JobMeta { + if (self.i < self.items.len and self.items[self.i].arrival <= now) { + defer self.i += 1; + return self.items[self.i]; + } + return null; + } + pub fn done(self: *Fixed) bool { + return self.i == self.items.len; + } + pub fn reset(self: *Fixed, seed: u64) void { + _ = seed; + self.i = 0; + } +}; diff --git a/src/adapters/arrivals/mmpp.zig b/src/adapters/arrivals/mmpp.zig new file mode 100644 index 0000000..1627411 --- /dev/null +++ b/src/adapters/arrivals/mmpp.zig @@ -0,0 +1,67 @@ +//! Bursty arrivals: a two-state Markov-modulated Poisson process (MMPP-2). +//! The source alternates between a calm state and a burst state; state +//! lengths are geometric with means `calm` and `burst_len` ticks; arrivals +//! per tick are Poisson with the state's rate. The burst rate is `ratio` +//! times the calm rate, and both are chosen so the long-run mean is `rate` +//! jobs per tick: +//! +//! low = rate·(calm + burst_len) / (calm + ratio·burst_len) +//! high = ratio · low +//! +//! Short-range bursty (correlations die out after a few state changes); +//! compare `selfsimilar` for bursts at every time scale. +const std = @import("std"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").arrival_source.Error; +const sample = @import("sample.zig"); + +pub const Mmpp = struct { + total: usize, + rate: f64, + ratio: f64 = 10, + calm: f64 = 40, + burst_len: f64 = 10, + prng: std.Random.DefaultPrng = .init(0), + generated: usize = 0, + cur: i64 = 0, // tick whose arrivals are pending + pending: usize = 0, + in_burst: bool = false, + + pub fn reset(self: *Mmpp, seed: u64) void { + self.prng = .init(seed +% 12); + self.generated = 0; + self.cur = 0; + // start in the stationary distribution + self.in_burst = self.prng.random().float(f64) < self.burst_len / (self.calm + self.burst_len); + self.pending = self.draw(); + } + + fn draw(self: *Mmpp) usize { + const r = self.prng.random(); + const low = self.rate * (self.calm + self.burst_len) / (self.calm + self.ratio * self.burst_len); + const n = sample.poisson(r, if (self.in_burst) self.ratio * low else low); + // state change at the end of the tick + const mean = if (self.in_burst) self.burst_len else self.calm; + if (r.float(f64) < 1.0 / @max(1.0, mean)) self.in_burst = !self.in_burst; + return n; + } + + pub fn next(self: *Mmpp, now: i64) Error!?model.JobMeta { + if (self.rate <= 0 or self.ratio < 1) return error.InvalidInput; + while (self.generated < self.total and self.cur <= now) { + if (self.pending > 0) { + self.pending -= 1; + const meta = model.JobMeta{ .id = @intCast(self.generated), .arrival = self.cur }; + self.generated += 1; + return meta; + } + self.cur += 1; + self.pending = self.draw(); + } + return null; + } + + pub fn done(self: *Mmpp) bool { + return self.generated >= self.total; + } +}; diff --git a/src/adapters/arrivals/pareto.zig b/src/adapters/arrivals/pareto.zig new file mode 100644 index 0000000..2d5893a --- /dev/null +++ b/src/adapters/arrivals/pareto.zig @@ -0,0 +1,38 @@ +//! Heavy-tailed arrivals: `total` jobs, inter-arrival gaps ~ Pareto(alpha) +//! with mean 1/rate ticks. Same mean rate as Poisson, but with α ≤ 2 the +//! gap variance is infinite: long silences followed by dense clusters. +//! α → ∞ approaches evenly spaced arrivals; α ≈ 1.2–1.6 is very bursty. +const std = @import("std"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").arrival_source.Error; +const sample = @import("sample.zig"); + +pub const ParetoArrivals = struct { + total: usize, + rate: f64, + alpha: f64 = 1.5, + prng: std.Random.DefaultPrng = .init(0), + generated: usize = 0, + t: f64 = 0, + + pub fn reset(self: *ParetoArrivals, seed: u64) void { + self.prng = .init(seed +% 11); + self.generated = 0; + self.t = 0; + } + + pub fn next(self: *ParetoArrivals, now: i64) Error!?model.JobMeta { + if (self.generated >= self.total) return null; + if (self.rate <= 0 or self.alpha <= 1) return error.InvalidInput; + const at: i64 = @intFromFloat(@floor(self.t)); + if (at > now) return null; + const meta = model.JobMeta{ .id = @intCast(self.generated), .arrival = at }; + self.generated += 1; + self.t += sample.pareto(self.prng.random(), self.alpha, 1.0 / self.rate); + return meta; + } + + pub fn done(self: *ParetoArrivals) bool { + return self.generated >= self.total; + } +}; diff --git a/src/adapters/arrivals/poisson.zig b/src/adapters/arrivals/poisson.zig new file mode 100644 index 0000000..ed0dd2b --- /dev/null +++ b/src/adapters/arrivals/poisson.zig @@ -0,0 +1,57 @@ +//! Poisson arrivals: `total` jobs, exponential inter-arrival gaps with mean +//! 1/rate ticks (rate = expected jobs per tick). Several jobs can arrive in +//! the same tick. rate = 0 → all jobs at tick 0 (batch). +const std = @import("std"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").arrival_source.Error; + +pub const Poisson = struct { + total: usize, + rate: f64, + prng: std.Random.DefaultPrng = .init(0), + generated: usize = 0, + t: f64 = 0, // continuous arrival clock + + pub fn reset(self: *Poisson, seed: u64) void { + self.prng = .init(seed); + self.generated = 0; + self.t = 0; + } + + pub fn next(self: *Poisson, now: i64) Error!?model.JobMeta { + if (self.generated >= self.total) return null; + const at: i64 = @intFromFloat(@floor(self.t)); + if (at > now) return null; + const meta = model.JobMeta{ .id = @intCast(self.generated), .arrival = at }; + self.generated += 1; + if (self.rate > 0) self.t += self.prng.random().floatExp(f64) / self.rate; + return meta; + } + + pub fn done(self: *Poisson) bool { + return self.generated >= self.total; + } +}; + +test "poisson: count, order, determinism" { + var p = Poisson{ .total = 50, .rate = 0.7 }; + p.reset(3); + var last: i64 = 0; + var n: usize = 0; + var now: i64 = 0; + while (!p.done()) : (now += 1) { + while (try p.next(now)) |m| { + try std.testing.expect(m.arrival <= now and m.arrival >= last); + last = m.arrival; + n += 1; + } + } + try std.testing.expectEqual(@as(usize, 50), n); + const end1 = last; + p.reset(3); + now = 0; + while (!p.done()) : (now += 1) while (try p.next(now)) |m| { + last = m.arrival; + }; + try std.testing.expectEqual(end1, last); +} diff --git a/src/adapters/arrivals/sample.zig b/src/adapters/arrivals/sample.zig new file mode 100644 index 0000000..dc4cad7 --- /dev/null +++ b/src/adapters/arrivals/sample.zig @@ -0,0 +1,42 @@ +//! Random sampling helpers shared by arrival sources. +const std = @import("std"); + +/// Poisson(λ) count. Knuth for small λ, normal approximation for large λ. +pub fn poisson(r: std.Random, lambda: f64) usize { + if (lambda <= 0) return 0; + if (lambda > 30) { + const x = lambda + @sqrt(lambda) * r.floatNorm(f64); + return @intFromFloat(@max(0, @round(x))); + } + const l = @exp(-lambda); + var k: usize = 0; + var p: f64 = 1; + while (true) { + p *= r.float(f64); + if (p <= l) return k; + k += 1; + } +} + +/// Pareto(α) sample with the given mean (α > 1): x_m / U^(1/α), +/// x_m = mean·(α−1)/α. Heavy-tailed: infinite variance for α ≤ 2. +pub fn pareto(r: std.Random, alpha: f64, mean: f64) f64 { + const xm = mean * (alpha - 1) / alpha; + const u = 1.0 - r.float(f64); // (0, 1] + return xm / std.math.pow(f64, u, 1.0 / alpha); +} + +test "sample means" { + var prng = std.Random.DefaultPrng.init(1); + const r = prng.random(); + var sp: f64 = 0; + var sq: f64 = 0; + const n = 200_000; + for (0..n) |_| { + sp += @floatFromInt(poisson(r, 2.5)); + sq += pareto(r, 2.5, 4.0); // finite variance → mean converges fast + } + try std.testing.expectApproxEqAbs(@as(f64, 2.5), sp / n, 0.05); + try std.testing.expectApproxEqAbs(@as(f64, 4.0), sq / n, 0.1); + try std.testing.expectEqual(@as(usize, 0), poisson(r, 0)); +} diff --git a/src/adapters/arrivals/self_similar.zig b/src/adapters/arrivals/self_similar.zig new file mode 100644 index 0000000..6cf21e7 --- /dev/null +++ b/src/adapters/arrivals/self_similar.zig @@ -0,0 +1,83 @@ +//! Self-similar arrivals: superposition of `sources` ON/OFF sources whose +//! ON and OFF periods are Pareto(alpha) with mean `period` ticks (Willinger +//! et al., "Self-similarity through high-variability", 1997). While ON a +//! source emits Poisson arrivals; the aggregate is long-range dependent with +//! Hurst parameter H = (3 − α)/2 (α = 1.4 → H = 0.8): bursts and lulls at +//! every time scale, as measured in real cluster and network traces. +//! +//! Fewer sources and longer periods = burstier: the ON-count fluctuation +//! adds rate²/sources of variance per tick. Defaults (8 sources, period 50) +//! give an index of dispersion of ~6 over 100 ticks and ~24 over 1000 +//! (Poisson: 1 at every scale). +//! +//! Each source is ON half the time on average, so the per-source ON rate is +//! 2·rate/sources and the long-run mean is `rate` jobs per tick. +const std = @import("std"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").arrival_source.Error; +const sample = @import("sample.zig"); + +pub const max_sources = 256; + +pub const SelfSimilar = struct { + total: usize, + rate: f64, + sources: usize = 8, + alpha: f64 = 1.4, + period: f64 = 50, + prng: std.Random.DefaultPrng = .init(0), + generated: usize = 0, + cur: i64 = 0, + pending: usize = 0, + on: [max_sources]bool = undefined, + left: [max_sources]f64 = undefined, // ticks left in the current period + + pub fn reset(self: *SelfSimilar, seed: u64) void { + self.prng = .init(seed +% 13); + self.generated = 0; + self.cur = 0; + const r = self.prng.random(); + for (0..@min(self.sources, max_sources)) |i| { + self.on[i] = r.boolean(); + self.left[i] = sample.pareto(r, self.alpha, self.period) * r.float(f64); // random phase + } + self.pending = self.draw(); + } + + fn draw(self: *SelfSimilar) usize { + const r = self.prng.random(); + const k = @min(self.sources, max_sources); + var n_on: usize = 0; + for (0..k) |i| { + if (self.on[i]) n_on += 1; + // advance this source by one tick + self.left[i] -= 1; + while (self.left[i] <= 0) { + self.on[i] = !self.on[i]; + self.left[i] += sample.pareto(r, self.alpha, self.period); + } + } + const per_on = 2.0 * self.rate / @as(f64, @floatFromInt(k)); + return sample.poisson(r, per_on * @as(f64, @floatFromInt(n_on))); + } + + pub fn next(self: *SelfSimilar, now: i64) Error!?model.JobMeta { + if (self.rate <= 0 or self.alpha <= 1 or self.sources == 0 or self.sources > max_sources) + return error.InvalidInput; + while (self.generated < self.total and self.cur <= now) { + if (self.pending > 0) { + self.pending -= 1; + const meta = model.JobMeta{ .id = @intCast(self.generated), .arrival = self.cur }; + self.generated += 1; + return meta; + } + self.cur += 1; + self.pending = self.draw(); + } + return null; + } + + pub fn done(self: *SelfSimilar) bool { + return self.generated >= self.total; + } +}; diff --git a/src/adapters/generators/deeprm.zig b/src/adapters/generators/deeprm.zig new file mode 100644 index 0000000..cea11a4 --- /dev/null +++ b/src/adapters/generators/deeprm.zig @@ -0,0 +1,53 @@ +//! DeepRM-style workload (Mao et al., HotNets'16), adapted: +//! * identical machines with capacity `cap` on every resource; +//! * 80% short jobs (duration 1..short_max), 20% long (long_min..long_max); +//! * one random dominant resource with demand in [0.25, 0.5]·cap, +//! the others in [0.05, 0.1]·cap; constant over the job's duration. +const std = @import("std"); +const grid = @import("../../grid.zig"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").usage_generator.Error; +const Elem = grid.Elem; +const Usage = grid.Usage; + +pub const DeepRM = struct { + n_machines: usize = 1, + cap: Elem = 100, + short_prob: f64 = 0.8, + short_max: u16 = 3, + long_min: u16 = 10, + long_max: u16 = 15, + prng: std.Random.DefaultPrng = .init(0), + + pub fn reset(self: *DeepRM, seed: u64) void { + self.prng = .init(seed +% 2); + } + + pub fn machineCount(self: *DeepRM) usize { + return self.n_machines; + } + + pub fn machine(self: *DeepRM, index: usize, cap: []Elem) Error!void { + _ = index; + @memset(cap, self.cap); + } + + pub fn job(self: *DeepRM, meta: model.JobMeta, out: Usage) Error!u16 { + _ = meta; + const r = self.prng.random(); + const n_ticks: u16 = @intCast(out.layout.n_ticks); + const dur = @min(n_ticks, if (r.float(f64) < self.short_prob) + r.intRangeAtMost(u16, 1, self.short_max) + else + r.intRangeAtMost(u16, self.long_min, self.long_max)); + + const c: f64 = @floatFromInt(self.cap); + const dom = r.uintLessThan(usize, out.layout.n_res); + for (0..out.layout.n_res) |res| { + const frac = if (res == dom) 0.25 + 0.25 * r.float(f64) else 0.05 + 0.05 * r.float(f64); + const d: Elem = @intFromFloat(@round(frac * c)); + @memset(out.resourceMut(res)[0..dur], d); + } + return dur; + } +}; diff --git a/src/adapters/generators/random_profiles.zig b/src/adapters/generators/random_profiles.zig new file mode 100644 index 0000000..0e7dd12 --- /dev/null +++ b/src/adapters/generators/random_profiles.zig @@ -0,0 +1,59 @@ +//! Random profiles: machines with given capacities (cycled), jobs with a +//! uniform random duration and per-resource demand. +//! * constant: one demand value per resource for the whole duration +//! * varying : demand changes at 1–3 random points in time +const std = @import("std"); +const grid = @import("../../grid.zig"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").usage_generator.Error; +const Elem = grid.Elem; +const Usage = grid.Usage; + +pub const RandomProfiles = struct { + n_machines: usize = 4, + /// Capacity per machine, cycled: machine i gets caps[i % caps.len] + /// on every resource. + caps: []const Elem = &.{ 100, 80, 60, 40 }, + dur_min: u16 = 1, + dur_max: u16 = 20, + demand_min: Elem = 0, + demand_max: Elem = 30, + varying: bool = false, + prng: std.Random.DefaultPrng = .init(0), + + pub fn reset(self: *RandomProfiles, seed: u64) void { + self.prng = .init(seed +% 1); + } + + pub fn machineCount(self: *RandomProfiles) usize { + return self.n_machines; + } + + pub fn machine(self: *RandomProfiles, index: usize, cap: []Elem) Error!void { + if (self.caps.len == 0) return error.InvalidInput; + @memset(cap, self.caps[index % self.caps.len]); + } + + pub fn job(self: *RandomProfiles, meta: model.JobMeta, out: Usage) Error!u16 { + _ = meta; + const r = self.prng.random(); + const hi: u16 = @intCast(@min(self.dur_max, out.layout.n_ticks)); + const lo = @min(self.dur_min, hi); + const dur = r.intRangeAtMost(u16, lo, hi); + for (0..out.layout.n_res) |res| { + const line = out.resourceMut(res)[0..dur]; + if (!self.varying) { + @memset(line, r.intRangeAtMost(Elem, self.demand_min, self.demand_max)); + continue; + } + var t: usize = 0; + while (t < dur) { + const seg = r.intRangeAtMost(usize, 1, @max(1, dur / 2)); + const end = @min(dur, t + seg); + @memset(line[t..end], r.intRangeAtMost(Elem, self.demand_min, self.demand_max)); + t = end; + } + } + return dur; + } +}; diff --git a/src/adapters/observers/event_log.zig b/src/adapters/observers/event_log.zig new file mode 100644 index 0000000..b6244e1 --- /dev/null +++ b/src/adapters/observers/event_log.zig @@ -0,0 +1,21 @@ +//! Event log observer: one line per event on stderr. For debugging. +const std = @import("std"); +const model = @import("../../model.zig"); + +pub const EventLog = struct { + /// Also log every tick (noisy). + ticks: bool = false, + + pub fn onEvent(self: *EventLog, ev: model.Event, st: *const model.State) void { + _ = st; + switch (ev) { + .episode_started => |e| std.debug.print("[start] seed={d}\n", .{e.seed}), + .job_arrived => |e| std.debug.print("[t={d}] arrive job={d} slot={d}\n", .{ e.tick, e.id, e.slot }), + .job_rejected => |e| std.debug.print("[t={d}] reject job={d} reason={t}\n", .{ e.tick, e.id, e.reason }), + .job_placed => |e| std.debug.print("[t={d}] place job={d} machine={d} dur={d} wait={d}\n", .{ e.tick, e.id, e.machine, e.dur, e.tick - e.arrival }), + .illegal_action => |e| std.debug.print("[t={d}] illegal {f}\n", .{ e.tick, e.action }), + .tick_advanced => |e| if (self.ticks) std.debug.print("[t={d}] tick\n", .{e.now}), + .episode_done => |e| std.debug.print("[t={d}] done makespan={d}{s}\n", .{ e.now, e.makespan, if (e.truncated) " (truncated)" else "" }), + } + } +}; diff --git a/src/adapters/observers/metrics.zig b/src/adapters/observers/metrics.zig new file mode 100644 index 0000000..06c8c05 --- /dev/null +++ b/src/adapters/observers/metrics.zig @@ -0,0 +1,81 @@ +//! Metrics observer: per-machine placements, waiting-time distribution; +//! prints a summary at the end of each episode. +const std = @import("std"); +const model = @import("../../model.zig"); + +pub const Metrics = struct { + gpa: std.mem.Allocator, + waits: std.ArrayList(i64) = .empty, + per_machine: std.ArrayList(usize) = .empty, + rejected: usize = 0, + illegal: usize = 0, + /// Print the summary on episode_done. + print_summary: bool = true, + + pub fn init(gpa: std.mem.Allocator) Metrics { + return .{ .gpa = gpa }; + } + + pub fn deinit(self: *Metrics) void { + self.waits.deinit(self.gpa); + self.per_machine.deinit(self.gpa); + } + + pub fn onEvent(self: *Metrics, ev: model.Event, st: *const model.State) void { + switch (ev) { + .episode_started => { + self.waits.clearRetainingCapacity(); + self.per_machine.clearRetainingCapacity(); + self.per_machine.appendNTimes(self.gpa, 0, st.machines.n) catch {}; + self.rejected = 0; + self.illegal = 0; + }, + .job_placed => |p| { + self.waits.append(self.gpa, p.tick - p.arrival) catch {}; + if (p.machine < self.per_machine.items.len) self.per_machine.items[p.machine] += 1; + }, + .job_rejected => self.rejected += 1, + .illegal_action => self.illegal += 1, + .episode_done => |d| if (self.print_summary) self.summary(d.makespan, d.truncated), + else => {}, + } + } + + pub fn percentile(self: *Metrics, p: f64) i64 { + const w = self.waits.items; + if (w.len == 0) return 0; + std.mem.sort(i64, w, {}, std.sort.asc(i64)); + const idx: usize = @intFromFloat(@round(p * @as(f64, @floatFromInt(w.len - 1)))); + return w[idx]; + } + + fn summary(self: *Metrics, makespan: i64, truncated: bool) void { + var total: i64 = 0; + for (self.waits.items) |x| total += x; + const n = self.waits.items.len; + const avg = if (n == 0) 0 else @as(f64, @floatFromInt(total)) / @as(f64, @floatFromInt(n)); + std.debug.print( + \\ + \\── metrics {s}────────────────────────────── + \\placed {d} + \\rejected {d} + \\illegal {d} + \\makespan {d} ticks + \\wait avg {d:.2} p50 {d} p90 {d} p99 {d} max {d} + \\per machine {any} + \\ + , .{ + if (truncated) "(truncated) " else "", + n, + self.rejected, + self.illegal, + makespan, + avg, + self.percentile(0.5), + self.percentile(0.9), + self.percentile(0.99), + self.percentile(1.0), + self.per_machine.items, + }); + } +}; diff --git a/src/adapters/observers/terminal_viz.zig b/src/adapters/observers/terminal_viz.zig new file mode 100644 index 0000000..e70677d --- /dev/null +++ b/src/adapters/observers/terminal_viz.zig @@ -0,0 +1,240 @@ +//! Terminal visualization observer. Redraws on every tick (and optionally on +//! every placement) and shows two colored matrices: +//! MACHINES: per machine (and per resource, or the busiest resource), +//! one column per tick of the horizon; cell = used / capacity. +//! JOBS: waiting jobs, oldest first; one column per tick of the job's +//! profile; cell = max over resources of demand / max capacity. +//! A frame is built in memory and written with one print (no flicker). +const std = @import("std"); +const model = @import("../../model.zig"); +const Elem = @import("../../grid.zig").Elem; + +pub const Options = struct { + /// Max tick columns; longer horizons are compressed (max over bucket). + max_cols: usize = 100, + /// Max waiting jobs listed. + max_jobs: usize = 20, + /// One row per resource (true) or per machine (false). + per_resource: bool = false, + /// Redraw also after each placement (slower, shows every decision). + on_place: bool = false, + /// Delay after each frame, ms. + delay_ms: u32 = 80, + color: bool = true, +}; + +pub const TerminalViz = struct { + gpa: std.mem.Allocator, + io: std.Io, + opts: Options, + out: std.ArrayList(u8) = .empty, + order: std.ArrayList(usize) = .empty, + last_color: u8 = 0, + placed: usize = 0, + rejected: usize = 0, + started: bool = false, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, opts: Options) TerminalViz { + return .{ .gpa = gpa, .io = io, .opts = opts }; + } + + pub fn deinit(self: *TerminalViz) void { + if (self.started) std.debug.print("\x1b[0m\x1b[?25h", .{}); + self.out.deinit(self.gpa); + self.order.deinit(self.gpa); + } + + // ---------------- Observer contract ---------------- + + pub fn onEvent(self: *TerminalViz, ev: model.Event, st: *const model.State) void { + switch (ev) { + .episode_started => { + self.placed = 0; + self.rejected = 0; + if (!self.started) std.debug.print("\x1b[?25l\x1b[2J", .{}); + self.started = true; + self.frame(st, "started"); + }, + .job_placed => { + self.placed += 1; + if (self.opts.on_place) self.frame(st, "placed"); + }, + .job_rejected => self.rejected += 1, + .tick_advanced => self.frame(st, "tick"), + .episode_done => |d| { + self.frame(st, if (d.truncated) "truncated" else "done"); + std.debug.print("\x1b[0m\x1b[?25h", .{}); + self.started = false; + }, + else => {}, + } + } + + fn frame(self: *TerminalViz, st: *const model.State, label: []const u8) void { + self.draw(st, label) catch return; // out of memory: skip the frame + std.debug.print("{s}", .{self.out.items}); + if (self.opts.delay_ms > 0) + self.io.sleep(.fromMilliseconds(self.opts.delay_ms), .awake) catch {}; + } + + // ---------------- drawing ---------------- + + const glyphs = [_][]const u8{ "·", "░", "▒", "▓", "█" }; + const colors = [_]u8{ 240, 34, 178, 208, 196 }; + + fn level(frac: f32) usize { + if (frac <= 0) return 0; + if (frac <= 0.25) return 1; + if (frac <= 0.5) return 2; + if (frac <= 0.75) return 3; + return 4; + } + + fn put(self: *TerminalViz, comptime fmt: []const u8, args: anytype) !void { + try self.out.print(self.gpa, fmt, args); + } + + fn esc(self: *TerminalViz, code: []const u8) !void { + if (self.opts.color) try self.out.appendSlice(self.gpa, code); + if (std.mem.eql(u8, code, "\x1b[0m")) self.last_color = 0; + } + + fn cell(self: *TerminalViz, frac: f32) !void { + const lv = level(frac); + if (self.opts.color and colors[lv] != self.last_color) { + try self.put("\x1b[38;5;{d}m", .{colors[lv]}); + self.last_color = colors[lv]; + } + try self.out.appendSlice(self.gpa, glyphs[lv]); + } + + fn usedFrac(free: []const Elem, cap: Elem, t0: usize, t1: usize) f32 { + if (cap == 0) return 0; + var used: Elem = 0; + for (free[t0..t1]) |f| used = @max(used, cap -| f); + return @as(f32, @floatFromInt(used)) / @as(f32, @floatFromInt(cap)); + } + + fn draw(self: *TerminalViz, st: *const model.State, label: []const u8) !void { + self.out.clearRetainingCapacity(); + const ms = st.machines; + const jobs = st.jobs; + const lay = ms.layout; + const n_ticks = lay.n_ticks; + const bucket = @max(1, (n_ticks + self.opts.max_cols - 1) / self.opts.max_cols); + const cols = (n_ticks + bucket - 1) / bucket; + + try self.out.appendSlice(self.gpa, "\x1b[H"); + + // header + try self.esc("\x1b[1m"); + try self.put("t = {d}", .{st.now}); + try self.esc("\x1b[0m"); + try self.put(" [{s}] waiting = {d} placed = {d} rejected = {d} util now = {d:.0}%\x1b[K\n", .{ + label, jobs.count, self.placed, self.rejected, ms.utilizationNow() * 100, + }); + try self.esc("\x1b[2m"); + try self.put("legend: · 0% ░ ≤25% ▒ ≤50% ▓ ≤75% █ >75% 1 col = {d} tick(s)\x1b[K\n\n", .{bucket}); + try self.esc("\x1b[0m"); + + // machines + try self.esc("\x1b[1m"); + try self.put("MACHINES (used / capacity over the horizon, tick 0 = now)\x1b[K\n", .{}); + try self.esc("\x1b[0m"); + try self.axis(cols, bucket, 15); + + for (0..ms.n) |m| { + const mach = ms.get(m); + if (self.opts.per_resource) { + for (0..lay.n_res) |r| { + if (r == 0) try self.put("M{d:<3}", .{m}) else try self.put(" ", .{}); + try self.put(" r{d:<2} {d:>5} |", .{ r, mach.cap[r] }); + for (0..cols) |c| { + const t0 = c * bucket; + try self.cell(usedFrac(mach.resource(r), mach.cap[r], t0, @min(n_ticks, t0 + bucket))); + } + try self.esc("\x1b[0m"); + try self.put("|\x1b[K\n", .{}); + } + } else { + try self.put("M{d:<3} cap {d:>5} |", .{ m, mach.cap[0] }); + for (0..cols) |c| { + const t0 = c * bucket; + const t1 = @min(n_ticks, t0 + bucket); + var frac: f32 = 0; + for (0..lay.n_res) |r| frac = @max(frac, usedFrac(mach.resource(r), mach.cap[r], t0, t1)); + try self.cell(frac); + } + try self.esc("\x1b[0m"); + try self.put("| {d:>3.0}%\x1b[K\n", .{mach.utilizationNow() * 100}); + } + } + + // jobs, oldest first + self.order.clearRetainingCapacity(); + var it = jobs.iter(); + while (it.next()) |s| try self.order.append(self.gpa, s); + const Ctx = struct { + arrival: []const i64, + fn lt(c: @This(), a: usize, b: usize) bool { + return c.arrival[a] < c.arrival[b] or (c.arrival[a] == c.arrival[b] and a < b); + } + }; + std.mem.sort(usize, self.order.items, Ctx{ .arrival = jobs.arrival }, Ctx.lt); + + const shown = @min(self.order.items.len, self.opts.max_jobs); + try self.esc("\x1b[1m"); + try self.put("\nJOBS (waiting, oldest first: {d} of {d})\x1b[K\n", .{ shown, self.order.items.len }); + try self.esc("\x1b[0m"); + try self.put(" id arr wait dur |\x1b[K\n", .{}); + + for (self.order.items[0..shown]) |s| { + const u = jobs.get(s); + const dur: usize = jobs.duration[s]; + try self.put("{d:>6} {d:>5} {d:>5} {d:>3} |", .{ + jobs.id[s], @as(u64, @intCast(jobs.arrival[s])), @as(u64, @intCast(st.now - jobs.arrival[s])), dur, + }); + const jcols = (dur + bucket - 1) / bucket; + for (0..jcols) |c| { + const t0 = c * bucket; + const t1 = @min(dur, t0 + bucket); + var frac: f32 = 0; + for (0..lay.n_res) |r| { + const mc: f32 = @floatFromInt(@max(1, ms.maxCap(r))); + for (u.resource(r)[t0..t1]) |v| frac = @max(frac, @as(f32, @floatFromInt(v)) / mc); + } + try self.cell(frac); + } + try self.esc("\x1b[0m"); + try self.put("\x1b[K\n", .{}); + } + if (self.order.items.len > shown) { + try self.esc("\x1b[2m"); + try self.put(" … {d} more\x1b[K\n", .{self.order.items.len - shown}); + try self.esc("\x1b[0m"); + } + try self.put("\x1b[J", .{}); + } + + fn axis(self: *TerminalViz, cols: usize, bucket: usize, indent: usize) !void { + try self.esc("\x1b[2m"); + for (0..indent) |_| try self.put(" ", .{}); + try self.put("|", .{}); + var c: usize = 0; + while (c < cols) { + if (c % 10 == 0) { + var buf: [16]u8 = undefined; + const s = try std.fmt.bufPrint(&buf, "{d}", .{c * bucket}); + if (c + s.len <= cols) { + try self.put("{s}", .{s}); + c += s.len; + continue; + } + } + try self.put(" ", .{}); + c += 1; + } + try self.put("|\x1b[K\n", .{}); + try self.esc("\x1b[0m"); + } +}; diff --git a/src/adapters/observers/trace.zig b/src/adapters/observers/trace.zig new file mode 100644 index 0000000..e43f544 --- /dev/null +++ b/src/adapters/observers/trace.zig @@ -0,0 +1,151 @@ +//! Trace observer: writes every event of every episode to a JSON Lines file, +//! with enough data to rebuild the full simulation state offline (replay, +//! visualization, analysis) without running the simulator again. +//! +//! One JSON object per line; `type` says which. Format version 1: +//! +//! {"type":"episode","v":1,"seed":S,"n_res":R,"n_ticks":T,"max_jobs":J,"caps":[[c..],..]} +//! {"type":"arrive","t":T,"id":I,"slot":S,"dur":D,"demand":[[..r0..],[..r1..]]} +//! {"type":"reject","t":T,"id":I,"reason":"pool_full|impossible|invalid_profile"} +//! {"type":"place","t":T,"id":I,"slot":S,"machine":M,"arrival":A,"dur":D} +//! {"type":"illegal","t":T} +//! {"type":"tick","t":T} time advanced to T (after arrivals at T) +//! {"type":"done","t":T,"makespan":M,"truncated":false} +//! +//! `caps` is [machine][resource]; `demand` is [resource][tick < dur]. +//! Ordering: within a tick, arrivals come before the `tick` line, so the +//! state right after a `tick` line is "start of tick T". The python side +//! (python/sched_env/replay.py) reads this format. +//! +//! I/O errors never stop the simulation: the first one is kept in `err` +//! and later events are dropped. + +const std = @import("std"); +const model = @import("../../model.zig"); + +pub const Trace = struct { + io: std.Io = undefined, + file: std.Io.File = undefined, + writer: std.Io.File.Writer = undefined, + buf: [64 * 1024]u8 = undefined, + /// Also write one line per tick (needed for replay; turn off only for + /// smaller files when you just want placements). + ticks: bool = true, + err: ?anyerror = null, + + /// Create (truncate) `path` relative to `dir`. `self` must not move + /// afterwards (the writer points into `buf`). + pub fn open(self: *Trace, io: std.Io, dir: std.Io.Dir, path: []const u8) !void { + self.io = io; + self.err = null; + self.file = try dir.createFile(io, path, .{}); + self.writer = self.file.writer(io, &self.buf); + } + + /// Flush and close. Returns the first I/O error, if any. + pub fn close(self: *Trace) !void { + self.writer.interface.flush() catch |e| { + if (self.err == null) self.err = e; + }; + self.file.close(self.io); + if (self.err) |e| return e; + } + + pub fn deinit(self: *Trace) void { + self.close() catch {}; + } + + pub fn onEvent(self: *Trace, ev: model.Event, st: *const model.State) void { + if (self.err != null) return; + self.write(ev, st) catch |e| { + self.err = e; + }; + } + + fn write(self: *Trace, ev: model.Event, st: *const model.State) !void { + const w = &self.writer.interface; + switch (ev) { + .episode_started => |e| { + const ms = st.machines; + const n_res = ms.layout.n_res; + try w.print("{{\"type\":\"episode\",\"v\":1,\"seed\":{d},\"n_res\":{d},\"n_ticks\":{d},\"max_jobs\":{d},\"caps\":[", .{ e.seed, n_res, ms.layout.n_ticks, st.jobs.cap }); + for (0..ms.n) |m| { + if (m > 0) try w.writeByte(','); + try writeList(w, ms.cap[m * n_res ..][0..n_res]); + } + try w.writeAll("]}\n"); + }, + .job_arrived => |e| { + const dur = st.jobs.duration[e.slot]; + try w.print("{{\"type\":\"arrive\",\"t\":{d},\"id\":{d},\"slot\":{d},\"dur\":{d},\"demand\":[", .{ e.tick, e.id, e.slot, dur }); + const job = st.jobs.get(e.slot); + for (0..st.jobs.layout.n_res) |r| { + if (r > 0) try w.writeByte(','); + try writeList(w, job.row(r)[0..dur]); + } + try w.writeAll("]}\n"); + }, + .job_rejected => |e| try w.print("{{\"type\":\"reject\",\"t\":{d},\"id\":{d},\"reason\":\"{t}\"}}\n", .{ e.tick, e.id, e.reason }), + .job_placed => |e| try w.print("{{\"type\":\"place\",\"t\":{d},\"id\":{d},\"slot\":{d},\"machine\":{d},\"arrival\":{d},\"dur\":{d}}}\n", .{ e.tick, e.id, e.slot, e.machine, e.arrival, e.dur }), + .illegal_action => |e| try w.print("{{\"type\":\"illegal\",\"t\":{d}}}\n", .{e.tick}), + .tick_advanced => |e| if (self.ticks) try w.print("{{\"type\":\"tick\",\"t\":{d}}}\n", .{e.now}), + .episode_done => |e| { + try w.print("{{\"type\":\"done\",\"t\":{d},\"makespan\":{d},\"truncated\":{}}}\n", .{ e.now, e.makespan, e.truncated }); + try w.flush(); + }, + } + } + + fn writeList(w: *std.Io.Writer, xs: anytype) !void { + try w.writeByte('['); + for (xs, 0..) |x, i| { + if (i > 0) try w.writeByte(','); + try w.print("{d}", .{x}); + } + try w.writeByte(']'); + } +}; + +test "trace: writes a parseable line per event" { + const sched_ports = @import("../../ports.zig"); + const Engine = @import("../../engine.zig").Engine; + const Poisson = @import("../arrivals/poisson.zig").Poisson; + const DeepRM = @import("../generators/deeprm.zig").DeepRM; + const Fifo = @import("../policies/fifo_backfill.zig").FifoBackfill; + const t = std.testing; + + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + + var arr = Poisson{ .total = 20, .rate = 0.5 }; + var gen = DeepRM{ .n_machines = 2 }; + var eng = try Engine.init(t.allocator, .{ .n_res = 2, .n_ticks = 10, .max_jobs = 8 }, .init(&arr), .init(&gen)); + defer eng.deinit(); + var tr = Trace{}; + try tr.open(t.io, tmp.dir, "run.jsonl"); + try eng.addObserver(sched_ports.Observer.init(&tr)); + try eng.reset(3); + var p = Fifo{}; + const st = try eng.run(&p, 10_000); + try tr.close(); + + const text = try tmp.dir.readFileAlloc(t.io, "run.jsonl", t.allocator, .limited(1 << 20)); + defer t.allocator.free(text); + + const kinds = [_][]const u8{ "episode", "done", "arrive", "place", "tick" }; + var counts: [kinds.len]usize = @splat(0); + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n'); + while (lines.next()) |line| { + const parsed = try std.json.parseFromSlice(std.json.Value, t.allocator, line, .{}); + defer parsed.deinit(); + const ty = parsed.value.object.get("type").?.string; + for (kinds, 0..) |k, i| if (std.mem.eql(u8, k, ty)) { + counts[i] += 1; + }; + } + try t.expectEqual(@as(usize, 1), counts[0]); + try t.expectEqual(@as(usize, 1), counts[1]); + try t.expectEqual(st.arrived, counts[2]); + try t.expectEqual(st.placed, counts[3]); + try t.expectEqual(@as(usize, @intCast(st.ticks)), counts[4]); +} diff --git a/src/adapters/policies/best_fit.zig b/src/adapters/policies/best_fit.zig new file mode 100644 index 0000000..cf2986e --- /dev/null +++ b/src/adapters/policies/best_fit.zig @@ -0,0 +1,37 @@ +//! Best fit: over all (job, machine) pairs that fit now, choose the pair +//! that leaves the least free capacity at tick 0 (normalized per resource), +//! packing machines tightly. Ties: oldest job. +//! +//! Scores are cached across decisions (`PairCache`): after a placement only +//! the chosen machine's scores are recomputed. +const std = @import("std"); +const model = @import("../../model.zig"); +const PairCache = @import("pair_cache.zig").PairCache; + +pub const BestFit = struct { + pub const name = "best_fit"; + + cache: PairCache = .{}, + + pub fn deinit(self: *BestFit) void { + self.cache.deinit(); + } + + /// Negated free capacity left after placing (higher = tighter). + fn score(_: void, st: *const model.State, s: usize, m: usize) f32 { + const mach = st.machines.get(m); + const job = st.jobs.get(s); + var left: f32 = 0; + for (0..st.machines.layout.n_res) |r| { + const cap: f32 = @floatFromInt(@max(1, mach.cap[r])); + const after: f32 = @floatFromInt(mach.freeNow(r) - job.row(r)[0]); + left += after / cap; + } + return -left; + } + + pub fn decide(self: *BestFit, st: *const model.State) model.Action { + self.cache.update(st, score, {}) catch @panic("best_fit: out of memory"); + return self.cache.pick(st, PairCache.noPen, {}); + } +}; diff --git a/src/adapters/policies/fifo_backfill.zig b/src/adapters/policies/fifo_backfill.zig new file mode 100644 index 0000000..b4165ce --- /dev/null +++ b/src/adapters/policies/fifo_backfill.zig @@ -0,0 +1,20 @@ +//! FIFO with backfill: place the oldest waiting job that fits now on any +//! machine (first machine that fits). If the oldest does not fit, younger +//! jobs may go first. Waits when nothing fits. +const model = @import("../../model.zig"); +const rules = @import("../../engine.zig").rules; + +pub const FifoBackfill = struct { + pub const name = "fifo"; + + pub fn decide(self: *FifoBackfill, st: *const model.State) model.Action { + _ = self; + // oldest first ((arrival, slot) order): the first job that fits anywhere + var it = st.jobs.byArrival(); + while (it.next()) |s| { + const m = rules.firstMachine(st, s) orelse continue; + return .{ .place = .{ .slot = @intCast(s), .machine = @intCast(m) } }; + } + return .wait; + } +}; diff --git a/src/adapters/policies/fifo_strict.zig b/src/adapters/policies/fifo_strict.zig new file mode 100644 index 0000000..38116c9 --- /dev/null +++ b/src/adapters/policies/fifo_strict.zig @@ -0,0 +1,15 @@ +//! Strict FIFO: only the oldest waiting job may start. If it does not fit, +//! wait. No starvation, lower utilization. +const model = @import("../../model.zig"); +const rules = @import("../../engine.zig").rules; + +pub const FifoStrict = struct { + pub const name = "fifo_strict"; + + pub fn decide(self: *FifoStrict, st: *const model.State) model.Action { + _ = self; + const s = st.jobs.oldest() orelse return .wait; + const m = rules.firstMachine(st, s) orelse return .wait; + return .{ .place = .{ .slot = @intCast(s), .machine = @intCast(m) } }; + } +}; diff --git a/src/adapters/policies/pair_cache.zig b/src/adapters/policies/pair_cache.zig new file mode 100644 index 0000000..0d584cd --- /dev/null +++ b/src/adapters/policies/pair_cache.zig @@ -0,0 +1,155 @@ +//! Incremental (job, machine) scores for pair-scanning policies. +//! +//! Within one tick a placement changes only the machine it lands on (and +//! removes one job), so after the first decision of a tick only that +//! machine's column of scores needs recomputing. The cache keeps: +//! * `score[s·n_m + m]`: score of slot s on machine m, NaN = does not fit; +//! * `best[s]`: the first machine with the highest score in row s. +//! It is rebuilt in full when `Machines.epoch` changes (reset, time +//! advance) and per column when `Machines.stamp[m]` changes (placement). +//! +//! Results are bit-identical to scoring every pair each decision: the same +//! function computes each score, and ties resolve the same way (first +//! machine within a job; across jobs the strictly older job, else the +//! first slot). Higher scores win; negate to minimize. +const std = @import("std"); +const model = @import("../../model.zig"); +const rules = @import("../../engine.zig").rules; + +const none = std.math.maxInt(u32); + +pub const PairCache = struct { + alloc: std.mem.Allocator = std.heap.page_allocator, + score: []f32 = &.{}, + best: []u32 = &.{}, + ids: []u64 = &.{}, + seen: []u64 = &.{}, + epoch: u64 = std.math.maxInt(u64), + n_m: usize = 0, + + pub fn deinit(self: *PairCache) void { + self.free(); + self.* = .{ .alloc = self.alloc }; + } + + fn free(self: *PairCache) void { + self.alloc.free(self.score); + self.alloc.free(self.best); + self.alloc.free(self.ids); + self.alloc.free(self.seen); + } + + fn ensure(self: *PairCache, n_s: usize, n_m: usize) !void { + if (self.best.len == n_s and self.n_m == n_m) return; + self.free(); + self.* = .{ .alloc = self.alloc }; + self.score = try self.alloc.alloc(f32, n_s * n_m); + self.best = try self.alloc.alloc(u32, n_s); + self.ids = try self.alloc.alloc(u64, n_s); + self.seen = try self.alloc.alloc(u64, n_m); + self.n_m = n_m; + } + + pub fn row(self: *const PairCache, s: usize) []const f32 { + return self.score[s * self.n_m ..][0..self.n_m]; + } + + /// Best machine of slot s, or null if it fits nowhere. + pub fn bestOf(self: *const PairCache, s: usize) ?usize { + return if (self.best[s] == none) null else self.best[s]; + } + + fn better(a: f32, b: f32) bool { + return a > b; + } + + fn rescan(self: *PairCache, s: usize) void { + const r = self.row(s); + var b: u32 = none; + for (r, 0..) |x, m| { + if (std.math.isNan(x)) continue; + if (b == none or better(x, r[b])) b = @intCast(m); + } + self.best[s] = b; + } + + fn fillRow(self: *PairCache, st: *const model.State, s: usize, comptime scoreFn: anytype, ctx: anytype) void { + const r = self.score[s * self.n_m ..][0..self.n_m]; + if (rules.knownBlocked(st, s)) { + @memset(r, std.math.nan(f32)); + } else for (0..self.n_m) |m| { + r[m] = if (rules.fitsNow(st, s, m)) scoreFn(ctx, st, s, m) else std.math.nan(f32); + } + self.ids[s] = st.jobs.id[s]; + self.rescan(s); + } + + /// Bring the cache up to date with `st`. `scoreFn(ctx, st, s, m) f32` + /// is only called for pairs that fit now. Marks jobs that fit nowhere + /// as blocked (`rules.markBlocked`). + pub fn update(self: *PairCache, st: *const model.State, comptime scoreFn: anytype, ctx: anytype) !void { + const ms = st.machines; + const j = st.jobs; + const full = self.best.len != j.cap or self.n_m != ms.n or self.epoch != ms.epoch; + try self.ensure(j.cap, ms.n); + if (full) { + self.epoch = ms.epoch; + @memcpy(self.seen, ms.stamp); + var it = j.iter(); + while (it.next()) |s| self.fillRow(st, s, scoreFn, ctx); + } else { + // slots whose job changed (not expected within an epoch; safe anyway) + var it = j.iter(); + while (it.next()) |s| if (self.ids[s] != j.id[s]) self.fillRow(st, s, scoreFn, ctx); + for (0..ms.n) |m| { + if (self.seen[m] == ms.stamp[m]) continue; + self.seen[m] = ms.stamp[m]; + var it2 = j.iter(); + while (it2.next()) |s| { + const b = self.best[s]; + if (b == none) continue; // capacity only shrinks within a tick + const cell = &self.score[s * self.n_m + m]; + const old = cell.*; + cell.* = if (rules.fitsNow(st, s, m)) scoreFn(ctx, st, s, m) else std.math.nan(f32); + const new = cell.*; + if (b == m) { + if (std.math.isNan(new) or new < old) self.rescan(s); + } else if (!std.math.isNan(new)) { + const bs = self.score[s * self.n_m + b]; + if (better(new, bs) or (new == bs and m < b)) self.best[s] = @intCast(m); + } + } + } + } + var it = j.iter(); + while (it.next()) |s| if (self.best[s] == none) rules.markBlocked(st, s); + } + + /// Best (slot, machine) by `row score − pen(s)` (pen = 0 for none). + pub fn pick(self: *const PairCache, st: *const model.State, comptime penFn: anytype, ctx: anytype) model.Action { + const j = st.jobs; + var best: ?struct { s: usize, score: f32 } = null; + var it = j.iter(); + while (it.next()) |s| { + const m = self.bestOf(s) orelse continue; + // max over m of (x − pen) = (max x) − pen: subtraction is monotone + const score = self.row(s)[m] - penFn(ctx, st, s); + if (best) |b| { + if (score < b.score) continue; + if (score == b.score and j.arrival[s] >= j.arrival[b.s]) continue; + } + best = .{ .s = s, .score = score }; + } + const b = best orelse return .wait; + // rounding may make an earlier machine tie after subtracting pen + const pen = penFn(ctx, st, b.s); + const m = for (self.row(b.s), 0..) |x, m| { + if (!std.math.isNan(x) and x - pen == b.score) break m; + } else unreachable; + return .{ .place = .{ .slot = @intCast(b.s), .machine = @intCast(m) } }; + } + + pub fn noPen(_: void, _: *const model.State, _: usize) f32 { + return 0; + } +}; diff --git a/src/adapters/policies/random.zig b/src/adapters/policies/random.zig new file mode 100644 index 0000000..35cabc5 --- /dev/null +++ b/src/adapters/policies/random.zig @@ -0,0 +1,35 @@ +//! Random: a uniformly random legal placement (reservoir sampling, no +//! allocation); waits only when nothing fits. Sanity baseline. +const std = @import("std"); +const model = @import("../../model.zig"); +const rules = @import("../../engine.zig").rules; + +pub const RandomPolicy = struct { + pub const name = "random"; + + prng: std.Random.DefaultPrng = .init(0), + + pub fn reset(self: *RandomPolicy, seed: u64) void { + self.prng = .init(seed ^ 0x9e3779b97f4a7c15); + } + + pub fn decide(self: *RandomPolicy, st: *const model.State) model.Action { + const r = self.prng.random(); + var seen: usize = 0; + var pick: model.Action = .wait; + var it = st.jobs.iter(); + while (it.next()) |s| { + if (rules.knownBlocked(st, s)) continue; + var fits_any = false; + for (0..st.machines.n) |m| { + if (!rules.fitsNow(st, s, m)) continue; + fits_any = true; + seen += 1; + if (r.uintLessThan(usize, seen) == 0) + pick = .{ .place = .{ .slot = @intCast(s), .machine = @intCast(m) } }; + } + if (!fits_any) rules.markBlocked(st, s); + } + return pick; + } +}; diff --git a/src/adapters/policies/sjf.zig b/src/adapters/policies/sjf.zig new file mode 100644 index 0000000..1565652 --- /dev/null +++ b/src/adapters/policies/sjf.zig @@ -0,0 +1,27 @@ +//! Shortest job first: among jobs that fit now, the one with the smallest +//! duration (ties: oldest). +const model = @import("../../model.zig"); +const rules = @import("../../engine.zig").rules; + +pub const ShortestFirst = struct { + pub const name = "sjf"; + + pub fn decide(self: *ShortestFirst, st: *const model.State) model.Action { + _ = self; + const j = st.jobs; + var best: ?usize = null; + var best_m: usize = 0; + var it = j.iter(); + while (it.next()) |s| { + if (best) |b| { + if (j.duration[s] > j.duration[b]) continue; + if (j.duration[s] == j.duration[b] and j.arrival[s] >= j.arrival[b]) continue; + } + const m = rules.firstMachine(st, s) orelse continue; + best = s; + best_m = m; + } + const s = best orelse return .wait; + return .{ .place = .{ .slot = @intCast(s), .machine = @intCast(best_m) } }; + } +}; diff --git a/src/adapters/policies/tetris.zig b/src/adapters/policies/tetris.zig new file mode 100644 index 0000000..3af34f9 --- /dev/null +++ b/src/adapters/policies/tetris.zig @@ -0,0 +1,99 @@ +//! Tetris (Grandl et al., SIGCOMM'14): multi-resource packing by alignment. +//! Over all (job, machine) pairs that fit now, pick the one whose demand is +//! most aligned with the machine's free capacity: +//! +//! a = Σ_r Σ_{t 0", .{}); + + sim.gen = try registry.generator(a, try cli.Spec.parse(a, "machines", std.mem.span(c.machines))); + errdefer sim.gen.deinit(); + sim.arr = try registry.arrivals(a, try cli.Spec.parse(a, "jobs", std.mem.span(c.jobs))); + errdefer sim.arr.deinit(); + sim.eng = try sched.Engine.init(gpa, cfg, sim.arr, sim.gen); + errdefer sim.eng.deinit(); + if (c.reward) |r| sim.eng.setReward(try registry.reward(a, try cli.Spec.parse(a, "reward", std.mem.span(r)))); + sim.started = false; + sim.trace = .{}; + sim.tracing = false; + sim.threaded = std.Io.Threaded.init_single_threaded; + try sim.eng.addObserver(.init(sim)); + return sim; +} + +export fn sim_create(cfg: *const SimConfig) ?*Sim { + return create(cfg) catch |e| { + if (e != error.InvalidArgs) std.debug.print("sim_create: {s}\n", .{@errorName(e)}); + return null; + }; +} + +export fn sim_destroy(sim: ?*Sim) void { + const s = sim orelse return; + _ = sim_trace_close(s); + s.eng.deinit(); + s.arr.deinit(); + s.gen.deinit(); + s.arena.deinit(); + gpa.destroy(s); +} + +/// 0 = ok, -1 = error. +export fn sim_reset(sim: *Sim, seed: u64) c_int { + sim.eng.reset(seed) catch return -1; + sim.started = true; + return 0; +} + +export fn sim_dims(sim: *const Sim, out: *SimDims) void { + const e = &sim.eng; + var max_cap: Elem = 0; + for (0..e.layout.n_res) |r| max_cap = @max(max_cap, e.machines.maxCap(r)); + out.* = .{ + .n_machines = @intCast(e.machines.n), + .n_res = @intCast(e.layout.n_res), + .n_ticks = @intCast(e.layout.n_ticks), + .max_jobs = @intCast(e.jobs.cap), + .n_actions = @intCast(e.jobs.cap * e.machines.n + 1), + .stride = @intCast(e.layout.stride), + .block = @intCast(e.layout.block), + .max_cap = max_cap, + .m_stride = @intCast(e.machines.ring.stride), + .m_block = @intCast(e.machines.ring.block), + }; +} + +/// 0 = ok, -1 = episode not running (call sim_reset), -2 = engine error. +export fn sim_step(sim: *Sim, action: u32, out: *SimStep) c_int { + if (!sim.started or sim.eng.done()) return -1; + const st = sim.eng.state(); + const r = sim.eng.step(rules.decode(&st, action)) catch return -2; + out.* = .{ + .reward = r.reward, + .terminated = @intFromBool(r.terminated), + .truncated = @intFromBool(r.truncated), + .placed = @intFromBool(r.placed), + .illegal = @intFromBool(r.illegal), + }; + return 0; +} + +/// mask must hold n_actions bytes; 1 = legal. +export fn sim_action_mask(sim: *const Sim, mask: [*]u8) void { + const st = sim.eng.state(); + const n = rules.actionCount(&st); + rules.actionMask(&st, @as([*]bool, @ptrCast(mask))[0..n]); +} + +/// valid must hold max_jobs bytes; 1 = slot holds a waiting job. +export fn sim_slot_valid(sim: *const Sim, valid: [*]u8) void { + const jobs = &sim.eng.jobs; + for (0..jobs.cap) |s| valid[s] = @intFromBool(jobs.isValid(s)); +} + +/// Free capacity, [n_machines][n_res][m_stride] u16; the horizon of each +/// row starts at sim_machine_head(). +export fn sim_machines_ptr(sim: *const Sim) [*]const Elem { + return sim.eng.machines.buf.ptr; +} +/// Offset of tick 0 (now) inside every machine row. Changes with time. +export fn sim_machine_head(sim: *const Sim) u32 { + return @intCast(sim.eng.machines.head); +} +/// Capacity, [n_machines][n_res] u16. +export fn sim_capacity_ptr(sim: *const Sim) [*]const Elem { + return sim.eng.machines.cap.ptr; +} +/// Waiting-job demand, [max_jobs][n_res][stride] u16 (0 for empty slots). +export fn sim_jobs_ptr(sim: *const Sim) [*]const Elem { + return sim.eng.jobs.buf.ptr; +} +/// Duration per slot, [max_jobs] u16 (meaningful for valid slots only). +export fn sim_duration_ptr(sim: *const Sim) [*]const u16 { + return sim.eng.jobs.duration.ptr; +} +/// Arrival tick per slot, [max_jobs] i64 (meaningful for valid slots only). +export fn sim_arrival_ptr(sim: *const Sim) [*]const i64 { + return sim.eng.jobs.arrival.ptr; +} + +/// Record every following event to a JSON Lines trace at `path` (created or +/// truncated; see src/adapters/observers/trace.zig for the format). Call +/// before sim_reset to capture whole episodes. 0 = ok, -1 = cannot create. +export fn sim_trace_open(sim: *Sim, path: [*:0]const u8) c_int { + _ = sim_trace_close(sim); + sim.trace = .{}; + sim.trace.open(sim.threaded.io(), std.Io.Dir.cwd(), std.mem.span(path)) catch return -1; + sim.tracing = true; + return 0; +} + +/// Flush and close the trace. 0 = ok (or none open), -1 = a write failed. +export fn sim_trace_close(sim: *Sim) c_int { + if (!sim.tracing) return 0; + sim.tracing = false; + sim.trace.close() catch return -1; + return 0; +} + +export fn sim_now(sim: *const Sim) i64 { + return sim.eng.now; +} + +export fn sim_stats(sim: *const Sim, out: *SimStats) void { + const s = sim.eng.stats; + out.* = .{ + .now = sim.eng.now, + .arrived = s.arrived, + .placed = s.placed, + .rejected = s.rejected, + .illegal = s.illegal, + .steps = s.steps, + .waiting = sim.eng.jobs.count, + .makespan = s.makespan, + .avg_wait = s.avgWait(), + .max_wait = s.max_wait, + .avg_util = s.avgUtil(), + .total_reward = s.total_reward, + }; +} + +/// Reset with `seed` and run a whole episode with a built-in policy +/// ("fifo", "sjf", "best_fit", …) at native speed. 0 = ok, -1 = error. +export fn sim_run_policy(sim: *Sim, name: [*:0]const u8, seed: u64, out: *SimStats) c_int { + sim.eng.reset(seed) catch return -1; + sim.started = true; + var buf: [1024]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&buf); + const spec = cli.Spec.parse(fba.allocator(), "policy", std.mem.span(name)) catch return -1; + _ = registry.runPolicy(&sim.eng, spec, seed, std.math.maxInt(usize)) catch return -1; + sim_stats(sim, out); + return 0; +} + +/// Action index a built-in policy would choose in the current state +/// (for stepping / visualizing heuristics from Python). -1 = unknown name. +/// Stateful policies (random) are reseeded from the clock and step count. +/// `name` is a policy spec, e.g. "tetris_srpt:weight=2". +export fn sim_policy_action(sim: *Sim, name: [*:0]const u8) i64 { + var buf: [1024]u8 = undefined; // per call: no growth when called every step + var fba = std.heap.FixedBufferAllocator.init(&buf); + const spec = cli.Spec.parse(fba.allocator(), "policy", std.mem.span(name)) catch return -1; + if (!registry.hasPolicy(spec.name)) return -1; + const seed = sim.eng.seed ^ (sim.eng.stats.steps *% 0x9e3779b97f4a7c15); + const act = registry.policyAction(&sim.eng, spec, seed) catch return -1; + const st = sim.eng.state(); + return @intCast(rules.encode(&st, act)); +} + +test "capi: create, mask, step to the end, run_policy" { + const cfg = SimConfig{ + .machines = "deeprm:n=2", + .jobs = "poisson:n=30,rate=0.5", + .n_res = 2, + .n_ticks = 20, + .max_jobs = 8, + }; + const sim = sim_create(&cfg) orelse return error.CreateFailed; + defer sim_destroy(sim); + + var d: SimDims = undefined; + sim_dims(sim, &d); + try std.testing.expectEqual(@as(u32, 8 * 2 + 1), d.n_actions); + + var res: SimStep = .{}; + try std.testing.expectEqual(@as(c_int, -1), sim_step(sim, 0, &res)); // before reset + try std.testing.expectEqual(@as(c_int, 0), sim_reset(sim, 1)); + + var mask: [17]u8 = undefined; + var steps: usize = 0; + while (true) : (steps += 1) { + sim_action_mask(sim, &mask); + try std.testing.expectEqual(@as(u8, 1), mask[16]); // wait always legal + var a: u32 = 16; + for (mask[0..16], 0..) |m, i| if (m == 1) { + a = @intCast(i); + break; + }; + try std.testing.expectEqual(@as(c_int, 0), sim_step(sim, a, &res)); + try std.testing.expectEqual(@as(u8, 0), res.illegal); + if (res.terminated == 1 or res.truncated == 1) break; + } + var st: SimStats = undefined; + sim_stats(sim, &st); + try std.testing.expectEqual(st.arrived, st.placed); + try std.testing.expectEqual(@as(c_int, -1), sim_step(sim, 16, &res)); // after end + + try std.testing.expectEqual(@as(c_int, 0), sim_run_policy(sim, "sjf", 1, &st)); + const want = st; + + // stepping sjf one decision at a time gives the same episode + try std.testing.expectEqual(@as(c_int, 0), sim_reset(sim, 1)); + while (true) { + const a = sim_policy_action(sim, "sjf"); + try std.testing.expect(a >= 0); + try std.testing.expectEqual(@as(c_int, 0), sim_step(sim, @intCast(a), &res)); + if (res.terminated == 1 or res.truncated == 1) break; + } + sim_stats(sim, &st); + try std.testing.expectEqual(want.avg_wait, st.avg_wait); + try std.testing.expectEqual(want.makespan, st.makespan); + try std.testing.expectEqual(@as(i64, -1), sim_policy_action(sim, "nope")); + try std.testing.expectEqual(st.arrived, st.placed); +} diff --git a/src/app/cli.zig b/src/app/cli.zig new file mode 100644 index 0000000..62a0c1b --- /dev/null +++ b/src/app/cli.zig @@ -0,0 +1,114 @@ +//! Command-line parsing: `--flag value` pairs and adapter specs of the form +//! name:key=value,key=value +//! Values: integers, floats, booleans (1/0/true/false/yes/no), +//! ranges "lo-hi", lists "a/b/c". + +const std = @import("std"); + +pub const Error = error{InvalidArgs}; + +pub fn fail(comptime fmt: []const u8, args: anytype) Error { + std.debug.print("error: " ++ fmt ++ "\n", args); + return error.InvalidArgs; +} + +pub const Spec = struct { + name: []const u8, + keys: []const []const u8, + values: []const []const u8, + /// Flag this spec came from, for error messages. + flag: []const u8, + + pub fn parse(arena: std.mem.Allocator, flag: []const u8, text: []const u8) !Spec { + const colon = std.mem.indexOfScalar(u8, text, ':'); + const name = if (colon) |c| text[0..c] else text; + if (name.len == 0) return fail("{s}: missing adapter name in '{s}'", .{ flag, text }); + + var keys: std.ArrayList([]const u8) = .empty; + var values: std.ArrayList([]const u8) = .empty; + if (colon) |c| { + var it = std.mem.splitScalar(u8, text[c + 1 ..], ','); + while (it.next()) |kv| { + if (kv.len == 0) continue; + const eq = std.mem.indexOfScalar(u8, kv, '=') orelse + return fail("{s}: expected key=value, got '{s}'", .{ flag, kv }); + try keys.append(arena, kv[0..eq]); + try values.append(arena, kv[eq + 1 ..]); + } + } + return .{ .name = name, .keys = keys.items, .values = values.items, .flag = flag }; + } + + pub fn raw(self: Spec, key: []const u8) ?[]const u8 { + for (self.keys, self.values) |k, v| if (std.mem.eql(u8, k, key)) return v; + return null; + } + + /// Reject keys not in `allowed` (catches typos). + pub fn only(self: Spec, allowed: []const []const u8) Error!void { + outer: for (self.keys) |k| { + for (allowed) |a| if (std.mem.eql(u8, k, a)) continue :outer; + return fail("{s} {s}: unknown option '{s}'", .{ self.flag, self.name, k }); + } + } + + pub fn int(self: Spec, comptime T: type, key: []const u8, default: T) Error!T { + const v = self.raw(key) orelse return default; + return std.fmt.parseInt(T, v, 10) catch fail("{s} {s}: '{s}' is not a valid integer for {s}", .{ self.flag, self.name, v, key }); + } + + pub fn float(self: Spec, key: []const u8, default: f64) Error!f64 { + const v = self.raw(key) orelse return default; + return std.fmt.parseFloat(f64, v) catch fail("{s} {s}: '{s}' is not a valid number for {s}", .{ self.flag, self.name, v, key }); + } + + pub fn boolean(self: Spec, key: []const u8, default: bool) Error!bool { + const v = self.raw(key) orelse return default; + return parseBool(v) orelse fail("{s} {s}: '{s}' is not a boolean for {s}", .{ self.flag, self.name, v, key }); + } + + pub fn range(self: Spec, comptime T: type, key: []const u8, lo: T, hi: T) Error![2]T { + const v = self.raw(key) orelse return .{ lo, hi }; + const dash = std.mem.indexOfScalar(u8, v, '-') orelse { + const x = std.fmt.parseInt(T, v, 10) catch return fail("{s} {s}: bad range '{s}' for {s}", .{ self.flag, self.name, v, key }); + return .{ x, x }; + }; + const a = std.fmt.parseInt(T, v[0..dash], 10) catch return fail("{s} {s}: bad range '{s}' for {s}", .{ self.flag, self.name, v, key }); + const b = std.fmt.parseInt(T, v[dash + 1 ..], 10) catch return fail("{s} {s}: bad range '{s}' for {s}", .{ self.flag, self.name, v, key }); + if (a > b) return fail("{s} {s}: range '{s}' has lo > hi", .{ self.flag, self.name, v }); + return .{ a, b }; + } + + pub fn list(self: Spec, arena: std.mem.Allocator, comptime T: type, key: []const u8, default: []const T) ![]const T { + const v = self.raw(key) orelse return default; + var out: std.ArrayList(T) = .empty; + var it = std.mem.splitScalar(u8, v, '/'); + while (it.next()) |p| try out.append(arena, std.fmt.parseInt(T, p, 10) catch + return fail("{s} {s}: bad list '{s}' for {s}", .{ self.flag, self.name, v, key })); + if (out.items.len == 0) return fail("{s} {s}: empty list for {s}", .{ self.flag, self.name, key }); + return out.items; + } +}; + +pub fn parseBool(v: []const u8) ?bool { + const t = [_][]const u8{ "1", "true", "yes", "on" }; + const f = [_][]const u8{ "0", "false", "no", "off" }; + for (t) |x| if (std.ascii.eqlIgnoreCase(v, x)) return true; + for (f) |x| if (std.ascii.eqlIgnoreCase(v, x)) return false; + return null; +} + +test "spec parsing" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const s = try Spec.parse(a, "--machines", "random:n=4,caps=100/80,dur=2-9,varying=yes"); + try std.testing.expectEqualStrings("random", s.name); + try std.testing.expectEqual(@as(usize, 4), try s.int(usize, "n", 1)); + try std.testing.expectEqualSlices(u16, &.{ 100, 80 }, try s.list(a, u16, "caps", &.{})); + try std.testing.expectEqual([2]u16{ 2, 9 }, try s.range(u16, "dur", 1, 1)); + try std.testing.expect(try s.boolean("varying", false)); + try std.testing.expectEqual(@as(usize, 7), try s.int(usize, "missing", 7)); + try s.only(&.{ "n", "caps", "dur", "varying" }); + try std.testing.expectEqualStrings("fifo", (try Spec.parse(a, "--policy", "fifo")).name); +} diff --git a/src/app/main.zig b/src/app/main.zig index 3780ef2..6d8dfc8 100644 --- a/src/app/main.zig +++ b/src/app/main.zig @@ -1,4 +1,127 @@ +//! Composition root: parse the command line, build the chosen adapters, +//! wire them into the engine, run. + const std = @import("std"); -pub fn main() !void { - std.debug.print("Hello world", .{}); +const sched = @import("sched"); +const cli = @import("cli.zig"); +const registry = @import("registry.zig"); + +const usage_text = + \\sim — SIMD job-to-machine scheduling simulator + \\ + \\usage: sim [options] + \\ --machines usage generator (default random) + \\ --jobs arrival source (default poisson) + \\ --policy scheduling policy (default fifo), e.g. tetris_srpt:weight=2 + \\ --observe observer, repeatable (viz, metrics, log) + \\ --res resources per machine (default 10) + \\ --ticks horizon in ticks (default 100) + \\ --pool waiting-job slots (default 128) + \\ --reward neg_in_system | neg_waiting | slowdown | zero + \\ --max-ticks truncate episodes at this tick + \\ --seed random seed (default 42) + \\ --episodes episodes to run (default 1) + \\ --list list adapters and their options + \\ --help + \\ + \\spec: name:key=value,key=value e.g. random:n=8,caps=100/50,dur=1-10 + \\ + \\examples: + \\ sim --observe viz + \\ sim --machines deeprm:n=2 --jobs poisson:n=300,rate=0.8 --policy sjf --observe metrics + \\ sim --policy best_fit --observe viz:delay=30,per_resource=1 --observe metrics + \\ +; + +pub fn main(init: std.process.Init) !void { + run(init) catch |e| switch (e) { + error.InvalidArgs => std.process.exit(2), + else => return e, + }; +} + +fn run(init: std.process.Init) !void { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + + // ---------------- parse ---------------- + var machines_spec: []const u8 = "random"; + var jobs_spec: []const u8 = "poisson"; + var policy: []const u8 = "fifo"; + var reward_spec: ?[]const u8 = null; + var observe: std.ArrayList([]const u8) = .empty; + var cfg = sched.Config{}; + var seed: u64 = 42; + var episodes: usize = 1; + + var i: usize = 1; + while (i < args.len) : (i += 1) { + const a = args[i]; + if (std.mem.eql(u8, a, "--help") or std.mem.eql(u8, a, "-h")) { + std.debug.print("{s}", .{usage_text}); + return; + } + if (std.mem.eql(u8, a, "--list")) { + std.debug.print("{s}", .{registry.list_text}); + return; + } + if (i + 1 >= args.len) return cli.fail("{s} needs a value (see --help)", .{a}); + const v = args[i + 1]; + i += 1; + if (std.mem.eql(u8, a, "--machines")) machines_spec = v + else if (std.mem.eql(u8, a, "--jobs")) jobs_spec = v + else if (std.mem.eql(u8, a, "--policy")) policy = v + else if (std.mem.eql(u8, a, "--observe")) try observe.append(arena, v) + else if (std.mem.eql(u8, a, "--res")) cfg.n_res = try parseNum(usize, a, v) + else if (std.mem.eql(u8, a, "--ticks")) cfg.n_ticks = try parseNum(usize, a, v) + else if (std.mem.eql(u8, a, "--pool")) cfg.max_jobs = try parseNum(usize, a, v) + else if (std.mem.eql(u8, a, "--max-ticks")) cfg.max_ticks = try parseNum(i64, a, v) + else if (std.mem.eql(u8, a, "--seed")) seed = try parseNum(u64, a, v) + else if (std.mem.eql(u8, a, "--episodes")) episodes = try parseNum(usize, a, v) + else if (std.mem.eql(u8, a, "--reward")) reward_spec = v + else return cli.fail("unknown option '{s}' (see --help)", .{a}); + } + const policy_spec = try cli.Spec.parse(arena, "--policy", policy); + if (!registry.hasPolicy(policy_spec.name)) return cli.fail("--policy: unknown policy '{s}' (see --list)", .{policy_spec.name}); + + // ---------------- build adapters ---------------- + const gen = try registry.generator(arena, try cli.Spec.parse(arena, "--machines", machines_spec)); + defer gen.deinit(); + const arr = try registry.arrivals(arena, try cli.Spec.parse(arena, "--jobs", jobs_spec)); + defer arr.deinit(); + + var eng = sched.Engine.init(gpa, cfg, arr, gen) catch |e| switch (e) { + error.ZeroResources, error.ZeroTicks => return cli.fail("--res and --ticks must be > 0", .{}), + error.NoMachines => return cli.fail("--machines: n must be > 0", .{}), + else => return e, + }; + defer eng.deinit(); + if (reward_spec) |rs| eng.setReward(try registry.reward(arena, try cli.Spec.parse(arena, "--reward", rs))); + + for (observe.items) |o| try eng.addObserver(try registry.observer(arena, gpa, io, try cli.Spec.parse(arena, "--observe", o))); + defer eng.observers.deinitAll(); + + // ---------------- run ---------------- + for (0..episodes) |e| { + const ep_seed = seed +% e; + try eng.reset(ep_seed); + const t0 = std.Io.Timestamp.now(io, .awake); + const st = try registry.runPolicy(&eng, policy_spec, ep_seed, 100_000_000); + const us = t0.durationTo(std.Io.Timestamp.now(io, .awake)).toMicroseconds(); + + std.debug.print( + "episode {d} seed {d} policy {s} placed {d}/{d} makespan {d} avg wait {d:.2} util {d:.1}% reward {d:.0} steps {d} {d} us\n", + .{ e, ep_seed, policy, st.placed, st.arrived, st.makespan, st.avgWait(), st.avgUtil() * 100, st.total_reward, st.steps, us }, + ); + } +} + +fn parseNum(comptime T: type, flag: []const u8, v: []const u8) !T { + return std.fmt.parseInt(T, v, 10) catch cli.fail("{s}: '{s}' is not a valid number", .{ flag, v }); +} + +test { + _ = cli; } diff --git a/src/app/registry.zig b/src/app/registry.zig new file mode 100644 index 0000000..d50e839 --- /dev/null +++ b/src/app/registry.zig @@ -0,0 +1,283 @@ +//! Registry: maps adapter names typed by the user to constructors. +//! Adding an adapter = one entry here; the engine and other adapters do not +//! change. Adapters are allocated in the arena and live for the whole run. + +const std = @import("std"); +const sched = @import("sched"); +const cli = @import("cli.zig"); + +const ports = sched.ports; +const A = sched.adapters; +const Elem = sched.Elem; +const Spec = cli.Spec; + +// ---------------------------------------------------------------- generators + +pub fn generator(arena: std.mem.Allocator, s: Spec) !ports.UsageGenerator { + if (std.mem.eql(u8, s.name, "random")) { + try s.only(&.{ "n", "caps", "dur", "demand", "varying" }); + const g = try arena.create(A.generators.RandomProfiles); + const dur = try s.range(u16, "dur", 1, 20); + const dem = try s.range(Elem, "demand", 0, 30); + g.* = .{ + .n_machines = try s.int(usize, "n", 4), + .caps = try s.list(arena, Elem, "caps", &.{ 100, 80, 60, 40 }), + .dur_min = dur[0], + .dur_max = dur[1], + .demand_min = dem[0], + .demand_max = dem[1], + .varying = try s.boolean("varying", false), + }; + return .init(g); + } + if (std.mem.eql(u8, s.name, "deeprm")) { + try s.only(&.{ "n", "cap", "short", "long", "short_prob" }); + const g = try arena.create(A.generators.DeepRM); + const long = try s.range(u16, "long", 10, 15); + g.* = .{ + .n_machines = try s.int(usize, "n", 1), + .cap = try s.int(Elem, "cap", 100), + .short_max = try s.int(u16, "short", 3), + .long_min = long[0], + .long_max = long[1], + .short_prob = try s.float("short_prob", 0.8), + }; + return .init(g); + } + return cli.fail("--machines: unknown generator '{s}' (see --list)", .{s.name}); +} + +// ---------------------------------------------------------------- arrivals + +pub fn arrivals(arena: std.mem.Allocator, s: Spec) !ports.ArrivalSource { + if (std.mem.eql(u8, s.name, "poisson")) { + try s.only(&.{ "n", "rate" }); + const p = try arena.create(A.arrivals.Poisson); + p.* = .{ .total = try s.int(usize, "n", 500), .rate = try s.float("rate", 1.0) }; + return .init(p); + } + if (std.mem.eql(u8, s.name, "mmpp")) { + try s.only(&.{ "n", "rate", "ratio", "calm", "burst" }); + const p = try arena.create(A.arrivals.Mmpp); + p.* = .{ + .total = try s.int(usize, "n", 500), + .rate = try s.float("rate", 1.0), + .ratio = try s.float("ratio", 10), + .calm = try s.float("calm", 40), + .burst_len = try s.float("burst", 10), + }; + if (p.rate <= 0 or p.ratio < 1) return cli.fail("--jobs mmpp: need rate > 0 and ratio >= 1", .{}); + return .init(p); + } + if (std.mem.eql(u8, s.name, "pareto")) { + try s.only(&.{ "n", "rate", "alpha" }); + const p = try arena.create(A.arrivals.ParetoArrivals); + p.* = .{ .total = try s.int(usize, "n", 500), .rate = try s.float("rate", 1.0), .alpha = try s.float("alpha", 1.5) }; + if (p.rate <= 0 or p.alpha <= 1) return cli.fail("--jobs pareto: need rate > 0 and alpha > 1", .{}); + return .init(p); + } + if (std.mem.eql(u8, s.name, "selfsimilar")) { + try s.only(&.{ "n", "rate", "sources", "alpha", "period" }); + const p = try arena.create(A.arrivals.SelfSimilar); + p.* = .{ + .total = try s.int(usize, "n", 500), + .rate = try s.float("rate", 1.0), + .sources = try s.int(usize, "sources", 8), + .alpha = try s.float("alpha", 1.4), + .period = try s.float("period", 50), + }; + if (p.rate <= 0 or p.alpha <= 1 or p.sources == 0 or p.sources > 256) + return cli.fail("--jobs selfsimilar: need rate > 0, alpha > 1, 1 <= sources <= 256", .{}); + return .init(p); + } + if (std.mem.eql(u8, s.name, "batch")) { + try s.only(&.{"n"}); + const p = try arena.create(A.arrivals.Poisson); + p.* = .{ .total = try s.int(usize, "n", 200), .rate = 0 }; + return .init(p); + } + return cli.fail("--jobs: unknown arrival source '{s}' (see --list)", .{s.name}); +} + +// ---------------------------------------------------------------- rewards + +pub fn reward(arena: std.mem.Allocator, s: Spec) !ports.Reward { + if (std.mem.eql(u8, s.name, "neg_in_system")) { + try s.only(&.{}); + return .init(try arena.create(A.rewards.NegInSystem)); + } + if (std.mem.eql(u8, s.name, "neg_waiting")) { + try s.only(&.{}); + return .init(try arena.create(A.rewards.NegWaiting)); + } + if (std.mem.eql(u8, s.name, "zero")) { + try s.only(&.{}); + return .init(try arena.create(A.rewards.Zero)); + } + if (std.mem.eql(u8, s.name, "slowdown")) { + try s.only(&.{"min_dur"}); + const r = try arena.create(A.rewards.Slowdown); + r.* = .{ .min_dur = try s.int(u16, "min_dur", 1) }; + return .init(r); + } + return cli.fail("--reward: unknown reward '{s}' (see --list)", .{s.name}); +} + +// ---------------------------------------------------------------- observers + +pub fn observer(arena: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, s: Spec) !ports.Observer { + if (std.mem.eql(u8, s.name, "viz")) { + try s.only(&.{ "delay", "per_resource", "on_place", "jobs", "cols", "color" }); + const v = try arena.create(A.observers.TerminalViz); + v.* = .init(gpa, io, .{ + .delay_ms = try s.int(u32, "delay", 80), + .per_resource = try s.boolean("per_resource", false), + .on_place = try s.boolean("on_place", false), + .max_jobs = try s.int(usize, "jobs", 20), + .max_cols = try s.int(usize, "cols", 100), + .color = try s.boolean("color", true), + }); + return .init(v); + } + if (std.mem.eql(u8, s.name, "metrics")) { + try s.only(&.{}); + const m = try arena.create(A.observers.Metrics); + m.* = .init(gpa); + return .init(m); + } + if (std.mem.eql(u8, s.name, "trace")) { + try s.only(&.{ "path", "ticks" }); + const t = try arena.create(A.observers.Trace); + t.* = .{ .ticks = try s.boolean("ticks", true) }; + const path = s.raw("path") orelse "trace.jsonl"; + t.open(io, std.Io.Dir.cwd(), path) catch |e| + return cli.fail("--observe trace: cannot create '{s}': {t}", .{ path, e }); + return .init(t); + } + if (std.mem.eql(u8, s.name, "log")) { + try s.only(&.{"ticks"}); + const l = try arena.create(A.observers.EventLog); + l.* = .{ .ticks = try s.boolean("ticks", false) }; + return .init(l); + } + return cli.fail("--observe: unknown observer '{s}' (see --list)", .{s.name}); +} + +// ---------------------------------------------------------------- policies +// Chosen at run time, executed through a comptime-specialized loop per type. + +pub const policy_types = .{ + A.policies.FifoBackfill, + A.policies.FifoStrict, + A.policies.ShortestFirst, + A.policies.BestFit, + A.policies.RandomPolicy, + A.policies.Tetris, + A.policies.TetrisSrpt, +}; + +pub fn hasPolicy(name: []const u8) bool { + inline for (policy_types) |P| if (std.mem.eql(u8, name, P.name)) return true; + return false; +} + +/// Build policy P from a spec: every numeric field of P is an option +/// (e.g. `tetris_srpt:weight=2`); other fields keep their defaults. +pub fn makePolicy(comptime P: type, s: Spec) !P { + const info = @typeInfo(P).@"struct"; + const numeric = comptime blk: { + var names: []const []const u8 = &.{}; + for (info.field_names, info.field_types) |n, T| switch (@typeInfo(T)) { + .float, .int => names = names ++ .{n}, + else => {}, + }; + break :blk names; + }; + try s.only(numeric); + var p = P{}; + inline for (info.field_names, info.field_types) |n, T| switch (@typeInfo(T)) { + .float => @field(p, n) = @floatCast(try s.float(n, @field(p, n))), + .int => @field(p, n) = try s.int(T, n, @field(p, n)), + else => {}, + }; + return p; +} + +pub fn runPolicy(eng: *sched.Engine, s: Spec, seed: u64, max_steps: usize) !sched.Stats { + inline for (policy_types) |P| { + if (std.mem.eql(u8, s.name, P.name)) { + comptime ports.assertPolicy(P); + var p = try makePolicy(P, s); + defer ports.policy.deinitIfAny(P, &p); + ports.policy.resetIfAny(P, &p, seed); + return eng.run(&p, max_steps); + } + } + return cli.fail("--policy: unknown policy '{s}' (see --list)", .{s.name}); +} + +/// The action policy `s` would take in the current state. +pub fn policyAction(eng: *sched.Engine, s: Spec, seed: u64) !sched.Action { + const st = eng.state(); + inline for (policy_types) |P| { + if (std.mem.eql(u8, s.name, P.name)) { + var p = try makePolicy(P, s); + defer ports.policy.deinitIfAny(P, &p); + ports.policy.resetIfAny(P, &p, seed); + return p.decide(&st); + } + } + return cli.fail("policy: unknown policy '{s}' (see --list)", .{s.name}); +} + +test "policy specs set numeric fields" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = try makePolicy(A.policies.TetrisSrpt, try Spec.parse(a, "--policy", "tetris_srpt:weight=2.5")); + try std.testing.expectEqual(@as(f32, 2.5), p.weight); + const d = try makePolicy(A.policies.TetrisSrpt, try Spec.parse(a, "--policy", "tetris_srpt")); + try std.testing.expectEqual(@as(f32, 1.5), d.weight); +} + +pub const list_text = + \\Machines / usage generators (--machines): + \\ random n=4 caps=100/80/60/40 dur=1-20 demand=0-30 varying=0 + \\ machines cycle through caps; uniform random duration and demand + \\ deeprm n=1 cap=100 short=3 long=10-15 short_prob=0.8 + \\ DeepRM workload: 80% short jobs, one dominant resource per job + \\ + \\Job arrivals (--jobs): + \\ poisson n=500 rate=1.0 exponential gaps, mean 1/rate ticks + \\ mmpp n=500 rate=1.0 ratio=10 calm=40 burst=10 + \\ bursty: calm/burst states (mean lengths in ticks), burst rate = ratio x calm rate + \\ pareto n=500 rate=1.0 alpha=1.5 heavy-tailed gaps (infinite variance if alpha <= 2) + \\ selfsimilar n=500 rate=1.0 sources=8 alpha=1.4 period=50 + \\ Pareto ON/OFF sources, long-range dependent, Hurst H = (3 - alpha)/2 + \\ batch n=200 all jobs at tick 0 + \\ + \\Policies (--policy): + \\ fifo oldest job that fits now (backfill) + \\ fifo_strict only the oldest job; wait if it does not fit + \\ sjf shortest job that fits now + \\ best_fit (job, machine) pair leaving least free capacity + \\ random random legal placement + \\ 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) + \\ + \\Rewards (--reward), per elapsed tick: + \\ neg_in_system -(waiting + running) (default) + \\ neg_waiting -waiting + \\ slowdown min_dur=1 -sum 1/max(T_j, min_dur) over jobs in system (DeepRM) + \\ zero 0 + \\ + \\Observers (--observe, repeatable): + \\ viz delay=80 per_resource=0 on_place=0 jobs=20 cols=100 color=1 + \\ metrics wait percentiles, utilization, jobs per machine + \\ log ticks=0 one line per event + \\ trace path=trace.jsonl ticks=1 + \\ every event + job profiles as JSON Lines, for replay / visualization + \\ (python python/examples/replay.py trace.jsonl) + \\ +; diff --git a/src/engine.zig b/src/engine.zig new file mode 100644 index 0000000..626b5bc --- /dev/null +++ b/src/engine.zig @@ -0,0 +1,11 @@ +//! Engine layer: rules and the step loop. +pub const rules = @import("engine/rules.zig"); +pub const Config = rules.Config; +pub const Engine = @import("engine/engine.zig").Engine; +pub const StepResult = @import("engine/engine.zig").StepResult; +pub const Stats = @import("engine/engine.zig").Stats; + +test { + _ = rules; + _ = @import("engine/engine.zig"); +} diff --git a/src/engine/engine.zig b/src/engine/engine.zig index e69de29..5672a6c 100644 --- a/src/engine/engine.zig +++ b/src/engine/engine.zig @@ -0,0 +1,311 @@ +//! Engine: applies actions and enforces the rules. It makes no decisions +//! (Policy port), creates no data itself (ArrivalSource, UsageGenerator +//! ports) and does no I/O (Observer port). +//! +//! One step = one action: +//! .place → validate, subtract the job from the machine, emit job_placed +//! .wait → advance time one tick (or more with skip_empty), pull arrivals, +//! emit tick_advanced, return the tick reward +//! Illegal actions are reported, penalized and treated as .wait. + +const std = @import("std"); +const grid = @import("../grid.zig"); +const model = @import("../model.zig"); +const ports = @import("../ports.zig"); +pub const rules = @import("rules.zig"); + +const Elem = grid.Elem; +const Layout = grid.Layout; +const Machines = model.Machines; +const Jobs = model.Jobs; +const State = model.State; +const Action = model.Action; +const Event = model.Event; + +pub const Config = rules.Config; + +pub const StepResult = struct { + reward: f32 = 0, + terminated: bool = false, + truncated: bool = false, + placed: bool = false, + illegal: bool = false, +}; + +pub const Stats = struct { + arrived: usize = 0, + placed: usize = 0, + rejected: usize = 0, + illegal: usize = 0, + steps: usize = 0, + total_wait: i64 = 0, + max_wait: i64 = 0, + makespan: i64 = 0, + total_reward: f64 = 0, + util_sum: f64 = 0, // sum over ticks of utilization at tick 0 + ticks: i64 = 0, + + pub fn avgWait(s: Stats) f64 { + if (s.placed == 0) return 0; + return @as(f64, @floatFromInt(s.total_wait)) / @as(f64, @floatFromInt(s.placed)); + } + pub fn avgUtil(s: Stats) f64 { + if (s.ticks == 0) return 0; + return s.util_sum / @as(f64, @floatFromInt(s.ticks)); + } +}; + +pub const Engine = struct { + gpa: std.mem.Allocator, + cfg: Config, + layout: Layout, + machines: Machines, + jobs: Jobs, + arrivals: ports.ArrivalSource, + generator: ports.UsageGenerator, + observers: ports.ObserverList = .{}, + /// Tick reward; null = rules.defaultTickReward (−(waiting + running)). + reward: ?ports.Reward = null, + + now: i64 = 0, + seed: u64 = 0, + running: std.ArrayList(model.RunningJob) = .empty, + stats: Stats = .{}, + finished: bool = false, + + pub fn init( + gpa: std.mem.Allocator, + cfg: Config, + arrivals: ports.ArrivalSource, + generator: ports.UsageGenerator, + ) !Engine { + const layout = try Layout.init(cfg.n_res, cfg.n_ticks, cfg.padding); + + const n_m = generator.machineCount(); + if (n_m == 0) return error.NoMachines; + const caps = try gpa.alloc(Elem, n_m * cfg.n_res); + defer gpa.free(caps); + for (0..n_m) |m| try generator.machine(m, caps[m * cfg.n_res ..][0..cfg.n_res]); + + var machines = try Machines.init(gpa, layout, n_m, caps); + errdefer machines.deinit(gpa); + const jobs = try Jobs.init(gpa, layout, cfg.max_jobs); + + return .{ + .gpa = gpa, + .cfg = cfg, + .layout = layout, + .machines = machines, + .jobs = jobs, + .arrivals = arrivals, + .generator = generator, + }; + } + + pub fn deinit(self: *Engine) void { + self.machines.deinit(self.gpa); + self.jobs.deinit(self.gpa); + self.running.deinit(self.gpa); + } + + pub fn setReward(self: *Engine, r: ?ports.Reward) void { + self.reward = r; + } + + /// Jobs currently running (started, not finished). + pub fn runningJobs(self: *const Engine) []const model.RunningJob { + return self.running.items; + } + + pub fn addObserver(self: *Engine, o: ports.Observer) !void { + try self.observers.add(o); + } + + pub fn state(self: *const Engine) State { + return .{ .now = self.now, .machines = &self.machines, .jobs = &self.jobs }; + } + + pub fn done(self: *const Engine) bool { + return self.finished; + } + + // ------------------------------------------------------------------ + // episode + // ------------------------------------------------------------------ + + pub fn reset(self: *Engine, seed: u64) !void { + self.seed = seed; + self.arrivals.reset(seed); + self.generator.reset(seed); + if (self.reward) |r| r.reset(seed); + self.machines.resetAll(); + self.jobs.clearAll(); + self.running.clearRetainingCapacity(); + self.now = 0; + self.stats = .{}; + self.finished = false; + + self.emit(.{ .episode_started = .{ .seed = seed } }); + try self.pullArrivals(); + _ = self.checkEnd(); + } + + /// Apply one action. + pub fn step(self: *Engine, action: Action) !StepResult { + std.debug.assert(!self.finished); + var res = StepResult{}; + self.stats.steps += 1; + + var act = action; + if (!rules.isLegal(&self.state(), act)) { + res.illegal = true; + res.reward += self.cfg.illegal_penalty; + self.stats.illegal += 1; + self.emit(.{ .illegal_action = .{ .action = act, .tick = self.now } }); + act = .wait; + } + + switch (act) { + .place => |p| { + try self.placeNow(p.slot, p.machine); + res.placed = true; + }, + .wait => { + res.reward += try self.advanceTick(); + if (self.cfg.skip_empty) { + while (self.jobs.count == 0 and !self.endReached()) + res.reward += try self.advanceTick(); + } + }, + } + + const end = self.checkEnd(); + res.terminated = end == .terminated; + res.truncated = end == .truncated; + self.stats.total_reward += res.reward; + return res; + } + + /// Run a full episode with any policy that has + /// `decide(self, *const State) Action` (comptime-dispatched, inlinable). + pub fn run(self: *Engine, policy: anytype, max_steps: usize) !Stats { + while (!self.finished and self.stats.steps < max_steps) { + const st = self.state(); + _ = try self.step(policy.decide(&st)); + } + return self.stats; + } + + // ------------------------------------------------------------------ + // internals + // ------------------------------------------------------------------ + + fn emit(self: *Engine, ev: Event) void { + if (self.observers.len == 0) return; + const st = self.state(); + self.observers.emit(ev, &st); + } + + fn placeNow(self: *Engine, slot: usize, m: usize) !void { + const dur = self.jobs.duration[slot]; + self.machines.get(m).place(self.jobs.get(slot), dur, 0); + self.machines.touch(m); + + const wait = self.now - self.jobs.arrival[slot]; + const finish = self.now + dur; + try self.running.append(self.gpa, .{ .id = self.jobs.id[slot], .machine = @intCast(m), .start = self.now, .dur = dur }); + self.stats.placed += 1; + self.stats.total_wait += wait; + self.stats.max_wait = @max(self.stats.max_wait, wait); + self.stats.makespan = @max(self.stats.makespan, finish); + + self.emit(.{ .job_placed = .{ + .id = self.jobs.id[slot], + .slot = @intCast(slot), + .machine = @intCast(m), + .tick = self.now, + .arrival = self.jobs.arrival[slot], + .dur = dur, + } }); + self.jobs.remove(slot); + } + + /// One tick of time. Returns that tick's reward. + fn advanceTick(self: *Engine) !f32 { + const reward = if (self.reward) |r| blk: { + const st = self.state(); + break :blk r.tick(&.{ .state = &st, .running = self.running.items }); + } else rules.defaultTickReward(self.jobs.count, self.running.items.len); + self.stats.util_sum += self.machines.utilizationNow(); + self.stats.ticks += 1; + + self.machines.advanceAll(1); + self.now += 1; + + var i: usize = 0; + while (i < self.running.items.len) { + if (self.running.items[i].finish() <= self.now) { + _ = self.running.swapRemove(i); + } else i += 1; + } + + try self.pullArrivals(); + self.jobs.clearBlocked(); // capacity freed up: re-check everything + self.emit(.{ .tick_advanced = .{ .now = self.now } }); + return reward; + } + + fn pullArrivals(self: *Engine) !void { + while (try self.arrivals.next(self.now)) |meta| { + const slot = self.jobs.acquire() orelse { + self.reject(meta.id, .pool_full); + continue; + }; + const dur = self.generator.job(meta, self.jobs.get(slot)) catch |e| switch (e) { + error.OutOfMemory => return e, + else => { + self.jobs.abort(slot); + self.reject(meta.id, .invalid_profile); + continue; + }, + }; + if (dur == 0 or dur > self.layout.n_ticks) { + self.jobs.abort(slot); + self.reject(meta.id, .invalid_profile); + continue; + } + self.jobs.commit(slot, meta, dur); + + if (self.cfg.drop_impossible and !self.machines.anyCanEverFit(self.jobs.peakOf(slot))) { + self.jobs.remove(slot); + self.reject(meta.id, .impossible); + continue; + } + self.stats.arrived += 1; + self.emit(.{ .job_arrived = .{ .id = meta.id, .slot = @intCast(slot), .tick = self.now } }); + } + } + + fn reject(self: *Engine, id: u32, reason: model.RejectReason) void { + self.stats.rejected += 1; + self.emit(.{ .job_rejected = .{ .id = id, .reason = reason, .tick = self.now } }); + } + + const End = enum { none, terminated, truncated }; + + fn endReached(self: *const Engine) bool { + const all_done = self.arrivals.done() and self.jobs.count == 0 and self.running.items.len == 0; + const trunc = if (self.cfg.max_ticks) |mt| self.now >= mt else false; + return all_done or trunc; + } + + fn checkEnd(self: *Engine) End { + if (self.finished) return .none; + const all_done = self.arrivals.done() and self.jobs.count == 0 and self.running.items.len == 0; + const trunc = if (self.cfg.max_ticks) |mt| self.now >= mt else false; + if (!all_done and !trunc) return .none; + self.finished = true; + self.emit(.{ .episode_done = .{ .now = self.now, .makespan = self.stats.makespan, .truncated = !all_done } }); + return if (all_done) .terminated else .truncated; + } +}; diff --git a/src/engine/rules.zig b/src/engine/rules.zig index e69de29..b95860a 100644 --- a/src/engine/rules.zig +++ b/src/engine/rules.zig @@ -0,0 +1,106 @@ +//! Simulation rules: configuration, legality, default reward, action encoding. +//! Shared by the engine (enforcement) and by policies (queries), so both +//! use exactly the same definition of "fits". + +const std = @import("std"); +const grid = @import("../grid.zig"); +const model = @import("../model.zig"); +const State = model.State; +const Action = model.Action; + +pub const Config = struct { + n_res: usize = 10, + n_ticks: usize = 100, + /// Job slots in the waiting pool (observation size). + max_jobs: usize = 128, + /// Memory padding rule (CPU, or grid.simd_gpu.unified_padding). + padding: grid.Padding = grid.simd.padding, + /// Added to the reward of an illegal action (then treated as wait). + illegal_penalty: f32 = -1.0, + /// Truncate the episode at this tick (null = never). + max_ticks: ?i64 = null, + /// Drop arriving jobs that no machine could ever run. + drop_impossible: bool = true, + /// When the pool is empty, fast-forward time until a job arrives. + skip_empty: bool = true, +}; + +/// Can `slot` start now (tick 0) on machine `m`? Cheap checks, then SIMD. +pub fn fitsNow(state: *const State, slot: usize, m: usize) bool { + const jobs = state.jobs; + const mach = state.machines.get(m); + const job = jobs.get(slot); + if (!mach.mayFit(job, jobs.peakOf(slot), 0)) return false; + return mach.canPlace(job, jobs.duration[slot], 0); +} + +/// Is `action` legal in `state`? +pub fn isLegal(state: *const State, action: Action) bool { + return switch (action) { + .wait => true, + .place => |p| p.slot < state.jobs.cap and state.jobs.isValid(p.slot) and + p.machine < state.machines.n and fitsNow(state, p.slot, p.machine), + }; +} + +/// First machine on which `slot` fits now, or null. +pub fn firstMachine(state: *const State, slot: usize) ?usize { + if (state.jobs.isBlocked(slot)) return null; + for (0..state.machines.n) |m| if (fitsNow(state, slot, m)) return m; + state.jobs.markBlocked(slot); + return null; +} + +/// Known (this tick) to fit on no machine? Policies that scan all +/// (job, machine) pairs skip such jobs; after a scan that found no machine +/// they call markBlocked. Valid until time advances (the engine clears it). +pub inline fn knownBlocked(state: *const State, slot: usize) bool { + return state.jobs.isBlocked(slot); +} +pub inline fn markBlocked(state: *const State, slot: usize) void { + state.jobs.markBlocked(slot); +} + +/// Default tick reward when no Reward port is set: −(waiting + running). +pub fn defaultTickReward(waiting: usize, running: usize) f32 { + return -@as(f32, @floatFromInt(waiting + running)); +} + +// ---------------- flat action encoding (for RL / Gymnasium) ---------------- +// index < max_jobs * n_machines : place(slot = i / n_machines, machine = i % n_machines) +// index == max_jobs * n_machines: wait + +pub fn actionCount(state: *const State) usize { + return state.jobs.cap * state.machines.n + 1; +} + +pub fn decode(state: *const State, index: usize) Action { + const n_m = state.machines.n; + if (index >= state.jobs.cap * n_m) return .wait; + return .{ .place = .{ .slot = @intCast(index / n_m), .machine = @intCast(index % n_m) } }; +} + +pub fn encode(state: *const State, action: Action) usize { + return switch (action) { + .wait => state.jobs.cap * state.machines.n, + .place => |p| p.slot * state.machines.n + p.machine, + }; +} + +/// mask[i] = action i is legal. `mask.len == actionCount(state)`. +pub fn actionMask(state: *const State, mask: []bool) void { + std.debug.assert(mask.len == actionCount(state)); + @memset(mask, false); + mask[mask.len - 1] = true; // wait + var it = state.jobs.iter(); + while (it.next()) |s| { + if (state.jobs.isBlocked(s)) continue; + var any = false; + for (0..state.machines.n) |m| { + const f = fitsNow(state, s, m); + mask[s * state.machines.n + m] = f; + any = any or f; + } + if (!any) state.jobs.markBlocked(s); + } +} diff --git a/src/grid.zig b/src/grid.zig new file mode 100644 index 0000000..87c9a09 --- /dev/null +++ b/src/grid.zig @@ -0,0 +1,21 @@ +//! Grid layer: padded, aligned [resource][tick] grids of `Elem`. +//! CPU SIMD operations in `Usage`; padding rules for CPU, GPU and unified +//! memory in `simd` / `simd_gpu`. Knows nothing about jobs or machines. + +pub const types = @import("grid/types.zig"); +pub const Elem = types.Elem; +pub const Padding = types.Padding; + +pub const simd = @import("grid/simd.zig"); +pub const simd_gpu = @import("grid/simd_gpu.zig"); + +pub const Layout = @import("grid/layout.zig").Layout; +pub const Usage = @import("grid/usage.zig").Usage; + +test { + _ = types; + _ = simd; + _ = simd_gpu; + _ = @import("grid/layout.zig"); + _ = @import("grid/usage.zig"); +} diff --git a/src/grid/layout.zig b/src/grid/layout.zig index e69de29..df93b1e 100644 --- a/src/grid/layout.zig +++ b/src/grid/layout.zig @@ -0,0 +1,77 @@ +//! Runtime shape of a [resource][tick] grid, padded by a Padding rule +//! (CPU, GPU or unified). Every grid used together must share one Layout. +//! +//! row r: tick 0 … tick n_ticks-1 | padding | ← stride elements +//! +//! * stride: multiple of padding.lanes, with at least `lanes` slack after +//! the real ticks, so windows rounded up to whole vectors / warps stay +//! inside their row. +//! * block: elements per grid, rounded so each grid in a pool starts at a +//! multiple of padding.align_bytes. + +const std = @import("std"); +const types = @import("types.zig"); +const Elem = types.Elem; +pub const Padding = types.Padding; + +pub const Layout = struct { + n_res: usize, + n_ticks: usize, + stride: usize, + block: usize, + padding: Padding, + + pub const Error = error{ ZeroResources, ZeroTicks, InvalidPadding }; + + pub fn init(n_res: usize, n_ticks: usize, padding: Padding) Error!Layout { + if (n_res == 0) return error.ZeroResources; + if (n_ticks == 0) return error.ZeroTicks; + try padding.validate(); + + const stride = std.mem.alignForward(usize, n_ticks + padding.lanes, padding.lanes); + const per_align = @max(1, padding.align_bytes / @sizeOf(Elem)); + return .{ + .n_res = n_res, + .n_ticks = n_ticks, + .stride = stride, + .block = std.mem.alignForward(usize, n_res * stride, per_align), + .padding = padding, + }; + } + + pub fn bytesPerGrid(self: Layout) usize { + return self.block * @sizeOf(Elem); + } + + pub inline fn rowOffset(self: Layout, r: usize) usize { + return r * self.stride; + } + + pub inline fn gridOffset(self: Layout, i: usize) usize { + return i * self.block; + } + + pub fn eql(a: Layout, b: Layout) bool { + return a.n_res == b.n_res and a.n_ticks == b.n_ticks and + a.stride == b.stride and a.block == b.block; + } +}; + +test "layout for cpu, gpu and unified padding" { + const t = std.testing; + const pads = [_]Padding{ + .{ .lanes = 8, .align_bytes = 128 }, + .{ .lanes = 32, .align_bytes = 256 }, + Padding.combine(.{ .lanes = 16, .align_bytes = 64 }, .{ .lanes = 32, .align_bytes = 256 }), + }; + for (pads) |p| { + for ([_]usize{ 1, 7, 100, 128 }) |n| { + const lay = try Layout.init(10, n, p); + try t.expect(lay.stride % p.lanes == 0); + try t.expect(lay.stride >= n + p.lanes); + try t.expect(lay.bytesPerGrid() % p.align_bytes == 0); + } + } + try t.expectError(error.ZeroResources, Layout.init(0, 10, pads[0])); + try t.expectError(error.InvalidPadding, Layout.init(1, 10, .{ .lanes = 3, .align_bytes = 64 })); +} diff --git a/src/grid/simd.zig b/src/grid/simd.zig index e69de29..cbbf0ab 100644 --- a/src/grid/simd.zig +++ b/src/grid/simd.zig @@ -0,0 +1,62 @@ +//! CPU SIMD constants and vector helpers for the grid layer. +//! +//! Set at build time: +//! zig build -Dlanes= -Dcache-line= +//! 0 (default) = derive from the compilation target. + +const std = @import("std"); +const opts = @import("build_options"); +const types = @import("types.zig"); + +pub const Elem = types.Elem; + +/// Cache-line size in bytes (target arch default if not set). +pub const CACHE: usize = if (opts.cache_line != 0) opts.cache_line else std.atomic.cache_line; + +/// Elements per SIMD vector (target CPU default if not set). +/// For u16: NEON → 8, AVX2 → 16, AVX-512 → 32. +pub const L: usize = if (opts.lanes != 0) opts.lanes else (std.simd.suggestVectorLength(Elem) orelse 8); + +/// One SIMD vector of grid elements. +pub const V = @Vector(L, Elem); + +/// Allocator alignment for CPU grid buffers. +pub const ALIGN = std.mem.Alignment.fromByteUnits(CACHE); + +/// Padding rule for grids processed by the CPU. +pub const padding = types.Padding{ .lanes = L, .align_bytes = CACHE }; + +/// Load L consecutive elements starting at p[i]. +pub inline fn load(p: []const Elem, i: usize) V { + return p[i..][0..L].*; +} + +/// Store one vector at p[i]. +pub inline fn store(p: []Elem, i: usize, v: V) void { + p[i..][0..L].* = v; +} + +/// Round n up to whole vectors. +pub inline fn span(n: usize) usize { + return std.mem.alignForward(usize, n, L); +} + +comptime { + if (!std.math.isPowerOfTwo(CACHE)) + @compileError(std.fmt.comptimePrint("cache-line must be a power of two, got {d}", .{CACHE})); + if (CACHE < 16) + @compileError(std.fmt.comptimePrint("cache-line must be at least 16 bytes, got {d}", .{CACHE})); + if (!std.math.isPowerOfTwo(L)) + @compileError(std.fmt.comptimePrint("lanes must be a power of two, got {d}", .{L})); +} + +test "cpu simd helpers" { + try std.testing.expect(std.math.isPowerOfTwo(L)); + try std.testing.expectEqual(@as(usize, 0), span(0)); + try std.testing.expectEqual(L, span(1)); + + var a: [2 * L]Elem = @splat(1); + store(&a, L, load(&a, 0) + @as(V, @splat(1))); + try std.testing.expectEqual(@as(Elem, 2), a[L]); + try std.testing.expectEqual(@as(Elem, 1), a[0]); +} diff --git a/src/grid/simd_gpu.zig b/src/grid/simd_gpu.zig new file mode 100644 index 0000000..4da87b7 --- /dev/null +++ b/src/grid/simd_gpu.zig @@ -0,0 +1,62 @@ +//! GPU constants for the grid layer: how grids must be padded and aligned +//! so GPU kernels can process them efficiently. +//! +//! This file has no GPU API code. It defines the memory contract that a GPU +//! backend (Metal / CUDA / Vulkan, in adapters/) relies on: +//! * rows padded to whole warps (SIMD-groups), so each thread of a warp +//! reads one tick and no thread needs bounds checks; +//! * grids aligned to `ALIGN_BYTES`, so loads are coalesced and buffers +//! can be bound at any grid offset. +//! +//! Set at build time: +//! zig build -Dgpu-warp= -Dgpu-align= +//! 0 (default) = the defaults below. + +const std = @import("std"); +const opts = @import("build_options"); +const types = @import("types.zig"); +const cpu = @import("simd.zig"); + +pub const Elem = types.Elem; + +/// Threads per warp / SIMD-group / wavefront. +/// NVIDIA: 32, Apple: 32, AMD: 32 or 64. Default 32. +pub const WARP: usize = if (opts.gpu_warp != 0) opts.gpu_warp else 32; + +/// Alignment of every grid in a GPU buffer, in bytes. +/// 256 satisfies CUDA's device-pointer alignment and Metal/Vulkan +/// buffer-offset rules on common hardware. +pub const ALIGN_BYTES: usize = if (opts.gpu_align != 0) opts.gpu_align else 256; + +/// Padding rule for grids processed only by the GPU. +pub const padding = types.Padding{ .lanes = WARP, .align_bytes = ALIGN_BYTES }; + +/// Padding rule for unified memory (Apple Silicon, CUDA managed memory): +/// the same buffer is used by CPU SIMD code (Usage views) and GPU kernels, +/// so it must satisfy both. +pub const unified_padding = types.Padding.combine(cpu.padding, padding); + +/// Allocator alignment for unified buffers. +pub const UNIFIED_ALIGN = std.mem.Alignment.fromByteUnits(unified_padding.align_bytes); + +/// Kernel launch helper: how many thread groups of `group_size` threads +/// cover `n` work items. +pub inline fn groups(n: usize, group_size: usize) usize { + return (n + group_size - 1) / group_size; +} + +comptime { + if (!std.math.isPowerOfTwo(WARP)) + @compileError(std.fmt.comptimePrint("gpu-warp must be a power of two, got {d}", .{WARP})); + if (!std.math.isPowerOfTwo(ALIGN_BYTES) or ALIGN_BYTES < 16) + @compileError(std.fmt.comptimePrint("gpu-align must be a power of two >= 16, got {d}", .{ALIGN_BYTES})); +} + +test "gpu padding" { + try std.testing.expect(std.math.isPowerOfTwo(WARP)); + try unified_padding.validate(); + // Unified padding must be usable by the CPU SIMD code. + try std.testing.expect(unified_padding.lanes % cpu.L == 0); + try std.testing.expect(unified_padding.align_bytes % cpu.CACHE == 0); + try std.testing.expectEqual(@as(usize, 4), groups(100, 32)); +} diff --git a/src/grid/types.zig b/src/grid/types.zig new file mode 100644 index 0000000..7ccddba --- /dev/null +++ b/src/grid/types.zig @@ -0,0 +1,44 @@ +//! Types shared by every part of the grid layer, CPU and GPU. + +const std = @import("std"); + +/// Element type of every grid cell (demand / free capacity). +/// u16: 0 … 65535, half the memory of i32 and twice the values per vector. +/// Change it here only; everything else derives from it. +pub const Elem = u16; + +/// How a grid is padded and aligned in memory. Each target (CPU SIMD, +/// GPU, unified CPU+GPU) provides its own; Layout is computed from it. +pub const Padding = struct { + /// Every row length (stride) is a multiple of this many elements: + /// SIMD lanes on the CPU, threads per warp / SIMD-group on the GPU. + lanes: usize, + /// Every grid starts at a multiple of this many bytes: + /// cache line on the CPU, buffer/coalescing alignment on the GPU. + align_bytes: usize, + + /// Padding that satisfies both a and b (for unified memory, where the + /// CPU and the GPU work on the same buffer). + pub fn combine(a: Padding, b: Padding) Padding { + return .{ + .lanes = std.math.lcm(a.lanes, b.lanes), + .align_bytes = @max(a.align_bytes, b.align_bytes), + }; + } + + pub fn validate(self: Padding) error{InvalidPadding}!void { + if (self.lanes == 0 or !std.math.isPowerOfTwo(self.lanes)) return error.InvalidPadding; + if (!std.math.isPowerOfTwo(self.align_bytes)) return error.InvalidPadding; + if (self.align_bytes < @sizeOf(Elem)) return error.InvalidPadding; + } +}; + +test "padding combine" { + const cpu = Padding{ .lanes = 8, .align_bytes = 128 }; + const gpu = Padding{ .lanes = 32, .align_bytes = 256 }; + const u = Padding.combine(cpu, gpu); + try std.testing.expectEqual(@as(usize, 32), u.lanes); + try std.testing.expectEqual(@as(usize, 256), u.align_bytes); + try u.validate(); + try std.testing.expectError(error.InvalidPadding, (Padding{ .lanes = 12, .align_bytes = 64 }).validate()); +} diff --git a/src/grid/usage.zig b/src/grid/usage.zig index e69de29..38df11a 100644 --- a/src/grid/usage.zig +++ b/src/grid/usage.zig @@ -0,0 +1,242 @@ +//! Usage: CPU view of one [resource][stride] grid, with SIMD operations. +//! +//! Works on any buffer the CPU can read whose Layout padding is compatible +//! with the CPU SIMD rule: plain RAM (simd.padding) or unified CPU+GPU +//! memory (simd_gpu.unified_padding). A GPU-only buffer is not accessible +//! through Usage; GPU backends operate on whole pools with kernels instead. +//! +//! Elements are unsigned (Elem = u16). Subtraction below zero is a bug: +//! Debug builds panic, release builds are undefined. Callers must check +//! first (e.g. Machine.canPlace before subAt). + +const std = @import("std"); +const simd = @import("simd.zig"); +const types = @import("types.zig"); +const Layout = @import("layout.zig").Layout; + +const Elem = types.Elem; +const L = simd.L; +const V = simd.V; +const load = simd.load; +const store = simd.store; +const span = simd.span; + +pub const Usage = struct { + ptr: [*]align(simd.CACHE) Elem, + layout: Layout, + + /// True if CPU SIMD code may operate on grids with this layout. + pub fn compatible(layout: Layout) bool { + return layout.stride % L == 0 and layout.padding.align_bytes % simd.CACHE == 0; + } + + /// View the grid that starts at buf[0]. + pub fn fromSlice(buf: []align(simd.CACHE) Elem, layout: Layout) Usage { + std.debug.assert(compatible(layout)); + std.debug.assert(buf.len >= layout.block); + return .{ .ptr = buf.ptr, .layout = layout }; + } + + /// View grid i of a pool laid out [grid][res][stride]. + pub fn fromPool(pool: []align(simd.CACHE) Elem, layout: Layout, i: usize) Usage { + std.debug.assert(compatible(layout)); + const off = layout.gridOffset(i); + std.debug.assert(off + layout.block <= pool.len); + return .{ .ptr = @alignCast(pool[off..].ptr), .layout = layout }; + } + + /// Whole grid, padding included. + pub fn all(self: Usage) []Elem { + return self.ptr[0..self.layout.block]; + } + + /// Full padded row r. + pub inline fn row(self: Usage, r: usize) []Elem { + std.debug.assert(r < self.layout.n_res); + return self.ptr[self.layout.rowOffset(r)..][0..self.layout.stride]; + } + + pub fn clear(self: Usage) void { + @memset(self.all(), 0); + } + + // ---------------- element / resource access ---------------- + + pub inline fn get(self: Usage, r: usize, t: usize) Elem { + std.debug.assert(t < self.layout.n_ticks); + return self.row(r)[t]; + } + + /// Usage of resource r through time: real ticks [0, n_ticks). + pub fn resource(self: Usage, r: usize) []const Elem { + return self.row(r)[0..self.layout.n_ticks]; + } + + pub fn resourceMut(self: Usage, r: usize) []Elem { + return self.row(r)[0..self.layout.n_ticks]; + } + + /// Copy values into resource r's line, ticks [0, values.len). + pub fn set(self: Usage, r: usize, values: []const Elem) void { + std.debug.assert(values.len <= self.layout.n_ticks); + @memcpy(self.row(r)[0..values.len], values); + } + + // ---------------- whole-grid arithmetic ---------------- + + pub fn sub(self: Usage, other: Usage) void { + std.debug.assert(self.layout.eql(other.layout)); + self.subAt(other, 0, self.layout.stride); + } + + pub fn add(self: Usage, other: Usage) void { + std.debug.assert(self.layout.eql(other.layout)); + self.addAt(other, 0, self.layout.stride); + } + + // ---------------- offset arithmetic ---------------- + + /// self[r][t+k] -= other[r][k], k < span(dur). Must not go below 0. + pub fn subAt(self: Usage, other: Usage, t: usize, dur: usize) void { + const n = span(dur); + std.debug.assert(t + n <= self.layout.stride); + for (0..self.layout.n_res) |r| { + const m = self.row(r); + const j = other.row(r); + var k: usize = 0; + while (k < n) : (k += L) store(m, t + k, load(m, t + k) - load(j, k)); + } + } + + /// self[r][t+k] += other[r][k], k < span(dur). + pub fn addAt(self: Usage, other: Usage, t: usize, dur: usize) void { + const n = span(dur); + std.debug.assert(t + n <= self.layout.stride); + for (0..self.layout.n_res) |r| { + const m = self.row(r); + const j = other.row(r); + var k: usize = 0; + while (k < n) : (k += L) store(m, t + k, load(m, t + k) + load(j, k)); + } + } + + /// other[r][k] <= self[r][t+k] for all r, k < span(dur)? + pub fn covers(self: Usage, other: Usage, t: usize, dur: usize) bool { + const n = span(dur); + std.debug.assert(t + n <= self.layout.stride); + for (0..self.layout.n_res) |r| { + const m = self.row(r); + const j = other.row(r); + var k: usize = 0; + while (k < n) : (k += L) + if (@reduce(.Or, load(j, k) > load(m, t + k))) return false; + } + return true; + } + + // ---------------- time and summaries ---------------- + + /// Shift every row left by `k` ticks, filling the last k slots with tail[r]. + pub fn shiftLeft(self: Usage, k: usize, tail: []const Elem) void { + std.debug.assert(tail.len == self.layout.n_res); + const s = self.layout.stride; + std.debug.assert(k <= s); + for (0..self.layout.n_res) |r| { + const rw = self.row(r); + std.mem.copyForwards(Elem, rw[0 .. s - k], rw[k..s]); + @memset(rw[s - k ..], tail[r]); + } + } + + /// out[r] = max over ticks [0, span(dur)) of resource r. + pub fn peak(self: Usage, dur: usize, out: []Elem) void { + std.debug.assert(out.len == self.layout.n_res); + const n = span(dur); + for (0..self.layout.n_res) |r| { + var acc: V = @splat(0); + var k: usize = 0; + while (k < n) : (k += L) acc = @max(acc, load(self.row(r), k)); + out[r] = @reduce(.Max, acc); + } + } +}; + +// ------------------------------------------------------------------ +// tests +// ------------------------------------------------------------------ + +const testing = std.testing; +const gpu = @import("simd_gpu.zig"); + +fn testPool(n: usize, layout: Layout, comptime alignment: std.mem.Alignment) ![]align(alignment.toByteUnits()) Elem { + const buf = try testing.allocator.alignedAlloc(Elem, alignment, n * layout.block); + @memset(buf, 0); + return buf; +} + +test "get / set / resource" { + const layout = try Layout.init(3, 20, simd.padding); + const buf = try testPool(1, layout, simd.ALIGN); + defer testing.allocator.free(buf); + const u = Usage.fromSlice(buf, layout); + + u.set(1, &.{ 5, 6, 7 }); + try testing.expectEqual(@as(Elem, 7), u.get(1, 2)); + try testing.expectEqual(@as(usize, 20), u.resource(0).len); +} + +test "place / unplace / covers" { + const layout = try Layout.init(2, 10, simd.padding); + const buf = try testPool(2, layout, simd.ALIGN); + defer testing.allocator.free(buf); + const m = Usage.fromPool(buf, layout, 0); + const j = Usage.fromPool(buf, layout, 1); + + for (0..2) |r| @memset(m.row(r), 10); + j.set(0, &.{ 4, 4 }); + j.set(1, &.{ 1, 1 }); + + try testing.expect(m.covers(j, 3, 2)); + m.subAt(j, 3, 2); + try testing.expectEqualSlices(Elem, &.{ 10, 10, 10, 6, 6, 10 }, m.resource(0)[0..6]); + m.addAt(j, 3, 2); + try testing.expectEqual(@as(Elem, 10), m.get(0, 3)); + + j.set(0, &.{11}); + try testing.expect(!m.covers(j, 0, 1)); +} + +test "shiftLeft by k / peak" { + const layout = try Layout.init(2, 6, simd.padding); + const buf = try testPool(1, layout, simd.ALIGN); + defer testing.allocator.free(buf); + const u = Usage.fromSlice(buf, layout); + + u.set(0, &.{ 1, 2, 3, 4 }); + u.set(1, &.{ 9, 0, 0 }); + var pk: [2]Elem = undefined; + u.peak(4, &pk); + try testing.expectEqualSlices(Elem, &.{ 4, 9 }, &pk); + + u.shiftLeft(2, &.{ 7, 7 }); + try testing.expectEqualSlices(Elem, &.{ 3, 4, 0 }, u.resource(0)[0..3]); + try testing.expectEqual(@as(Elem, 7), u.row(0)[layout.stride - 1]); + try testing.expectEqual(@as(Elem, 7), u.row(0)[layout.stride - 2]); +} + +test "usage on a unified (CPU+GPU) layout" { + const layout = try Layout.init(4, 100, gpu.unified_padding); + try testing.expect(Usage.compatible(layout)); + const buf = try testPool(2, layout, gpu.UNIFIED_ALIGN); + defer testing.allocator.free(buf); + + const m = Usage.fromPool(buf, layout, 0); + const j = Usage.fromPool(buf, layout, 1); + for (0..4) |r| @memset(m.row(r), 5); + j.set(2, &.{ 3, 3, 3 }); + try testing.expect(m.covers(j, 50, 3)); + m.subAt(j, 50, 3); + try testing.expectEqual(@as(Elem, 2), m.get(2, 51)); + // every grid in the pool starts on a GPU-aligned address + try testing.expect(@intFromPtr(j.ptr) % gpu.ALIGN_BYTES == 0); +} diff --git a/src/model.zig b/src/model.zig new file mode 100644 index 0000000..aec7d93 --- /dev/null +++ b/src/model.zig @@ -0,0 +1,17 @@ +//! Model layer: domain state (machines, jobs) built on the grid layer. +pub const types = @import("model/types.zig"); +pub const State = types.State; +pub const Action = types.Action; +pub const Event = types.Event; +pub const JobMeta = types.JobMeta; +pub const RejectReason = types.RejectReason; +pub const RunningJob = types.RunningJob; + +pub const Machines = @import("model/machines.zig").Machines; +pub const Machine = @import("model/machines.zig").Machine; +pub const Jobs = @import("model/jobs.zig").Jobs; + +test { + _ = @import("model/machines.zig"); + _ = @import("model/jobs.zig"); +} diff --git a/src/model/jobs.zig b/src/model/jobs.zig index e69de29..1202465 100644 --- a/src/model/jobs.zig +++ b/src/model/jobs.zig @@ -0,0 +1,364 @@ +//! Jobs: fixed slot pool [slot][res][stride] (== observation buffer), +//! struct-of-arrays metadata, a validity bitmask, and a doubly linked list +//! of the waiting jobs in (arrival, slot) order — so FIFO-style policies +//! visit the oldest job first and can stop early instead of scanning the +//! whole pool. +//! +//! Adding a job is two-phase so a generator can write the profile directly +//! into the pool without copies: +//! const slot = jobs.acquire() orelse …; // cleared, not yet visible +//! … write profile into jobs.get(slot) … +//! jobs.commit(slot, meta, dur); // enforce invariants, peaks, visible +//! or jobs.abort(slot) to give the slot back. + +const std = @import("std"); +const grid = @import("../grid.zig"); +const types = @import("types.zig"); +const simd = grid.simd; +const Elem = grid.Elem; +const Layout = grid.Layout; +const Usage = grid.Usage; + +pub const Jobs = struct { + layout: Layout, + cap: usize, + buf: []align(simd.CACHE) Elem, + duration: []u16, + arrival: []i64, + id: []u32, + peak: []Elem, // [slot * n_res + r] + valid: []u64, // committed, waiting jobs + reserved: []u64, // acquired but not committed + /// Memo: waiting jobs known to fit on no machine this tick. Capacity only + /// shrinks within a tick, so the bit stays true until the engine clears + /// it when time advances. Written through `*const Jobs` (slice), like a + /// cache: it never changes what the simulation does. + blocked: []u64, + count: usize = 0, + // waiting jobs ordered by (arrival, slot); none = end of list + prev: []u32, + next: []u32, + head: u32 = none, + tail: u32 = none, + + pub const none = std.math.maxInt(u32); + + pub fn init(a: std.mem.Allocator, layout: Layout, max_jobs: usize) !Jobs { + std.debug.assert(max_jobs > 0); + const words = (max_jobs + 63) / 64; + const buf = try a.alignedAlloc(Elem, simd.ALIGN, max_jobs * layout.block); + errdefer a.free(buf); + const duration = try a.alloc(u16, max_jobs); + errdefer a.free(duration); + const arrival = try a.alloc(i64, max_jobs); + errdefer a.free(arrival); + const id = try a.alloc(u32, max_jobs); + errdefer a.free(id); + const peak = try a.alloc(Elem, max_jobs * layout.n_res); + errdefer a.free(peak); + const valid = try a.alloc(u64, words); + errdefer a.free(valid); + const reserved = try a.alloc(u64, words); + errdefer a.free(reserved); + const blocked = try a.alloc(u64, words); + errdefer a.free(blocked); + const prev = try a.alloc(u32, max_jobs); + errdefer a.free(prev); + const next = try a.alloc(u32, max_jobs); + + var self = Jobs{ + .layout = layout, + .cap = max_jobs, + .buf = buf, + .duration = duration, + .arrival = arrival, + .id = id, + .peak = peak, + .valid = valid, + .reserved = reserved, + .blocked = blocked, + .prev = prev, + .next = next, + }; + self.clearAll(); + return self; + } + + pub fn deinit(self: *Jobs, a: std.mem.Allocator) void { + a.free(self.buf); + a.free(self.duration); + a.free(self.arrival); + a.free(self.id); + a.free(self.peak); + a.free(self.valid); + a.free(self.reserved); + a.free(self.blocked); + a.free(self.prev); + a.free(self.next); + } + + /// Empty the pool. + pub fn clearAll(self: *Jobs) void { + @memset(self.buf, 0); + @memset(self.valid, 0); + @memset(self.reserved, 0); + @memset(self.blocked, 0); + self.count = 0; + self.head = none; + self.tail = none; + } + + pub fn get(self: Jobs, slot: usize) Usage { + return Usage.fromPool(self.buf, self.layout, slot); + } + + pub fn isValid(self: Jobs, slot: usize) bool { + return testBit(self.valid, slot); + } + + pub fn peakOf(self: Jobs, slot: usize) []const Elem { + return self.peak[slot * self.layout.n_res ..][0..self.layout.n_res]; + } + + pub fn full(self: Jobs) bool { + return self.findFree() == null; + } + + // ---------------- two-phase add ---------------- + + /// Reserve a free, cleared slot. Not visible to iterators yet. + pub fn acquire(self: *Jobs) ?usize { + const slot = self.findFree() orelse return null; + setBit(self.reserved, slot); + clearBit(self.blocked, slot); + self.get(slot).clear(); + return slot; + } + + /// Give back an acquired slot without adding a job. + pub fn abort(self: *Jobs, slot: usize) void { + std.debug.assert(testBit(self.reserved, slot)); + clearBit(self.reserved, slot); + self.get(slot).clear(); + } + + /// Make an acquired slot a waiting job. Enforces the pool invariants: + /// zero beyond `dur`, then computes peaks. + pub fn commit(self: *Jobs, slot: usize, meta: types.JobMeta, dur: u16) void { + std.debug.assert(testBit(self.reserved, slot)); + std.debug.assert(dur >= 1 and dur <= self.layout.n_ticks); + const u = self.get(slot); + for (0..self.layout.n_res) |r| @memset(u.row(r)[dur..], 0); + + self.duration[slot] = dur; + self.arrival[slot] = meta.arrival; + self.id[slot] = meta.id; + u.peak(dur, self.peak[slot * self.layout.n_res ..][0..self.layout.n_res]); + + clearBit(self.reserved, slot); + setBit(self.valid, slot); + self.count += 1; + self.link(@intCast(slot)); + } + + /// One-shot add from a flat [n_res][dur] profile (tests, simple sources). + pub fn add(self: *Jobs, meta: types.JobMeta, req: []const Elem, dur: u16) ?usize { + std.debug.assert(req.len == self.layout.n_res * dur); + const slot = self.acquire() orelse return null; + const u = self.get(slot); + for (0..self.layout.n_res) |r| u.set(r, req[r * dur ..][0..dur]); + self.commit(slot, meta, dur); + return slot; + } + + /// Remove a waiting job (placed or dropped). + pub fn remove(self: *Jobs, slot: usize) void { + std.debug.assert(self.isValid(slot)); + clearBit(self.valid, slot); + clearBit(self.blocked, slot); + self.get(slot).clear(); + self.count -= 1; + self.unlink(@intCast(slot)); + } + + // ---------------- per-tick "fits nowhere" memo ---------------- + + pub inline fn isBlocked(self: Jobs, slot: usize) bool { + return testBit(self.blocked, slot); + } + pub inline fn markBlocked(self: Jobs, slot: usize) void { + setBit(self.blocked, slot); + } + /// Called by the engine when time advances (capacity may have freed up). + pub fn clearBlocked(self: Jobs) void { + @memset(self.blocked, 0); + } + + // ---------------- iteration ---------------- + + pub const Iter = struct { + valid: []const u64, + word: usize = 0, + bits: u64, + + pub fn next(it: *Iter) ?usize { + while (it.bits == 0) { + it.word += 1; + if (it.word >= it.valid.len) return null; + it.bits = it.valid[it.word]; + } + const b = @ctz(it.bits); + it.bits &= it.bits - 1; + return it.word * 64 + b; + } + }; + + /// Waiting jobs in slot order. + pub fn iter(self: Jobs) Iter { + return .{ .valid = self.valid, .bits = self.valid[0] }; + } + + /// Slot of the oldest waiting job (lowest arrival, then lowest slot). O(1). + pub fn oldest(self: Jobs) ?usize { + return if (self.head == none) null else self.head; + } + + pub const ArrivalIter = struct { + next_slot: u32, + links: []const u32, + + pub fn next(it: *ArrivalIter) ?usize { + if (it.next_slot == none) return null; + const s = it.next_slot; + it.next_slot = it.links[s]; + return s; + } + }; + + /// Waiting jobs, oldest first: (arrival, slot) order. + pub fn byArrival(self: Jobs) ArrivalIter { + return .{ .next_slot = self.head, .links = self.next }; + } + + /// Insert at its (arrival, slot) position. Arrivals come in time order, + /// so this walks back over at most the jobs of the current tick. + fn link(self: *Jobs, s: u32) void { + var after = self.tail; // insert after this node + while (after != none and self.before(s, after)) after = self.prev[after]; + const before_node = if (after == none) self.head else self.next[after]; + self.prev[s] = after; + self.next[s] = before_node; + if (after == none) self.head = s else self.next[after] = s; + if (before_node == none) self.tail = s else self.prev[before_node] = s; + } + + fn unlink(self: *Jobs, s: u32) void { + const p = self.prev[s]; + const n = self.next[s]; + if (p == none) self.head = n else self.next[p] = n; + if (n == none) self.tail = p else self.prev[n] = p; + } + + /// Does slot a come before slot b in (arrival, slot) order? + inline fn before(self: Jobs, a: u32, b: u32) bool { + return self.arrival[a] < self.arrival[b] or (self.arrival[a] == self.arrival[b] and a < b); + } + + // ---------------- bits ---------------- + + fn findFree(self: Jobs) ?usize { + for (self.valid, self.reserved, 0..) |v, r, i| { + const used = v | r; + if (used != ~@as(u64, 0)) { + const slot = i * 64 + @ctz(~used); + return if (slot < self.cap) slot else null; + } + } + return null; + } + + inline fn testBit(m: []const u64, i: usize) bool { + return (m[i / 64] >> @intCast(i % 64)) & 1 == 1; + } + inline fn setBit(m: []u64, i: usize) void { + m[i / 64] |= @as(u64, 1) << @intCast(i % 64); + } + inline fn clearBit(m: []u64, i: usize) void { + m[i / 64] &= ~(@as(u64, 1) << @intCast(i % 64)); + } +}; + +test "jobs: two-phase add, iterate, remove" { + const a = std.testing.allocator; + const layout = try Layout.init(2, 8, simd.padding); + var jobs = try Jobs.init(a, layout, 70); + defer jobs.deinit(a); + + const s0 = jobs.add(.{ .id = 7, .arrival = 3 }, &.{ 1, 2, 3, 4 }, 2).?; + try std.testing.expectEqualSlices(Elem, &.{ 2, 4 }, jobs.peakOf(s0)); + + const s1 = jobs.acquire().?; + try std.testing.expect(s1 != s0); + jobs.get(s1).set(0, &.{ 9, 9, 9 }); + jobs.commit(s1, .{ .id = 8, .arrival = 1 }, 1); // tick 1,2 must be zeroed + try std.testing.expectEqual(@as(Elem, 0), jobs.get(s1).get(0, 1)); + try std.testing.expectEqual(@as(?usize, s1), jobs.oldest()); + + const s2 = jobs.acquire().?; + jobs.abort(s2); + + var n: usize = 0; + var it = jobs.iter(); + while (it.next()) |_| n += 1; + try std.testing.expectEqual(@as(usize, 2), n); + + jobs.remove(s0); + try std.testing.expectEqual(@as(usize, 1), jobs.count); +} + +test "jobs: arrival order list stays sorted by (arrival, slot) under churn" { + const a = std.testing.allocator; + const layout = try Layout.init(1, 4, simd.padding); + var jobs = try Jobs.init(a, layout, 40); + defer jobs.deinit(a); + var prng = std.Random.DefaultPrng.init(9); + const r = prng.random(); + var t: i64 = 0; + for (0..2000) |i| { + // mostly in-order arrivals, sometimes out of order (allowed by the API) + if (r.uintLessThan(u32, 3) == 0) t += 1; + const at = if (r.uintLessThan(u32, 10) == 0) t - r.intRangeAtMost(i64, 0, 3) else t; + if (!jobs.full() and r.boolean()) { + _ = jobs.add(.{ .id = @intCast(i), .arrival = at }, &.{1}, 1); + } else if (jobs.count > 0) { + // remove a random waiting job + var k = r.uintLessThan(usize, jobs.count); + var it = jobs.iter(); + while (it.next()) |s| { + if (k == 0) { + jobs.remove(s); + break; + } + k -= 1; + } + } + // list == valid set, in (arrival, slot) order; oldest() == head + var n: usize = 0; + var last: ?usize = null; + var it = jobs.byArrival(); + while (it.next()) |s| : (n += 1) { + try std.testing.expect(jobs.isValid(s)); + if (last) |l| try std.testing.expect(jobs.arrival[l] < jobs.arrival[s] or + (jobs.arrival[l] == jobs.arrival[s] and l < s)); + last = s; + } + try std.testing.expectEqual(jobs.count, n); + // oldest() matches a brute-force scan + var best: ?usize = null; + var it2 = jobs.iter(); + while (it2.next()) |s| { + if (best == null or jobs.arrival[s] < jobs.arrival[best.?]) best = s; + } + try std.testing.expectEqual(best, jobs.oldest()); + } +} diff --git a/src/model/machines.zig b/src/model/machines.zig index e69de29..5d09662 100644 --- a/src/model/machines.zig +++ b/src/model/machines.zig @@ -0,0 +1,293 @@ +//! Machines: one pool owning N grids of FREE capacity (cap - used), +//! laid out [machine][res][stride], plus `Machine`, a per-machine view with +//! the fit test and placement operations. +//! +//! Time is a sliding window. Each row stores `n_ticks + slack` ticks +//! (the `ring` layout); the horizon [now, now + n_ticks) is the window +//! starting at `head`: +//! +//! row r: | stale … | head: tick 0 … tick n_ticks-1 | cap cap cap … | pad | +//! +//! Advancing time is `head += k`: no data moves. Every slot at or after +//! head + n_ticks is always full capacity, so newly visible ticks are +//! already correct. When the window would run past the slack, the live +//! ticks are copied back to the start of the row once (`compact`), i.e. +//! one row copy every `slack` ticks: O(1) amortized per tick instead of +//! O(n_ticks). Windows stay contiguous, so the SIMD fit test is unchanged. + +const std = @import("std"); +const grid = @import("../grid.zig"); +const simd = grid.simd; +const Elem = grid.Elem; +const Layout = grid.Layout; +const Usage = grid.Usage; + +/// View of one machine. Owns nothing. Tick t of the horizon is +/// `free.row(r)[head + t]`. +pub const Machine = struct { + free: Usage, // ring layout + cap: []const Elem, // [n_res] + head: usize, + horizon: usize, // n_ticks + + /// Empty machine: every slot, slack and padding included, at full capacity. + pub fn reset(self: Machine) void { + for (0..self.free.layout.n_res) |r| @memset(self.free.row(r), self.cap[r]); + } + + /// Free capacity of resource r over the horizon, ticks [0, n_ticks). + pub fn resource(self: Machine, r: usize) []const Elem { + return self.free.row(r)[self.head..][0..self.horizon]; + } + + /// Cheap necessary conditions: peak within capacity, first tick within + /// free capacity at tick t. No grid scan. + pub fn mayFit(self: Machine, job: Usage, peak: []const Elem, t: usize) bool { + for (0..self.free.layout.n_res) |r| { + if (peak[r] > self.cap[r]) return false; + if (job.row(r)[0] > self.free.row(r)[self.head + t]) return false; + } + return true; + } + + /// Could a job with this peak ever run here (on an empty machine)? + pub fn canEverFit(self: Machine, peak: []const Elem) bool { + for (self.cap, peak) |c, p| if (p > c) return false; + return true; + } + + /// Exact test: horizon + SIMD comparison against free capacity. + pub fn canPlace(self: Machine, job: Usage, dur: usize, t: usize) bool { + if (t + dur > self.horizon) return false; + return self.free.covers(job, self.head + t, dur); + } + + pub fn place(self: Machine, job: Usage, dur: usize, t: usize) void { + std.debug.assert(self.canPlace(job, dur, t)); + self.free.subAt(job, self.head + t, dur); + } + + pub fn unplace(self: Machine, job: Usage, dur: usize, t: usize) void { + self.free.addAt(job, self.head + t, dur); + } + + /// Earliest start tick at which the job fits, or null. + pub fn earliestFit(self: Machine, job: Usage, dur: usize) ?usize { + if (dur > self.horizon) return null; + var t: usize = 0; + while (t + dur <= self.horizon) : (t += 1) + if (self.free.covers(job, self.head + t, dur)) return t; + return null; + } + + pub fn freeNow(self: Machine, r: usize) Elem { + return self.free.row(r)[self.head]; + } + + /// Mean over resources of used/cap at tick 0, in [0, 1]. + pub fn utilizationNow(self: Machine) f32 { + const n_res = self.free.layout.n_res; + var s: f32 = 0; + for (0..n_res) |r| { + const c: f32 = @floatFromInt(self.cap[r]); + if (c > 0) s += 1.0 - @as(f32, @floatFromInt(self.freeNow(r))) / c; + } + return s / @as(f32, @floatFromInt(n_res)); + } + + /// True if nothing is running (every tick of the horizon at full capacity). + pub fn idle(self: Machine) bool { + for (0..self.free.layout.n_res) |r| + for (self.resource(r)) |v| if (v != self.cap[r]) return false; + return true; + } + + /// Move the live window [head, head + horizon) to the start of the row + /// and refill everything after it with capacity. + fn compact(self: Machine) void { + const stride = self.free.layout.stride; + const keep = @min(self.horizon, stride -| self.head); + for (0..self.free.layout.n_res) |r| { + const rw = self.free.row(r); + std.mem.copyForwards(Elem, rw[0..keep], rw[self.head..][0..keep]); + @memset(rw[keep..], self.cap[r]); + } + } +}; + +pub const Machines = struct { + /// Logical layout: n_res, n_ticks (horizon). Shared with jobs. + layout: Layout, + /// Storage layout of each machine: n_ticks + slack ticks per row. + ring: Layout, + n: usize, + buf: []align(simd.CACHE) Elem, + cap: []Elem, // [machine * n_res + r] + /// Start of the horizon inside every row (all machines share it). + head: usize = 0, + /// Change stamps for caches kept across decisions (see + /// 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. + 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 { + std.debug.assert(n_machines > 0); + std.debug.assert(caps.len == n_machines * layout.n_res); + // slack = horizon (at least a few vectors): one compaction per + // n_ticks advances, row memory doubled. + const slack = @max(layout.n_ticks, 4 * layout.padding.lanes); + const ring = try Layout.init(layout.n_res, layout.n_ticks + slack, layout.padding); + const buf = try a.alignedAlloc(Elem, simd.ALIGN, n_machines * ring.block); + errdefer a.free(buf); + const cap = try a.dupe(Elem, caps); + errdefer a.free(cap); + const stamp = try a.alloc(u64, n_machines); + @memset(stamp, 0); + var self = Machines{ .layout = layout, .ring = ring, .n = n_machines, .buf = buf, .cap = cap, .stamp = stamp }; + self.resetAll(); + return self; + } + + pub fn deinit(self: *Machines, a: std.mem.Allocator) void { + a.free(self.buf); + a.free(self.cap); + a.free(self.stamp); + } + + fn tick(self: *Machines) u64 { + self.clock += 1; + return self.clock; + } + + /// Record that machine m changed (a job was placed on it). + pub fn touch(self: *Machines, m: usize) void { + self.stamp[m] = self.tick(); + } + + pub fn get(self: Machines, i: usize) Machine { + std.debug.assert(i < self.n); + return .{ + .free = Usage.fromPool(self.buf, self.ring, i), + .cap = self.cap[i * self.layout.n_res ..][0..self.layout.n_res], + .head = self.head, + .horizon = self.layout.n_ticks, + }; + } + + pub fn resetAll(self: *Machines) void { + self.head = 0; + self.epoch = self.tick(); + for (0..self.n) |i| self.get(i).reset(); + } + + /// Global time skip: every machine advances k ticks together. + /// O(1) unless the window reaches the end of the slack. + pub fn advanceAll(self: *Machines, k: usize) void { + self.head += k; + self.epoch = self.tick(); + if (self.head + self.layout.n_ticks <= self.ring.n_ticks) return; + for (0..self.n) |i| self.get(i).compact(); + self.head = 0; + } + + pub fn anyCanEverFit(self: Machines, peak: []const Elem) bool { + for (0..self.n) |i| if (self.get(i).canEverFit(peak)) return true; + return false; + } + + pub fn allIdle(self: Machines) bool { + for (0..self.n) |i| if (!self.get(i).idle()) return false; + return true; + } + + pub fn utilizationNow(self: Machines) f32 { + var s: f32 = 0; + for (0..self.n) |i| s += self.get(i).utilizationNow(); + return s / @as(f32, @floatFromInt(self.n)); + } + + /// Largest capacity of resource r over all machines. + pub fn maxCap(self: Machines, r: usize) Elem { + var m: Elem = 0; + for (0..self.n) |i| m = @max(m, self.cap[i * self.layout.n_res + r]); + return m; + } +}; + +test "machines: place, earliestFit, advance" { + const a = std.testing.allocator; + const layout = try Layout.init(2, 10, simd.padding); + var ms = try Machines.init(a, layout, 2, &.{ 10, 10, 5, 5 }); + defer ms.deinit(a); + + const jb = try a.alignedAlloc(Elem, simd.ALIGN, layout.block); + defer a.free(jb); + @memset(jb, 0); + const job = Usage.fromSlice(jb, layout); + job.set(0, &.{ 8, 8 }); + job.set(1, &.{ 1, 1 }); + + try std.testing.expect(!ms.get(1).canPlace(job, 2, 0)); + try std.testing.expect(ms.get(0).canPlace(job, 2, 0)); + ms.get(0).place(job, 2, 0); + try std.testing.expectEqual(@as(Elem, 2), ms.get(0).freeNow(0)); + try std.testing.expectEqual(@as(?usize, 2), ms.get(0).earliestFit(job, 2)); + try std.testing.expect(!ms.allIdle()); + ms.advanceAll(2); + try std.testing.expectEqual(@as(Elem, 10), ms.get(0).freeNow(0)); + try std.testing.expect(ms.allIdle()); +} + +test "machines: sliding window matches a shifted reference across compactions" { + const a = std.testing.allocator; + const n_ticks = 7; + const layout = try Layout.init(2, n_ticks, simd.padding); + var ms = try Machines.init(a, layout, 1, &.{ 20, 9 }); + defer ms.deinit(a); + + const jb = try a.alignedAlloc(Elem, simd.ALIGN, layout.block); + defer a.free(jb); + + // reference: plain arrays shifted by hand + var ref: [2][n_ticks]Elem = .{ @splat(20), @splat(9) }; + var prng = std.Random.DefaultPrng.init(5); + const rnd = prng.random(); + + for (0..10 * ms.ring.n_ticks) |_| { + // try to place a random job somewhere in the horizon + @memset(jb, 0); + const job = Usage.fromSlice(jb, layout); + const dur = rnd.intRangeAtMost(usize, 1, n_ticks); + for (0..2) |r| @memset(job.resourceMut(r)[0..dur], rnd.intRangeAtMost(Elem, 0, 6)); + const t = rnd.uintLessThan(usize, n_ticks - dur + 1); + const m = ms.get(0); + var fits = true; + for (0..2) |r| for (0..dur) |k| { + if (job.get(r, k) > ref[r][t + k]) fits = false; + }; + try std.testing.expectEqual(fits, m.canPlace(job, dur, t)); + if (fits) { + m.place(job, dur, t); + for (0..2) |r| for (0..dur) |k| { + ref[r][t + k] -= job.get(r, k); + }; + } + // advance 1 or 2 ticks + const k = rnd.intRangeAtMost(usize, 1, 2); + ms.advanceAll(k); + for (0..2) |r| { + std.mem.copyForwards(Elem, ref[r][0 .. n_ticks - k], ref[r][k..]); + @memset(ref[r][n_ticks - k ..], ms.cap[r]); + try std.testing.expectEqualSlices(Elem, &ref[r], ms.get(0).resource(r)); + } + } + + // a jump longer than the horizon empties the machine + ms.advanceAll(3 * n_ticks); + try std.testing.expect(ms.allIdle()); +} diff --git a/src/model/types.zig b/src/model/types.zig index 269869a..afaecbb 100644 --- a/src/model/types.zig +++ b/src/model/types.zig @@ -1,2 +1,66 @@ -// A scheduling decision -pub const Action = union(enum) { place: struct { slot: u32, machine: u32 }, wait }; +//! Plain data shared by the model, the engine and the ports. + +const std = @import("std"); +const grid = @import("../grid.zig"); +const Machines = @import("machines.zig").Machines; +const Jobs = @import("jobs.zig").Jobs; + +pub const Elem = grid.Elem; + +/// Read-only view of the simulation, handed to policies and observers. +/// Only the engine mutates the simulation. +pub const State = struct { + now: i64, + machines: *const Machines, + jobs: *const Jobs, +}; + +/// A scheduling decision. +pub const Action = union(enum) { + /// Start the job in `slot` on `machine` now (tick 0). + place: struct { slot: u32, machine: u32 }, + /// Place nothing more this tick: time advances by one tick. + wait, + + pub fn format(self: Action, w: *std.Io.Writer) std.Io.Writer.Error!void { + switch (self) { + .place => |p| try w.print("place(slot={d}, machine={d})", .{ p.slot, p.machine }), + .wait => try w.writeAll("wait"), + } + } +}; + +/// A job that has started and not yet finished. +pub const RunningJob = struct { + id: u32, + machine: u32, + start: i64, + dur: u16, + + pub fn finish(self: RunningJob) i64 { + return self.start + self.dur; + } +}; + +/// Why a job could not enter the pool. +pub const RejectReason = enum { pool_full, impossible, invalid_profile }; + +/// Everything the engine announces to observers. +pub const Event = union(enum) { + episode_started: struct { seed: u64 }, + job_arrived: struct { id: u32, slot: u32, tick: i64 }, + job_rejected: struct { id: u32, reason: RejectReason, tick: i64 }, + job_placed: struct { id: u32, slot: u32, machine: u32, tick: i64, arrival: i64, dur: u16 }, + illegal_action: struct { action: Action, tick: i64 }, + tick_advanced: struct { now: i64 }, + episode_done: struct { now: i64, makespan: i64, truncated: bool }, +}; + +/// Job metadata from an ArrivalSource. The profile (grid) comes from a +/// UsageGenerator when the job arrives. +pub const JobMeta = struct { + id: u32, + arrival: i64, + /// Optional class tag a generator may use to pick a distribution. + class: u16 = 0, +}; diff --git a/src/ports.zig b/src/ports.zig new file mode 100644 index 0000000..902871e --- /dev/null +++ b/src/ports.zig @@ -0,0 +1,35 @@ +//! Ports: the interfaces between the engine and the outside world. +//! Policy — decides the next Action (hot, comptime or runtime) +//! Observer — reacts to Events (runtime, several at once) +//! UsageGenerator — creates machine capacities and job profiles +//! ArrivalSource — creates job metadata (which jobs, when) +//! Reward — scores each elapsed tick +const model = @import("model.zig"); +pub const State = model.State; +pub const Action = model.Action; +pub const Event = model.Event; +pub const JobMeta = model.JobMeta; + +pub const policy = @import("ports/policy.zig"); +pub const Policy = policy.Policy; +pub const assertPolicy = policy.assertPolicy; + +pub const Observer = @import("ports/observer.zig").Observer; +pub const ObserverList = @import("ports/observer.zig").ObserverList; + +pub const usage_generator = @import("ports/usage_generator.zig"); +pub const UsageGenerator = usage_generator.UsageGenerator; + +pub const arrival_source = @import("ports/arrival_source.zig"); +pub const ArrivalSource = arrival_source.ArrivalSource; + +pub const reward = @import("ports/reward.zig"); +pub const Reward = reward.Reward; + +test { + _ = @import("ports/reward.zig"); + _ = @import("ports/policy.zig"); + _ = @import("ports/observer.zig"); + _ = @import("ports/usage_generator.zig"); + _ = @import("ports/arrival_source.zig"); +} diff --git a/src/ports/.gitkeep b/src/ports/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/ports/arrival_source.zig b/src/ports/arrival_source.zig new file mode 100644 index 0000000..816b01a --- /dev/null +++ b/src/ports/arrival_source.zig @@ -0,0 +1,117 @@ +//! ArrivalSource port: creates job metadata — which jobs exist and WHEN they +//! arrive. It does not create the usage profile; the engine asks the +//! UsageGenerator for that when a job arrives. +//! +//! Contract for an implementation type `T`: +//! pub fn next(self: *T, now: i64) Error!?JobMeta +//! Next job with arrival <= now, or null if none (yet) at this tick. +//! Called repeatedly each tick until it returns null. +//! pub fn done(self: *T) bool +//! True when no further job will ever be returned. +//! optional: +//! pub fn reset(self: *T, seed: u64) void +//! pub fn deinit(self: *T) void +//! +//! Rules: +//! * Non-decreasing arrival times; never return arrival > now. +//! * Unique ids within an episode. +//! * Deterministic for a given seed. +//! +//! Example adapters: fixed list (tests), Poisson / uniform random arrivals, +//! trace replay (CSV / SWF), externally pushed (Python). + +const std = @import("std"); +const types = @import("../model/types.zig"); +pub const JobMeta = types.JobMeta; + +pub const Error = error{ OutOfMemory, InvalidInput, ReadFailed }; + +pub const ArrivalSource = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + next: *const fn (ptr: *anyopaque, now: i64) Error!?JobMeta, + done: *const fn (ptr: *anyopaque) bool, + reset: *const fn (ptr: *anyopaque, seed: u64) void, + deinit: *const fn (ptr: *anyopaque) void, + }; + + pub fn next(self: ArrivalSource, now: i64) Error!?JobMeta { + return self.vtable.next(self.ptr, now); + } + pub fn done(self: ArrivalSource) bool { + return self.vtable.done(self.ptr); + } + pub fn reset(self: ArrivalSource, seed: u64) void { + self.vtable.reset(self.ptr, seed); + } + pub fn deinit(self: ArrivalSource) void { + self.vtable.deinit(self.ptr); + } + + pub fn init(impl: anytype) ArrivalSource { + const Ptr = @TypeOf(impl); + const T = @typeInfo(Ptr).pointer.child; + inline for (.{ "next", "done" }) |name| { + if (!@hasDecl(T, name)) + @compileError(@typeName(T) ++ " is not an ArrivalSource: missing `" ++ name ++ "`"); + } + const gen = struct { + fn cast(p: *anyopaque) Ptr { + return @ptrCast(@alignCast(p)); + } + fn next(p: *anyopaque, now: i64) Error!?JobMeta { + return cast(p).next(now); + } + fn done(p: *anyopaque) bool { + return cast(p).done(); + } + fn reset(p: *anyopaque, seed: u64) void { + if (@hasDecl(T, "reset")) cast(p).reset(seed); + } + fn deinit(p: *anyopaque) void { + if (@hasDecl(T, "deinit")) cast(p).deinit(); + } + }; + const vt = VTable{ .next = gen.next, .done = gen.done, .reset = gen.reset, .deinit = gen.deinit }; + return .{ .ptr = impl, .vtable = &vt }; + } +}; + +test "arrival source port: fixed list" { + const Fixed = struct { + items: []const JobMeta, + i: usize = 0, + pub fn next(self: *@This(), now: i64) Error!?JobMeta { + if (self.i < self.items.len and self.items[self.i].arrival <= now) { + defer self.i += 1; + return self.items[self.i]; + } + return null; + } + pub fn done(self: *@This()) bool { + return self.i == self.items.len; + } + pub fn reset(self: *@This(), seed: u64) void { + _ = seed; + self.i = 0; + } + }; + + var impl = Fixed{ .items = &.{ + .{ .id = 0, .arrival = 0 }, + .{ .id = 1, .arrival = 0 }, + .{ .id = 2, .arrival = 3 }, + } }; + const src = ArrivalSource.init(&impl); + + var n: usize = 0; + while (try src.next(0)) |_| n += 1; + try std.testing.expectEqual(@as(usize, 2), n); + try std.testing.expect((try src.next(2)) == null); + try std.testing.expectEqual(@as(u32, 2), (try src.next(3)).?.id); + try std.testing.expect(src.done()); + src.reset(0); + try std.testing.expect(!src.done()); +} diff --git a/src/ports/observer.zig b/src/ports/observer.zig new file mode 100644 index 0000000..9a9a5e9 --- /dev/null +++ b/src/ports/observer.zig @@ -0,0 +1,114 @@ +//! Observer port: reacts to engine events (visualization, logging, metrics, +//! invariant checks, trace recording). Several observers can be attached at +//! once through `ObserverList`. +//! +//! Contract for an implementation type `T`: +//! pub fn onEvent(self: *T, event: Event, state: *const State) void +//! optional: +//! pub fn deinit(self: *T) void +//! +//! Rules: +//! * Read only: never change simulation state. +//! * Must not influence results: a run with or without observers must +//! produce the same placements. +//! * Errors (e.g. a failed file write) are handled inside the observer +//! (log, set a flag); `onEvent` cannot fail the simulation. + +const std = @import("std"); +const types = @import("../model/types.zig"); +pub const State = types.State; +pub const Event = types.Event; + +pub const Observer = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + onEvent: *const fn (ptr: *anyopaque, event: Event, state: *const State) void, + deinit: *const fn (ptr: *anyopaque) void, + }; + + pub fn onEvent(self: Observer, event: Event, state: *const State) void { + self.vtable.onEvent(self.ptr, event, state); + } + + pub fn deinit(self: Observer) void { + self.vtable.deinit(self.ptr); + } + + /// Wrap `impl: *T` as an Observer. + pub fn init(impl: anytype) Observer { + const Ptr = @TypeOf(impl); + const T = @typeInfo(Ptr).pointer.child; + if (!@hasDecl(T, "onEvent")) + @compileError(@typeName(T) ++ " is not an Observer: missing `pub fn onEvent(self: *T, event: Event, state: *const State) void`"); + const gen = struct { + fn onEvent(p: *anyopaque, event: Event, state: *const State) void { + const self: Ptr = @ptrCast(@alignCast(p)); + self.onEvent(event, state); + } + fn deinit(p: *anyopaque) void { + const self: Ptr = @ptrCast(@alignCast(p)); + if (@hasDecl(T, "deinit")) self.deinit(); + } + }; + const vt = VTable{ .onEvent = gen.onEvent, .deinit = gen.deinit }; + return .{ .ptr = impl, .vtable = &vt }; + } +}; + +/// Fixed-capacity list of observers; `emit` fans an event out to all of them. +/// No allocation: attaching observers never touches the heap. +pub const ObserverList = struct { + pub const max = 8; + + items: [max]Observer = undefined, + len: usize = 0, + + pub fn add(self: *ObserverList, o: Observer) error{TooManyObservers}!void { + if (self.len == max) return error.TooManyObservers; + self.items[self.len] = o; + self.len += 1; + } + + pub fn emit(self: *const ObserverList, event: Event, state: *const State) void { + for (self.items[0..self.len]) |o| o.onEvent(event, state); + } + + /// Calls each observer's deinit, in reverse order of attachment. + pub fn deinitAll(self: *ObserverList) void { + var i = self.len; + while (i > 0) { + i -= 1; + self.items[i].deinit(); + } + self.len = 0; + } +}; + +test "observer port: fan-out to several observers" { + const Counter = struct { + placed: usize = 0, + ticks: usize = 0, + pub fn onEvent(self: *@This(), event: Event, state: *const State) void { + _ = state; + switch (event) { + .job_placed => self.placed += 1, + .tick_advanced => self.ticks += 1, + else => {}, + } + } + }; + var a = Counter{}; + var b = Counter{}; + var list = ObserverList{}; + try list.add(Observer.init(&a)); + try list.add(Observer.init(&b)); + + const state: State = undefined; + list.emit(.{ .tick_advanced = .{ .now = 1 } }, &state); + list.emit(.{ .job_placed = .{ .id = 0, .slot = 0, .machine = 0, .tick = 1, .arrival = 0, .dur = 3 } }, &state); + try std.testing.expectEqual(@as(usize, 1), a.ticks); + try std.testing.expectEqual(@as(usize, 1), b.placed); + list.deinitAll(); +} diff --git a/src/ports/policy.zig b/src/ports/policy.zig new file mode 100644 index 0000000..ca99ddf --- /dev/null +++ b/src/ports/policy.zig @@ -0,0 +1,100 @@ +//! Policy port: decides what the engine does next. +//! +//! Two forms of the same contract: +//! * Comptime (hot path, zero cost): any type `P` with +//! pub fn decide(self: *P, state: *const State) Action +//! and optionally +//! pub fn reset(self: *P, seed: u64) void +//! Check it with `assertPolicy(P)`; the engine is then specialized for P +//! and `decide` can be inlined into the step loop. +//! * Runtime (`Policy`): a type-erased handle for when the policy must be +//! chosen or swapped at run time, or lives outside Zig (e.g. Python). +//! +//! Rules for implementers: +//! * Never mutate the state (it is `*const`). +//! * Return an action you believe is legal; the engine validates anyway +//! and reports illegal ones as `Event.illegal_action`. +//! * Several `.place` actions may be returned in a row within one tick; +//! return `.wait` when you want time to advance. + +const std = @import("std"); +const types = @import("../model/types.zig"); +pub const State = types.State; +pub const Action = types.Action; + +/// Compile-time check that `P` implements the policy contract. +pub fn assertPolicy(comptime P: type) void { + if (!@hasDecl(P, "decide")) + @compileError(@typeName(P) ++ " is not a Policy: missing `pub fn decide(self: *" ++ @typeName(P) ++ ", state: *const State) Action`"); + const F = @TypeOf(P.decide); + const info = @typeInfo(F).@"fn"; + if (info.param_types.len != 2 or info.return_type.? != Action) + @compileError(@typeName(P) ++ ".decide must be fn(*Self, *const State) Action"); +} + +/// Call `reset` if the policy has one. +pub fn resetIfAny(comptime P: type, p: *P, seed: u64) void { + if (@hasDecl(P, "reset")) p.reset(seed); +} + +/// Call `deinit` if the policy has one (policies that keep caches). +pub fn deinitIfAny(comptime P: type, p: *P) void { + if (@hasDecl(P, "deinit")) p.deinit(); +} + +/// Runtime (type-erased) policy. +pub const Policy = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + decide: *const fn (ptr: *anyopaque, state: *const State) Action, + reset: *const fn (ptr: *anyopaque, seed: u64) void, + }; + + pub fn decide(self: Policy, state: *const State) Action { + return self.vtable.decide(self.ptr, state); + } + + pub fn reset(self: Policy, seed: u64) void { + self.vtable.reset(self.ptr, seed); + } + + /// Wrap any comptime policy (`impl: *P`) as a runtime Policy. + pub fn init(impl: anytype) Policy { + const Ptr = @TypeOf(impl); + const P = @typeInfo(Ptr).pointer.child; + comptime assertPolicy(P); + const gen = struct { + fn decide(p: *anyopaque, state: *const State) Action { + const self: Ptr = @ptrCast(@alignCast(p)); + return self.decide(state); + } + fn reset(p: *anyopaque, seed: u64) void { + const self: Ptr = @ptrCast(@alignCast(p)); + resetIfAny(P, self, seed); + } + }; + const vt = VTable{ .decide = gen.decide, .reset = gen.reset }; + return .{ .ptr = impl, .vtable = &vt }; + } +}; + +test "policy port: comptime check and runtime wrapper" { + const AlwaysWait = struct { + calls: usize = 0, + pub fn decide(self: *@This(), state: *const State) Action { + _ = state; + self.calls += 1; + return .wait; + } + }; + comptime assertPolicy(AlwaysWait); + + var impl = AlwaysWait{}; + const p = Policy.init(&impl); + const state: State = undefined; // not read by this policy + try std.testing.expect(p.decide(&state) == .wait); + p.reset(1); // no reset decl → no-op + try std.testing.expectEqual(@as(usize, 1), impl.calls); +} diff --git a/src/ports/reward.zig b/src/ports/reward.zig new file mode 100644 index 0000000..83782f9 --- /dev/null +++ b/src/ports/reward.zig @@ -0,0 +1,97 @@ +//! Reward port: turns one elapsed tick into a scalar reward (for RL and for +//! comparing policies on a common objective). +//! +//! Contract for an implementation type `T`: +//! pub fn tick(self: *T, ctx: *const Context) f32 +//! Reward for the tick that is ending. Called once per elapsed tick, +//! before time advances: `ctx.state.jobs` are the jobs still waiting +//! and `ctx.running` the jobs running during that tick. +//! optional: +//! pub fn reset(self: *T, seed: u64) void +//! pub fn deinit(self: *T) void +//! +//! Rules: +//! * Read only; deterministic. +//! * Placements pay nothing; illegal actions are penalized by the engine +//! (Config.illegal_penalty), not by this port. +//! * The sum over an episode is what an RL agent maximizes, so a reward of +//! −(something per tick) minimizes the time-integral of that something. +//! +//! With no Reward set, the engine uses −(waiting + running) per tick. + +const std = @import("std"); +const types = @import("../model/types.zig"); +pub const State = types.State; +pub const RunningJob = types.RunningJob; + +pub const Context = struct { + state: *const State, + running: []const RunningJob, +}; + +pub const Reward = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + tick: *const fn (ptr: *anyopaque, ctx: *const Context) f32, + reset: *const fn (ptr: *anyopaque, seed: u64) void, + deinit: *const fn (ptr: *anyopaque) void, + }; + + pub fn tick(self: Reward, ctx: *const Context) f32 { + return self.vtable.tick(self.ptr, ctx); + } + pub fn reset(self: Reward, seed: u64) void { + self.vtable.reset(self.ptr, seed); + } + pub fn deinit(self: Reward) void { + self.vtable.deinit(self.ptr); + } + + /// Wrap `impl: *T` as a Reward. + pub fn init(impl: anytype) Reward { + const Ptr = @TypeOf(impl); + const T = @typeInfo(Ptr).pointer.child; + if (!@hasDecl(T, "tick")) + @compileError(@typeName(T) ++ " is not a Reward: missing `pub fn tick(self: *T, ctx: *const Context) f32`"); + const gen = struct { + fn cast(p: *anyopaque) Ptr { + return @ptrCast(@alignCast(p)); + } + fn tick(p: *anyopaque, ctx: *const Context) f32 { + return cast(p).tick(ctx); + } + fn reset(p: *anyopaque, seed: u64) void { + if (@hasDecl(T, "reset")) cast(p).reset(seed); + } + fn deinit(p: *anyopaque) void { + if (@hasDecl(T, "deinit")) cast(p).deinit(); + } + }; + const vt = VTable{ .tick = gen.tick, .reset = gen.reset, .deinit = gen.deinit }; + return .{ .ptr = impl, .vtable = &vt }; + } +}; + +test "reward port: wrapper calls through" { + const Const = struct { + v: f32, + resets: usize = 0, + pub fn tick(self: *@This(), ctx: *const Context) f32 { + return self.v - @as(f32, @floatFromInt(ctx.running.len)); + } + pub fn reset(self: *@This(), seed: u64) void { + _ = seed; + self.resets += 1; + } + }; + var impl = Const{ .v = 2 }; + const r = Reward.init(&impl); + const st: State = undefined; // not read + const run = [_]RunningJob{.{ .id = 0, .machine = 0, .start = 0, .dur = 1 }}; + try std.testing.expectEqual(@as(f32, 1), r.tick(&.{ .state = &st, .running = &run })); + r.reset(3); + r.deinit(); // no deinit decl → no-op + try std.testing.expectEqual(@as(usize, 1), impl.resets); +} diff --git a/src/ports/usage_generator.zig b/src/ports/usage_generator.zig new file mode 100644 index 0000000..58be0cd --- /dev/null +++ b/src/ports/usage_generator.zig @@ -0,0 +1,150 @@ +//! UsageGenerator port: creates resource usage — job requirement profiles +//! (the [resource][tick] grid of a job) and machine capacities. +//! +//! The engine owns all memory. It hands the generator: +//! * for a job: an already CLEARED Usage view of the job's slot; the +//! generator writes the profile (via `set` / `resourceMut`) for ticks +//! [0, dur) and returns `dur`. The engine then enforces the invariants +//! (1 <= dur <= n_ticks, zero past dur, values >= 0) and computes peaks. +//! * for a machine: an `n_res`-long slice to fill with capacities. +//! +//! Splitting "what a job needs" (this port) from "when a job arrives" +//! (ArrivalSource) lets you mix any arrival process with any profile +//! distribution, e.g. a real trace's arrival times with synthetic profiles. +//! +//! Contract for an implementation type `T`: +//! pub fn machineCount(self: *T) usize +//! pub fn machine(self: *T, index: usize, cap: []Elem) Error!void +//! pub fn job(self: *T, meta: JobMeta, out: Usage) Error!u16 +//! optional: +//! pub fn reset(self: *T, seed: u64) void +//! pub fn deinit(self: *T) void +//! +//! Rules: +//! * Deterministic for a given seed (reproducible experiments). +//! * Write only real ticks [0, dur) of `out`; never write padding. +//! * Do not keep the `out` view after returning — it points into the pool. + +const std = @import("std"); +const types = @import("../model/types.zig"); +const grid = @import("../grid.zig"); +const Usage = grid.Usage; +const Elem = grid.Elem; +pub const JobMeta = types.JobMeta; + +pub const Error = error{ OutOfMemory, InvalidInput, ReadFailed, EndOfData }; + +pub const UsageGenerator = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + machineCount: *const fn (ptr: *anyopaque) usize, + machine: *const fn (ptr: *anyopaque, index: usize, cap: []Elem) Error!void, + job: *const fn (ptr: *anyopaque, meta: JobMeta, out: Usage) Error!u16, + reset: *const fn (ptr: *anyopaque, seed: u64) void, + deinit: *const fn (ptr: *anyopaque) void, + }; + + pub fn machineCount(self: UsageGenerator) usize { + return self.vtable.machineCount(self.ptr); + } + pub fn machine(self: UsageGenerator, index: usize, cap: []Elem) Error!void { + return self.vtable.machine(self.ptr, index, cap); + } + pub fn job(self: UsageGenerator, meta: JobMeta, out: Usage) Error!u16 { + return self.vtable.job(self.ptr, meta, out); + } + pub fn reset(self: UsageGenerator, seed: u64) void { + self.vtable.reset(self.ptr, seed); + } + pub fn deinit(self: UsageGenerator) void { + self.vtable.deinit(self.ptr); + } + + pub fn init(impl: anytype) UsageGenerator { + const Ptr = @TypeOf(impl); + const T = @typeInfo(Ptr).pointer.child; + inline for (.{ "machineCount", "machine", "job" }) |name| { + if (!@hasDecl(T, name)) + @compileError(@typeName(T) ++ " is not a UsageGenerator: missing `" ++ name ++ "`"); + } + const gen = struct { + fn cast(p: *anyopaque) Ptr { + return @ptrCast(@alignCast(p)); + } + fn machineCount(p: *anyopaque) usize { + return cast(p).machineCount(); + } + fn machine(p: *anyopaque, index: usize, cap: []Elem) Error!void { + return cast(p).machine(index, cap); + } + fn job(p: *anyopaque, meta: JobMeta, out: Usage) Error!u16 { + return cast(p).job(meta, out); + } + fn reset(p: *anyopaque, seed: u64) void { + if (@hasDecl(T, "reset")) cast(p).reset(seed); + } + fn deinit(p: *anyopaque) void { + if (@hasDecl(T, "deinit")) cast(p).deinit(); + } + }; + const vt = VTable{ + .machineCount = gen.machineCount, + .machine = gen.machine, + .job = gen.job, + .reset = gen.reset, + .deinit = gen.deinit, + }; + return .{ .ptr = impl, .vtable = &vt }; + } +}; + +test "usage generator port" { + const Layout = grid.Layout; + const simd = grid.simd; + + // Example adapter: N identical machines, constant-demand random jobs. + const Uniform = struct { + n: usize, + cap: Elem, + prng: std.Random.DefaultPrng, + + pub fn machineCount(self: *@This()) usize { + return self.n; + } + pub fn machine(self: *@This(), index: usize, cap: []Elem) Error!void { + _ = index; + @memset(cap, self.cap); + } + pub fn job(self: *@This(), meta: JobMeta, out: Usage) Error!u16 { + _ = meta; + const r = self.prng.random(); + const dur = r.intRangeAtMost(usize, 1, @min(5, out.layout.n_ticks)); + for (0..out.layout.n_res) |res| + @memset(out.resourceMut(res)[0..dur], r.intRangeAtMost(Elem, 0, self.cap)); + return @intCast(dur); + } + pub fn reset(self: *@This(), seed: u64) void { + self.prng = .init(seed); + } + }; + + var impl = Uniform{ .n = 3, .cap = 10, .prng = .init(1) }; + const g = UsageGenerator.init(&impl); + try std.testing.expectEqual(@as(usize, 3), g.machineCount()); + + var cap: [2]Elem = undefined; + try g.machine(0, &cap); + try std.testing.expectEqual(@as(Elem, 10), cap[1]); + + const layout = try Layout.init(2, 8, simd.padding); + const a = std.testing.allocator; + const buf = try a.alignedAlloc(Elem, simd.ALIGN, layout.block); + defer a.free(buf); + @memset(buf, 0); + const dur = try g.job(.{ .id = 0, .arrival = 0 }, Usage.fromSlice(buf, layout)); + try std.testing.expect(dur >= 1 and dur <= 5); + g.reset(1); + g.deinit(); +} diff --git a/src/root.zig b/src/root.zig index 5a71250..c586e93 100644 --- a/src/root.zig +++ b/src/root.zig @@ -1,18 +1,48 @@ -//! By convention, root.zig is the root source file when making a package. +//! sched: a SIMD job-to-machine scheduling simulator. +//! +//! const sched = @import("sched"); +//! var arrivals = sched.adapters.arrivals.Poisson{ .total = 500, .rate = 0.5 }; +//! var profiles = sched.adapters.generators.RandomProfiles{}; +//! var eng = try sched.Engine.init(gpa, .{}, .init(&arrivals), .init(&profiles)); +//! defer eng.deinit(); +//! try eng.reset(42); +//! var policy = sched.adapters.policies.FifoBackfill{}; +//! const stats = try eng.run(&policy, 1_000_000); +//! +//! Layers (each imports only the ones above it): +//! grid — aligned [resource][tick] grids, SIMD operations +//! model — machines, jobs, State / Action / Event +//! ports — Policy, Observer, UsageGenerator, ArrivalSource +//! engine — rules and the step loop +//! adapters — concrete policies, sources, generators, observers + const std = @import("std"); -const Io = std.Io; -/// This is a documentation comment to explain the `printAnotherMessage` function below. -/// -/// Accepting an `Io.Writer` instance is a handy way to write reusable code. -pub fn printAnotherMessage(writer: *Io.Writer) Io.Writer.Error!void { - try writer.print("Run `zig build test` to run the tests.\n", .{}); -} +pub const version = std.SemanticVersion{ .major = 0, .minor = 1, .patch = 0 }; -pub fn add(a: i32, b: i32) i32 { - return a + b; -} +pub const grid = @import("grid.zig"); +pub const model = @import("model.zig"); +pub const ports = @import("ports.zig"); +pub const engine = @import("engine.zig"); +pub const adapters = @import("adapters.zig"); + +pub const Elem = grid.Elem; +pub const Layout = grid.Layout; +pub const Usage = grid.Usage; +pub const Machines = model.Machines; +pub const Jobs = model.Jobs; +pub const State = model.State; +pub const Action = model.Action; +pub const Event = model.Event; +pub const JobMeta = model.JobMeta; +pub const Engine = engine.Engine; +pub const Config = engine.Config; +pub const Stats = engine.Stats; -test "basic add functionality" { - try std.testing.expect(add(3, 7) == 10); +test { + _ = grid; + _ = model; + _ = ports; + _ = engine; + _ = adapters; } diff --git a/tests/.gitkeep b/tests/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/tests/engine_test.zig b/tests/engine_test.zig new file mode 100644 index 0000000..29dd090 --- /dev/null +++ b/tests/engine_test.zig @@ -0,0 +1,137 @@ +//! Integration tests: whole episodes through the public API. +const std = @import("std"); +const sched = @import("sched"); +const A = sched.adapters; +const rules = sched.engine.rules; + +const testing = std.testing; + +fn makeEngine(arr: *A.arrivals.Poisson, gen: *A.generators.RandomProfiles, cfg: sched.Config) !sched.Engine { + return sched.Engine.init(testing.allocator, cfg, .init(arr), .init(gen)); +} + +/// Checks invariants after every event. +const InvariantChecker = struct { + failures: usize = 0, + placed_ids: std.AutoHashMapUnmanaged(u32, void) = .empty, + dup: usize = 0, + + pub fn onEvent(self: *InvariantChecker, ev: sched.Event, st: *const sched.State) void { + // job pool: count matches bitmask, padding zero beyond duration + var n: usize = 0; + var it = st.jobs.iter(); + while (it.next()) |s| { + n += 1; + const u = st.jobs.get(s); + for (0..st.jobs.layout.n_res) |r| { + for (u.row(r)[st.jobs.duration[s]..]) |v| if (v != 0) { + self.failures += 1; + }; + } + if (st.jobs.arrival[s] > st.now) self.failures += 1; + } + if (n != st.jobs.count) self.failures += 1; + // free capacity never above capacity (unsigned: never below 0 either) + for (0..st.machines.n) |m| { + const mach = st.machines.get(m); + for (0..st.machines.layout.n_res) |r| + for (mach.resource(r)) |v| if (v > mach.cap[r]) { + self.failures += 1; + }; + } + switch (ev) { + .job_placed => |p| { + const gop = self.placed_ids.getOrPut(testing.allocator, p.id) catch return; + if (gop.found_existing) self.dup += 1; + }, + else => {}, + } + } +}; + +test "episode: every job placed once, invariants hold, all policies" { + inline for (.{ A.policies.FifoBackfill, A.policies.FifoStrict, A.policies.ShortestFirst, A.policies.BestFit, A.policies.RandomPolicy }) |P| { + var arr = A.arrivals.Poisson{ .total = 200, .rate = 0.8 }; + var gen = A.generators.RandomProfiles{ .n_machines = 3, .varying = true }; + var eng = try makeEngine(&arr, &gen, .{ .n_res = 4, .n_ticks = 40, .max_jobs = 64 }); + defer eng.deinit(); + var chk = InvariantChecker{}; + defer chk.placed_ids.deinit(testing.allocator); + try eng.addObserver(.init(&chk)); + + try eng.reset(7); + var p = P{}; + defer sched.ports.policy.deinitIfAny(P, &p); + const st = try eng.run(&p, 1_000_000); + + try testing.expect(eng.done()); + try testing.expectEqual(@as(usize, 0), chk.failures); + try testing.expectEqual(@as(usize, 0), chk.dup); + try testing.expectEqual(st.arrived, st.placed); + try testing.expectEqual(@as(usize, 200), st.arrived + st.rejected); + try testing.expect(eng.machines.allIdle()); + } +} + +test "determinism: same seed, same result; different seed, different result" { + var results: [3]sched.Stats = undefined; + for ([_]u64{ 1, 1, 2 }, 0..) |seed, i| { + var arr = A.arrivals.Poisson{ .total = 300, .rate = 0.6 }; + var gen = A.generators.RandomProfiles{}; + var eng = try makeEngine(&arr, &gen, .{ .n_res = 5, .n_ticks = 50 }); + defer eng.deinit(); + try eng.reset(seed); + var p = A.policies.FifoBackfill{}; + results[i] = try eng.run(&p, 1_000_000); + } + try testing.expectEqual(results[0].makespan, results[1].makespan); + try testing.expectEqual(results[0].total_wait, results[1].total_wait); + try testing.expect(results[0].total_wait != results[2].total_wait or results[0].makespan != results[2].makespan); +} + +test "illegal action: penalized, treated as wait" { + var arr = A.arrivals.Poisson{ .total = 5, .rate = 0 }; + var gen = A.generators.RandomProfiles{ .n_machines = 1 }; + var eng = try makeEngine(&arr, &gen, .{ .n_res = 2, .n_ticks = 30, .max_jobs = 8 }); + defer eng.deinit(); + try eng.reset(3); + + const t0 = eng.now; + const r = try eng.step(.{ .place = .{ .slot = 7, .machine = 0 } }); // empty slot + try testing.expect(r.illegal); + try testing.expect(r.reward <= -1.0); + try testing.expectEqual(t0 + 1, eng.now); +} + +test "action encoding and mask" { + var arr = A.arrivals.Poisson{ .total = 10, .rate = 0 }; + var gen = A.generators.RandomProfiles{ .n_machines = 2 }; + var eng = try makeEngine(&arr, &gen, .{ .n_res = 3, .n_ticks = 30, .max_jobs = 16 }); + defer eng.deinit(); + try eng.reset(5); + + const st = eng.state(); + const n = rules.actionCount(&st); + try testing.expectEqual(@as(usize, 16 * 2 + 1), n); + const mask = try testing.allocator.alloc(bool, n); + defer testing.allocator.free(mask); + rules.actionMask(&st, mask); + try testing.expect(mask[n - 1]); // wait always legal + for (0..n) |i| { + const a = rules.decode(&st, i); + try testing.expectEqual(i, rules.encode(&st, a)); + try testing.expectEqual(mask[i], rules.isLegal(&st, a)); + } +} + +test "truncation" { + var arr = A.arrivals.Poisson{ .total = 1000, .rate = 0.1 }; + var gen = A.generators.RandomProfiles{}; + var eng = try makeEngine(&arr, &gen, .{ .n_res = 2, .n_ticks = 20, .max_ticks = 50 }); + defer eng.deinit(); + try eng.reset(1); + var p = A.policies.FifoBackfill{}; + _ = try eng.run(&p, 1_000_000); + try testing.expect(eng.done()); + try testing.expectEqual(@as(i64, 50), eng.now); +} diff --git a/tests/scenario_test.zig b/tests/scenario_test.zig new file mode 100644 index 0000000..7c6cab3 --- /dev/null +++ b/tests/scenario_test.zig @@ -0,0 +1,809 @@ +//! Scenario tests: small hand-built workloads whose correct outcome is worked +//! out by hand (comments show the arithmetic), plus a property test that +//! compares the engine against a deliberately naive reference simulator. +//! +//! Reward convention checked here (default reward = neg_in_system): each +//! `.wait` pays −(waiting + running) for the tick that ends, counted before +//! time advances; `.place` pays 0. + +const std = @import("std"); +const sched = @import("sched"); +const A = sched.adapters; +const rules = sched.engine.rules; +const Elem = sched.Elem; +const Action = sched.Action; +const testing = std.testing; + +// ------------------------------------------------------------------ helpers + +/// One scripted job: arrival, and its demand profile flat [n_res][dur]. +const JobSpec = struct { + arrival: i64 = 0, + dur: u16, + /// Flat [n_res][dur]; or n_res values for constant demand. + demand: []const Elem, +}; + +/// UsageGenerator + ArrivalSource from a fixed script. +const Script = struct { + caps: []const Elem, // flat [n_machines][n_res] + n_res: usize, + jobs: []const JobSpec, + metas: [64]sched.JobMeta = undefined, + fixed: A.arrivals.Fixed = .{ .items = &.{} }, + + fn init(self: *Script) void { + for (self.jobs, 0..) |j, i| self.metas[i] = .{ .id = @intCast(i), .arrival = j.arrival }; + self.fixed = .{ .items = self.metas[0..self.jobs.len] }; + } + + // UsageGenerator + pub fn machineCount(self: *Script) usize { + return self.caps.len / self.n_res; + } + pub fn machine(self: *Script, i: usize, cap: []Elem) sched.ports.usage_generator.Error!void { + @memcpy(cap, self.caps[i * self.n_res ..][0..self.n_res]); + } + pub fn job(self: *Script, meta: sched.JobMeta, out: sched.Usage) sched.ports.usage_generator.Error!u16 { + const j = self.jobs[meta.id]; + const n = @min(j.dur, out.layout.n_ticks); // never write past the horizon + for (0..self.n_res) |r| { + if (j.demand.len == self.n_res) { + @memset(out.resourceMut(r)[0..n], j.demand[r]); + } else { + @memcpy(out.resourceMut(r)[0..n], j.demand[r * j.dur ..][0..n]); + } + } + return j.dur; + } +}; + +/// Records events for assertions. +const Recorder = struct { + const Placed = struct { id: u32, machine: u32, tick: i64 }; + placed: std.ArrayList(Placed) = .empty, + rejected: std.ArrayList(sched.model.RejectReason) = .empty, + illegal: usize = 0, + done: ?struct { now: i64, truncated: bool } = null, + + pub fn onEvent(self: *Recorder, ev: sched.Event, st: *const sched.State) void { + _ = st; + switch (ev) { + .job_placed => |p| self.placed.append(testing.allocator, .{ .id = p.id, .machine = p.machine, .tick = p.tick }) catch {}, + .job_rejected => |r| self.rejected.append(testing.allocator, r.reason) catch {}, + .illegal_action => self.illegal += 1, + .episode_done => |d| self.done = .{ .now = d.now, .truncated = d.truncated }, + else => {}, + } + } + fn deinit(self: *Recorder) void { + self.placed.deinit(testing.allocator); + self.rejected.deinit(testing.allocator); + } + fn tickOf(self: Recorder, id: u32) ?i64 { + for (self.placed.items) |p| if (p.id == id) return p.tick; + return null; + } + fn machineOf(self: Recorder, id: u32) ?u32 { + for (self.placed.items) |p| if (p.id == id) return p.machine; + return null; + } +}; + +/// Engine + script + recorder, wired together. +const Sim = struct { + script: Script, + rec: Recorder = .{}, + eng: sched.Engine = undefined, + + fn start(self: *Sim, cfg: sched.Config) !void { + self.script.init(); + self.eng = try sched.Engine.init(testing.allocator, cfg, .init(&self.script.fixed), .init(&self.script)); + try self.eng.addObserver(.init(&self.rec)); + try self.eng.reset(0); + } + fn deinit(self: *Sim) void { + self.eng.deinit(); + self.rec.deinit(); + } + fn slotOf(self: *Sim, id: u32) u32 { + var it = self.eng.jobs.iter(); + while (it.next()) |s| if (self.eng.jobs.id[s] == id) return @intCast(s); + @panic("job not waiting"); + } + fn place(self: *Sim, id: u32, m: u32) !sched.engine.StepResult { + return self.eng.step(.{ .place = .{ .slot = self.slotOf(id), .machine = m } }); + } + fn wait(self: *Sim) !sched.engine.StepResult { + return self.eng.step(.wait); + } + fn free(self: *Sim, m: usize, r: usize) []const Elem { + return self.eng.machines.get(m).resource(r); + } +}; + +fn cfg1(n_res: usize, n_ticks: usize) sched.Config { + return .{ .n_res = n_res, .n_ticks = n_ticks, .max_jobs = 16 }; +} + +// ------------------------------------------------------------------ basic mechanics + +test "scenario: one job — placement, aging, finish, reward, termination" { + // cap 10/10; job0 needs 4 (res 0) and 1 (res 1) for 3 ticks. + var sim = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 2, .jobs = &.{ + .{ .dur = 3, .demand = &.{ 4, 1 } }, + } } }; + // skip_empty off: step through each tick (with it on, one wait would + // fast-forward straight to the end, see the skip_empty scenario) + try sim.start(.{ .n_res = 2, .n_ticks = 6, .max_jobs = 4, .skip_empty = false }); + defer sim.deinit(); + + try testing.expectEqual(@as(usize, 1), sim.eng.jobs.count); + const r0 = try sim.place(0, 0); + try testing.expect(r0.placed and !r0.illegal); + try testing.expectEqual(@as(f32, 0), r0.reward); // placing pays nothing + try testing.expectEqualSlices(Elem, &.{ 6, 6, 6, 10, 10, 10 }, sim.free(0, 0)); + try testing.expectEqualSlices(Elem, &.{ 9, 9, 9, 10, 10, 10 }, sim.free(0, 1)); + + // tick 0 ends: 1 running → −1; the profile slides left + var r = try sim.wait(); + try testing.expectEqual(@as(f32, -1), r.reward); + try testing.expectEqual(@as(i64, 1), sim.eng.now); + try testing.expectEqualSlices(Elem, &.{ 6, 6, 10, 10, 10, 10 }, sim.free(0, 0)); + r = try sim.wait(); + try testing.expect(!r.terminated); + r = try sim.wait(); // now = 3: job finished, nothing left → terminated + try testing.expect(r.terminated and !r.truncated); + try testing.expect(sim.eng.done()); + + const s = sim.eng.stats; + try testing.expectEqual(@as(i64, 3), s.makespan); + try testing.expectEqual(@as(f64, -3), s.total_reward); // 3 ticks × −1 + try testing.expectEqual(@as(f64, 0), s.avgWait()); + try testing.expect(sim.eng.machines.allIdle()); + try testing.expectEqual(@as(i64, 3), sim.rec.done.?.now); +} + +test "scenario: capacity blocks the second job until the first finishes" { + // one machine cap 10; two jobs of demand 6 → cannot overlap. + // job0 runs [0,4), job1 [4,6). waits 0 and 4. + // reward: ticks 0..3 → −(1 waiting + 1 running) ×4 = −8; ticks 4,5 → −1 ×2 = −2. + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ + .{ .dur = 4, .demand = &.{6} }, + .{ .dur = 2, .demand = &.{6} }, + } } }; + try sim.start(cfg1(1, 8)); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 1000); + + try testing.expectEqual(@as(?i64, 0), sim.rec.tickOf(0)); + try testing.expectEqual(@as(?i64, 4), sim.rec.tickOf(1)); + try testing.expectEqual(@as(i64, 6), s.makespan); + try testing.expectEqual(@as(i64, 4), s.max_wait); + try testing.expectEqual(@as(f64, 2), s.avgWait()); + try testing.expectEqual(@as(f64, -10), s.total_reward); +} + +test "scenario: a second machine removes the conflict" { + var sim = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 1, .jobs = &.{ + .{ .dur = 4, .demand = &.{6} }, + .{ .dur = 2, .demand = &.{6} }, + } } }; + try sim.start(cfg1(1, 8)); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 1000); + try testing.expectEqual(@as(?u32, 0), sim.rec.machineOf(0)); + try testing.expectEqual(@as(?u32, 1), sim.rec.machineOf(1)); + try testing.expectEqual(@as(i64, 0), s.max_wait); + try testing.expectEqual(@as(i64, 4), s.makespan); +} + +test "scenario: exact fit to the last unit is allowed, one more is not" { + var sim = Sim{ .script = .{ .caps = &.{ 10, 7 }, .n_res = 2, .jobs = &.{ + .{ .dur = 2, .demand = &.{ 10, 7 } }, // exactly full + .{ .dur = 1, .demand = &.{ 0, 1 } }, // 1 unit too many on res 1 + } } }; + try sim.start(cfg1(2, 4)); + defer sim.deinit(); + const st = sim.eng.state(); + try testing.expect(rules.fitsNow(&st, sim.slotOf(0), 0)); + _ = try sim.place(0, 0); + const st2 = sim.eng.state(); + try testing.expect(!rules.fitsNow(&st2, sim.slotOf(1), 0)); + try testing.expectEqualSlices(Elem, &.{ 0, 0, 10, 10 }, sim.free(0, 0)); +} + +test "scenario: time-varying profiles — the whole window must fit, not just tick 0" { + // job0 uses 8,8,2,2 → free 2,2,8,8. job1 needs 2,8: tick 0 fits (2 ≤ 2) + // but tick 1 does not (8 > 2). One tick later free is 2,8,8,10 → fits. + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ + .{ .dur = 4, .demand = &.{ 8, 8, 2, 2 } }, + .{ .dur = 2, .demand = &.{ 2, 8 } }, + } } }; + try sim.start(cfg1(1, 6)); + defer sim.deinit(); + _ = try sim.place(0, 0); + try testing.expectEqualSlices(Elem, &.{ 2, 2, 8, 8, 10, 10 }, sim.free(0, 0)); + + const m = sim.eng.machines.get(0); + const s1 = sim.slotOf(1); + try testing.expect(m.mayFit(sim.eng.jobs.get(s1), sim.eng.jobs.peakOf(s1), 0)); // cheap check passes + const st = sim.eng.state(); + try testing.expect(!rules.fitsNow(&st, s1, 0)); // full check rejects + try testing.expectEqual(@as(?usize, 1), m.earliestFit(sim.eng.jobs.get(s1), 2)); + + var p = A.policies.FifoBackfill{}; + _ = try sim.eng.run(&p, 1000); + try testing.expectEqual(@as(?i64, 1), sim.rec.tickOf(1)); + try testing.expectEqual(@as(i64, 4), sim.eng.stats.makespan); +} + +test "scenario: resources are independent — one full resource blocks" { + // res 0 has room, res 1 is full → no fit. + var sim = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 2, .jobs = &.{ + .{ .dur = 3, .demand = &.{ 1, 10 } }, + .{ .dur = 1, .demand = &.{ 1, 1 } }, + } } }; + try sim.start(cfg1(2, 5)); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + _ = try sim.eng.run(&p, 1000); + try testing.expectEqual(@as(?i64, 3), sim.rec.tickOf(1)); +} + +test "scenario: a job as long as the horizon fits; finishing frees exactly at dur" { + var sim = Sim{ .script = .{ .caps = &.{5}, .n_res = 1, .jobs = &.{ + .{ .dur = 5, .demand = &.{5} }, + .{ .dur = 5, .demand = &.{5} }, + } } }; + try sim.start(cfg1(1, 5)); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 1000); + try testing.expectEqual(@as(?i64, 5), sim.rec.tickOf(1)); + try testing.expectEqual(@as(i64, 10), s.makespan); +} + +// ------------------------------------------------------------------ policies + +test "scenario: backfill lets a small job jump ahead; strict FIFO does not" { + // cap 10. job0 (t0, 7 × 5 ticks) runs; job1 (t0, 5 × 3) must wait until 5; + // job2 (t1, 3 × 2) fits next to job0 (7+3 = 10). + // backfill: job2 starts at 1 → waits 0,5,0. strict: job2 waits behind job1, + // both start at 5 (5+3 = 8) → waits 0,5,4. + const jobs = [_]JobSpec{ + .{ .dur = 5, .demand = &.{7} }, + .{ .dur = 3, .demand = &.{5} }, + .{ .arrival = 1, .dur = 2, .demand = &.{3} }, + }; + var bf = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try bf.start(cfg1(1, 8)); + defer bf.deinit(); + var p1 = A.policies.FifoBackfill{}; + const a = try bf.eng.run(&p1, 1000); + try testing.expectEqual(@as(?i64, 1), bf.rec.tickOf(2)); + try testing.expectEqual(@as(i64, 5), a.total_wait); + + var st = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try st.start(cfg1(1, 8)); + defer st.deinit(); + var p2 = A.policies.FifoStrict{}; + const b = try st.eng.run(&p2, 1000); + try testing.expectEqual(@as(?i64, 5), st.rec.tickOf(2)); + try testing.expectEqual(@as(i64, 9), b.total_wait); + try testing.expectEqual(a.makespan, b.makespan); // both end at 8 + try testing.expectEqual(@as(i64, 8), b.makespan); +} + +test "scenario: SJF orders by duration, FIFO by arrival" { + // three exclusive jobs (demand = cap) at t0, durations 3,1,2. + // SJF: 1 [0,1), 2 [1,3), 0 [3,6) → waits 0+1+3 = 4. + // FIFO: 0 [0,3), 1 [3,4), 2 [4,6) → waits 0+3+4 = 7. + const jobs = [_]JobSpec{ + .{ .dur = 3, .demand = &.{10} }, + .{ .dur = 1, .demand = &.{10} }, + .{ .dur = 2, .demand = &.{10} }, + }; + var a = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try a.start(cfg1(1, 8)); + defer a.deinit(); + var sjf = A.policies.ShortestFirst{}; + const sa = try a.eng.run(&sjf, 1000); + try testing.expectEqual(@as(i64, 4), sa.total_wait); + try testing.expectEqual(@as(?i64, 3), a.rec.tickOf(0)); + + var b = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try b.start(cfg1(1, 8)); + defer b.deinit(); + var fifo = A.policies.FifoBackfill{}; + const sb = try b.eng.run(&fifo, 1000); + try testing.expectEqual(@as(i64, 7), sb.total_wait); + try testing.expectEqual(sa.makespan, sb.makespan); +} + +test "scenario: best_fit packs the tighter machine, FIFO takes the first" { + // machines cap 10 and 5; job demand 5 → leaves 0.5 vs 0.0 normalized. + const jobs = [_]JobSpec{.{ .dur = 1, .demand = &.{5} }}; + var a = Sim{ .script = .{ .caps = &.{ 10, 5 }, .n_res = 1, .jobs = &jobs } }; + try a.start(cfg1(1, 4)); + defer a.deinit(); + var bf = A.policies.BestFit{}; + defer bf.deinit(); + _ = try a.eng.run(&bf, 100); + try testing.expectEqual(@as(?u32, 1), a.rec.machineOf(0)); + + var b = Sim{ .script = .{ .caps = &.{ 10, 5 }, .n_res = 1, .jobs = &jobs } }; + try b.start(cfg1(1, 4)); + defer b.deinit(); + var ff = A.policies.FifoBackfill{}; + _ = try b.eng.run(&ff, 100); + try testing.expectEqual(@as(?u32, 0), b.rec.machineOf(0)); +} + +test "scenario: slowdown reward sums to minus the total slowdown" { + // jobs (dur 1, 4, 2) exclusive on one machine, SJF order 0,2,1: + // starts 0,1,3 → slowdowns (0+1)/1, (3+4)/4, (1+2)/2 = 1 + 1.75 + 1.5 = 4.25 + const jobs = [_]JobSpec{ + .{ .dur = 1, .demand = &.{10} }, + .{ .dur = 4, .demand = &.{10} }, + .{ .dur = 2, .demand = &.{10} }, + }; + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try sim.start(cfg1(1, 8)); + defer sim.deinit(); + var slow = A.rewards.Slowdown{}; + sim.eng.setReward(.init(&slow)); + var p = A.policies.ShortestFirst{}; + const s = try sim.eng.run(&p, 100); + try testing.expectApproxEqAbs(@as(f64, -4.25), s.total_reward, 1e-5); + + // bounded slowdown: denominators below min_dur are raised to it + var bsim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try bsim.start(cfg1(1, 8)); + defer bsim.deinit(); + var bounded = A.rewards.Slowdown{ .min_dur = 4 }; + bsim.eng.setReward(.init(&bounded)); + const b = try bsim.eng.run(&p, 100); + // (0+1)/4 + (3+4)/4 + (1+2)/4 = 11/4 + try testing.expectApproxEqAbs(@as(f64, -2.75), b.total_reward, 1e-5); +} + +test "scenario: tetris aligns job shape with free capacity, best_fit packs tick 0" { + // two resources. m0 has room on res 0, m1 on res 1 (both 10 at tick 0 + // after the blockers). job2 is res-1 heavy → tetris sends it to m1. + // m0 cap (10, 10), blocker uses (2, 8) → free (8, 2) + // m1 cap (10, 10), blocker uses (8, 2) → free (2, 8) + // job2 demand (1, 2): fits both; alignment m0 = 1·8+2·2 = 12, m1 = 1·2+2·8 = 18 + var sim = Sim{ .script = .{ .caps = &.{ 10, 10, 10, 10 }, .n_res = 2, .jobs = &.{ + .{ .dur = 6, .demand = &.{ 2, 8 } }, + .{ .dur = 6, .demand = &.{ 8, 2 } }, + .{ .arrival = 1, .dur = 2, .demand = &.{ 1, 2 } }, + } } }; + try sim.start(cfg1(2, 8)); + defer sim.deinit(); + _ = try sim.place(0, 0); + _ = try sim.place(1, 1); + _ = try sim.wait(); // job2 arrives + var t = A.policies.Tetris{}; + defer t.deinit(); + const st = sim.eng.state(); + const a = t.decide(&st); + try testing.expectEqual(@as(u32, 1), a.place.machine); + // best_fit sees a tie at tick 0 (both leave 0.7 of capacity) → first machine + var bf0 = A.policies.BestFit{}; + defer bf0.deinit(); + try testing.expectEqual(@as(u32, 0), bf0.decide(&st).place.machine); + + // time matters: a job whose demand is high later is sent to the machine + // that frees up later in its run. m0 free (2,2,10,10), m1 free (6,6,6,6) + // on one resource; job needs (2,2,6,6): fits both, aligns with m0. + var sim2 = Sim{ .script = .{ .caps = &.{ 10, 10 }, .n_res = 1, .jobs = &.{ + .{ .dur = 2, .demand = &.{8} }, + .{ .dur = 6, .demand = &.{4} }, + .{ .arrival = 0, .dur = 4, .demand = &.{ 2, 2, 6, 6 } }, + } } }; + try sim2.start(cfg1(1, 8)); + defer sim2.deinit(); + _ = try sim2.place(0, 0); + _ = try sim2.place(1, 1); + const st2 = sim2.eng.state(); + const a2 = t.decide(&st2); + try testing.expectEqual(@as(u32, 0), a2.place.machine); // 2·2+2·2+6·10+6·10=128 vs 2·6·2+6·6·2=96 + var bf = A.policies.BestFit{}; + defer bf.deinit(); + try testing.expectEqual(@as(u32, 0), bf.decide(&st2).place.machine); // tick 0: m0 leaves 0 vs m1 4 +} + +test "scenario: tetris_srpt trades packing for short jobs via its weight" { + // empty machine cap 10. big job A (8 × 4 ticks) vs small job B (2 × 1). + // alignment a = demand·free/cap² summed over time: A 3.2, B 0.2. + // ε = weight · mean(a)/mean(dur) = weight · 1.7/2.5. + // weight 0 → scores 3.2, 0.2 → A (pure tetris) + // weight 1.5 → 3.2 − 1.02·4 = −0.88, 0.2 − 1.02 = −0.82 → B + const jobs = [_]JobSpec{ + .{ .dur = 4, .demand = &.{8} }, + .{ .dur = 1, .demand = &.{2} }, + }; + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try sim.start(cfg1(1, 8)); + defer sim.deinit(); + const st = sim.eng.state(); + const big = sim.slotOf(0); + const small = sim.slotOf(1); + + var pure = A.policies.Tetris{}; + defer pure.deinit(); + try testing.expectEqual(big, pure.decide(&st).place.slot); + var w0 = A.policies.TetrisSrpt{ .weight = 0 }; + defer w0.deinit(); + try testing.expectEqual(big, w0.decide(&st).place.slot); + var w = A.policies.TetrisSrpt{}; + defer w.deinit(); + try testing.expectEqual(small, w.decide(&st).place.slot); + // nothing fits → wait + _ = try sim.place(0, 0); + _ = try sim.place(1, 0); + const st2 = sim.eng.state(); + try testing.expect(w.decide(&st2) == .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} }, + .{ .dur = 2, .demand = &.{3} }, + .{ .dur = 2, .demand = &.{3} }, + } } }; + try sim.start(cfg1(1, 4)); + defer sim.deinit(); + for (0..3) |i| _ = try sim.place(@intCast(i), 0); + try testing.expectEqual(@as(i64, 0), sim.eng.now); + try testing.expectEqualSlices(Elem, &.{ 1, 1, 10, 10 }, sim.free(0, 0)); +} + +// ------------------------------------------------------------------ illegal actions + +test "scenario: illegal actions are penalized, counted, and act as wait" { + // job0 fills the machine; job1 cannot fit. + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ + .{ .dur = 5, .demand = &.{10} }, + .{ .dur = 1, .demand = &.{1} }, + } } }; + try sim.start(cfg1(1, 8)); + defer sim.deinit(); + _ = try sim.place(0, 0); + + // does not fit → penalty −1 plus the tick: 1 waiting + 1 running = −2 → −3 + var r = try sim.place(1, 0); + try testing.expect(r.illegal and !r.placed); + try testing.expectEqual(@as(f32, -3), r.reward); + try testing.expectEqual(@as(i64, 1), sim.eng.now); + + // empty slot / machine out of range + r = try sim.eng.step(.{ .place = .{ .slot = 15, .machine = 0 } }); + try testing.expect(r.illegal); + r = try sim.eng.step(.{ .place = .{ .slot = sim.slotOf(1), .machine = 7 } }); + try testing.expect(r.illegal); + // slot index beyond the pool + r = try sim.eng.step(.{ .place = .{ .slot = 999, .machine = 0 } }); + try testing.expect(r.illegal); + + try testing.expectEqual(@as(usize, 4), sim.eng.stats.illegal); + try testing.expectEqual(@as(usize, 4), sim.rec.illegal); + try testing.expectEqual(@as(i64, 4), sim.eng.now); + try testing.expectEqual(@as(usize, 1), sim.eng.jobs.count); // job1 still waiting, untouched + try testing.expectEqual(@as(usize, 1), sim.eng.stats.placed); +} + +test "scenario: action mask agrees with legality for every action" { + var sim = Sim{ .script = .{ .caps = &.{ 10, 4, 6, 6 }, .n_res = 2, .jobs = &.{ + .{ .dur = 2, .demand = &.{ 5, 5 } }, // fits m0 only + .{ .dur = 2, .demand = &.{ 3, 3 } }, // fits both + .{ .dur = 2, .demand = &.{ 11, 0 } }, // impossible → dropped + } } }; + try sim.start(cfg1(2, 4)); + defer sim.deinit(); + const st = sim.eng.state(); + const n = rules.actionCount(&st); + const mask = try testing.allocator.alloc(bool, n); + defer testing.allocator.free(mask); + rules.actionMask(&st, mask); + var legal: usize = 0; + for (0..n) |i| { + const act = rules.decode(&st, i); + try testing.expectEqual(rules.isLegal(&st, act), mask[i]); + try testing.expectEqual(i, rules.encode(&st, act)); + if (mask[i]) legal += 1; + } + try testing.expectEqual(@as(usize, 1 + 2 + 1), legal); // job0→m0, job1→m0/m1, wait +} + +// ------------------------------------------------------------------ admission + +test "scenario: full pool rejects, impossible and invalid jobs are dropped" { + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ + // the pool check comes first, so the bad jobs arrive while slots are free + .{ .dur = 1, .demand = &.{11} }, // impossible on every machine + .{ .dur = 9, .demand = &.{1} }, // longer than the horizon (4) + .{ .dur = 0, .demand = &.{1} }, // zero duration + .{ .dur = 1, .demand = &.{1} }, + .{ .dur = 1, .demand = &.{1} }, + .{ .dur = 1, .demand = &.{1} }, // pool (2 slots) now full + } } }; + try sim.start(.{ .n_res = 1, .n_ticks = 4, .max_jobs = 2 }); + defer sim.deinit(); + + try testing.expectEqual(@as(usize, 2), sim.eng.jobs.count); + try testing.expectEqual(@as(usize, 2), sim.eng.stats.arrived); + // rejected slots were handed back: the two admitted jobs got slots 0 and 1 + try testing.expect(sim.eng.jobs.isValid(0) and sim.eng.jobs.isValid(1)); + try testing.expectEqual(@as(usize, 4), sim.eng.stats.rejected); + const R = sched.model.RejectReason; + try testing.expectEqualSlices(R, &.{ .impossible, .invalid_profile, .invalid_profile, .pool_full }, sim.rec.rejected.items); + + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 100); + try testing.expectEqual(@as(usize, 2), s.placed); + try testing.expect(sim.eng.done()); +} + +test "scenario: impossible job kept (drop_impossible = false) waits until truncation" { + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &.{ + .{ .dur = 1, .demand = &.{11} }, + } } }; + try sim.start(.{ .n_res = 1, .n_ticks = 4, .max_jobs = 2, .drop_impossible = false, .max_ticks = 20 }); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 1000); + try testing.expect(sim.rec.done.?.truncated); + try testing.expectEqual(@as(i64, 20), sim.eng.now); + try testing.expectEqual(@as(usize, 0), s.placed); + try testing.expectEqual(@as(f64, -20), s.total_reward); // 1 waiting × 20 ticks +} + +// ------------------------------------------------------------------ time + +test "scenario: skip_empty fast-forwards an idle gap in one step" { + // job0 [0,2); job1 arrives at 50. After placing job0, one wait jumps to 50. + // reward: ticks 0,1 → −1 each (job0 running); 2..49 → 0. + const jobs = [_]JobSpec{ + .{ .dur = 2, .demand = &.{1} }, + .{ .arrival = 50, .dur = 1, .demand = &.{1} }, + }; + var a = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try a.start(cfg1(1, 4)); + defer a.deinit(); + _ = try a.place(0, 0); + const r = try a.wait(); + try testing.expectEqual(@as(i64, 50), a.eng.now); + try testing.expectEqual(@as(f32, -2), r.reward); + try testing.expectEqual(@as(usize, 1), a.eng.jobs.count); + + var b = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try b.start(.{ .n_res = 1, .n_ticks = 4, .max_jobs = 4, .skip_empty = false }); + defer b.deinit(); + _ = try b.place(0, 0); + _ = try b.wait(); + try testing.expectEqual(@as(i64, 1), b.eng.now); + var p = A.policies.FifoBackfill{}; + const sb = try b.eng.run(&p, 1000); + // same outcome either way + try testing.expectEqual(@as(i64, 51), sb.makespan); + try testing.expectEqual(@as(f64, -3), sb.total_reward); // −2 for job0, −1 for job1 +} + +test "scenario: reward kinds" { + // two exclusive jobs dur 2 each at t0 on one machine: + // ticks 0,1: 1 waiting + 1 running; ticks 2,3: 0 waiting + 1 running. + const jobs = [_]JobSpec{ .{ .dur = 2, .demand = &.{10} }, .{ .dur = 2, .demand = &.{10} } }; + var in_sys = A.rewards.NegInSystem{}; + var waiting = A.rewards.NegWaiting{}; + var zero = A.rewards.Zero{}; + var slow = A.rewards.Slowdown{}; + const want = [_]struct { r: ?sched.ports.Reward, v: f64 }{ + .{ .r = null, .v = -6 }, // default = neg_in_system + .{ .r = .init(&in_sys), .v = -6 }, // 2+2+1+1 + .{ .r = .init(&waiting), .v = -2 }, // 1+1 + .{ .r = .init(&zero), .v = 0 }, + // slowdown: −Σ 1/T per job per tick in system; job0 2 ticks, job1 4 ticks, + // T = 2 → −(2 + 4)/2 = −3 = −(slowdown 1 + slowdown 2) + .{ .r = .init(&slow), .v = -3 }, + }; + for (want) |w| { + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try sim.start(.{ .n_res = 1, .n_ticks = 4, .max_jobs = 4 }); + defer sim.deinit(); + sim.eng.setReward(w.r); + var p = A.policies.FifoBackfill{}; + const s = try sim.eng.run(&p, 100); + try testing.expectEqual(w.v, s.total_reward); + } +} + +test "scenario: reset replays the same episode" { + const jobs = [_]JobSpec{ + .{ .dur = 3, .demand = &.{6} }, + .{ .arrival = 1, .dur = 2, .demand = &.{6} }, + .{ .arrival = 2, .dur = 1, .demand = &.{4} }, + }; + var sim = Sim{ .script = .{ .caps = &.{10}, .n_res = 1, .jobs = &jobs } }; + try sim.start(cfg1(1, 4)); + defer sim.deinit(); + var p = A.policies.FifoBackfill{}; + const a = try sim.eng.run(&p, 100); + try sim.eng.reset(0); + try testing.expect(sim.eng.machines.allIdle()); + try testing.expectEqual(@as(i64, 0), sim.eng.now); + const b = try sim.eng.run(&p, 100); + try testing.expectEqual(a.total_wait, b.total_wait); + try testing.expectEqual(a.makespan, b.makespan); + try testing.expectEqual(a.total_reward, b.total_reward); +} + +// ------------------------------------------------------------------ reference model + +/// Naive reference: keeps a list of running jobs and recomputes every +/// machine's free capacity from scratch, tick by tick. No SIMD, no padding, +/// no sliding window — just the definition. +const Reference = struct { + const Run = struct { machine: usize, start: i64, spec: JobSpec }; + running: std.ArrayList(Run) = .empty, + + fn deinit(self: *Reference) void { + self.running.deinit(testing.allocator); + } + + fn demandAt(spec: JobSpec, n_res: usize, r: usize, k: usize) Elem { + if (k >= spec.dur) return 0; + return if (spec.demand.len == n_res) spec.demand[r] else spec.demand[r * spec.dur + k]; + } + + fn free(self: Reference, caps: []const Elem, n_res: usize, m: usize, r: usize, now: i64, t: usize) i64 { + var f: i64 = caps[m * n_res + r]; + for (self.running.items) |run| { + if (run.machine != m) continue; + const k = now + @as(i64, @intCast(t)) - run.start; + if (k < 0 or k >= run.spec.dur) continue; + f -= demandAt(run.spec, n_res, r, @intCast(k)); + } + return f; + } + + fn fits(self: Reference, caps: []const Elem, n_res: usize, n_ticks: usize, m: usize, spec: JobSpec, now: i64) bool { + if (spec.dur > n_ticks) return false; + for (0..n_res) |r| for (0..spec.dur) |k| { + if (demandAt(spec, n_res, r, k) > self.free(caps, n_res, m, r, now, k)) return false; + }; + return true; + } + + fn runningAt(self: Reference, now: i64) usize { + var n: usize = 0; + for (self.running.items) |run| { + if (run.start <= now and now < run.start + run.spec.dur) n += 1; + } + return n; + } +}; + +test "property: engine matches the naive reference on random workloads" { + const n_res = 3; + const n_ticks = 8; // small horizon → the machine window compacts very often + const caps = [_]Elem{ 12, 9, 15, 6, 10, 8 }; // 2 machines + + var prng = std.Random.DefaultPrng.init(2024); + const rnd = prng.random(); + + for (0..20) |episode| { + // random script: 60 jobs, random arrivals, time-varying profiles + var specs: [60]JobSpec = undefined; + var demand_store: [60][n_res * n_ticks]Elem = undefined; + var t: i64 = 0; + for (&specs, 0..) |*s, i| { + t += rnd.intRangeAtMost(i64, 0, 2); + const dur = rnd.intRangeAtMost(u16, 1, n_ticks); + for (0..n_res * dur) |k| demand_store[i][k] = rnd.intRangeAtMost(Elem, 0, 7); + s.* = .{ .arrival = t, .dur = dur, .demand = demand_store[i][0 .. n_res * dur] }; + } + + var sim = Sim{ .script = .{ .caps = &caps, .n_res = n_res, .jobs = &specs } }; + try sim.start(.{ .n_res = n_res, .n_ticks = n_ticks, .max_jobs = 32, .skip_empty = false, .drop_impossible = false }); + defer sim.deinit(); + var ref = Reference{}; + defer ref.deinit(); + + var expected_reward: f64 = 0; + var steps: usize = 0; + while (!sim.eng.done()) : (steps += 1) { + try testing.expect(steps < 100_000); + const now = sim.eng.now; + + // 1. free capacity equals the reference everywhere in the horizon + for (0..2) |m| for (0..n_res) |r| { + const row = sim.free(m, r); + for (0..n_ticks) |k| try testing.expectEqual(ref.free(&caps, n_res, m, r, now, k), @as(i64, row[k])); + }; + + // 2. legality equals the reference for every (slot, machine) + const st = sim.eng.state(); + var it = sim.eng.jobs.iter(); + var options: [64]Action = undefined; + var n_opt: usize = 0; + while (it.next()) |s| { + var first: ?usize = null; + for (0..2) |m| { + const spec = specs[sim.eng.jobs.id[s]]; + const ok = ref.fits(&caps, n_res, n_ticks, m, spec, now); + try testing.expectEqual(ok, rules.fitsNow(&st, s, m)); + if (ok) { + if (first == null) first = m; + options[n_opt] = .{ .place = .{ .slot = @intCast(s), .machine = @intCast(m) } }; + n_opt += 1; + } + } + // the per-tick "fits nowhere" memo never hides a fit + try testing.expectEqual(first, rules.firstMachine(&st, s)); + try testing.expectEqual(first == null, sim.eng.jobs.isBlocked(s)); + } + + // 3. random policy: mostly legal placements, sometimes wait / illegal + const roll = rnd.uintLessThan(u32, 10); + const act: Action = if (n_opt > 0 and roll < 7) + options[rnd.uintLessThan(usize, n_opt)] + else if (roll == 9) + .{ .place = .{ .slot = rnd.uintLessThan(u32, 32), .machine = rnd.uintLessThan(u32, 3) } } + else + .wait; + + const legal = rules.isLegal(&st, act); + const waiting = sim.eng.jobs.count; + if (legal and act == .place) { + const p = act.place; + try ref.running.append(testing.allocator, .{ .machine = p.machine, .start = now, .spec = specs[sim.eng.jobs.id[p.slot]] }); + } else { + expected_reward += -@as(f64, @floatFromInt(waiting + ref.runningAt(now))); + if (!legal) expected_reward += -1.0; + } + const res = try sim.eng.step(act); + try testing.expectEqual(!legal, res.illegal); + } + + // 4. episode-level results + const s = sim.eng.stats; + try testing.expectEqual(@as(usize, 60), s.arrived); + try testing.expectEqual(@as(usize, 60), s.placed); + try testing.expectApproxEqAbs(expected_reward, s.total_reward, 1e-6); + var makespan: i64 = 0; + for (ref.running.items) |run| makespan = @max(makespan, run.start + run.spec.dur); + try testing.expectEqual(makespan, s.makespan); + try testing.expect(sim.eng.machines.allIdle()); + _ = episode; + } +} + +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| { + for (0..4) |seed| { + var arr = A.arrivals.Poisson{ .total = 400, .rate = 4 }; + var gen = A.generators.RandomProfiles{ .n_machines = 6, .varying = true }; + var eng = try sched.Engine.init(testing.allocator, .{ .n_res = 3, .n_ticks = 30, .max_jobs = 48 }, .init(&arr), .init(&gen)); + defer eng.deinit(); + try eng.reset(seed); + var cached = P{ .cache = .{ .alloc = testing.allocator } }; + defer cached.deinit(); + var steps: usize = 0; + while (!eng.finished and steps < 20_000) : (steps += 1) { + const st = eng.state(); + var fresh = P{ .cache = .{ .alloc = testing.allocator } }; + defer fresh.deinit(); + const want = fresh.decide(&st); + const got = cached.decide(&st); + try testing.expectEqual(want, got); + _ = try eng.step(got); + } + } + } +}