techfreakworm commited on
Commit
45cef14
·
unverified ·
1 Parent(s): a335bfa

test: the real-pipeline tier — every mode through the app's own generate() on a tiny random checkpoint, on the CPU and on MPS

Browse files

The offline suite only ever exercised fakes. It was green at 1102 tests while
five blockers were live. `scripts/local_smoke.py` runs the pinned diffusers
LTX-2.5 classes on optimum-intel-internal-testing/tiny-random-ltx2.5 (~95 MB,
pinned revision, fetched only with --fetch). It goes through `import app`,
`generate()`, the GPU entrypoint and `get_pipeline` on the resolved device:
- every mode, with its required media made on the fly, at <=128 px and <=17 frames;
- the duration head;
- prompt enhancement with the tiny enhancer through the app's own `enhance()`;
- a rank-4 LoRA on the tiny transformer's real attention Linears (12 modules attached);
- stage 2 with tiny random upsampler and decoder models built from the real configs;
- the typed refusal of a too-large stage 2 off CUDA;
- on MPS, the typed self-test refusal under `enforce`.
Each case reports PASS/FAIL, the exception, the artifact and verify_streams'
verdict. The script prints a table, writes JSON, and exits non-zero on any
unexpected result. That includes an EXPECTED_FAILURES entry that starts passing:
the two StageRunner stage-2 bugs left for the next brief are listed by case, so
fixing one without removing its entry turns it red.

Measured today: 18 PASS and 6 expected failures on the CPU (peak RSS 3.3 GB); on
MPS the same plus one recorded skip (peak 6.4 GB). The skip is image-route
enhancement, which crossed 8.6 GB RSS and was killed by the script's own 8 GB
watchdog. Enhancement runs last because its MPS decode leaves memory that
clearing does not return. A snapshot over 1 GB is refused.

`tests/test_real_pipeline_tiny.py` runs it in a subprocess, FULL env only,
skipping when the snapshot is not cached. It covers the 11 modes on the CPU with
streams re-probed per the registry, one MPS mode with the refusal and the
unverified-output warning, and the RoPE parity bound. It takes about 20 s.
`L1=1 scripts/gate.sh` adds the CPU tier to the gate.

scripts/gate.sh CHANGED
@@ -7,6 +7,12 @@
7
  # nothing without them: this suite ran green in torch-less venvs for its whole
8
  # history while failing 34 tests and erroring 20 with requirements.txt
9
  # installed. Run it in the environment README.md's install lines build.
 
 
 
 
 
 
10
  set -u
11
  PYTHON=${PYTHON:-python3}
12
  cd "$(dirname "$0")/.." || exit 2
@@ -29,5 +35,10 @@ else
29
  echo "gate: ruff is not installed here, so lint was NOT checked"
30
  fi
31
 
 
 
 
 
 
32
  if [ "$status" -eq 0 ]; then echo "gate: PASS ($where)"; else echo "gate: FAIL ($where)"; fi
33
  exit "$status"
 
7
  # nothing without them: this suite ran green in torch-less venvs for its whole
8
  # history while failing 34 tests and erroring 20 with requirements.txt
9
  # installed. Run it in the environment README.md's install lines build.
10
+ #
11
+ # L1=1 PYTHON=... scripts/gate.sh
12
+ #
13
+ # also runs the real-pipeline tier on the CPU: every mode through generate() on
14
+ # the tiny random checkpoint (scripts/local_smoke.py; needs torch + diffusers
15
+ # and the ~95 MB checkpoint, fetched once with `local_smoke.py --fetch`).
16
  set -u
17
  PYTHON=${PYTHON:-python3}
18
  cd "$(dirname "$0")/.." || exit 2
 
35
  echo "gate: ruff is not installed here, so lint was NOT checked"
36
  fi
37
 
38
+ if [ "${L1:-0}" = "1" ]; then
39
+ echo "gate: L1 real-pipeline tier (scripts/local_smoke.py --device cpu)"
40
+ "$PYTHON" scripts/local_smoke.py --device cpu || status=1
41
+ fi
42
+
43
  if [ "$status" -eq 0 ]; then echo "gate: PASS ($where)"; else echo "gate: FAIL ($where)"; fi
44
  exit "$status"
