File size: 16,406 Bytes
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
86b22af
65e1c10
 
86b22af
 
 
 
addfd4b
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
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
"""Capture complete LTX-2.5 attention inputs from SGLang video serving."""

import contextvars
import functools
import json
import os
from pathlib import Path


def install(writer):
    import torch
    # Preserve the checkpoint's optional keyframe tag. The sampled decoder
    # path has no auxiliary keyframe stream and does not read this parameter.
    module_init = torch.nn.Module.__init__

    @functools.wraps(module_init)
    def init_with_keyframe_tag(self, *a, **kw):
        module_init(self, *a, **kw)
        if type(self).__name__ == "LTX2VideoDiffusionDecoder3d":
            self.register_parameter("type_emb", torch.nn.Parameter(torch.empty(128)))

    # Delay SGLang module imports until its worker initializes the platform.
    torch.nn.Module.__init__ = init_with_keyframe_tag
    active = contextvars.ContextVar("ltx_capture", default=None)
    counters = {}
    instrumented = set()
    original_call = torch.nn.Module._call_impl
    audio_sdpa = os.environ.get("INFERENCE_CAPTURE_LTX_AUDIO_SDPA", "default")
    video_sdpa = os.environ.get("INFERENCE_CAPTURE_LTX_VIDEO_SDPA", "default")
    policies = {64: audio_sdpa, 128: video_sdpa}
    if any(policy not in ("default", "math") for policy in policies.values()):
        raise ValueError(f"Unknown LTX SDPA backend: {policies}")
    if "math" in policies.values():
        from torch.nn.attention import SDPBackend, sdpa_kernel

        # Select a standard serving backend for every transformer layer. BF16
        # cuDNN SDPA rounds attention probabilities before the value product;
        # math SDPA keeps FP32 intermediates while retaining BF16 Q/K/V and O.
        # The context is entered at the actual SDPA call, inside LocalAttention's
        # own backend context. It also covers layers beyond the captured block.
        torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(False)
        original_sdpa = torch.nn.functional.scaled_dot_product_attention

        @functools.wraps(original_sdpa)
        def transformer_math_sdpa(query, key, value, *args, **kwargs):
            if active.get() is not None and policies.get(query.shape[-1]) == "math":
                with sdpa_kernel(SDPBackend.MATH):
                    output = original_sdpa(query, key, value, *args, **kwargs)
                # LTX flattens heads with view() after transposing H/N. cuDNN
                # supplies that storage order; normalize math SDPA's layout to
                # the same contract, preserving every output value.
                return output.transpose(-3, -2).contiguous().transpose(-3, -2)
            return original_sdpa(query, key, value, *args, **kwargs)

        torch.nn.functional.scaled_dot_product_attention = transformer_math_sdpa

    def request():
        path = Path(os.environ["INFERENCE_CAPTURE_REQUEST"])
        return json.loads(path.read_text()) if path.is_file() else None

    def instrument_dense(model):
        for label, attention in model.transformer_blocks[0].named_children():
            if type(attention).__name__ != "LTX2Attention":
                continue
            original = attention.attn.forward

            def capture(q, k, v, *a, _original=original, _label=label, **kw):
                output = _original(q, k, v, *a, **kw)
                context = active.get()
                if context is None or context["step"] not in context["capture_steps"]:
                    return output
                modality = "video" if q.shape[-1] == 128 else "audio"
                name = f"noncausal_dense_attention_h32_d{q.shape[-1]}"
                provenance = dict(context, operation="LTX2Attention.attn", variant=_label,
                    sdpa_backend=audio_sdpa if modality == "audio" else video_sdpa,
                    actual_attention_batch=int(q.shape[0]),
                    module_path="transformer_blocks.0." + _label,
                    adapter="Preserve post-normalization/RoPE Q/K/V; verify that the engine mask is all-visible and omit the redundant mask input.")
                if writer.wants(name, provenance):
                    mask = kw.get("attn_mask")
                    if mask is not None:
                        visible = mask == 0 if mask.is_floating_point() else mask.bool()
                        if not bool(visible.all()):
                            raise ValueError("Mask-free attention capture requires an all-visible engine mask")
                    writer.write(name, dict(Q=q, K=k, V=v),
                                 output.reshape_as(q), provenance)
                return output

            attention.attn.forward = capture

    def instrument_neighborhood(module):
        original = module.project_qkv
        state = {}

        @functools.wraps(original)
        def project(hidden_states):
            qkv = original(hidden_states)
            req = request()
            if req is not None:
                kt, ky, kx = module.kernel_size
                name = f"neighborhood_attention_3d_h{module.heads}_d64_kt{kt}_ky{ky}_kx{kx}"
                provenance = dict(req, step=0, operation="LTX2VideoVaeNeighborhoodAttention",
                    actual_attention_batch=int(qkv[0].shape[0]),
                    variant="grid_" + "x".join(map(str, qkv[0].shape[1:4])),
                    module_path=f"diffusion_decoder.attention_h{module.heads}_{kt}x{ky}x{kx}",
                    adapter="Capture the complete grid after normalization, query scaling and RoPE, before output projection.")
                if name in writer.definitions and writer.wants(name, provenance):
                    state.update(qkv=qkv, name=name, provenance=provenance)
            return qkv

        def before_projection(_module, args):
            if state:
                q, k, v = state.pop("qkv")
                writer.write(state.pop("name"), dict(Q=q, K=k, V=v), args[0].reshape_as(q),
                             state.pop("provenance"))

        module.project_qkv = project
        module.to_out[0].register_forward_pre_hook(before_projection)

    @functools.wraps(original_call)
    def call(module, *a, **kw):
        name = type(module).__name__
        if name == "LTX2VideoVaeNeighborhoodAttention" and id(module) not in instrumented:
            instrument_neighborhood(module)
            instrumented.add(id(module))
        if name != "LTX2VideoTransformer3DModel":
            return original_call(module, *a, **kw)
        req = request()
        if req is None:
            return original_call(module, *a, **kw)
        if id(module) not in instrumented:
            instrument_dense(module)
            instrumented.add(id(module))
        step = counters.get(req["request_id"], 0)
        counters[req["request_id"]] = step + 1
        token = active.set(dict(req, step=step))
        try:
            return original_call(module, *a, **kw)
        finally:
            active.reset(token)

    torch.nn.Module._call_impl = call


