File size: 31,482 Bytes
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f5a41c
 
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
"""Capture selected, complete operator inputs from an executing serving engine.

Set INFERENCE_CAPTURE_ROOT to an output dataset and INFERENCE_CAPTURE_REQUEST
to a JSON request receipt. Import install() before starting the engine. Child
processes use the adjacent sitecustomize module through PYTHONPATH.
"""

import contextvars
import functools
import hashlib
import json
import os
from pathlib import Path
import threading
import uuid


_ACTIVE = contextvars.ContextVar("inference_capture_active", default=None)
_ATTENTION = contextvars.ContextVar("inference_capture_attention", default=None)
_MODULE_PATH = contextvars.ContextVar("inference_capture_module", default=None)
_INSTALLED = False
_WRITER = None


class CaptureWriter:
    """Write immutable snapshots, deduplicating identical tensor contents."""

    def __init__(self, root, definitions):
        self.root = Path(root)
        self.definitions = {}
        for path in Path(definitions).rglob("*.json"):
            definition = json.loads(path.read_text())
            self.definitions[definition["name"]] = (path.parent.name, definition)
        self.seen = set()
        self.lock = threading.RLock()
        selected = os.environ.get("INFERENCE_CAPTURE_ONLY", "")
        self.enabled = set(selected.split(",")) if selected else set(self.definitions)
        if self.enabled - self.definitions.keys():
            raise ValueError(f"Unknown capture definitions: {self.enabled - self.definitions.keys()}")

    def tensor(self, value, name):
        import torch
        from safetensors.torch import save_file

        # Copy before the engine can mutate or reuse its storage.
        value = value.detach().to(device="cpu", copy=True).contiguous()
        header = json.dumps([str(value.dtype), list(value.shape)]).encode()
        digest = hashlib.sha256(header)
        digest.update(memoryview(value.reshape(-1).view(torch.uint8).numpy()))
        relative = Path("blob/workloads") / name / (digest.hexdigest() + ".safetensors")
        path = self.root / relative
        if not path.exists():
            path.parent.mkdir(parents=True, exist_ok=True)
            temporary = path.with_suffix(f".{os.getpid()}.tmp")
            save_file({"tensor": value}, str(temporary))
            temporary.replace(path)
        return {"type": "safetensors", "path": relative.as_posix(), "tensor_key": "tensor"}

    def wants(self, name, provenance):
        return name in self.enabled and self._selection_key(name, provenance) not in self.seen

    @staticmethod
    def _selection_key(name, provenance):
        return (name, provenance["request_id"], provenance.get("selection_step", provenance["step"]), provenance.get("variant"))

    def write(self, name, inputs, output, provenance):
        import torch

        with self.lock:
            if not self.wants(name, provenance):
                return
            family, definition = self.definitions[name]
            if set(inputs) != set(definition["inputs"]):
                raise ValueError(f"Incomplete capture for {name}")
            axes = {k: v["value"] for k, v in definition["axes"].items() if v["type"] == "const"}
            descriptors = {}
            for key, spec in definition["inputs"].items():
                value = inputs[key]
                if spec["shape"] is None:
                    if isinstance(value, torch.Tensor):
                        raise TypeError(f"{key} must retain its Python scalar interface")
                    descriptors[key] = {"type": "scalar", "value": value}
                    continue
                if str(value.dtype) != "torch." + spec["dtype"]:
                    raise TypeError(f"{name}/{key}: {value.dtype} != {spec['dtype']}")
                if value.ndim != len(spec["shape"]):
                    raise ValueError(f"Invalid rank: {name}/{key}")
                for symbol, dimension in zip(spec["shape"], value.shape):
                    if isinstance(symbol, int):
                        if symbol != dimension:
                            raise ValueError(f"Invalid constant dimension: {name}/{key}")
                    elif symbol in axes and axes[symbol] != dimension:
                        raise ValueError(f"Inconsistent {symbol}: {name}/{key}")
                    else:
                        axes[symbol] = dimension
                descriptors[key] = self.tensor(value, name)
            variable_axes = {k: axes[k] for k, spec in definition["axes"].items() if spec["type"] == "var"}
            identity = json.dumps([name, descriptors, provenance], sort_keys=True)
            workload_id = str(uuid.uuid5(uuid.NAMESPACE_URL, identity))
            row = {"definition": name, "workload": {"uuid": workload_id, "axes": variable_axes, "inputs": descriptors}}
            path = self.root / "workloads" / family / (name + ".jsonl")
            path.parent.mkdir(parents=True, exist_ok=True)
            expected = ({key: self.tensor(output[key], name) for key in definition["outputs"]}
                        if isinstance(output, dict) else self.tensor(output, name))
            receipt = dict(provenance, definition=name, uuid=workload_id, axes=variable_axes,
                           expected_output=expected)
            receipt_path = self.root / "results" / "captures.jsonl"
            receipt_path.parent.mkdir(parents=True, exist_ok=True)
            with receipt_path.open("a") as stream:
                stream.write(json.dumps(receipt, sort_keys=True) + "\n")
            with path.open("a") as stream:
                stream.write(json.dumps(row, sort_keys=True) + "\n")
            self.seen.add(self._selection_key(name, provenance))
            print(f"CAPTURE {name} {variable_axes} {workload_id}", flush=True)


