inference-kernels / scripts /run_modal_capture.py
ubospica's picture
Publish complete Inference Kernels dataset
65e1c10
Raw History Blame
18.7 kB
"""Run the capture on an isolated Modal GPU and retrieve every dumped tensor."""
import argparse
import concurrent.futures
import fcntl
import hashlib
import io
import json
from pathlib import Path
import shutil
import tarfile
import threading
import time
from types import SimpleNamespace
import modal
ROOT = Path(__file__).resolve().parents[1]
MODELS = {
"image": ("Qwen/Qwen-Image-2.1-Turbo", "fc13ba1986fcb905854dc8de2f52eee395f49b5b", "qwen-image21"),
"qwen-next": ("nvidia/Qwen3.8-Flash-Next-NVFP4", "fc694b54fb0174e0913e6adf86691ef85a4ead47", "qwen-next-nvfp4"),
"deepseek41": ("deepseek-ai/DeepSeek-V4.1-Flash", "5254448103b6254fc646dacbca1cbbf20e9216c1", "deepseek41"),
"ltx25": ("pinecoresystems/LTX-2.5-serving", "93deb76408feee57d04b3cfeed3ded56a7a068ee", "ltx-2.5-sglang"),
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--name", required=True)
parser.add_argument("--kind", choices=list(MODELS), default="image")
parser.add_argument("--volume", default="inference-kernels-capture-20261014")
parser.add_argument("--image", default="im-vgNLOxfbAM8S5H1zofJQON")
parser.add_argument("--model-path")
parser.add_argument("--reference-image", help="Conditioning image path on the worker volume.")
parser.add_argument("--audio-sdpa-backend", choices=("default", "math"), default="default")
parser.add_argument("--video-sdpa-backend", choices=("default", "math"), default="default")
parser.add_argument("--num-outputs", type=int, choices=[1, 2, 4], default=1,
help="Images or videos generated per request; independent of retrieval filters.")
parser.add_argument("--lock-directory", type=Path, required=True)
parser.add_argument("--case", action="append")
parser.add_argument("--max-output-tokens", type=int)
parser.add_argument("--retrieve-only", action="store_true")
parser.add_argument("--prepare-model", action="store_true", help="Download the pinned full checkpoint on a CPU worker, then exit.")
parser.add_argument("--batch-sizes", type=lambda value: {int(item) for item in value.split(',')},
help="Retrieve representative batch sizes; retain the complete raw capture on the volume.")
parser.add_argument("--context-endpoints", action="store_true",
help="For QSA contexts above 65536 tokens, retrieve the first and last captured decode step.")
args = parser.parse_args()
repo_id, revision, folder = MODELS[args.kind]
args.model_path = args.model_path or "/task/data/models/" + folder
output = ROOT / "results" / "capture" / args.name
if args.retrieve_only:
receipt = json.loads((output / "run.json").read_text())
return retrieve(output, receipt, modal.Volume.from_name(receipt["volume"]), args.batch_sizes, args.context_endpoints)
output.mkdir(parents=True, exist_ok=False)
remote_relative = "captures/" + args.name
remote = "/task/data/" + remote_relative
app = modal.App.lookup("inference-kernels-capture-20261014", create_if_missing=True)
volume = modal.Volume.from_name(args.volume, create_if_missing=True)
image = modal.Image.from_id(args.image)
environment = {name: "/task/data/cache/" + folder for name, folder in (
("HF_HOME", "hf"), ("XDG_CACHE_HOME", "xdg"), ("TRITON_CACHE_DIR", "triton"),
("TORCH_EXTENSIONS_DIR", "torch"), ("CUDA_CACHE_PATH", "cuda"),
("FLASHINFER_WORKSPACE_BASE", "flashinfer"), ("TVM_FFI_CACHE_DIR", "tvm"),
("DG_JIT_CACHE_DIR", "deepgemm"), ("DJ_JIT_CACHE_DIR", "deepjit"),
("TILELANG_CACHE_DIR", "tilelang"),
)}
environment.update(PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1",
OMP_NUM_THREADS="8", MAX_JOBS="8")
receipt = dict(started_at=time.time(), image_id=args.image, volume=args.volume,
remote_dataset=remote_relative)
def save():
(output / "run.json").write_text(json.dumps(receipt, indent=2) + "\n")
if args.prepare_model:
sandbox = modal.Sandbox.create(app=app, image=image, cpu=8, memory=32768, timeout=14400,
volumes={"/task/data": volume}, env=environment)
receipt.update(sandbox_id=sandbox.object_id, model=repo_id, revision=revision, model_path=args.model_path)
save()
try:
source = ("from huggingface_hub import snapshot_download; "
f"print(snapshot_download({repo_id!r}, revision={revision!r}, local_dir={args.model_path!r}, max_workers=8))")
command = ["python", "-u", "-c", source]
if args.kind == "ltx25":
command = ["python", "-u", "-c", (ROOT / "scripts/prepare_ltx.py").read_text(),
"--source", "/task/data/models/ltx-2.5-original", "--output", args.model_path]
process = sandbox.exec(*command, timeout=13800)
with (output / "download.log").open("w") as log:
for line in process.stdout:
print(line, end="", flush=True)
log.write(line)
log.write(process.stderr.read())
process.wait()
receipt["returncode"] = process.returncode
finally:
sandbox.terminate()
receipt["finished_at"] = time.time()
save()
raise SystemExit(receipt.get("returncode", 1))
with modal.enable_output():
sandbox = modal.Sandbox.create(app=app, image=image, gpu="B200:4" if args.kind == "deepseek41" else "B200", cpu=16,
memory=524288 if args.kind == "deepseek41" else 262144, timeout=14400,
volumes={"/task/data": volume}, env=environment)
receipt["sandbox_id"] = sandbox.object_id
save()
print("SANDBOX", sandbox.object_id, flush=True)
locks = []
try:
process = sandbox.exec("nvidia-smi", "--query-gpu=uuid,name,memory.used", "--format=csv,noheader")
receipt["gpu"] = process.stdout.read().strip()
process.wait()
if process.returncode:
raise RuntimeError("GPU inventory failed")
args.lock_directory.mkdir(parents=True, exist_ok=True)
for gpu in receipt["gpu"].splitlines():
if int(gpu.rsplit(",", 1)[1].strip().split()[0]) > 64:
raise RuntimeError("The allocated GPU already has substantial memory in use")
lock = (args.lock_directory / ("modal-" + gpu.split(",")[0] + ".lock")).open("a+")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
locks.append(lock)
archive = io.BytesIO()
receipt["source_sha256"] = {}
with tarfile.open(fileobj=archive, mode="w:gz") as bundle:
for path in [ROOT / "scripts/capture_inputs.py", ROOT / "scripts/sitecustomize.py",
ROOT / "scripts/capture_llm.py", ROOT / "scripts/agentx_shapes.json",
ROOT / "scripts/capture_ltx.py",
*sorted((ROOT / "definitions").rglob("*.json"))]:
bundle.add(path, arcname=str(path.relative_to(ROOT)))
receipt["source_sha256"][str(path.relative_to(ROOT))] = hashlib.sha256(path.read_bytes()).hexdigest()
process = sandbox.exec("mkdir", "-p", "/task/repo")
process.wait()
process = sandbox.exec("tar", "xzf", "-", "-C", "/task/repo", text=False)
process.stdin.write(archive.getvalue())
process.stdin.write_eof()
process.stdin.drain()
process.wait()
if process.returncode:
raise RuntimeError("Capture source upload failed")
worker = {"image": "scripts/capture_inputs.py", "ltx25": "scripts/capture_ltx.py"}.get(args.kind, "scripts/capture_llm.py")
command = ["python", "-u", worker, "--model-path", args.model_path,
"--output-root", remote]
if args.kind in ("qwen-next", "deepseek41"):
command.extend(("--kind", args.kind))
if args.kind in ("image", "ltx25"):
command.extend(("--num-outputs", str(args.num_outputs)))
if args.kind == "ltx25":
command.extend(("--audio-sdpa-backend", args.audio_sdpa_backend))
command.extend(("--video-sdpa-backend", args.video_sdpa_backend))
if args.reference_image:
command.extend(("--reference-image", args.reference_image))
for case in args.case or []:
command.extend(("--case", case))
if args.max_output_tokens:
command.extend(("--max-output-tokens", str(args.max_output_tokens)))
receipt["command"] = command
save()
process = sandbox.exec(*command, workdir="/task/repo", timeout=13200)
with (output / "client.log").open("w") as log:
def copy(stream):
for line in stream:
print(line, end="", flush=True)
log.write(line)
log.flush()
threads = [threading.Thread(target=copy, args=(stream,))
for stream in (process.stdout, process.stderr)]
for thread in threads:
thread.start()
process.wait()
for thread in threads:
thread.join()
receipt["returncode"] = process.returncode
if process.returncode == 0:
process = sandbox.exec("python", "-u", "scripts/capture_inputs.py",
"--replay-root", remote, "--device", "cuda",
workdir="/task/repo", timeout=5400)
with (output / "replay.log").open("w") as log:
for line in process.stdout:
print(line, end="", flush=True)
log.write(line)
log.write(process.stderr.read())
process.wait()
receipt["replay_returncode"] = process.returncode
receipt["returncode"] = process.returncode
finally:
inventory_code = (
"import json,hashlib; from pathlib import Path; "
f"root=Path({remote!r}); "
"print(json.dumps([{'relative':str(p.relative_to(root)), 'size':p.stat().st_size, "
"'sha256':hashlib.sha256(p.read_bytes()).hexdigest() if p.suffix in ('.json','.jsonl') else None} "
"for p in root.rglob('*') if p.is_file()]))"
)
try:
if "gpu" in receipt:
process = sandbox.exec("python", "-c", inventory_code)
inventory_text = process.stdout.read()
process.wait()
if process.returncode == 0:
receipt["files"] = json.loads(inventory_text)
finally:
try:
sandbox.terminate()
finally:
for lock in locks:
fcntl.flock(lock, fcntl.LOCK_UN)
lock.close()
receipt["finished_at"] = time.time()
save()
retrieve(output, receipt, volume, args.batch_sizes, args.context_endpoints)
raise SystemExit(receipt.get("returncode", 1))
def retrieve(output, receipt, volume, batch_sizes=None, context_endpoints=False):
# Shutdown commits the mounted volume. Stream files without a duplicate
# multi-gigabyte archive on the local disk.
if "files" not in receipt:
raise RuntimeError("The worker did not provide a complete file inventory")
remote_relative = receipt["remote_dataset"]
entries = [SimpleNamespace(path=remote_relative + "/" + item["relative"],
size=item["size"], sha256=item["sha256"])
for item in receipt["files"]]
dataset = output / "dataset"
if batch_sizes or context_endpoints:
def read_metadata(relative):
item = next(item for item in receipt['files'] if item['relative'] == relative)
for attempt in range(15):
try:
data = b''.join(volume.read_file(remote_relative + '/' + relative))
if len(data) == item['size'] and hashlib.sha256(data).hexdigest() == item['sha256']:
return data.decode()
except FileNotFoundError:
pass
time.sleep(2)
raise IOError(f'Incomplete metadata: {relative}')
rewritten = {}
ids = set()
blobs = set()
source_receipts = [json.loads(line) for line in read_metadata('results/captures.jsonl').splitlines()]
eligible = {row['uuid'] for row in source_receipts
if not batch_sizes or row['axes'].get('B', 1) in batch_sizes}
if context_endpoints:
groups = {}
for row in source_receipts:
if (row['uuid'] in eligible and row['definition'].startswith('qsa_')
and max(row.get('scheduler_sequence_lengths', [0])) > 65536):
groups.setdefault((row['definition'], row['request_id']), []).append(row)
for rows in groups.values():
endpoints = {min(row['step'] for row in rows), max(row['step'] for row in rows)}
eligible.difference_update(row['uuid'] for row in rows if row['step'] not in endpoints)
def collect(value):
if isinstance(value, dict):
if value.get('type') == 'safetensors':
blobs.add(value['path'])
else:
for child in value.values(): collect(child)
elif isinstance(value, list):
for child in value: collect(child)
for item in receipt['files']:
relative = item['relative']
if relative.startswith('workloads/') and relative.endswith('.jsonl'):
selected = [row for line in read_metadata(relative).splitlines()
for row in [json.loads(line)] if row['workload']['uuid'] in eligible]
ids.update(row['workload']['uuid'] for row in selected)
collect(selected)
rewritten[relative] = ''.join(json.dumps(row, sort_keys=True) + '\n' for row in selected)
selected = [row for row in source_receipts if row['uuid'] in ids]
collect(selected)
rewritten['results/captures.jsonl'] = ''.join(json.dumps(row, sort_keys=True) + '\n' for row in selected)
report = json.loads(read_metadata('results/replay.json'))
total = len(report['cases'])
report['cases'] = [case for case in report['cases'] if case['uuid'] in ids]
receipt['selection'] = dict(batch_sizes=sorted(batch_sizes) if batch_sizes else None,
context_endpoints=context_endpoints, source_workloads=total,
retrieved_workloads=len(ids), raw_capture_retained=remote_relative)
report['selection'] = receipt['selection']
rewritten['results/replay.json'] = json.dumps(report, indent=2) + '\n'
for item in receipt['files']:
if item['relative'].startswith('blob/') and item['relative'] not in blobs:
(dataset / item['relative']).unlink(missing_ok=True)
entries = [entry for entry in entries if not entry.path.startswith(remote_relative + '/blob/')
or str(Path(entry.path).relative_to(remote_relative)) in blobs]
for entry in entries:
relative = str(Path(entry.path).relative_to(remote_relative))
if relative in rewritten:
data = rewritten[relative].encode()
target = dataset / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
entry.size, entry.sha256 = len(data), hashlib.sha256(data).hexdigest()
required = sum(entry.size for entry in entries)
for entry in entries:
relative = Path(entry.path).relative_to(remote_relative)
if relative.parts[:2] != ("blob", "workloads"):
continue
target, existing = dataset / relative, ROOT / relative
if not target.exists() and existing.is_file() and existing.stat().st_size == entry.size:
target.parent.mkdir(parents=True, exist_ok=True)
try:
target.hardlink_to(existing)
except OSError:
pass # A different filesystem can still use normal retrieval.
def complete(entry):
target = dataset / Path(entry.path).relative_to(remote_relative)
return (target.is_file() and target.stat().st_size == entry.size
and (entry.sha256 is None or hashlib.sha256(target.read_bytes()).hexdigest() == entry.sha256))
pending = [entry for entry in entries if not complete(entry)]
needed = sum(entry.size for entry in pending)
if needed + 2 * 1024**3 > shutil.disk_usage(output).free:
raise OSError(f"Need {needed} bytes plus 2 GiB reserve to retrieve the complete dataset")
def fetch(entry):
relative = Path(entry.path).relative_to(remote_relative)
target = dataset / relative
target.parent.mkdir(parents=True, exist_ok=True)
for attempt in range(15):
written = 0
digest = hashlib.sha256()
try:
with target.open("wb") as stream:
for chunk in volume.read_file(entry.path):
written += stream.write(chunk)
digest.update(chunk)
except FileNotFoundError:
time.sleep(2)
continue
if written == entry.size and (entry.sha256 is None or digest.hexdigest() == entry.sha256):
return
time.sleep(2)
raise IOError(f"Incomplete retrieval: {entry.path}")
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
list(executor.map(fetch, pending))
receipt.update(retrieved_files=len(entries), retrieved_bytes=required)
(output / "run.json").write_text(json.dumps(receipt, indent=2) + "\n")
print(f"RETRIEVED {len(entries)} files, {required} bytes", flush=True)
if __name__ == "__main__":
main()