def main():
    import argparse
    import hashlib
    import importlib.metadata
    import signal
    import subprocess
    import time
    import requests

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model-path", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--case", action="append")
    parser.add_argument("--port", type=int, default=30000)
    parser.add_argument("--reference-image", type=Path)
    parser.add_argument("--audio-sdpa-backend", choices=("default", "math"), default="default",
                        help="Use standard math SDPA with FP32 intermediates for all dimension-64 transformer attention calls.")
    parser.add_argument("--video-sdpa-backend", choices=("default", "math"), default="default",
                        help="Use standard math SDPA with FP32 intermediates for all dimension-128 transformer attention calls.")
    parser.add_argument("--num-outputs", type=int, choices=[1, 2, 4], default=1,
                        help="Generate this many videos in each real serving request.")
    args = parser.parse_args()
    results = args.output_root.resolve() / "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
    environment = dict(os.environ, INFERENCE_CAPTURE_ROOT=str(args.output_root.resolve()),
        INFERENCE_CAPTURE_DEFINITIONS=str(scripts.parent / "definitions"),
        INFERENCE_CAPTURE_REQUEST=str(request_file), INFERENCE_CAPTURE_MODEL="ltx25",
        INFERENCE_CAPTURE_LTX_AUDIO_SDPA=args.audio_sdpa_backend,
        INFERENCE_CAPTURE_LTX_VIDEO_SDPA=args.video_sdpa_backend,
        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", "LTX-2.5-Diffusers",
        "--host", "127.0.0.1", "--port", str(args.port), "--performance-mode", "speed",
        "--scheduler-port", str(args.port + 20), "--master-port", str(args.port + 21),
        "--attention-backend", "torch_sdpa", "--enable-torch-compile", "false",
        "--enable-breakable-cuda-graph", "false", "--warmup-mode", "off",
        "--load-diffusion-decoder", "true", "--vae-tiling", "false",
        "--vae-sp", "false", "--input-save-path", str(results / "inputs"),
        "--diffusion-decoder-tiling", "false", "--output-path", str(results / "videos")]
    provenance = dict(model="Lightricks/LTX-2.5", model_revision="49b093a39c19169a8a81721dcc541e07e945232f",
        conversion=json.loads((args.model_path / "conversion.json").read_text()),
        engine="SGLang", engine_version=importlib.metadata.version("sglang"), server_command=command,
        sampling_sigmas=[1, .99375, .9875, .98125, .975, .909375, .725, .421875],
        source="https://github.com/sgl-project/sglang/tree/684fea8a/python/sglang/multimodal_gen",
        decoder_adapter="Retain the original optional keyframe tag; use the complete ordinary-video decoder path.",
        audio_sdpa_backend=args.audio_sdpa_backend,
        video_sdpa_backend=args.video_sdpa_backend,
        video_precision_adapter=("Select PyTorch math SDPA for every dimension-128 transformer attention call; keep BF16 inputs/outputs and FP32 intermediates; normalize output storage to the engine's sequence-major flattening contract."
                                 if args.video_sdpa_backend == "math" else "Use the engine's default SDPA dispatch."),
        audio_precision_adapter=("Select PyTorch math SDPA for every dimension-64 transformer attention call; keep BF16 inputs/outputs and FP32 intermediates; normalize output storage to the engine's sequence-major flattening contract."
                                 if args.audio_sdpa_backend == "math" else "Use the engine's default SDPA dispatch."))
    (results / "server.json").write_text(json.dumps(provenance, indent=2) + "\n")
    cases = [
        ("text_video", "768x448", 49, "A red ceramic teapot on a wooden table beside a window. The camera slowly moves closer as steam rises from the spout. Soft afternoon light and gentle room ambience."),
        ("image_video", "512x320", 49, "The camera slowly moves around the ceramic teapot. Soft steam rises from its spout while the table and window remain still. Quiet indoor ambience."),
        ("long_video", "512x320", 121, "A small wooden boat crosses a calm lake at sunrise. The camera follows smoothly as ripples spread behind the boat. Birds call softly from the shore."),
    ]
    url = f"http://127.0.0.1:{args.port}"
    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() + 1500
            while True:
                if server.poll() is not None:
                    raise RuntimeError(f"Serving process exited: {server.returncode}")
                try:
                    if requests.get(url + "/health", timeout=5).ok:
                        break
                except requests.RequestException:
                    pass
                if time.monotonic() > deadline:
                    raise TimeoutError("Video serving startup exceeded 1500 seconds")
                time.sleep(2)
            for case, size, frames, prompt in cases:
                if args.case and case not in args.case:
                    continue
                payload = dict(prompt=prompt, size=size, num_frames=frames, fps=24, seed=42,
                    num_outputs_per_prompt=args.num_outputs,
                    num_inference_steps=8, guidance_scale=1.0, enhance_prompt=False,
                    extra_body=dict(use_diffusion_decoder=True))
                suffix = "" if args.num_outputs == 1 else f"_batch{args.num_outputs}"
                receipt = dict(provenance, request_id="ltx25_" + case + suffix, request=payload,
                               requested_outputs=args.num_outputs,
                               capture_steps=[0, 4, 7], started_at=time.time())
                if case == "image_video":
                    if args.reference_image is None:
                        raise ValueError("image_video requires --reference-image from the Qwen Image capture")
                    payload["input_reference"] = str(args.reference_image.resolve())
                    receipt["reference_image_sha256"] = hashlib.sha256(args.reference_image.read_bytes()).hexdigest()
                temporary = request_file.with_suffix(".tmp")
                temporary.write_text(json.dumps(receipt))
                temporary.replace(request_file)
                print("REQUEST", case, size, frames, flush=True)
                response = requests.post(url + "/v1/videos", json=payload, timeout=120)
                receipt["status_code"] = response.status_code
                if not response.ok:
                    receipt["error"] = response.text
                    (results / (case + ".json")).write_text(json.dumps(receipt, indent=2) + "\n")
                response.raise_for_status()
                job = response.json()
                deadline = time.monotonic() + 5400
                while job["status"] not in ("completed", "failed"):
                    if time.monotonic() > deadline:
                        raise TimeoutError("Video generation exceeded 5400 seconds")
                    time.sleep(2)
                    response = requests.get(url + "/v1/videos/" + job["id"], timeout=30)
                    response.raise_for_status()
                    job = response.json()
                receipt.update(response=job, finished_at=time.time())
                if job["status"] == "completed":
                    outputs = []
                    for index in range(job.get("num_outputs") or 1):
                        response = requests.get(url + "/v1/videos/" + job["id"] + "/content",
                                                params={"variant": index}, timeout=120)
                        response.raise_for_status()
                        filename = case + ("" if index == 0 else f"_{index}") + ".mp4"
                        (results / filename).write_bytes(response.content)
                        outputs.append(dict(path=filename, sha256=hashlib.sha256(response.content).hexdigest()))
                    receipt.update(outputs=outputs, actual_outputs=len(outputs))
                (results / (case + ".json")).write_text(json.dumps(receipt, indent=2) + "\n")
                if job["status"] != "completed":
                    raise RuntimeError(f"Video request failed: {job}")
                if receipt["actual_outputs"] != args.num_outputs:
                    raise RuntimeError("Video output count does not match the serving request")
                print("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()