def _provenance(context, operation, **extra):
    return dict(context["request"], step=context["step"], operation=operation,
                process_id=os.getpid(), module_path=_MODULE_PATH.get(), **extra)


def _gemm(a, weight, output, operation):
    import torch

    context = _ACTIVE.get()
    if context is None or not context["selected"]:
        return
    if a.dtype != torch.bfloat16 or weight.dtype != torch.bfloat16:
        return
    n, k = weight.shape
    name = f"dense_gemm_bf16_nt_n{n}_k{k}"
    if name not in _WRITER.definitions:
        return
    provenance = _provenance(context, operation, variant=f"rows_{a.numel() // k}")
    if _WRITER.wants(name, provenance):
        _WRITER.write(name, {"A": a.reshape(-1, k), "W": weight},
                      output.reshape(-1, n), provenance)


def _block_attention(q, k, v, prefix_length, segments, output, context, operation):
    import math
    import torch

    name = "prefix_cached_block_causal_h32_d128"
    if not prefix_length:
        name += "_prefix0"
    provenance = _provenance(context, operation, prefix_segments=segments,
                            adapter="Preserve post-normalization/RoPE tensors; materialize the engine's segment visibility.")
    if not _WRITER.wants(name, provenance):
        return
    image_ids = torch.full((k.shape[1],), -1, dtype=torch.int32, device=q.device)
    next_image = 0
    for start, end, is_image in segments:
        if is_image:
            image_ids[start:end] = next_image
            next_image += 1
    if prefix_length:
        image_ids[prefix_length:] = next_image
    inputs = dict(Q=q, K_current=k[:, prefix_length:], V_current=v[:, prefix_length:],
                  K_prefix=k[:, :prefix_length], V_prefix=v[:, :prefix_length],
                  image_ids=image_ids,
                  key_valid=torch.ones((q.shape[0], k.shape[1]), dtype=torch.bool, device=q.device),
                  sm_scale=1 / math.sqrt(q.shape[-1]))
    _WRITER.write(name, inputs, output, provenance)