scripts/local_smoke.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """The real-pipeline tier ("L1"): every mode through the app's own generate().
3
+
4
+ Runs the pinned diffusers LTX-2.5 pipelines -- real classes, real code paths --
5
+ on a public ~95 MB random-weight checkpoint, on the CPU or on Apple's MPS:
6
+
7
+ python scripts/local_smoke.py --device cpu [--fetch] [--out DIR]
8
+ python scripts/local_smoke.py --device mps --out DIR
9
+ python scripts/local_smoke.py --rope-parity --out DIR
10
+
11
+ It imports ``app`` the way the Space does, so a run goes UI-seam ->
12
+ ``generate()`` -> the ``@spaces.GPU`` entrypoint -> ``pipelines.get_pipeline``
13
+ on the device ``LTX25_DEVICE`` resolves to, with the weights read from
14
+ ``LTX25_MODEL_SNAPSHOT_DIR``. Output quality means nothing here; which code
15
+ paths, ops and dtypes run is the point. Every case reports PASS/FAIL, the
16
+ exception class and first line, the artifact and ``tests/verify_streams.py``'s
17
+ verdict; a table is printed, JSON is written, and the exit code is non-zero on
18
+ any unexpected result -- including an entry of :data:`EXPECTED_FAILURES` that
19
+ now passes, so a fix cannot land without its entry being removed.
20
+
21
+ Safety: tiny sizes only (<= 128 px, <= 17 frames; the CPU stage-2 decoder at 9
22
+ frames), a snapshot larger than 1 GB is refused, and the process kills itself
23
+ past 8 GB of resident memory. ``--fetch`` is the only thing that downloads: the
24
+ tiny checkpoint at its pinned revision and two stage-2 ``config.json`` files.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import os
32
+ import shutil
33
+ import sys
34
+ import tempfile
35
+ import threading
36
+ import time
37
+ import traceback
38
+ import wave
39
+ from pathlib import Path
40
+
41
+ REPO = Path(__file__).resolve().parent.parent
42
+ for _path in (REPO, REPO / "tests"):
43
+ if str(_path) not in sys.path:
44
+ sys.path.insert(0, str(_path))
45
+
46
+ from ltx25_studio import model_files # noqa: E402 - stdlib-only module
47
+
48
+ MAX_SNAPSHOT_BYTES = 1_000_000_000
49
+ RSS_LIMIT_BYTES = 8 * 1024**3
50
+ SIZE, FRAMES = 128, 17
51
+ STAGE_2_SIZE, STAGE_2_FRAMES = 64, 9
52
+ FRAME_RATE = 24.0
53
+ SEED = 1234
54
+ PROMPT = "a red ball bouncing on a wooden floor, with a hollow knock on each bounce"
55
+
56
+ #: Tiny stage-2 models: the real configs with reduced widths and depths. The
57
+ #: stage-1 neighbourhood kernel shrinks (3,7,7)->(3,3,3) because a 128 px output
58
+ #: is a 4x4 latent grid, and stage 5's temporal kernel 11->9 because 9 frames is
59
+ #: what the dense CPU decoder fits.
60
+ TINY_STAGE_2 = {
61
+ "latent_upsampler": {"in_channels": 8, "mid_channels": 32, "num_blocks_per_stage": 1},
62
+ "diffusion_decoder": {
63
+ "latent_channels": 8,
64
+ "decoder_head_dim": 8,
65
+ "decoder_stage_channels": [64, 32, 16, 16, 8],
66
+ "decoder_stage_depths": [1, 1, 1, 1, 1],
67
+ "decoder_t_emb_dim": 32,
68
+ "decoder_stage_kernels": [[3, 3, 3], [3, 7, 7], [3, 5, 5], [3, 5, 5]],
69
+ "decoder_stage5_kernel": [9, 11, 11],
70
+ },
71
+ }
72
+
73
+ #: Known failures that belong to another owner. ``case -> (exception class,
74
+ #: message substring, reason)``. A listed case that passes is an UNEXPECTED
75
+ #: PASS: remove its entry in the same change as the fix.
76
+ _STAGE_2_SIZE_BUG = (
77
+ "DecodeError",
78
+ "expected shape",
79
+ "StageRunner strips height/width for stage 2 and LTX2ConditionPipeline.prepare_latents "
80
+ "sizes its mask from the 512x768 defaults (recon B N1; pipelines.py StageRunner, next brief)",
81
+ )
82
+ EXPECTED_FAILURES: dict[str, tuple[str, str, str]] = {
83
+ "stage2:image_to_video": _STAGE_2_SIZE_BUG,
84
+ "stage2:image_text_to_video": _STAGE_2_SIZE_BUG,
85
+ "stage2:video_to_video": _STAGE_2_SIZE_BUG,
86
+ "stage2:image_to_audio_video": _STAGE_2_SIZE_BUG,
87
+ "stage2:image_text_to_audio_video": _STAGE_2_SIZE_BUG,
88
+ "stage2:audio_to_video": (
89
+ "DecodeError",
90
+ "multiple values for keyword argument",
91
+ "StageRunner forwards the request's noise_scale/audio_latents and stage_2_kwargs adds "
92
+ "them again (probe bug B; pipelines.py StageRunner, next brief)",
93
+ ),
94
+ }
95
+
96
+ #: Cases not run on a device, with the measured reason. Unlike an expected
97
+ #: failure these never execute, so they cannot turn red by themselves.
98
+ SKIP_BY_DEVICE: dict[str, dict[str, str]] = {
99
+ "mps": {
100
+ "enhance:image_text_to_video": (
101
+ "not run on MPS: measured 8.60 GB RSS (watchdog kill) on 2026-11-16 -- the random "
102
+ "tiny enhancer decodes 600 tokens of noise through the image route; the text-only "
103
+ "route passes on MPS and both pass on the CPU"
104
+ ),
105
+ },
106
+ }
107
+
108
+ #: Device-specific known failures, merged over the table above for that device.
109
+ EXPECTED_FAILURES_BY_DEVICE: dict[str, dict[str, tuple[str, str, str]]] = {}
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # safety
114
+ # ---------------------------------------------------------------------------
115
+
116
+
117
+ def start_watchdog() -> dict:
118
+ """Kill this process past 8 GB resident (or 8 GB MPS driver memory)."""
119
+ import psutil
120
+
121
+ peak = {"rss": 0, "mps": 0}
122
+ process = psutil.Process(os.getpid())
123
+
124
+ def watch():
125
+ while True:
126
+ rss = process.memory_info().rss
127
+ mps = 0
128
+ torch = sys.modules.get("torch")
129
+ if torch is not None:
130
+ try:
131
+ if torch.backends.mps.is_available():
132
+ mps = int(torch.mps.driver_allocated_memory())
133
+ except Exception:
134
+ mps = 0
135
+ peak["rss"], peak["mps"] = max(peak["rss"], rss), max(peak["mps"], mps)
136
+ if rss > RSS_LIMIT_BYTES or mps > RSS_LIMIT_BYTES:
137
+ sys.stderr.write(
138
+ f"\nlocal_smoke: RSS {rss / 1e9:.2f} GB / MPS {mps / 1e9:.2f} GB is past the "
139
+ f"8 GB limit; killing this process\n"
140
+ )
141
+ sys.stderr.flush()
142
+ os._exit(99)
143
+ time.sleep(0.2)
144
+
145
+ threading.Thread(target=watch, daemon=True).start()
146
+ return peak
147
+
148
+
149
+ def _tree_bytes(path: Path) -> int:
150
+ total = 0
151
+ for root, _dirs, files in os.walk(path, followlinks=True):
152
+ for name in files:
153
+ total += os.stat(os.path.join(root, name)).st_size
154
+ return total
155
+
156
+
157
+ def tiny_snapshot(*, fetch: bool, explicit: str | None = None) -> Path:
158
+ """The tiny checkpoint's snapshot directory, refusing anything over 1 GB."""
159
+ if explicit:
160
+ path = Path(explicit).resolve()
161
+ else:
162
+ from huggingface_hub import snapshot_download
163
+
164
+ path = Path(
165
+ snapshot_download(
166
+ model_files.TINY_REPO_ID,
167
+ revision=model_files.TINY_REVISION,
168
+ local_files_only=not fetch,
169
+ )
170
+ )
171
+ size = _tree_bytes(path)
172
+ if size > MAX_SNAPSHOT_BYTES:
173
+ raise SystemExit(
174
+ f"local_smoke: {path} holds {size / 1e9:.2f} GB; this tier runs tiny checkpoints "
175
+ f"only (limit {MAX_SNAPSHOT_BYTES / 1e9:.0f} GB). Refusing."
176
+ )
177
+ return path
178
+
179
+
180
+ def _real_config(subfolder: str, *, fetch: bool) -> dict:
181
+ from huggingface_hub import hf_hub_download
182
+
183
+ path = hf_hub_download(
184
+ model_files.REPO_ID,
185
+ f"{subfolder}/config.json",
186
+ revision=model_files.REVISION,
187
+ local_files_only=not fetch,
188
+ )
189
+ return {k: v for k, v in json.loads(Path(path).read_text()).items() if not k.startswith("_")}
190
+
191
+
192
+ def composite_snapshot(tiny: Path, into: Path, *, fetch: bool) -> tuple[Path, str | None]:
193
+ """Tiny base (symlinked) plus tiny random stage-2 models built from real configs.
194
+
195
+ Returns ``(path, why stage 2 is unavailable or None)``.
196
+ """
197
+ import torch
198
+ from diffusers import LTX2VideoDiffusionDecoderModel
199
+ from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
200
+
201
+ into.mkdir(parents=True, exist_ok=True)
202
+ for child in tiny.iterdir():
203
+ (into / child.name).symlink_to(child.resolve() if child.is_file() else child)
204
+ try:
205
+ configs = {sub: _real_config(sub, fetch=fetch) for sub in TINY_STAGE_2}
206
+ except Exception as exc: # noqa: BLE001 - offline without the configs
207
+ return (
208
+ into,
209
+ f"the real stage-2 configs are not cached ({exc.__class__.__name__}); rerun with --fetch",
210
+ )
211
+ torch.manual_seed(0)
212
+ for sub, cls in (
213
+ ("latent_upsampler", LTX2LatentUpsamplerModel),
214
+ ("diffusion_decoder", LTX2VideoDiffusionDecoderModel),
215
+ ):
216
+ model = cls.from_config({**configs[sub], **TINY_STAGE_2[sub]}).to(torch.bfloat16)
217
+ model.save_pretrained(into / sub, safe_serialization=True)
218
+ return into, None
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # media, generated on the fly
223
+ # ---------------------------------------------------------------------------
224
+
225
+
226
+ def make_image(size: int):
227
+ """A PIL image, as the UI's ``gr.Image(type="pil")`` hands one over."""
228
+ import numpy as np
229
+ import PIL.Image
230
+
231
+ rng = np.random.default_rng(0)
232
+ pixels = (rng.random((size, size, 3)) * 255).astype("uint8")
233
+ pixels[size // 4 : size // 2, size // 4 : size // 2] = [220, 30, 30]
234
+ return PIL.Image.fromarray(pixels)
235
+
236
+
237
+ def make_video(path: Path, size: int, frames: int) -> str:
238
+ import av
239
+ import numpy as np
240
+
241
+ with av.open(str(path), "w") as container:
242
+ stream = container.add_stream("libx264", rate=int(FRAME_RATE))
243
+ stream.width = stream.height = size
244
+ stream.pix_fmt = "yuv420p"
245
+ for index in range(frames):
246
+ pixels = np.full((size, size, 3), 40, dtype="uint8")
247
+ x = (8 + index * 6) % (size - 24)
248
+ pixels[size // 3 : size // 3 + 24, x : x + 24] = [30, 200, 60]
249
+ for packet in stream.encode(av.VideoFrame.from_ndarray(pixels, format="rgb24")):
250
+ container.mux(packet)
251
+ for packet in stream.encode(None):
252
+ container.mux(packet)
253
+ return str(path)
254
+
255
+
256
+ def make_audio(path: Path, frames: int, rate: int = 48000) -> str:
257
+ import numpy as np
258
+
259
+ count = round(frames / FRAME_RATE * rate)
260
+ t = np.arange(count) / rate
261
+ stereo = np.stack([0.4 * np.sin(2 * np.pi * 440 * t), 0.4 * np.sin(2 * np.pi * 660 * t)], 1)
262
+ with wave.open(str(path), "wb") as handle:
263
+ handle.setnchannels(2)
264
+ handle.setsampwidth(2)
265
+ handle.setframerate(rate)
266
+ handle.writeframes((stereo * 32767).astype("<i2").tobytes())
267
+ return str(path)
268
+
269
+
270
+ def make_lora(path: Path, transformer, rank: int = 4) -> int:
271
+ """A rank-4 adapter on the tiny transformer's real attention Linears."""
272
+ import torch
273
+ from safetensors.torch import save_file
274
+
275
+ generator = torch.Generator().manual_seed(3)
276
+ tensors = {}
277
+ for name, module in transformer.named_modules():
278
+ if not isinstance(module, torch.nn.Linear):
279
+ continue
280
+ if not any(name.endswith(suffix) for suffix in ("attn1.to_q", "attn1.to_k", "attn1.to_v")):
281
+ continue
282
+ down = torch.randn(rank, module.in_features, generator=generator) * 0.01
283
+ up = torch.randn(module.out_features, rank, generator=generator) * 0.01
284
+ tensors[f"diffusion_model.{name}.lora_A.weight"] = down.contiguous()
285
+ tensors[f"diffusion_model.{name}.lora_B.weight"] = up.contiguous()
286
+ metadata = {"model_version": "2.5.0", "lora_rank": str(rank), "lora_alpha": str(rank)}
287
+ save_file(tensors, str(path), metadata=metadata)
288
+ return len(tensors) // 2
289
+
290
+
291
+ # ---------------------------------------------------------------------------
292
+ # cases
293
+ # ---------------------------------------------------------------------------
294
+
295
+
296
+ def _media_for(mode_id: str, media: Path, size: int, frames: int) -> dict:
297
+ from ltx25_studio import modes
298
+
299
+ fields: dict = {}
300
+ for kind in modes.get_mode(mode_id).inputs:
301
+ if kind == "text":
302
+ fields["prompt"] = PROMPT
303
+ elif kind == "image":
304
+ fields["image"] = make_image(size)
305
+ elif kind == "video":
306
+ fields["video"] = make_video(media / f"video_{size}_{frames}.mp4", size, frames)
307
+ elif kind == "audio":
308
+ fields["audio"] = make_audio(media / f"audio_{frames}.wav", frames)
309
+ return fields
310
+
311
+
312
+ def build_cases(device: str, media: Path, stage_2_ready: str | None) -> list[dict]:
313
+ """``{"id", "mode", "request", "expect_error"?, "env"?, "skip"?}`` per case."""
314
+ from ltx25_studio import modes
315
+
316
+ cases = []
317
+ for mode_id in modes.MODES:
318
+ request = dict(
319
+ mode=mode_id,
320
+ seed=SEED,
321
+ width=SIZE,
322
+ height=SIZE,
323
+ num_frames=FRAMES,
324
+ frame_rate=FRAME_RATE,
325
+ **_media_for(mode_id, media, SIZE, FRAMES),
326
+ )
327
+ cases.append({"id": f"mode:{mode_id}", "mode": mode_id, "request": request})
328
+ cases.append(
329
+ {
330
+ "id": "duration_head:text_to_audio_video",
331
+ "mode": "text_to_audio_video",
332
+ "request": dict(
333
+ mode="text_to_audio_video",
334
+ seed=SEED,
335
+ width=SIZE,
336
+ height=SIZE,
337
+ frame_rate=FRAME_RATE,
338
+ prompt=PROMPT,
339
+ auto_duration=True,
340
+ min_seconds=0.3,
341
+ max_seconds=0.7,
342
+ ),
343
+ }
344
+ )
345
+ cases.append(
346
+ {
347
+ "id": "lora:text_to_video",
348
+ "mode": "text_to_video",
349
+ "lora": True,
350
+ "request": dict(
351
+ mode="text_to_video",
352
+ seed=SEED,
353
+ width=SIZE,
354
+ height=SIZE,
355
+ num_frames=FRAMES,
356
+ frame_rate=FRAME_RATE,
357
+ prompt=PROMPT,
358
+ ),
359
+ }
360
+ )
361
+ for mode_id in modes.MODES:
362
+ if modes.get_mode(mode_id).skip_stage_2:
363
+ continue
364
+ case = {
365
+ "id": f"stage2:{mode_id}",
366
+ "mode": mode_id,
367
+ "stage_2": True,
368
+ "request": dict(
369
+ mode=mode_id,
370
+ seed=SEED,
371
+ width=STAGE_2_SIZE,
372
+ height=STAGE_2_SIZE,
373
+ num_frames=STAGE_2_FRAMES,
374
+ frame_rate=FRAME_RATE,
375
+ enable_stage_2=True,
376
+ **_media_for(mode_id, media, STAGE_2_SIZE, STAGE_2_FRAMES),
377
+ ),
378
+ }
379
+ if stage_2_ready is not None:
380
+ case["skip"] = stage_2_ready
381
+ cases.append(case)
382
+ # Off CUDA a stage-2 request above the CPU decoder's limit is refused, typed.
383
+ cases.append(
384
+ {
385
+ "id": "stage2_too_large:text_to_video",
386
+ "mode": "text_to_video",
387
+ "expect_error": "StageTwoNeedsCudaError",
388
+ "request": dict(
389
+ mode="text_to_video",
390
+ seed=SEED,
391
+ width=SIZE,
392
+ height=SIZE,
393
+ num_frames=FRAMES,
394
+ frame_rate=FRAME_RATE,
395
+ prompt=PROMPT,
396
+ enable_stage_2=True,
397
+ ),
398
+ }
399
+ )
400
+ # Last: on MPS the random tiny enhancer's 600-token decode leaves resident
401
+ # memory behind (0.89 -> 6.06 GB RSS measured, not returned by clearing the
402
+ # enhancer or the MPS cache), which stacked under stage 2 crossed 8 GB.
403
+ for mode_id in ("text_to_video", "image_text_to_video"):
404
+ cases.append(
405
+ {
406
+ "id": f"enhance:{mode_id}",
407
+ "mode": mode_id,
408
+ "enhance": True,
409
+ "request": dict(
410
+ mode=mode_id,
411
+ seed=SEED,
412
+ width=SIZE,
413
+ height=SIZE,
414
+ num_frames=FRAMES,
415
+ frame_rate=FRAME_RATE,
416
+ enhance_prompt=True,
417
+ **_media_for(mode_id, media, SIZE, FRAMES),
418
+ ),
419
+ }
420
+ )
421
+ for case in cases:
422
+ reason = SKIP_BY_DEVICE.get(device, {}).get(case["id"])
423
+ if reason:
424
+ case["skip"] = reason
425
+ return cases
426
+
427
+
428
+ def _first_line(exc: BaseException) -> str:
429
+ text = str(exc).strip()
430
+ return text.splitlines()[0][:300] if text else repr(exc)
431
+
432
+
433
+ def classify(case_id: str, error: BaseException | None, streams_ok: bool | None, expected) -> str:
434
+ entry = expected.get(case_id)
435
+ if entry is None:
436
+ return "PASS" if error is None and streams_ok is not False else "FAIL"
437
+ cls, needle, _reason = entry
438
+ if error is None:
439
+ return "XPASS"
440
+ if type(error).__name__ == cls and needle in str(error):
441
+ return "XFAIL"
442
+ return "FAIL"
443
+
444
+
445
+ def _flush(out: Path, device: str, rows) -> None:
446
+ """Rows so far, so a watchdog kill still leaves a readable record."""
447
+ (out / f"local_smoke_{device}.partial.json").write_text(json.dumps(rows, indent=2, default=str))
448
+
449
+
450
+ def run_cases(cases, *, device: str, out: Path, expected) -> list[dict]:
451
+ from verify_streams import verify
452
+
453
+ from ltx25_studio import enhance, generate, pipelines
454
+ from ltx25_studio.lora import apply as lora_apply
455
+ from ltx25_studio.lora import validate_lora
456
+
457
+ base = pipelines._CACHE["__base__"]
458
+ rate = int(base.vocoder.config.output_sampling_rate)
459
+ attached: list[int] = []
460
+ real_apply = lora_apply.apply_lora
461
+
462
+ def counting_apply(*args, **kwargs):
463
+ report = real_apply(*args, **kwargs)
464
+ attached.append(report.attached)
465
+ return report
466
+
467
+ def tiny_enhancer(prompt, image=None):
468
+ return enhance.enhance(
469
+ prompt,
470
+ image=image,
471
+ repo_id="tiny-local",
472
+ loader=lambda repo_id: (base.prompt_enhancer, base.processor),
473
+ )
474
+
475
+ rows = []
476
+ for case in cases:
477
+ row = {"case": case["id"], "mode": case["mode"], "device": device}
478
+ if case.get("skip"):
479
+ row.update(outcome="SKIP", error=case["skip"])
480
+ rows.append(row)
481
+ continue
482
+ request = dict(case["request"])
483
+ seams: dict = {"output_root": str(out / "outputs")}
484
+ if case.get("enhance"):
485
+ enhance.clear_enhancer_cache()
486
+ seams["enhancer"] = tiny_enhancer
487
+ if case.get("lora"):
488
+ adapter = out / "media" / "tiny_rank4.safetensors"
489
+ row["lora_pairs"] = make_lora(adapter, base.transformer)
490
+ report = validate_lora(str(adapter), transformer=base.transformer, manifest=None)
491
+ request["loras"] = ({"source": str(adapter), "weight": 1.0, "report": report},)
492
+ attached.clear()
493
+ lora_apply.apply_lora = counting_apply
494
+ print(f"... {case['id']} (RSS {_rss() / 1e9:.2f} GB)", flush=True)
495
+ started = time.perf_counter()
496
+ error = None
497
+ result = None
498
+ try:
499
+ result = generate.generate(**request, **seams)
500
+ except Exception as exc: # noqa: BLE001 - every failure is a row, not a crash
501
+ error = exc
502
+ row["traceback"] = traceback.format_exc(limit=6)[-1500:]
503
+ finally:
504
+ lora_apply.apply_lora = real_apply
505
+ row["seconds"] = round(time.perf_counter() - started, 2)
506
+ row["rss_gb_after"] = round(_rss() / 1e9, 2)
507
+ if case.get("lora"):
508
+ row["lora_attached_modules"] = sum(attached)
509
+ streams_ok = None
510
+ if result is not None:
511
+ row["artifact"] = str(result.output_path)
512
+ scale = 2 if case.get("stage_2") else 1
513
+ geometry = (
514
+ (request["width"] * scale, request["height"] * scale)
515
+ if "video" in _exports(case["mode"])
516
+ else None
517
+ )
518
+ verdict = verify(
519
+ case["mode"],
520
+ result.output_path,
521
+ frame_rate=FRAME_RATE,
522
+ sampling_rate=rate,
523
+ geometry=geometry,
524
+ )
525
+ streams_ok = verdict.ok
526
+ row["streams"] = "MATCHES" if verdict.ok else "; ".join(verdict.problems)
527
+ row["streams_actual"] = verdict.actual
528
+ row["warnings"] = list(result.warnings)
529
+ if case.get("lora") and not sum(attached):
530
+ streams_ok = False
531
+ row["streams"] = "the adapter attached to 0 modules"
532
+ if case.get("expect_error"):
533
+ ok = error is not None and type(error).__name__ == case["expect_error"]
534
+ row["outcome"] = "PASS" if ok else "FAIL"
535
+ row["expected_error"] = case["expect_error"]
536
+ else:
537
+ row["outcome"] = classify(case["id"], error, streams_ok, expected)
538
+ if error is not None:
539
+ row["error_type"] = type(error).__name__
540
+ row["error"] = _first_line(error)
541
+ if case["id"] in expected:
542
+ row["expected_failure_reason"] = expected[case["id"]][2]
543
+ rows.append(row)
544
+ _flush(out, device, rows)
545
+ print(
546
+ f"[{row['outcome']:5}] {row['case']:40} {row['seconds']:6.2f}s "
547
+ f"{row.get('error_type', '')} {row.get('error', '')[:100]}",
548
+ flush=True,
549
+ )
550
+ return rows
551
+
552
+
553
+ def _rss() -> int:
554
+ import psutil
555
+
556
+ return psutil.Process(os.getpid()).memory_info().rss
557
+
558
+
559
+ def _exports(mode_id: str):
560
+ from ltx25_studio import modes
561
+
562
+ return modes.get_mode(mode_id).exports
563
+
564
+
565
+ def print_table(rows) -> None:
566
+ print()
567
+ print(f"{'outcome':7} {'case':40} {'streams':10} exception / artifact")
568
+ for row in rows:
569
+ detail = (
570
+ f"{row.get('error_type')}: {row.get('error', '')[:90]}"
571
+ if row.get("error_type")
572
+ else row.get("artifact", row.get("error", ""))
573
+ )
574
+ streams = (
575
+ "-" if "streams" not in row else ("ok" if row["streams"] == "MATCHES" else "MISMATCH")
576
+ )
577
+ print(f"{row['outcome']:7} {row['case']:40} {streams:10} {detail}")
578
+
579
+
580
+ # ---------------------------------------------------------------------------
581
+ # the RoPE parity measurement (one transformer forward)
582
+ # ---------------------------------------------------------------------------
583
+
584
+
585
+ def rope_parity(snapshot: Path) -> dict:
586
+ """cpu/fp32 with float64 RoPE (reference) vs MPS with the app's handling."""
587
+ import torch
588
+ from diffusers import LTX2VideoTransformer3DModel
589
+
590
+ from ltx25_studio import device as device_module
591
+
592
+ def load():
593
+ return LTX2VideoTransformer3DModel.from_pretrained(
594
+ str(snapshot), subfolder="transformer", dtype=torch.float32
595
+ ).eval()
596
+
597
+ config = load().config
598
+ generator = torch.Generator().manual_seed(0)
599
+ frames, height, width, audio_frames, text = 3, 4, 4, 18, 16
600
+ inputs = {
601
+ "hidden_states": torch.randn(
602
+ 1, frames * height * width, config.in_channels, generator=generator
603
+ ),
604
+ "audio_hidden_states": torch.randn(
605
+ 1, audio_frames, config.audio_in_channels, generator=generator
606
+ ),
607
+ "encoder_hidden_states": torch.randn(1, text, config.caption_channels, generator=generator),
608
+ "audio_encoder_hidden_states": torch.randn(
609
+ 1, text, config.caption_channels, generator=generator
610
+ ),
611
+ "timestep": torch.tensor([990.0]),
612
+ "sigma": torch.tensor([0.99]),
613
+ "encoder_attention_mask": torch.ones(1, text),
614
+ "audio_encoder_attention_mask": torch.ones(1, text),
615
+ }
616
+ fixed = {
617
+ "num_frames": frames,
618
+ "height": height,
619
+ "width": width,
620
+ "fps": FRAME_RATE,
621
+ "audio_num_frames": audio_frames,
622
+ "use_cross_timestep": True,
623
+ "return_dict": False,
624
+ }
625
+
626
+ def forward(model, where):
627
+ with torch.no_grad():
628
+ out = model.to(where)(**{k: v.to(where) for k, v in inputs.items()}, **fixed)
629
+ return [tensor.float().cpu() for tensor in out]
630
+
631
+ def flip(model):
632
+ for module in model.modules():
633
+ if hasattr(module, "double_precision"):
634
+ module.double_precision = False
635
+ return model
636
+
637
+ reference = forward(load(), "cpu")
638
+ candidates = {
639
+ "mps fp32, RoPE on the CPU in float64 (shipped handling)": None,
640
+ "cpu fp32, RoPE in float32 (cost of the flag alone)": lambda: forward(flip(load()), "cpu"),
641
+ "mps fp32, RoPE in float32 on MPS (the double_precision=False alternative)": (
642
+ lambda: forward(flip(load()), "mps")
643
+ ),
644
+ }
645
+
646
+ def handled():
647
+ model = load()
648
+ device_module.compute_rope_on_cpu(("transformer", model))
649
+ return forward(model, "mps")
650
+
651
+ candidates["mps fp32, RoPE on the CPU in float64 (shipped handling)"] = handled
652
+ rows = {}
653
+ for label, run in candidates.items():
654
+ outputs = run()
655
+ rows[label] = {
656
+ name: {
657
+ "max_abs": float((got - ref).abs().max()),
658
+ "mean_abs": float((got - ref).abs().mean()),
659
+ "ref_abs_max": float(ref.abs().max()),
660
+ }
661
+ for name, got, ref in zip(("video", "audio"), outputs, reference, strict=True)
662
+ }
663
+ return {
664
+ "torch": torch.__version__,
665
+ "inputs": "one transformer forward, seed 0, 3x4x4 latents",
666
+ "results": rows,
667
+ }
668
+
669
+
670
+ # ---------------------------------------------------------------------------
671
+ # main
672
+ # ---------------------------------------------------------------------------
673
+
674
+
675
+ def _environment(args, composite: Path, out: Path) -> None:
676
+ os.environ["LTX25_DEVICE"] = args.device
677
+ os.environ["LTX25_MODEL_SNAPSHOT_DIR"] = str(composite)
678
+ os.environ["LTX25_CPU_DTYPE"] = args.cpu_dtype
679
+ os.environ["LTX25_OUTPUT_DIR"] = str(out / "outputs")
680
+ os.environ["LTX25_PREFETCH_ENHANCER"] = "0"
681
+ os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
682
+ if not args.fetch:
683
+ os.environ["HF_HUB_OFFLINE"] = "1"
684
+
685
+
686
+ def main(argv=None) -> int:
687
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
688
+ parser.add_argument("--device", choices=("cpu", "mps"), default="cpu")
689
+ parser.add_argument("--cpu-dtype", choices=("fp32", "bf16"), default="fp32")
690
+ parser.add_argument(
691
+ "--fetch", action="store_true", help="download the tiny checkpoint (~95 MB)"
692
+ )
693
+ parser.add_argument("--snapshot", help="a local tiny snapshot instead of the HF cache")
694
+ parser.add_argument("--out", default=None, help="directory for JSON, media and outputs")
695
+ parser.add_argument("--only", default="", help="comma-separated case-id prefixes")
696
+ parser.add_argument("--rope-parity", action="store_true", help="measure RoPE parity only")
697
+ args = parser.parse_args(argv)
698
+
699
+ out = Path(args.out or tempfile.mkdtemp(prefix="ltx25_smoke_")).resolve()
700
+ (out / "media").mkdir(parents=True, exist_ok=True)
701
+ peak = start_watchdog()
702
+ tiny = tiny_snapshot(fetch=args.fetch, explicit=args.snapshot)
703
+
704
+ if args.rope_parity:
705
+ parity = rope_parity(tiny)
706
+ (out / "rope_parity.json").write_text(json.dumps(parity, indent=2))
707
+ print(json.dumps(parity, indent=2))
708
+ return 0
709
+
710
+ work = Path(tempfile.mkdtemp(prefix="ltx25_composite_"))
711
+ try:
712
+ composite, stage_2_missing = composite_snapshot(tiny, work / "snapshot", fetch=args.fetch)
713
+ _environment(args, composite, out)
714
+ return _run(args, out, composite, stage_2_missing, peak)
715
+ finally:
716
+ shutil.rmtree(work, ignore_errors=True)
717
+
718
+
719
+ def _run(args, out: Path, composite: Path, stage_2_missing, peak) -> int:
720
+ import importlib
721
+
722
+ from ltx25_studio import modes
723
+
724
+ # Tiny tier: the 256 px render of the audio-only modes is held to <= 128 px.
725
+ modes.MIN_RESOLUTION = SIZE
726
+ expected = {**EXPECTED_FAILURES, **EXPECTED_FAILURES_BY_DEVICE.get(args.device, {})}
727
+ rows: list[dict] = []
728
+
729
+ from ltx25_studio import device as device_module
730
+ from ltx25_studio import generate, pipelines
731
+
732
+ if args.device == "mps":
733
+ # Under the default (enforce), a failed self-test must refuse, typed.
734
+ os.environ["LTX25_MPS_SELF_TEST"] = "enforce"
735
+ self_test = device_module.mps_self_test()
736
+ app = importlib.import_module("app")
737
+ meta = {
738
+ "device": app.DEVICE.describe(),
739
+ "precision": pipelines.precision_summary(app.DEVICE),
740
+ "snapshot": str(composite),
741
+ "stage_2_models": stage_2_missing or "tiny random, built from the real configs",
742
+ }
743
+ if args.device == "mps":
744
+ meta["mps_self_test"] = self_test.describe()
745
+ row = {"case": "mps_self_test:enforce", "mode": "text_to_video", "device": "mps"}
746
+ if self_test.ok:
747
+ row.update(outcome="SKIP", error="the self-test passed; there is nothing to refuse")
748
+ else:
749
+ try:
750
+ generate.generate(
751
+ mode="text_to_video",
752
+ seed=SEED,
753
+ width=SIZE,
754
+ height=SIZE,
755
+ num_frames=FRAMES,
756
+ prompt=PROMPT,
757
+ )
758
+ row.update(outcome="FAIL", error="a failed self-test did not refuse generation")
759
+ except device_module.MpsNumericsError as exc:
760
+ row.update(
761
+ outcome="PASS",
762
+ error_type=type(exc).__name__,
763
+ error=_first_line(exc),
764
+ expected_error="MpsNumericsError",
765
+ )
766
+ rows.append(row)
767
+ print(f"[{row['outcome']:5}] {row['case']}: {row.get('error', '')[:120]}")
768
+ # The rest exercises the MPS path itself, with the failure acknowledged.
769
+ os.environ["LTX25_MPS_SELF_TEST"] = "warn"
770
+
771
+ for kind in ("condition", "text2video"):
772
+ pipelines.get_pipeline(pipeline=kind)
773
+ base = pipelines._CACHE["__base__"]
774
+ meta["audio_vae_shim"] = _install_tiny_audio_vae_shim(base.audio_vae)
775
+
776
+ cases = build_cases(args.device, out / "media", stage_2_missing)
777
+ if args.only:
778
+ prefixes = tuple(p.strip() for p in args.only.split(",") if p.strip())
779
+ cases = [case for case in cases if case["id"].startswith(prefixes)]
780
+ rows += run_cases(cases, device=args.device, out=out, expected=expected)
781
+
782
+ meta.update(
783
+ _versions(),
784
+ peak_rss_gb=round(peak["rss"] / 1e9, 2),
785
+ peak_mps_driver_gb=round(peak["mps"] / 1e9, 2),
786
+ )
787
+ unexpected = [row["case"] for row in rows if row["outcome"] in ("FAIL", "XPASS")]
788
+ payload = {
789
+ "meta": meta,
790
+ "expected_failures": {k: v[2] for k, v in expected.items()},
791
+ "unexpected": unexpected,
792
+ "cases": rows,
793
+ }
794
+ target = out / f"local_smoke_{args.device}.json"
795
+ target.write_text(json.dumps(payload, indent=2, default=str))
796
+ (out / f"local_smoke_{args.device}.partial.json").unlink(missing_ok=True)
797
+ print_table(rows)
798
+ counts = {
799
+ o: sum(r["outcome"] == o for r in rows) for o in ("PASS", "XFAIL", "SKIP", "FAIL", "XPASS")
800
+ }
801
+ print(f"\n{counts} -> {target}")
802
+ if unexpected:
803
+ print(f"UNEXPECTED: {unexpected}")
804
+ return 1 if unexpected else 0
805
+
806
+
807
+ def _install_tiny_audio_vae_shim(audio_vae) -> str:
808
+ """Tiny-checkpoint artifact, not an app fix: its audio VAE has ``ch_mult=[1]``.
809
+
810
+ So its encoder does not downsample while the class assumes 4x4. The posterior
811
+ is average-pooled 4x4 to the shape the real VAE produces; everything after it
812
+ is real code.
813
+ """
814
+ import torch.nn.functional as functional
815
+ from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
816
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
817
+
818
+ if getattr(audio_vae, "_tiny_shim", False):
819
+ return "already installed"
820
+ original = audio_vae.encode
821
+
822
+ def encode(x, return_dict=True):
823
+ params = original(x, return_dict=True).latent_dist.parameters
824
+ pooled = functional.avg_pool2d(params.float(), kernel_size=4, ceil_mode=True)
825
+ dist = DiagonalGaussianDistribution(pooled.to(params.dtype))
826
+ return AutoencoderKLOutput(latent_dist=dist) if return_dict else (dist,)
827
+
828
+ audio_vae.encode = encode
829
+ audio_vae._tiny_shim = True
830
+ return "audio_vae.encode posterior avg-pooled 4x4 (tiny ch_mult=[1] artifact)"
831
+
832
+
833
+ def _versions() -> dict:
834
+ import diffusers
835
+ import torch
836
+
837
+ return {
838
+ "torch": torch.__version__,
839
+ "diffusers": diffusers.__version__,
840
+ "python": sys.version.split()[0],
841
+ }
842
+
843
+
844
+ if __name__ == "__main__":
845
+ sys.exit(main())
tests/test_real_pipeline_tiny.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The real-pipeline tier: the pinned diffusers pipelines, not fakes.
2
+
3
+ The offline suite was green at 1102 tests while five blockers were live,
4
+ because it only ever exercised fakes. These specs run the real LTX-2.5 classes
5
+ on a public ~95 MB random-weight checkpoint through the app's own
6
+ ``generate()`` -- the seam the UI uses -- via ``scripts/local_smoke.py`` in a
7
+ subprocess, so this process's state (the cached pipeline, the GPU dispatch, the
8
+ environment) is untouched.
9
+
10
+ FULL env only. Skips, with the reason, when the tiny snapshot is not in the HF
11
+ cache: tests never download (``python scripts/local_smoke.py --fetch`` does).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import subprocess
19
+ import sys
20
+
21
+ import pytest
22
+ from conftest import REPO_ROOT
23
+
24
+ pytest.importorskip("torch")
25
+ pytest.importorskip("diffusers")
26
+
27
+ from ltx25_studio import model_files, modes # noqa: E402
28
+
29
+ SMOKE = REPO_ROOT / "scripts" / "local_smoke.py"
30
+
31
+
32
+ def _tiny_snapshot_cached() -> bool:
33
+ try:
34
+ from huggingface_hub import snapshot_download
35
+
36
+ snapshot_download(
37
+ model_files.TINY_REPO_ID, revision=model_files.TINY_REVISION, local_files_only=True
38
+ )
39
+ except Exception:
40
+ return False
41
+ return True
42
+
43
+
44
+ pytestmark = pytest.mark.skipif(
45
+ not _tiny_snapshot_cached(),
46
+ reason=(
47
+ f"{model_files.TINY_REPO_ID}@{model_files.TINY_REVISION[:8]} is not in the HF cache; "
48
+ f"run `python scripts/local_smoke.py --fetch` once (about 95 MB)"
49
+ ),
50
+ )
51
+
52
+
53
+ def _smoke(tmp_path, *args) -> dict:
54
+ env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "HF_HUB_OFFLINE": "1"}
55
+ finished = subprocess.run(
56
+ [sys.executable, str(SMOKE), *args, "--out", str(tmp_path)],
57
+ cwd=str(REPO_ROOT),
58
+ env=env,
59
+ capture_output=True,
60
+ text=True,
61
+ timeout=300,
62
+ )
63
+ names = ("local_smoke_cpu.json", "local_smoke_mps.json", "rope_parity.json")
64
+ reports = [tmp_path / name for name in names if (tmp_path / name).is_file()]
65
+ assert reports, (
66
+ f"local_smoke wrote no report (exit {finished.returncode}):\n"
67
+ f"{finished.stdout[-2000:]}\n{finished.stderr[-3000:]}"
68
+ )
69
+ payload = json.loads(reports[0].read_text())
70
+ payload["_exit"] = finished.returncode
71
+ payload["_stdout"] = finished.stdout[-3000:]
72
+ return payload
73
+
74
+
75
+ @pytest.fixture(scope="module")
76
+ def cpu_modes(tmp_path_factory):
77
+ return _smoke(tmp_path_factory.mktemp("cpu"), "--device", "cpu", "--only", "mode:")
78
+
79
+
80
+ def test_every_mode_runs_on_the_cpu_through_generate(cpu_modes):
81
+ rows = {row["mode"]: row for row in cpu_modes["cases"]}
82
+
83
+ assert set(rows) == set(modes.MODES), sorted(set(modes.MODES) ^ set(rows))
84
+ failed = {
85
+ m: (r.get("error_type"), r.get("error")) for m, r in rows.items() if r["outcome"] != "PASS"
86
+ }
87
+ assert not failed, failed
88
+ assert cpu_modes["_exit"] == 0, cpu_modes["_stdout"]
89
+
90
+
91
+ @pytest.mark.parametrize("mode_id", list(modes.MODES))
92
+ def test_each_artifact_carries_the_streams_its_mode_declares(cpu_modes, mode_id):
93
+ """Re-probed here, independently of the script's own verdict."""
94
+ from verify_streams import expected_streams, probe_streams
95
+
96
+ row = next(row for row in cpu_modes["cases"] if row["mode"] == mode_id)
97
+ actual = probe_streams(row["artifact"])
98
+ expected = expected_streams(mode_id)
99
+
100
+ assert actual is not None, f"{row['artifact']} could not be opened"
101
+ assert actual["video"] == expected["video"] and actual["audio"] == expected["audio"], (
102
+ mode_id,
103
+ actual,
104
+ )
105
+ if expected["audio"]:
106
+ assert actual["audio_channels"] == 2 and actual["sampling_rate"] == 48000, actual
107
+ if expected["video"]:
108
+ assert (actual["width"], actual["height"]) == (128, 128), actual
109
+
110
+
111
+ def test_the_cpu_run_used_the_resolved_device(cpu_modes):
112
+ assert cpu_modes["meta"]["device"].startswith("cpu"), cpu_modes["meta"]
113
+
114
+
115
+ def test_one_mode_runs_on_mps(tmp_path):
116
+ torch = pytest.importorskip("torch")
117
+ if not torch.backends.mps.is_available():
118
+ pytest.skip("no MPS device on this machine")
119
+
120
+ payload = _smoke(tmp_path, "--device", "mps", "--only", "mode:text_to_audio_video")
121
+
122
+ rows = {row["case"]: row for row in payload["cases"]}
123
+ assert rows["mode:text_to_audio_video"]["outcome"] == "PASS", rows
124
+ assert rows["mode:text_to_audio_video"]["streams"] == "MATCHES", rows
125
+ refusal = rows["mps_self_test:enforce"]
126
+ if "FAILED" in payload["meta"]["mps_self_test"]:
127
+ assert refusal["outcome"] == "PASS" and refusal["error_type"] == "MpsNumericsError", refusal
128
+ notes = rows["mode:text_to_audio_video"]["warnings"]
129
+ assert any("Unverified" in note for note in notes), (
130
+ f"under LTX25_MPS_SELF_TEST=warn every result must carry the warning: {notes}"
131
+ )
132
+ assert payload["_exit"] == 0, payload["_stdout"]
133
+
134
+
135
+ def test_the_rope_handling_matches_the_float64_cpu_reference(tmp_path):
136
+ """One transformer forward: cpu/fp32 with float64 RoPE vs MPS with ours.
137
+
138
+ The bound is relative to the output's own magnitude: fp32 MPS kernels
139
+ measured ~6e-5 relative per transformer call in the probe.
140
+ """
141
+ torch = pytest.importorskip("torch")
142
+ if not torch.backends.mps.is_available():
143
+ pytest.skip("no MPS device on this machine")
144
+
145
+ payload = _smoke(tmp_path, "--rope-parity")
146
+
147
+ shipped = next(v for k, v in payload["results"].items() if "shipped" in k)
148
+ for stream, numbers in shipped.items():
149
+ relative = numbers["max_abs"] / numbers["ref_abs_max"]
150
+ assert relative < 1e-3, (stream, numbers)