Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
12 changes: 11 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,14 @@ zig-out/
/debug/
/build/
/build-*/
/docgen_tmp/
/docgen_tmp/
# Python
__pycache__/
*.pyc
.venv/
.pytest_cache/

# generated outputs
python/out/
*.zip
bench/compare.png
31 changes: 31 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -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.
Empty file removed bench/.gitkeep
Empty file.
130 changes: 130 additions & 0 deletions bench/compare.py
Original file line number Diff line number Diff line change
@@ -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 | <each Python backend> µ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()
47 changes: 47 additions & 0 deletions bench/engine_bench.zig
Original file line number Diff line number Diff line change
@@ -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(),
});
}
}
Loading
Loading