def _instrument_image_model(model):
    """Attach only to the first transformer block; retain full model execution."""
    import inspect
    import torch

    attention = model.transformer_blocks[0].attn
    if getattr(attention, "_input_capture_installed", False):
        return
    attention._input_capture_installed = True
    original_sample = attention.attend_sample
    sample_signature = inspect.signature(original_sample)

    @functools.wraps(original_sample)
    def sample(*args, **kwargs):
        context = _ACTIVE.get()
        if context is None or not context["selected"]:
            return original_sample(*args, **kwargs)
        bound = sample_signature.bind(*args, **kwargs).arguments
        layout = bound.get("layout")
        segments = layout["segments"] if layout is not None else bound["segments"]
        prefix_rope = layout["prefix_rope"] if layout is not None else bound["prefix_rope"]
        if bound.get("prefix_pad") is not None:
            raise ValueError("Padded prefix capture needs an explicit padding-mask adapter")
        state = {"segments": segments, "prefix_length": prefix_rope.shape[0], "prefix_calls": []}
        token = _ATTENTION.set(state)
        try:
            result = original_sample(*args, **kwargs)
            calls = state["prefix_calls"]
            if calls:
                # The serving implementation evaluates each prefix segment
                # separately. Their concatenation is the definition's full
                # initial block-causal operator, with identical visibility.
                _block_attention(torch.cat([c[0] for c in calls], 1), calls[-1][1],
                                 calls[-1][2], 0, segments,
                                 torch.cat([c[3] for c in calls], 1), context,
                                 "QwenImage21Attention.local_attn (all prefix segments)")
            return result
        finally:
            _ATTENTION.reset(token)

    attention.attend_sample = sample
    local_forward = attention.local_attn.forward

    @functools.wraps(local_forward)
    def local(q, k, v, *args, **kwargs):
        output = local_forward(q, k, v, *args, **kwargs)
        state = _ATTENTION.get()
        if state is not None:
            state["prefix_calls"].append((q.detach().clone(), k.detach().clone(),
                                          v.detach().clone(), output.detach().clone()))
        return output

    attention.local_attn.forward = local
    target_forward = attention.target_attn.forward

    @functools.wraps(target_forward)
    def target(q, k, v, *args, **kwargs):
        output = target_forward(q, k, v, *args, **kwargs)
        state, context = _ATTENTION.get(), _ACTIVE.get()
        if state is not None:
            _block_attention(q, k, v, state["prefix_length"], state["segments"],
                             output, context, "QwenImage21Attention.target_attn")
        return output

    attention.target_attn.forward = target
    prefix_forward = attention.target_attn.forward_with_replicated_kv_prefix

    @functools.wraps(prefix_forward)
    def target_prefix(q, kp, vp, k, v, *args, **kwargs):
        output = prefix_forward(q, kp, vp, k, v, *args, **kwargs)
        state, context = _ATTENTION.get(), _ACTIVE.get()
        if state is not None:
            _block_attention(q, torch.cat((kp, k), 1), torch.cat((vp, v), 1),
                             kp.shape[1], state["segments"], output, context,
                             "QwenImage21Attention.target_attn.forward_with_replicated_kv_prefix")
        return output

    attention.target_attn.forward_with_replicated_kv_prefix = target_prefix


