File size: 18,663 Bytes
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""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()