Spaces:
Running on Zero
fix: an explicit diffusion decode, or stage 2, that the decoder cannot take is refused before dispatch
Browse filesBoth facts are known before a GPU is reserved: the decoder's minimum size (read
from its config file, the same one the run will load) and, off CUDA, the size
its CPU path can hold. prepare_request now checks them, so the user is told
"refused before running, nothing was billed" (gpu_used False) and the UI's
readiness check can disable Generate with the reason. auto is never refused; it
falls back to conv with a note as before. The runner keeps the same checks
against the loaded decoder; the two share pipelines.check_decoder_minimum and
pipelines.check_cpu_decoder_size.
The tiny stack used by the real-pipeline tests now has its own composite
snapshot, and its runs point LTX25_MODEL_SNAPSHOT_DIR at it, so the gate reads
the tiny decoder's config rather than whatever real checkpoint the HF cache
holds.
Files changed (5)
614 unmodified lines615616617618619620621622623614 unmodified lines_checked_conditions(request, spec)_checked_lora_files(request)_checked_stage_2_size(request, spec)return request, spec, scope_notes + length_notesdef _checked_stage_2_size(request: GenerationRequest, spec) -> None:"""A stage-2 request this device cannot decode is refused before dispatch (no-op on CUDA)."""if not stage_2_enabled(spec, request):614 unmodified lines615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661614 unmodified lines_checked_conditions(request, spec)_checked_lora_files(request)_checked_stage_2_size(request, spec)_checked_decoder(request, spec)return request, spec, scope_notes + length_notesdef _checked_decoder(request: GenerationRequest, spec) -> None:"""An explicit diffusion decode, or stage 2, the decoder could not take: refused now.Below the decoder's minimum, or off CUDA beyond what its CPU path can hold.``auto`` is never refused (it falls back to conv with a note)."""stage_2 = stage_2_enabled(spec, request)explicit = decoder_policy(spec, request) == "diffusion"if not (stage_2 or explicit):returnfrom . import device as device_modulefrom . import pipelinesframes = Noneif not request.auto_duration:frames = request.num_frameselse:frames, _longest = constraints.duration_head_frame_range(min_seconds=request.min_seconds,max_seconds=request.max_seconds,frame_rate=float(request.frame_rate),)pipelines.check_decoder_minimum(pipelines.pinned_decoder_config(),width=request.width,height=request.height,num_frames=frames,scale=pipelines.STAGE_2_SPATIAL_SCALE if stage_2 else 1,stage_2=stage_2,)where = device_module.current().deviceif explicit and not stage_2 and where not in (None, "cuda"):pipelines.check_cpu_decoder_size(width=request.width, height=request.height, num_frames=frames)def _checked_stage_2_size(request: GenerationRequest, spec) -> None:"""A stage-2 request this device cannot decode is refused before dispatch (no-op on CUDA)."""if not stage_2_enabled(spec, request):
64 unmodified lines6566676869701 unmodified line7273747576771189 unmodified lines126712681269127012711272127316 unmodified lines129012911292129312941295138 unmodified lines14341435143614371438143914401441144214431444144514461447144814491450145114521453145464 unmodified lines"BASE_KIND","assert_compression_ratios","assert_frame_rate_default","check_decoder_size","clear_cache","configure_vae_tiling",1 unmodified line"derive_pipeline","get_pipeline","mmap_backing_report","VAE_TILE_MIN_HEIGHT","VAE_TILE_MIN_WIDTH","VAE_TILE_MIN_NUM_FRAMES",1189 unmodified lines``scale`` is how much the graph enlarges the request before decoding (2 forstage 2, 1 for a single-stage diffusion decode)."""config = _decoder_config(decoder)if config is None or not (width and height and num_frames):returnfrom .constraints import DIMENSION_MULTIPLE16 unmodified linesraise DecoderTooSmallError(output=output, minimum=minimum, smallest=smallest, stage_2=stage_2)def stage_2_kwargs(latents, *, audio_latents=None) -> dict:"""Stage-2 refinement over upsampled latents.138 unmodified linesif self.device != "cuda":if policy == "auto":return "conv", OFF_CUDA_DECODER_NOTEfrom . import device as device_moduletokens = (int(frames) * (int(height) // 4) * (int(width) // 4)if width and height and frameselse None)limit = device_module.OFF_CUDA_DECODER_TOKEN_LIMITif tokens is None or tokens > limit:raise DecoderUnavailableError(reason=(f"without an NVIDIA (CUDA) GPU it runs only on the CPU, for very small "f"videos (up to {limit} decoder positions; this one needs {tokens})"))try:self._decoder_ready()except ModelLoadError as exc:64 unmodified lines65666768697071721 unmodified line747576777879801189 unmodified lines12701271127212731274127512761277127812791280128112821283128412851286128716 unmodified lines1304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346138 unmodified lines148514861487148814891490149164 unmodified lines"BASE_KIND","assert_compression_ratios","assert_frame_rate_default","check_cpu_decoder_size","check_decoder_minimum","check_decoder_size","clear_cache","configure_vae_tiling",1 unmodified line"derive_pipeline","get_pipeline","mmap_backing_report","pinned_decoder_config","VAE_TILE_MIN_HEIGHT","VAE_TILE_MIN_WIDTH","VAE_TILE_MIN_NUM_FRAMES",1189 unmodified lines``scale`` is how much the graph enlarges the request before decoding (2 forstage 2, 1 for a single-stage diffusion decode)."""check_decoder_minimum(_decoder_config(decoder),width=width,height=height,num_frames=num_frames,scale=scale,stage_2=stage_2,)def check_decoder_minimum(config, *, width, height, num_frames, scale: int, stage_2: bool) -> None:""":func:`check_decoder_size` against a decoder config (the loaded one, or its file)."""if config is None or not (width and height and num_frames):returnfrom .constraints import DIMENSION_MULTIPLE16 unmodified linesraise DecoderTooSmallError(output=output, minimum=minimum, smallest=smallest, stage_2=stage_2)def check_cpu_decoder_size(*, width, height, num_frames) -> None:"""Off CUDA a single-stage diffusion decode runs on the CPU, at very small sizes only."""from . import device as device_modulefrom .errors import DecoderUnavailableErrortokens = (int(num_frames) * (int(height) // 4) * (int(width) // 4)if width and height and num_frameselse None)limit = device_module.OFF_CUDA_DECODER_TOKEN_LIMITif tokens is None or tokens > limit:raise DecoderUnavailableError(reason=(f"without an NVIDIA (CUDA) GPU it runs only on the CPU, for very small "f"videos (up to {limit} decoder positions; this one needs {tokens})"))def pinned_decoder_config() -> dict | None:"""The diffusion decoder's config read from its file, or None where it is absent.For checks before a run (no model loaded); the loaded decoder is checked again."""import jsonfrom . import preflightfrom .errors import LTXStudioErrortry:path = preflight.component_dir("diffusion_decoder") / "config.json"return json.loads(path.read_text()) if path.is_file() else Noneexcept (OSError, ValueError, LTXStudioError):return Nonedef stage_2_kwargs(latents, *, audio_latents=None) -> dict:"""Stage-2 refinement over upsampled latents.138 unmodified linesif self.device != "cuda":if policy == "auto":return "conv", OFF_CUDA_DECODER_NOTEcheck_cpu_decoder_size(width=width, height=height, num_frames=frames)try:self._decoder_ready()except ModelLoadError as exc:
26 unmodified lines272829303132214 unmodified lines24724824925025125225326 unmodified linesfrom __future__ import annotationsimport argparseimport jsonimport osimport shutil214 unmodified linesdecoder = LTX2VideoDiffusionDecodePipeline(diffusion_decoder=decoder_model, scheduler=base.scheduler)stack = {"base": base}for kind, pipe in (("condition", base),("text2video", pipelines.derive_pipeline(base, LTX2Pipeline)),26 unmodified lines27282930313233214 unmodified lines24824925025125225325425525625725825926026126226326 unmodified linesfrom __future__ import annotationsimport argparseimport atexitimport jsonimport osimport shutil214 unmodified linesdecoder = LTX2VideoDiffusionDecodePipeline(diffusion_decoder=decoder_model, scheduler=base.scheduler)# A snapshot directory with the same tiny stage-2 configs, for the checks that# read the decoder's config before a run (LTX25_MODEL_SNAPSHOT_DIR points at it).work = Path(tempfile.mkdtemp(prefix="ltx25_tiny_stack_"))atexit.register(shutil.rmtree, work, ignore_errors=True)snapshot, missing = composite_snapshot(tiny_snapshot(fetch=False), work / "snapshot", fetch=False)if missing:raise RuntimeError(missing)stack = {"base": base, "snapshot": snapshot}for kind, pipe in (("condition", base),("text2video", pipelines.derive_pipeline(base, LTX2Pipeline)),
317 unmodified lines318319320317 unmodified linesassert labels.index("sampling") < labels.index("decoding the frames"), labelsassert fractions == sorted(fractions), fractions317 unmodified lines318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424317 unmodified linesassert labels.index("sampling") < labels.index("decoding the frames"), labelsassert fractions == sorted(fractions), fractions# --------------------------------------------------------------------------# refused before dispatch: an explicit diffusion decode, or stage 2, the decoder# cannot take (the decoder's minimum; off CUDA, the CPU path's size)# --------------------------------------------------------------------------@pytest.fixturedef pinned_decoder(monkeypatch, tmp_path):"""The pinned decoder's config.json where the check looks for it."""import jsonfrom ltx25_studio import preflightmonkeypatch.delenv(config.ENV_MODEL_SNAPSHOT_DIR, raising=False)monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))target = preflight.component_dir("diffusion_decoder") / "config.json"target.parent.mkdir(parents=True)target.write_text(json.dumps(REAL_DECODER_CONFIG))def _on(monkeypatch, name):import dataclassesfrom ltx25_studio import deviceresolution = dataclasses.replace(device.resolve(None), device=name)monkeypatch.setattr(device, "current", lambda: resolution)def _dispatched(monkeypatch):calls = []monkeypatch.setattr(generate_module, "_GPU_DISPATCH", lambda **kw: calls.append(kw))return calls@pytest.mark.usefixtures("pinned_decoder")def test_an_explicit_diffusion_below_the_minimum_is_refused_before_dispatch(monkeypatch):from ltx25_studio.errors import categorise_on(monkeypatch, "cuda")calls = _dispatched(monkeypatch)with pytest.raises(DecoderTooSmallError) as caught:generate_module.generate(mode="text_to_video", prompt="p", decoder="diffusion", **SMALL, seed=7)assert not callsassert categorise(caught.value).gpu_used is False@pytest.mark.usefixtures("pinned_decoder")def test_stage_2_below_the_decoders_minimum_is_refused_before_dispatch(monkeypatch):_on(monkeypatch, "cuda")calls = _dispatched(monkeypatch)with pytest.raises(DecoderTooSmallError) as caught:generate_module.generate(mode="text_to_video",prompt="p",enable_stage_2=True,width=96,height=64,num_frames=17,seed=7,)assert not calls and caught.value.stage_2 is True@pytest.mark.usefixtures("pinned_decoder")def test_an_explicit_diffusion_off_cuda_beyond_the_cpu_path_is_refused_before_dispatch(monkeypatch,):_on(monkeypatch, "mps")calls = _dispatched(monkeypatch)with pytest.raises(DecoderUnavailableError):generate_module.prepare_request(generate_module.GenerationRequest(mode="text_to_video", prompt="p", decoder="diffusion", **OK))assert not calls@pytest.mark.usefixtures("pinned_decoder")@pytest.mark.parametrize("device_name", ["cuda", "mps"])def test_auto_is_never_refused_before_dispatch(monkeypatch, device_name):_on(monkeypatch, device_name)generate_module.prepare_request(generate_module.GenerationRequest(mode="text_to_video", prompt="p", **SMALL))@pytest.mark.usefixtures("pinned_decoder")def test_an_explicit_diffusion_that_fits_passes_the_gate(monkeypatch):_on(monkeypatch, "cuda")generate_module.prepare_request(generate_module.GenerationRequest(mode="text_to_video", prompt="p", decoder="diffusion", **OK))
12 unmodified lines131415161718194 unmodified lines21321421521621721821922022122222322412 unmodified linesfrom __future__ import annotationsimport jsonimport osimport subprocess194 unmodified lines**smoke._media_for(mode_id, media, width, frames),)request.update(overrides)return generate.generate(**request,pipeline_factory=lambda pipeline: tiny[pipeline],output_root=out / "outputs",retention_bytes=10**9,)@pytest.mark.parametrize("mode_id", STAGE_2_MODES)12 unmodified lines13141516171819194 unmodified lines21421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424512 unmodified linesfrom __future__ import annotationsimport contextlibimport jsonimport osimport subprocess194 unmodified lines**smoke._media_for(mode_id, media, width, frames),)request.update(overrides)with tiny_snapshot_env(tiny):return generate.generate(**request,pipeline_factory=lambda pipeline: tiny[pipeline],output_root=out / "outputs",retention_bytes=10**9,)@contextlib.contextmanagerdef tiny_snapshot_env(tiny):"""``LTX25_MODEL_SNAPSHOT_DIR`` at the tiny stack's snapshot, for the length of a run.The gate reads the decoder's config before a run; with the tiny stack it mustread the tiny decoder's, not whatever real checkpoint the HF cache holds."""name = "LTX25_MODEL_SNAPSHOT_DIR"before = os.environ.get(name)os.environ[name] = str(tiny["snapshot"])try:yieldfinally:if before is None:os.environ.pop(name, None)else:os.environ[name] = before@pytest.mark.parametrize("mode_id", STAGE_2_MODES)