def install():
    """Install process-local hooks without importing SGLang during startup."""
    global _INSTALLED, _WRITER
    if _INSTALLED or not os.environ.get("INFERENCE_CAPTURE_ROOT"):
        return
    import torch
    import torch.nn.functional as functional

    _INSTALLED = True
    _WRITER = CaptureWriter(os.environ["INFERENCE_CAPTURE_ROOT"],
                            os.environ["INFERENCE_CAPTURE_DEFINITIONS"])
    if os.environ.get("INFERENCE_CAPTURE_MODEL") == "ltx25":
        from capture_ltx import install as install_ltx

        install_ltx(_WRITER)
        return
    original_call = torch.nn.Module._call_impl
    counters = {}
    module_paths = {}

    @functools.wraps(original_call)
    def call(module, *args, **kwargs):
        if type(module).__name__ != "QwenImage21Transformer2DModel":
            if _ACTIVE.get() is None:
                return original_call(module, *args, **kwargs)
            module_token = _MODULE_PATH.set(module_paths.get(id(module)))
            try:
                return original_call(module, *args, **kwargs)
            finally:
                _MODULE_PATH.reset(module_token)
        request_path = Path(os.environ["INFERENCE_CAPTURE_REQUEST"])
        if not request_path.is_file():
            return original_call(module, *args, **kwargs)
        request = json.loads(request_path.read_text())
        hidden_states = kwargs.get("hidden_states", args[0] if args else None)
        request["model_batch_size"] = int(hidden_states.shape[0])
        request_id = request["request_id"]
        step = counters.get(request_id, 0)
        counters[request_id] = step + 1
        if id(module) not in module_paths:
            module_paths.update({id(child): name for name, child in module.named_modules()})
        _instrument_image_model(module)
        token = _ACTIVE.set({"request": request, "step": step,
                             "selected": step in request.get("capture_steps", [0, 4, 7])})
        try:
            return original_call(module, *args, **kwargs)
        finally:
            _ACTIVE.reset(token)

    torch.nn.Module._call_impl = call
    linear = functional.linear

    @functools.wraps(linear)
    def captured_linear(a, weight, bias=None):
        output = linear(a, weight, bias)
        if bias is None:
            _gemm(a, weight, output, "torch.nn.functional.linear")
        return output

    functional.linear = captured_linear
    mm = torch.mm

    @functools.wraps(mm)
    def captured_mm(a, b, *args, **kwargs):
        output = mm(a, b, *args, **kwargs)
        _gemm(a, b.t(), output, "torch.mm")
        return output

    torch.mm = captured_mm

    # Some SGLang releases do not read Turbo's saved sampling schedule.
    # Apply the checkpoint's exact sigmas, without changing any model weights.
    if os.environ.get("INFERENCE_CAPTURE_SIGMAS"):
        from sglang.multimodal_gen.configs.pipeline_configs.qwen_image21 import QwenImage21PipelineConfig

        sigmas = json.loads(os.environ["INFERENCE_CAPTURE_SIGMAS"])

        def prepare_sigmas(self, requested, num_inference_steps):
            if requested is not None:
                return requested
            if num_inference_steps != len(sigmas):
                raise ValueError("The request must use the checkpoint's Turbo step count")
            return sigmas.copy()

        QwenImage21PipelineConfig.prepare_sigmas = prepare_sigmas

    if os.environ.get("INFERENCE_CAPTURE_MODEL") == "qwen-next":
        from capture_llm import install_qwen

        install_qwen(_WRITER)
    elif os.environ.get("INFERENCE_CAPTURE_MODEL") == "deepseek41":
        from capture_llm import install_deepseek

        install_deepseek(_WRITER)


