capstan-rl 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
capstan/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ import json
2
+ import os
3
+ import time
4
+ from contextlib import contextmanager
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ __all__ = ["phase", "record_logprobs", "record_phase"]
10
+
11
+
12
+ def _out() -> Path:
13
+ path = Path(os.environ.get("CAPSTAN_OUT", "capstan_run"))
14
+ path.mkdir(parents=True, exist_ok=True)
15
+ return path
16
+
17
+
18
+ def _numpy(x):
19
+ if hasattr(x, "detach"):
20
+ x = x.detach().float().cpu()
21
+ return np.asarray(x, dtype=np.float64)
22
+
23
+
24
+ # One file per process: Ray workers and engine subprocesses write concurrently, and appends to one file can interleave.
25
+ def record_phase(name, seconds, step=None):
26
+ row = {"step": step, "phase": name, "seconds": float(seconds), "end": time.time()}
27
+ with open(_out() / f"phases_{os.getpid()}.jsonl", "a") as f:
28
+ f.write(json.dumps(row) + "\n")
29
+
30
+
31
+ # Wall-clock time: the block must end on a sync point (e.g. results copied to CPU), or GPU work leaks into the next one.
32
+ @contextmanager
33
+ def phase(name, step=None):
34
+ start = time.perf_counter()
35
+ try:
36
+ yield
37
+ finally:
38
+ record_phase(name, time.perf_counter() - start, step)
39
+
40
+
41
+ def record_logprobs(rollout, trainer, step, timesteps=None):
42
+ arrays = {"rollout": _numpy(rollout), "trainer": _numpy(trainer)}
43
+ if timesteps is not None:
44
+ arrays["timesteps"] = _numpy(timesteps)
45
+ np.savez(_out() / f"logprobs_step{step:06d}_pid{os.getpid()}.npz", **arrays)
@@ -0,0 +1,42 @@
1
+ import importlib.abc
2
+ import importlib.util
3
+ import sys
4
+
5
+ _WRAPPED = "_capstan_wrapped"
6
+
7
+
8
+ def wrap(owner, name, make):
9
+ original = getattr(owner, name)
10
+ if getattr(original, _WRAPPED, False):
11
+ return
12
+ wrapper = make(original)
13
+ setattr(wrapper, _WRAPPED, True)
14
+ setattr(owner, name, wrapper)
15
+
16
+
17
+ # Patch a module once something else imports it, so a hook never imports a framework into a process that would not.
18
+ def when_imported(name, patch):
19
+ if name in sys.modules:
20
+ patch(sys.modules[name])
21
+ else:
22
+ sys.meta_path.insert(0, _PatchOnImport(name, patch))
23
+
24
+
25
+ class _PatchOnImport(importlib.abc.MetaPathFinder):
26
+ def __init__(self, name, patch):
27
+ self.name = name
28
+ self.patch = patch
29
+
30
+ def find_spec(self, fullname, path, target=None):
31
+ if fullname != self.name:
32
+ return None
33
+ sys.meta_path.remove(self)
34
+ spec = importlib.util.find_spec(fullname)
35
+ exec_module = spec.loader.exec_module
36
+
37
+ def exec_and_patch(module):
38
+ exec_module(module)
39
+ self.patch(module)
40
+
41
+ spec.loader.exec_module = exec_and_patch
42
+ return spec
@@ -0,0 +1,81 @@
1
+ import json
2
+ import os
3
+ import runpy
4
+ import sys
5
+
6
+ import capstan
7
+ from capstan.adapters import when_imported, wrap
8
+
9
+ TRAINER_MODULE = "verl_omni.trainer.main_diffusion"
10
+
11
+ PHASES = {
12
+ "timing_s/step": "step",
13
+ "timing_s/gen": "rollout",
14
+ "timing_s/reward": "reward",
15
+ "timing_s/old_log_prob": "recompute",
16
+ "timing_s/update_actor": "update",
17
+ "timing_s/update_weights": "sync",
18
+ }
19
+
20
+ # The drift hook runs before verl-omni logs the step, so log-probs wait here until Tracking.log gives the step number.
21
+ _pending = []
22
+
23
+
24
+ def _log(original):
25
+ def log(self, data, step, *args, **kwargs):
26
+ for arrays in _pending:
27
+ capstan.record_logprobs(step=step, **arrays)
28
+ _pending.clear()
29
+ for key, phase in PHASES.items():
30
+ if key in data:
31
+ capstan.record_phase(phase, data[key], step)
32
+ # Everything verl-omni logs, kept to cross-check against its own rollout_corr/* drift metrics.
33
+ with open(capstan._out() / "verl_omni_metrics.jsonl", "a") as f:
34
+ f.write(json.dumps({"step": step, **data}, default=float) + "\n")
35
+ return original(self, data, step, *args, **kwargs)
36
+
37
+ return log
38
+
39
+
40
+ # Called once per training step with the trainer recompute and the rollout log-probs of the same batch.
41
+ def _corr_metrics(original):
42
+ def compute(log_prob, rollout_log_prob, timesteps=None):
43
+ arrays = {"rollout": capstan._numpy(rollout_log_prob), "trainer": capstan._numpy(log_prob)}
44
+ if timesteps is not None:
45
+ arrays["timesteps"] = capstan._numpy(timesteps)
46
+ _pending.append(arrays)
47
+ return original(log_prob, rollout_log_prob, timesteps=timesteps)
48
+
49
+ return compute
50
+
51
+
52
+ def install():
53
+ if not os.environ.get("CAPSTAN_OUT"):
54
+ return
55
+ when_imported("verl.utils.tracking", lambda m: wrap(m.Tracking, "log", _log))
56
+ when_imported(
57
+ "verl_omni.trainer.diffusion.rollout_correction",
58
+ lambda m: wrap(m, "compute_rollout_corr_metrics_from_logprobs", _corr_metrics),
59
+ )
60
+
61
+
62
+ def _ray_init(original):
63
+ # The trainer and its workers are Ray actors in other processes, so install() must run there too.
64
+ def init(*args, **kwargs):
65
+ runtime_env = dict(kwargs.get("runtime_env") or {})
66
+ env_vars = dict(runtime_env.get("env_vars") or {})
67
+ runtime_env["env_vars"] = {**env_vars, "CAPSTAN_OUT": os.environ["CAPSTAN_OUT"]}
68
+ runtime_env["worker_process_setup_hook"] = "capstan.adapters.verl_omni.install"
69
+ kwargs["runtime_env"] = runtime_env
70
+ return original(*args, **kwargs)
71
+
72
+ return init
73
+
74
+
75
+ def run(overrides):
76
+ import ray
77
+
78
+ install()
79
+ wrap(ray, "init", _ray_init)
80
+ sys.argv = [TRAINER_MODULE, *overrides]
81
+ runpy.run_module(TRAINER_MODULE, run_name="__main__", alter_sys=True)
@@ -0,0 +1,141 @@
1
+ import logging
2
+ import os
3
+
4
+ import capstan
5
+ from capstan.adapters import when_imported, wrap
6
+
7
+ logger = logging.getLogger("capstan")
8
+
9
+ # The one name Capstan relies on: the pipeline verl-omni exports from this package (its __all__). Subclasses such as
10
+ # the MixGRPO pipeline call into it. The scheduler is found on the pipeline instance, not by import path.
11
+ PIPELINE_PACKAGE = "verl_omni.pipelines.qwen_image_flow_grpo"
12
+ PIPELINE_CLASS = "QwenImagePipelineWithLogProb"
13
+ TESTED_WITH = "verl-omni 81f3b65"
14
+
15
+ # (label, CUDA event) pairs for the request this process is generating; None outside a request.
16
+ _marks = None
17
+
18
+
19
+ def _mark(label):
20
+ import torch
21
+
22
+ event = torch.cuda.Event(enable_timing=True)
23
+ event.record()
24
+ _marks.append((label, event))
25
+
26
+
27
+ def _record(marks):
28
+ labels = [label for label, _ in marks]
29
+ if "diffuse_start" not in labels or "diffuse_end" not in labels:
30
+ return
31
+ marks[-1][1].synchronize()
32
+ first, last = labels.index("diffuse_start"), labels.index("diffuse_end")
33
+ events = [event for _, event in marks]
34
+ capstan.record_phase("rollout/encode", events[0].elapsed_time(events[first]) / 1000)
35
+ for before, (label, after) in zip(events[first : last - 1], marks[first + 1 : last], strict=True):
36
+ capstan.record_phase(f"rollout/{label}_step", before.elapsed_time(after) / 1000)
37
+ capstan.record_phase("rollout/decode", events[last].elapsed_time(events[-1]) / 1000)
38
+
39
+
40
+ def _forward(original):
41
+ def forward(self, *args, **kwargs):
42
+ global _marks
43
+ scheduler = getattr(self, "scheduler", None)
44
+ if scheduler is not None:
45
+ wrap(type(scheduler), "step", _step)
46
+ _marks = []
47
+ _mark("start")
48
+ try:
49
+ return original(self, *args, **kwargs)
50
+ finally:
51
+ _mark("end")
52
+ marks, _marks = _marks, None
53
+ _record(marks)
54
+
55
+ return forward
56
+
57
+
58
+ def _diffuse(original):
59
+ def diffuse(self, *args, **kwargs):
60
+ if _marks is not None:
61
+ _mark("diffuse_start")
62
+ result = original(self, *args, **kwargs)
63
+ if _marks is not None:
64
+ _mark("diffuse_end")
65
+ return result
66
+
67
+ return diffuse
68
+
69
+
70
+ # ODE and SDE steps run the same transformer forward; only the scheduler step adds noise and a log-prob.
71
+ def _step(original):
72
+ def step(self, *args, **kwargs):
73
+ result = original(self, *args, **kwargs)
74
+ if _marks is not None:
75
+ level = kwargs.get("noise_level", 0.0)
76
+ noisy = bool((level > 0).any()) if hasattr(level, "any") else level > 0
77
+ _mark("sde" if noisy else "ode")
78
+ return result
79
+
80
+ return step
81
+
82
+
83
+ # Step mode (step_execution=True) never calls forward: the engine calls these per request, and denoise_step once per
84
+ # batch. Events wait for post_decode, which copies to the CPU and so has already synchronised.
85
+ _pending = []
86
+
87
+
88
+ def _in_sde_window(state):
89
+ start, end = state.sde_window
90
+ return start <= state.step_index < end
91
+
92
+
93
+ def _timed(part):
94
+ def make(original):
95
+ def method(self, *args, **kwargs):
96
+ if _marks is not None:
97
+ return original(self, *args, **kwargs)
98
+ import torch
99
+
100
+ label = part
101
+ if part == "step":
102
+ states = kwargs.get("states") or ()
103
+ label = "sde_step" if any(_in_sde_window(s) for s in states) else "ode_step"
104
+ start = torch.cuda.Event(enable_timing=True)
105
+ end = torch.cuda.Event(enable_timing=True)
106
+ start.record()
107
+ result = original(self, *args, **kwargs)
108
+ end.record()
109
+ _pending.append((label, start, end))
110
+ if part == "decode":
111
+ end.synchronize()
112
+ for name, a, b in _pending:
113
+ capstan.record_phase(f"rollout/{name}", a.elapsed_time(b) / 1000)
114
+ _pending.clear()
115
+ return result
116
+
117
+ return method
118
+
119
+ return make
120
+
121
+
122
+ def _patch_pipeline(package):
123
+ pipeline = getattr(package, PIPELINE_CLASS, None)
124
+ if pipeline is None or not hasattr(pipeline, "diffuse"):
125
+ # A profiler must not break training: record nothing, say why, and let capstan report flag the gap.
126
+ message = "%s.%s.diffuse not found; rollout split not recorded (tested with %s)"
127
+ logger.warning(message, PIPELINE_PACKAGE, PIPELINE_CLASS, TESTED_WITH)
128
+ return
129
+ wrap(pipeline, "forward", _forward)
130
+ wrap(pipeline, "diffuse", _diffuse)
131
+ # The scheduler update between batched forwards is not timed in step mode; it is elementwise and small.
132
+ for name, part in [("prepare_encode", "encode"), ("denoise_step", "step"), ("post_decode", "decode")]:
133
+ if hasattr(pipeline, name):
134
+ wrap(pipeline, name, _timed(part))
135
+
136
+
137
+ # vLLM general plugin: vllm-omni loads it in every engine process, including the diffusion worker.
138
+ def register():
139
+ if not os.environ.get("CAPSTAN_OUT"):
140
+ return
141
+ when_imported(PIPELINE_PACKAGE, _patch_pipeline)
capstan/cli.py ADDED
@@ -0,0 +1,45 @@
1
+ import argparse
2
+ import os
3
+
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(prog="capstan")
7
+ commands = parser.add_subparsers(dest="command", required=True)
8
+ run = commands.add_parser("run", help="run a training job with capstan recording it")
9
+ run.add_argument("framework", choices=["verl-omni"])
10
+ run.add_argument("--out", required=True, help="directory for the recorded phases and log-probs")
11
+ report = commands.add_parser("report", help="write profile.md and drift.md from a recorded run")
12
+ report.add_argument("run_dir")
13
+ report.add_argument("--out", help="where to write the tables (default: the run directory)")
14
+ report.add_argument(
15
+ "--skip", type=int, default=2, help="warm-up training steps to leave out of the profile (default: 2)"
16
+ )
17
+ gate = commands.add_parser("gate", help="judge an optimised run against its paired baseline run")
18
+ gate.add_argument("before")
19
+ gate.add_argument("after")
20
+ args, overrides = parser.parse_known_args()
21
+
22
+ if args.command == "gate":
23
+ if overrides:
24
+ parser.error(f"unrecognized arguments: {' '.join(overrides)}")
25
+ from capstan import report as reporting
26
+
27
+ print(reporting.gate(args.before, args.after), end="")
28
+ return
29
+
30
+ if args.command == "report":
31
+ if overrides:
32
+ parser.error(f"unrecognized arguments: {' '.join(overrides)}")
33
+ from capstan import report as reporting
34
+
35
+ reporting.write(args.run_dir, args.out or args.run_dir, args.skip)
36
+ return
37
+
38
+ os.environ["CAPSTAN_OUT"] = os.path.abspath(args.out)
39
+ from capstan.adapters import verl_omni
40
+
41
+ verl_omni.run(overrides)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
capstan/drift.py ADDED
@@ -0,0 +1,43 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+ # Fixed before the first real run. 1e-4 is the recipe's own PPO clip window (verl-omni diffusion_loss.clip_ratio):
6
+ # drift that large moves the ratio as far as one policy update is allowed to.
7
+ RATIO_TOL = 1e-4
8
+ MAX_OVER_FRACTION = 0.01
9
+ # Fixed on Nov 29, 2026 (after the batching and eager runs, checked against them afterwards): the stock recipe already
10
+ # fails RATIO_TOL (two different bf16 transformers, see bench/consistency.md), so an optimisation is also judged
11
+ # against its paired baseline.
12
+ GATE_P = 0.05
13
+
14
+
15
+ def drift_stats(rollout_lp, trainer_lp, ratio_tol=RATIO_TOL):
16
+ rollout_lp = np.asarray(rollout_lp, dtype=np.float64)
17
+ trainer_lp = np.asarray(trainer_lp, dtype=np.float64)
18
+ if rollout_lp.shape != trainer_lp.shape:
19
+ raise ValueError(f"shape mismatch: rollout {rollout_lp.shape}, trainer {trainer_lp.shape}")
20
+ # Inputs are verl-omni log-probs, already a mean over the latent, so d is per-element drift.
21
+ d = trainer_lp - rollout_lp
22
+ ratio = np.exp(d)
23
+ over = (np.abs(ratio - 1) > ratio_tol).sum()
24
+ return {
25
+ "mean_abs": float(np.abs(d).mean()),
26
+ "max_abs": float(np.abs(d).max()),
27
+ "ratio_p50": float(np.percentile(ratio, 50)),
28
+ "ratio_p99": float(np.percentile(ratio, 99)),
29
+ "over_tol": int(over),
30
+ "n": int(d.size),
31
+ "passed": bool(over <= MAX_OVER_FRACTION * d.size),
32
+ }
33
+
34
+
35
+ # One-sided two-proportion z-test: fails only if `after` has significantly more entries over RATIO_TOL than `before`.
36
+ # Caveat: treats entries as independent; samples share prompts, so p is somewhat optimistic.
37
+ def not_worse(before, after, p=GATE_P):
38
+ b, a = before["over_tol"] / before["n"], after["over_tol"] / after["n"]
39
+ pooled = (before["over_tol"] + after["over_tol"]) / (before["n"] + after["n"])
40
+ se = math.sqrt(pooled * (1 - pooled) * (1 / before["n"] + 1 / after["n"]))
41
+ z = (a - b) / se if se else 0.0
42
+ pvalue = 0.5 * math.erfc(z / math.sqrt(2))
43
+ return {"z": z, "p": pvalue, "passed": pvalue >= p}
capstan/report.py ADDED
@@ -0,0 +1,139 @@
1
+ import json
2
+ import re
3
+ from collections import defaultdict
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ from capstan.drift import GATE_P, MAX_OVER_FRACTION, RATIO_TOL, drift_stats, not_worse
9
+
10
+ TRAINER_PHASES = ["rollout", "reward", "recompute", "update", "sync"]
11
+ ROLLOUT_PARTS = {
12
+ "encode": "Text encode",
13
+ "ode_step": "ODE steps",
14
+ "sde_step": "SDE-window steps",
15
+ "decode": "VAE decode",
16
+ }
17
+
18
+
19
+ def _table(header, rows):
20
+ lines = ["| " + " | ".join(header) + " |", "|" + " --- |" * len(header)]
21
+ return "\n".join(lines + ["| " + " | ".join(str(c) for c in row) + " |" for row in rows])
22
+
23
+
24
+ def profile(run, skip):
25
+ rows = [json.loads(line) for f in sorted(run.glob("phases_*.jsonl")) for line in f.read_text().splitlines()]
26
+ steps = {r["step"]: r for r in rows if r["phase"] == "step" and r["step"] > skip}
27
+ if not steps:
28
+ raise SystemExit(f"no steps after skipping {skip} in {run}")
29
+ n = len(steps)
30
+ total = sum(r["seconds"] for r in steps.values()) / n
31
+ per_step = {
32
+ p: sum(r["seconds"] for r in rows if r["phase"] == p and r["step"] in steps) / n for p in TRAINER_PHASES
33
+ }
34
+ per_step["everything else, idle included"] = total - sum(per_step.values())
35
+ trainer_rows = [[p, f"{s:.2f}", f"{s / total:.1%}"] for p, s in per_step.items()]
36
+ trainer_rows.append(["step", f"{total:.2f}", "100%"])
37
+
38
+ # Rollout workers do not know the training step, so their records go to the step whose time window holds them.
39
+ windows = [(r["end"] - r["seconds"], r["end"]) for r in steps.values()]
40
+ parts = defaultdict(list)
41
+ for r in rows:
42
+ name = r["phase"].removeprefix("rollout/")
43
+ if name in ROLLOUT_PARTS and any(start <= r["end"] <= end for start, end in windows):
44
+ parts[name].append(r["seconds"])
45
+ worker_total = sum(sum(v) for v in parts.values())
46
+ part_rows = [
47
+ [label, f"{sum(parts[k]) / n:.2f}", f"{sum(parts[k]) / worker_total:.1%}", len(parts[k]) // n]
48
+ for k, label in ROLLOUT_PARTS.items()
49
+ if parts[k]
50
+ ]
51
+
52
+ out = [f"# Profile\n\nMean over {n} training step{'s' if n != 1 else ''}, skipping the first {skip} as warm-up.\n"]
53
+ out.append(_table(["Phase", "Time per step (s)", "Share of step"], trainer_rows))
54
+ out.append("\n## Inside rollout\n")
55
+ if part_rows:
56
+ out.append("GPU time summed over rollout workers, per training step.\n")
57
+ out.append(_table(["Part", "GPU seconds per step", "Share of rollout GPU time", "Calls per step"], part_rows))
58
+ else:
59
+ out.append(
60
+ "Not recorded. The split needs the vLLM plugin to find verl-omni's pipeline; check the rollout logs."
61
+ )
62
+ return "\n".join(out) + "\n"
63
+
64
+
65
+ def _logprobs(run):
66
+ by_step = defaultdict(list)
67
+ for f in Path(run).glob("logprobs_step*_pid*.npz"):
68
+ by_step[int(re.search(r"step(\d+)", f.name)[1])].append(np.load(f))
69
+ if not by_step:
70
+ raise SystemExit(f"no log-prob files in {run}")
71
+ return by_step
72
+
73
+
74
+ def _stats(arrays):
75
+ return drift_stats(np.concatenate([a["rollout"] for a in arrays]), np.concatenate([a["trainer"] for a in arrays]))
76
+
77
+
78
+ def gate(before, after):
79
+ b, a = (_stats([x for xs in _logprobs(run).values() for x in xs]) for run in (before, after))
80
+ g = not_worse(b, a)
81
+ verdict = "passed" if g["passed"] else "failed"
82
+ return (
83
+ f"Baseline gate, fixed on Nov 29, 2026: the optimised run fails only if it has significantly more "
84
+ f"entries over {RATIO_TOL:g} than its paired baseline (one-sided two-proportion z-test, p < {GATE_P:g}). "
85
+ f"This run {verdict}: {b['over_tol']} of {b['n']} → {a['over_tol']} of {a['n']} over, "
86
+ f"z = {g['z']:.2f}, p = {g['p']:.3g}.\n"
87
+ )
88
+
89
+
90
+ def drift(run):
91
+ by_step = _logprobs(run)
92
+
93
+ def row(label, s):
94
+ ratios = f"{s['ratio_p50']:.6f}", f"{s['ratio_p99']:.6f}"
95
+ return [label, s["n"], f"{s['mean_abs']:.3g}", f"{s['max_abs']:.3g}", *ratios, s["over_tol"]]
96
+
97
+ rows = [row(step, _stats(by_step[step])) for step in sorted(by_step)]
98
+ overall = _stats([a for arrays in by_step.values() for a in arrays])
99
+ rows.append(row("all", overall))
100
+ verdict = "passed" if overall["passed"] else "failed"
101
+ out = [
102
+ "# Drift\n",
103
+ f"Threshold, fixed before the first real run: |ratio − 1| ≤ {RATIO_TOL:g} for at least "
104
+ f"{1 - MAX_OVER_FRACTION:.0%} of (sample, SDE step) entries. This run {verdict}: "
105
+ f"{overall['over_tol']} of {overall['n']} entries over.\n",
106
+ _table(
107
+ ["Step", "Entries", "Mean abs drift", "Max abs drift", "Ratio p50", "Ratio p99", "Over threshold"], rows
108
+ ),
109
+ ]
110
+ arrays = [a for step in sorted(by_step) for a in by_step[step]]
111
+ if all("timesteps" in a for a in arrays):
112
+ out.append("\n## By SDE timestep\n")
113
+ out.append("Entries split by the SDE timestep they were sampled at; signed mean is trainer minus rollout.\n")
114
+ out.append(
115
+ _table(
116
+ ["Timestep", "Entries", "Mean drift (signed)", "Max abs drift", "Over threshold"], _by_timestep(arrays)
117
+ )
118
+ )
119
+ return "\n".join(out) + "\n"
120
+
121
+
122
+ def _by_timestep(arrays):
123
+ rollout = np.concatenate([a["rollout"] for a in arrays]).ravel()
124
+ trainer = np.concatenate([a["trainer"] for a in arrays]).ravel()
125
+ timesteps = np.round(np.concatenate([a["timesteps"] for a in arrays]).ravel().astype(np.float64), 2)
126
+ rows = []
127
+ for t in sorted(set(timesteps.tolist()), reverse=True):
128
+ mask = timesteps == t
129
+ s = drift_stats(rollout[mask], trainer[mask])
130
+ signed = float(np.mean(trainer[mask].astype(np.float64) - rollout[mask]))
131
+ rows.append([f"{t:g}", s["n"], f"{signed:.2g}", f"{s['max_abs']:.3g}", s["over_tol"]])
132
+ return rows
133
+
134
+
135
+ def write(run, out, skip):
136
+ run, out = Path(run), Path(out)
137
+ out.mkdir(parents=True, exist_ok=True)
138
+ (out / "profile.md").write_text(profile(run, skip))
139
+ (out / "drift.md").write_text(drift(run))
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.5
2
+ Name: capstan-rl
3
+ Version: 0.1.0
4
+ Summary: Measure, verify, and speed up the rollout step of RL post-training for flow and diffusion models.
5
+ Project-URL: Repository, https://github.com/Vishal-Padia/capstan
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: numpy
10
+ Description-Content-Type: text/markdown
11
+
12
+ # capstan
13
+
14
+ Measure, verify, and speed up the rollout step of RL post-training for flow and diffusion models.
15
+
16
+ RL post-training for diffusion models spends most of its GPU time sampling trajectories (10–50 denoising steps per sample, doubled with CFG). Speeding up rollout is only safe if the sampler and trainer still compute the same per-step log-probabilities—otherwise training silently goes off-policy. Capstan sits on top of the RL framework you already run, profiles where step time goes, checks rollout-vs-trainer log-prob drift, and gates rollout optimisations on both.
17
+
18
+ ## Results
19
+
20
+ Proof of concept on **Qwen-Image OCR LoRA** with **MixGRPO** (10 denoising steps, 2-step random SDE window, `true_cfg_scale=4.0`), `verl-omni` `81f3b65`, 5-step runs on Modal H100s (timings averaged over steps 3–5):
21
+
22
+ | Check | Result | Hardware & setup | Details |
23
+ | --- | --- | --- | --- |
24
+ | Baseline profile | Rollout is **58.2%** of a 758 s step (update 19.6%, reward 14.3%, recompute 4.8%, sync 3.1%). Transformer forwards are **97.4%** of rollout GPU time. | 4x H100 80 GB, request mode | [bench/profile.md](bench/profile.md) |
25
+ | Baseline drift | **Fails** the 1% bar: **7.2%** of entries (370 / 5120) have \|ratio − 1\| > 1e-4, reaching 44% at `t = 673`. | Same run | [bench/drift.md](bench/drift.md) |
26
+ | Batched rollout | Rollout 294.7 → 104.3 s (**2.83x**); full step 533.0 → 345.2 s (**1.54x**). Drift unchanged (321 → 304 / 5120 over; baseline gate passes, `p = 0.76`). | 4x H100 80 GB HBM3, request vs step mode (`max_num_seqs=16`), same host | [bench/before_after.md](bench/before_after.md) |
27
+ | No `torch.compile` in rollout | No speed cost (rollout 104.7 → 102.8 s; step 363.5 → 358.3 s). **3.2x fewer** drift failures (6.6% → 2.05%, 340 → 105 / 5120; baseline gate passes, still fails 1% bar). | 4x H100 80 GB HBM3, step mode with `enforce_eager=True`, same host | [bench/before_after.md](bench/before_after.md) |
28
+ | Root cause of baseline drift | Reproduces at step 0 on 1 GPU. No single bad kernel: `diffusers` vs itself (unpadded vs padded prompt) diverges as much as vs `vllm-omni` (`1.8e-2` vs `2.1e-2` after CFG) across 60 `bf16` blocks. | 1x H100 80 GB HBM3 | [bench/consistency.md](bench/consistency.md) |
29
+ | Batch invariance | Max per-element sampler drift between batch 1 and 16: **1.19e-07** (one `fp32` ULP). | 1x H100 80 GB, step mode | [bench/drift.md](bench/drift.md#batch-invariance) |
30
+
31
+ **Recommended rollout config:** `step_execution=True`, `max_num_seqs=16`, `enforce_eager=True`.
32
+
33
+ Notes on reading the numbers:
34
+ - **Per-element drift:** `verl-omni`'s per-step log-prob is already a mean over latent elements. Drift is `trainer - rollout` per `(sample, SDE step)`, and the importance ratio is `exp(trainer - rollout)` (trainer in the numerator).
35
+ - **Host variance:** Two Modal 4x H100 hosts ran the identical request-mode recipe at 758 s/step vs 533 s/step. Every before/after comparison runs both halves in one container on one host.
36
+ - **Weight sync:** Sync is ~3–4% here because this is a LoRA run, not full-parameter training.
37
+
38
+ ## What it does
39
+
40
+ - **Profiler (`capstan run`, `capstan report`):** Hooks `verl-omni` timers and `vllm-omni`'s diffusion pipeline (via a `vllm.general_plugins` entry point, no fork) to split each training step into rollout, reward, recompute, update, sync, and idle—and splits rollout GPU time into text encode, ODE steps, SDE-window steps, and VAE decode.
41
+ - **Numerics check (`capstan report`, `capstan gate`):** Records rollout and trainer log-probs per step plus batch invariance across batch sizes.
42
+ - **Absolute threshold** (fixed before the first real run): `|ratio − 1| ≤ 1e-4` for at least 99% of `(sample, SDE step)` entries. `1e-4` is the recipe's own PPO clip window (`diffusion_loss.clip_ratio`).
43
+ - **Baseline gate** (fixed Nov 29, 2026, after the batching and eager runs and checked against them afterwards): because the stock recipe already fails the absolute bar, `capstan gate <before> <after>` fails an optimisation if it produces significantly more entries over `1e-4` than its paired same-host baseline (one-sided two-proportion z-test, `p < 0.05`).
44
+ - **Optimisations:** Driven by the profile, measured in paired same-host runs, and gated by the drift check.
45
+
46
+ ## Quickstart
47
+
48
+ ### Run locally
49
+
50
+ 1. Install `verl-omni` at commit `81f3b65` following its [install guide](https://github.com/verl-project/verl-omni/blob/main/docs/start/install.md), add `uv pip install -e ".[ocr]"`, and build the OCR dataset into `$WORKSPACE/data/ocr/qwen_image/` with its `examples/flowgrpo_trainer/data_process/qwenimage_ocr.py`.
51
+ 2. Clone Capstan and install it into the same active Python ≥ 3.11 venv:
52
+
53
+ ```bash
54
+ git clone https://github.com/Vishal-Padia/capstan
55
+ uv pip install -e capstan
56
+ ```
57
+
58
+ (For the CLI alone, `uv pip install capstan-rl` or `uv pip install git+https://github.com/Vishal-Padia/capstan` works once published.)
59
+
60
+ 3. From the `verl-omni` repo root, run MixGRPO through Capstan. [`bench/run_mixgrpo.sh`](bench/run_mixgrpo.sh) is `verl-omni`'s `run_qwen_image_ocr_lora_mixgrpo.sh` wrapped with `capstan run`, `calculate_log_probs=True`, and no checkpoints/validation/W&B:
61
+
62
+ ```bash
63
+ STEPS=5 bash /path/to/capstan/bench/run_mixgrpo.sh
64
+ ```
65
+
66
+ Recordings are written to `runs/mixgrpo/` (`phases_<pid>.jsonl` per process, `logprobs_step<step>_pid<pid>.npz` per step).
67
+
68
+ 4. Generate tables or gate a paired before/after run:
69
+
70
+ ```bash
71
+ capstan report runs/mixgrpo # writes profile.md and drift.md (--skip 2 default, --out DIR)
72
+ capstan gate runs/before runs/after # baseline z-test gate
73
+ ```
74
+
75
+ ### Run on Modal
76
+
77
+ [`bench/modal_app.py`](bench/modal_app.py) builds the exact `verl-omni` `81f3b65` + `vllm 0.33` image and stores models, data, and runs on a Modal volume (`capstan-models`). Both models are public; no Hugging Face token is needed. Requires `pip install modal && modal setup`.
78
+
79
+ ```bash
80
+ modal run bench/modal_app.py::stage # download models + build OCR dataset (run once first)
81
+ modal run bench/modal_app.py::run --job dry # tiny random-weight check on 1x A10G/A10 (~8 min)
82
+ modal run bench/modal_app.py::run --job batch-invariance # 1x H100, batch 1 vs 16
83
+ modal run bench/modal_app.py::run --job mixgrpo --name baseline # 4x H100 stock recipe
84
+ modal run bench/modal_app.py::run --job mixgrpo-pair --name paired # 4x H100 request vs step mode, same host
85
+ modal run bench/modal_app.py::run --job eager-pair --name eager # 4x H100 compile on vs off, same host
86
+ ```
87
+
88
+ - Every job saves `host.txt`, logs, timings, log-probs, and reports to the volume and downloads them to `logs/<name>/`.
89
+ - `stage` must be run once before any other job (including `dry`, which reads the OCR dataset).
90
+ - `dry` generates reports with `--skip 0`; to regenerate locally, pass `--skip 0 --out <dir>`.
91
+ - `--step-mode` on `dry` and `mixgrpo` enables `step_execution=True, max_num_seqs=16`.
92
+ - For long 4x H100 jobs on a flaky connection, `modal deploy bench/modal_app.py`, spawn via `modal.Function.from_name("capstan", "mixgrpo_pair").spawn(name, 5, "eager")`, and download later with `modal run bench/modal_app.py::fetch --name <name>`.
93
+
94
+ ## Status, limitations, and roadmap
95
+
96
+ **Tested:** Qwen-Image OCR LoRA MixGRPO on 4x H100 (Modal, `verl-omni` `81f3b65`, 5 steps), 1x H100 for batch invariance / consistency / per-block hooks, and tiny random-weight models on 1x A10/A10G.
97
+
98
+ **Untested:** Other models, frameworks, or GPUs; full-parameter training; multi-node; runs longer than 5 steps; held-out reward evaluation. The two optimisations are each measured on one host pair and may not transfer to other recipes or hardware. The run steps have only been verified end-to-end by the author (and a fresh-environment check of the Modal `dry` job).
99
+
100
+ **Roadmap (not built yet):**
101
+ - Generalize beyond `QwenImagePipelineWithLogProb` to other diffusion/flow image and video DiTs
102
+ - FP8 (and experimental FP4) rollout paths gated by the same numerics check
103
+ - Streaming audio / TTS and state-space models
104
+ - Dedicated rollout kernels, engine, and weight-sync path
105
+ - Adapters for `verl`, `prime-rl`, `SkyRL`, and `TRL`
106
+
107
+ **Non-goals:** Not a new RL algorithm, not a replacement for existing RL frameworks, and not an autoregressive text-LLM inference server (vLLM and SGLang already cover that).
108
+
109
+ ## Credits
110
+
111
+ A huge thank you to [Modal](https://modal.com) for giving us a generous amount of credits to experiment and build Capstan.
112
+
113
+ Built on [verl-omni](https://github.com/verl-project/verl-omni) and [vllm-omni](https://github.com/vllm-project/vllm-omni). Algorithms: [Flow-GRPO](https://arxiv.org/abs/2505.05470) and [MixGRPO](https://arxiv.org/abs/2507.21802). The batch-invariance check and direct rollout-vs-trainer log-prob drift reporting borrow from the vLLM team's train–inference consistency work ([Nov 2025](https://vllm.ai/blog/2025-11-10-bitwise-consistent-train-inference), [Oct 2026](https://vllm.ai/blog/2026-10-14-train-inference-consistency)); their work makes the two bitwise identical, while Capstan measures and gates the gap.
114
+
115
+ ## License
116
+
117
+ [Apache 2.0](LICENSE)
@@ -0,0 +1,12 @@
1
+ capstan/__init__.py,sha256=AClnyAi53QsG7FrCGv2x2WcghgJSnaC66P2NRaRjjfk,1390
2
+ capstan/cli.py,sha256=CyjVDecTeg1CZeJ6hipFXC3IgfyKrq1LI8fS7xJMGb8,1693
3
+ capstan/drift.py,sha256=J93dfop8gwMBFTOGeg83rHQXS-wZbYTD2XhbAN_AX-k,2032
4
+ capstan/report.py,sha256=iAlNK6_RpdZ-LkgREqg1Ux5lxDCbGq5wk7C6D80RSrg,5946
5
+ capstan/adapters/__init__.py,sha256=S9v0AX_eKIljjDciHMjKa-C_Nm29tpvQ_DtAhLhZem4,1149
6
+ capstan/adapters/verl_omni.py,sha256=gO1RS6dnuIcHKXGLbNi4nGKldwHnF7lwi8HdQdZfOrA,2772
7
+ capstan/adapters/vllm_omni.py,sha256=--NF3w-ikWhwHIzwwf9z2sJdnTpYxscQbrUC7xIq9YY,4973
8
+ capstan_rl-0.1.0.dist-info/METADATA,sha256=SQsEbieu0-NWwgYZeumRxOMkJBbklfpTQu1DPM2NoJo,9488
9
+ capstan_rl-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ capstan_rl-0.1.0.dist-info/entry_points.txt,sha256=6tSAq_ohnwwSGgSFplXX0Cu_vowbxGHhX53fXwy0188,115
11
+ capstan_rl-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ capstan_rl-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ capstan = capstan.cli:main
3
+
4
+ [vllm.general_plugins]
5
+ capstan = capstan.adapters.vllm_omni:register
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.