def replay(dataset_root, device):
    """Compare full reference outputs against the captured serving outputs."""
    import time
    import traceback
    import torch
    from safetensors.torch import load_file

    root = Path(dataset_root).resolve()
    definitions = {d["name"]: d for path in (Path(__file__).resolve().parents[1] / "definitions").rglob("*.json")
                   for d in [json.loads(path.read_text())]}
    receipt_path = root / "captures.jsonl"
    if not receipt_path.exists():
        receipt_path = root / "results/captures.jsonl"
    receipts = {row["uuid"]: row for line in receipt_path.read_text().splitlines()
                for row in [json.loads(line)]}
    report = {"torch": torch.__version__, "device": device, "comparison": "all output elements",
              "tolerances": {"bfloat16": {"rtol": 0.016, "atol": 0.005},
                             "float32": {"rtol": 1e-4, "atol": 2e-5}, "integer": "exact",
                             "gdn_prefill_state": {"relative_rms": 0.01, "relative_max": 0.015,
                                                   "max_head_relative_rms": 0.02,
                                                   "reason": "The engine's chunk algorithm rounds intermediate matrix operands to BF16 although its final state is stored in FP32."}}, "cases": []}
    runtimes = {}

    def load(descriptor):
        if descriptor["type"] == "scalar":
            return descriptor["value"]
        if descriptor["type"] != "safetensors":
            raise ValueError("Captured workloads must not contain random inputs")
        return load_file(str(root / descriptor["path"]), device=device)[descriptor["tensor_key"]]

    for path in sorted((root / "workloads").rglob("*.jsonl")):
        for line in path.read_text().splitlines():
            trace = json.loads(line)
            name, workload = trace["definition"], trace["workload"]
            if "expected_output" not in receipts[workload["uuid"]]:
                continue  # Imported workloads (the MLSys 2026 GDN) have no engine output.
            started = time.monotonic()
            result = {"definition": name, "uuid": workload["uuid"], "axes": workload["axes"]}
            try:
                definition = definitions[name]
                if name not in runtimes:
                    namespace = {}
                    exec(compile(definition["reference"], name, "exec"), namespace)
                    runtimes[name] = namespace["run"]
                inputs = {key: load(workload["inputs"][key]) for key in definition["inputs"]}
                with torch.inference_mode():
                    actual = runtimes[name](**inputs)
                outputs = list(actual) if isinstance(actual, (list, tuple)) else [actual]
                expected = receipts[workload["uuid"]]["expected_output"]
                descriptors = [expected] if "type" in expected else list(expected.values())
                if len(outputs) != len(descriptors):
                    raise ValueError("Captured output count does not match the reference")
                result["max_absolute_errors"] = []
                for actual, descriptor in zip(outputs, descriptors):
                    expected = load(descriptor)
                    if actual.dtype != expected.dtype or actual.shape != expected.shape:
                        raise ValueError("Output dtype or shape mismatch")
                    if actual.is_floating_point():
                        if not torch.isfinite(actual).all() or not torch.isfinite(expected).all():
                            raise ValueError("Nonfinite output")
                        tolerance = report["tolerances"]["bfloat16" if actual.dtype == torch.bfloat16 else "float32"]
                        error = (actual.float() - expected.float()).abs().max().item() if actual.numel() else 0.0
                        if name.startswith("gated_delta_rule_prefill_") and actual.dtype == torch.float32:
                            difference = actual - expected
                            metrics = dict(relative_rms=(difference.norm() / expected.norm().clamp_min(1e-12)).item(),
                                           relative_max=(difference.abs().max() / expected.abs().max().clamp_min(1e-12)).item(),
                                           max_head_relative_rms=(difference.norm(dim=(-2, -1)) / expected.norm(dim=(-2, -1)).clamp_min(1e-12)).max().item())
                            result["state_comparison"] = metrics
                            for metric, value in metrics.items():
                                if value > report["tolerances"]["gdn_prefill_state"][metric]:
                                    raise AssertionError(f"GDN chunk state {metric}={value} exceeds its BF16 arithmetic bound")
                        else:
                            torch.testing.assert_close(actual, expected, **tolerance)
                    else:
                        torch.testing.assert_close(actual, expected, rtol=0, atol=0)
                        error = 0
                    result["max_absolute_errors"].append(error)
                result["status"] = "passed"
                del inputs, outputs, actual, expected
            except Exception:
                result.update(status="failed", error=traceback.format_exc())
            result["seconds"] = time.monotonic() - started
            report["cases"].append(result)
            (root / "results/replay.json").write_text(json.dumps(report, indent=2) + "\n")
            print("REPLAY", result["status"], name, result["axes"], flush=True)
    if not report["cases"] or any(case["status"] != "passed" for case in report["cases"]):
        raise RuntimeError("Captured-input replay failed; see results/replay.json")


def import_capture(source, destination):
    """Merge a validated capture without copying identical tensor storage."""
    import shutil

    source, destination = Path(source).resolve(), Path(destination).resolve()
    report = json.loads((source / "results/replay.json").read_text())
    if not report["cases"] or any(case["status"] != "passed" for case in report["cases"]):
        raise ValueError("Only a completely validated capture can be imported")
    receipts = [json.loads(line) for line in (source / "results/captures.jsonl").read_text().splitlines()]
    if {row["uuid"] for row in receipts} != {row["uuid"] for row in report["cases"]}:
        raise ValueError("Replay does not cover every captured workload")
    for path in (source / "blob").rglob("*.safetensors"):
        target = destination / path.relative_to(source)
        target.parent.mkdir(parents=True, exist_ok=True)
        if target.exists():
            if target.stat().st_size != path.stat().st_size:
                raise ValueError(f"Conflicting content-addressed tensor: {target}")
        else:
            try:
                os.link(path, target)
            except OSError:
                shutil.copyfile(path, target)
    for path in (source / "workloads").rglob("*.jsonl"):
        target = destination / path.relative_to(source)
        target.parent.mkdir(parents=True, exist_ok=True)
        existing = target.read_text().splitlines() if target.exists() else []
        ids = {json.loads(line)["workload"]["uuid"] for line in existing}
        with target.open("a") as stream:
            for line in path.read_text().splitlines():
                if json.loads(line)["workload"]["uuid"] not in ids:
                    stream.write(line + "\n")
    receipt_path = destination / "captures.jsonl"
    ids = {json.loads(line)["uuid"] for line in receipt_path.read_text().splitlines()} if receipt_path.exists() else set()
    comparisons = {case["uuid"]: case for case in report["cases"]}
    with receipt_path.open("a") as stream:
        for row in receipts:
            if row["uuid"] not in ids:
                comparison = comparisons[row["uuid"]]
                row["validation"] = dict(comparison, device=comparison.get("device", report["device"]),
                                         torch=comparison.get("torch", report["torch"]),
                                         tolerances=report["tolerances"])
                stream.write(json.dumps(row, sort_keys=True) + "\n")
    print(f"Imported {len(receipts)} validated workloads from {source}")


def main():
    """Run complete image requests against a locally launched SGLang server."""
    import argparse
    import base64
    import importlib.metadata
    import signal
    import subprocess
    import time
    import requests

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model-path", type=Path)
    parser.add_argument("--output-root", type=Path)
    parser.add_argument("--replay-root", type=Path)
    parser.add_argument("--import-capture", type=Path)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--port", type=int, default=30000)
    parser.add_argument("--case", action="append", choices=["square", "landscape", "edit", "alpha"])
    parser.add_argument("--num-outputs", type=int, choices=[1, 2, 4], default=1,
                        help="Generate this many images in each real serving request.")
    parser.add_argument("--reference-image", type=Path)
    args = parser.parse_args()
    if args.import_capture:
        if args.output_root is None:
            parser.error("Import requires --output-root")
        return import_capture(args.import_capture, args.output_root)
    if args.replay_root:
        return replay(args.replay_root, args.device)
    if args.model_path is None or args.output_root is None:
        parser.error("Serving capture requires --model-path and --output-root")
    root = args.output_root.resolve()
    results = root / "results"
    results.mkdir(parents=True, exist_ok=True)
    request_file = results / "active_request.json"
    request_file.unlink(missing_ok=True)
    scripts = Path(__file__).resolve().parent
    config = json.loads((args.model_path / "model_index.json").read_text())
    sigmas = config["sample_sigmas"]
    environment = dict(os.environ,
                       INFERENCE_CAPTURE_ROOT=str(root),
                       INFERENCE_CAPTURE_DEFINITIONS=str(scripts.parent / "definitions"),
                       INFERENCE_CAPTURE_REQUEST=str(request_file),
                       INFERENCE_CAPTURE_SIGMAS=json.dumps(sigmas),
                       PYTHONPATH=str(scripts) + os.pathsep + os.environ.get("PYTHONPATH", ""),
                       PYTHONDONTWRITEBYTECODE="1", OMP_NUM_THREADS="8")
    command = ["sglang", "serve", "--model-path", str(args.model_path.resolve()),
               "--model-id", "Qwen-Image-2.1", "--host", "127.0.0.1", "--port", str(args.port),
               "--scheduler-port", str(args.port + 20), "--master-port", str(args.port + 21),
               "--performance-mode", "speed", "--attention-backend", "torch_sdpa",
               "--enable-torch-compile", "false", "--enable-breakable-cuda-graph", "false",
               "--warmup-mode", "off", "--output-path", str(results / "images"),
               "--input-save-path", str(results / "inputs")]
    provenance = {"model": "Qwen/Qwen-Image-2.1-Turbo",
                  "model_revision": "fc13ba1986fcb905854dc8de2f52eee395f49b5b",
                  "engine": "SGLang", "engine_version": importlib.metadata.version("sglang"),
                  "server_command": command, "sampling_sigmas": sigmas,
                  "sampling_adapter": "Use the unmodified Turbo schedule stored in model_index.json.",
                  "source": "https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo"}
    (results / "server.json").write_text(json.dumps(provenance, indent=2) + "\n")
    url = f"http://127.0.0.1:{args.port}"
    cases = [
        ("square", "1024x1024", "A red ceramic teapot on a wooden table beside a window, soft afternoon light."),
        ("landscape", "1536x1024", "A quiet lakeside village at sunrise, reflections in the water, mountains behind the houses, wide landscape photograph."),
        ("edit", "1024x1024", "Change the teapot to cobalt blue while preserving the composition and lighting."),
        ("alpha", "1024x1024", "A single orange cat sitting, full body, isolated on a transparent background with an alpha channel. No floor or shadow."),
    ]
    with (results / "server.log").open("a") as log:
        server = subprocess.Popen(command, env=environment, stdout=log, stderr=subprocess.STDOUT,
                                  start_new_session=True)
        try:
            deadline = time.monotonic() + 1200
            while True:
                if server.poll() is not None:
                    raise RuntimeError(f"Serving process exited: {server.returncode}; see {results / 'server.log'}")
                try:
                    if requests.get(url + "/health", timeout=5).ok:
                        break
                except requests.RequestException:
                    pass
                if time.monotonic() > deadline:
                    raise TimeoutError("Serving startup exceeded 1200 seconds")
                time.sleep(2)
            for case, size, prompt in cases:
                if args.case and case not in args.case:
                    continue
                payload = dict(model="Qwen-Image-2.1", prompt=prompt, size=size,
                               n=args.num_outputs, num_inference_steps=len(sigmas), guidance_scale=1.0,
                               seed=42, response_format="b64_json", output_format="png")
                suffix = "" if args.num_outputs == 1 else f"_batch{args.num_outputs}"
                receipt = dict(provenance, request_id="qwen_image21_" + case + suffix,
                               requested_outputs=args.num_outputs, request=payload,
                               capture_steps=[0, 4, 7] if args.num_outputs == 1 else [0, 7], started_at=time.time())
                temporary = request_file.with_suffix(".tmp")
                temporary.write_text(json.dumps(receipt))
                temporary.replace(request_file)
                print(f"REQUEST {case} {size}", flush=True)
                if case == "edit":
                    image_path = args.reference_image or results / "square.png"
                    receipt["reference_image_sha256"] = hashlib.sha256(image_path.read_bytes()).hexdigest()
                    temporary.write_text(json.dumps(receipt))
                    temporary.replace(request_file)
                    with image_path.open("rb") as image:
                        response = requests.post(url + "/v1/images/edits", data=payload,
                                                 files={"image": ("square.png", image, "image/png")}, timeout=1800)
                else:
                    response = requests.post(url + "/v1/images/generations", json=payload, timeout=1800)
                receipt.update(status_code=response.status_code, finished_at=time.time())
                if not response.ok:
                    receipt["error"] = response.text
                else:
                    data = response.json()
                    outputs = []
                    for index, item in enumerate(data["data"]):
                        image = base64.b64decode(item.pop("b64_json"))
                        filename = case + ("" if index == 0 else f"_{index}") + ".png"
                        (results / filename).write_bytes(image)
                        outputs.append(dict(path=filename, sha256=hashlib.sha256(image).hexdigest()))
                    receipt.update(response=data, outputs=outputs, actual_outputs=len(outputs))
                (results / (case + ".json")).write_text(json.dumps(receipt, indent=2) + "\n")
                response.raise_for_status()
                if receipt["actual_outputs"] != args.num_outputs:
                    raise RuntimeError("Image output count does not match the serving request")
                print(f"COMPLETE {case}", flush=True)
        finally:
            request_file.unlink(missing_ok=True)
            if server.poll() is None:
                os.killpg(server.pid, signal.SIGTERM)
                try:
                    server.wait(timeout=30)
                except subprocess.TimeoutExpired:
                    os.killpg(server.pid, signal.SIGKILL)
                    server.wait()


if __name__ == "__main__":
    main()