Spaces:
Running on Zero
fix: the audio a user uploads must reach the model
Browse filesThere is no audio= argument on any LTX2 pipeline: audio enters as
pre-encoded audio_latents. The UI wrote request.audio, modes._with_audio
read request.audio_latents, and NOTHING JOINED THEM. Both ends were built.
encode_waveform_to_latents existed, was exported and documented, and had an
importer count of zero.
So audio_to_audio and audio_to_video discarded the upload and generated
fresh audio. The run succeeded, the artifact was valid, every test passed,
and only the user's own ears would ever have told them -- while the field's
help text said 'Encoded to audio latents before the call', describing a step
that did not exist. Resilience lesson 2 inverted: a silent success.
generate._prepared_audio joins them, after the pipeline exists because the
encode needs its audio_vae. A mode given audio with no audio_vae to encode
it now refuses loudly rather than generating a plausible track nobody asked
for. audio.load_waveform reads the file gr.Audio(type='filepath') hands us.
The fixtures were the reason this was invisible, so they are the larger part
of the change. test_ui_generate_seam ALREADY handed audio_to_audio an audio
input -- it just asserted nothing about where it went. FakePipeline now
carries an audio_vae because the real pipeline does, and FakeAudioVae is
deliberately rich: the encode reads all six PLAN 5.4 config parameters,
finds a mel front-end rather than building one, and asserts the latent rank,
so a thinner fake would let a broken encode pass.
Removing the join turns the acceptance tests red with the pipeline kwargs
printed -- noise_scale present, audio_latents absent, which is the mechanism
exactly: the input never travelled far enough for noise_scale to be what
discarded it.
Files changed (5)
58 unmodified lines596061626364247 unmodified lines31231331431531631758 unmodified lines"audio_params_from","decode_latents_to_waveform","encode_waveform_to_latents","export_sampling_rate_from","mel_front_end_for","validate_audio_latents_against_video",247 unmodified linesreturn encodeddef encode_waveform_to_latents(waveform, *, audio_vae, sampling_rate: int, to_mel=None):"""waveform -> mel -> ``audio_vae`` latents, ready to pass as ``audio_latents``.58 unmodified lines59606162636465247 unmodified lines31331431531631731831932032132232332432532632732832933033133233333433533658 unmodified lines"audio_params_from","decode_latents_to_waveform","encode_waveform_to_latents","load_waveform","export_sampling_rate_from","mel_front_end_for","validate_audio_latents_against_video",247 unmodified linesreturn encodeddef load_waveform(source):"""A user-supplied audio file -> ``(waveform, sampling_rate)``.``gr.Audio(type="filepath")`` hands us a path, so the file has to be readbefore anything can encode it. ``torchaudio`` is already a pinned dependencyand returns exactly the tensor :func:`encode_waveform_to_latents` expects,at the file's own rate -- which is then resampled to the VAE's rate there,using the VAE's number rather than ours.Lazy import for the same reason as ``_resampled``: this module must importwith no torch present, because the offline gate has none."""import torchaudiowaveform, rate = torchaudio.load(str(source))return waveform, int(rate)def encode_waveform_to_latents(waveform, *, audio_vae, sampling_rate: int, to_mel=None):"""waveform -> mel -> ``audio_vae`` latents, ready to pass as ``audio_latents``.
38 unmodified lines39404142434445223 unmodified lines269270271272273274215 unmodified lines49049149249349449538 unmodified linesfrom . import conditioning, constraints, modesfrom .constraints import DEFAULT_FRAME_RATEfrom .errors import DecodeError, EmptyOutputError, EncodeError, ModelLoadErrorlogger = logging.getLogger(__name__)223 unmodified lines)def _apply_loras(pipe, request: GenerationRequest):"""Attach every staged adapter, asserting each actually took.215 unmodified lineskwargs = _pipeline_kwargs(spec, request)_prepared_conditions(kwargs, request)_apply_loras(pipe, request)try:output = pipe(**kwargs)except Exception as exc:38 unmodified lines39404142434445464748495051223 unmodified lines275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317215 unmodified lines53353453553653753853954038 unmodified linesfrom . import conditioning, constraints, modesfrom .constraints import DEFAULT_FRAME_RATEfrom .errors import (DecodeError,EmptyOutputError,EncodeError,GenerationError,ModelLoadError,)logger = logging.getLogger(__name__)223 unmodified lines)def _prepared_audio(kwargs: dict, request: GenerationRequest, pipe) -> None:"""Encode the user's audio file into the latents the pipeline actually takes.**This is the step that did not exist.** There is no ``audio=`` argument onany LTX2 pipeline (PLAN §3.1c) -- audio enters as pre-encoded``audio_latents``. The UI collected a file into ``request.audio``,``modes._with_audio`` read ``request.audio_latents``, and *nothing joinedthem*: both ends were built, the encoder existed and was exported, and itsimporter count was zero. So the upload was discarded and the model generatedfresh audio. The run succeeded, the artifact was valid, every test passed,and only the user's own ears would ever have told them -- while the field'sown help text said the encode had happened.Skipped when ``audio_latents`` is already set, which is the programmaticroute and needs no file."""source = getattr(request, "audio", None)if source is None or kwargs.get("audio_latents") is not None:returnfrom . import audio as audio_moduletarget = getattr(pipe, "pipeline", pipe)audio_vae = getattr(target, "audio_vae", None)if audio_vae is None:raise GenerationError(f"mode {request.mode!r} was given an audio input but the pipeline exposes no "f"audio_vae to encode it with. Refusing to continue, because generating without "f"it returns a plausible track the user did not ask for and nothing reports it.")waveform, rate = audio_module.load_waveform(source)kwargs["audio_latents"] = audio_module.encode_waveform_to_latents(waveform, audio_vae=audio_vae, sampling_rate=rate)def _apply_loras(pipe, request: GenerationRequest):"""Attach every staged adapter, asserting each actually took.215 unmodified lineskwargs = _pipeline_kwargs(spec, request)_prepared_conditions(kwargs, request)_apply_loras(pipe, request)# After the pipeline exists, because encoding needs its `audio_vae`._prepared_audio(kwargs, request, pipe)try:output = pipe(**kwargs)except Exception as exc:
394 unmodified lines3953963973983994008 unmodified lines409410411412413414394 unmodified linesself.peft_config: dict[str, object] = {}class FakePipeline:"""Duck-types the bits of an ``LTX2*Pipeline`` that ``lora/apply.py`` touches.8 unmodified lines_lora_loadable_modules = ["transformer", "connectors"]def __init__(self, transformer_paths=None, connector_paths=None, dims=None):self.transformer = FakeComponent(TRANSFORMER_MODULE_PATHS if transformer_paths is None else transformer_paths,dims=dims,394 unmodified lines3953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574588 unmodified lines467468469470471472473474475476394 unmodified linesself.peft_config: dict[str, object] = {}class FakeAudioVae:"""Duck-types an audio VAE closely enough to really encode a waveform.Rich rather than minimal on purpose. ``encode_waveform_to_latents`` reads allsix PLAN 5.4 config parameters, *finds* a mel front-end rather than buildingone, and asserts the latent rank before returning -- so a thinner fake wouldlet a broken encode pass. That is the fixture failure that hid the bfloat16bug, and this path is the one that was connected to nothing.Its sampling rate matches the stub loader's, so ``_resampled`` short-circuitsand the whole encode runs with no torch present."""def __init__(self, sampling_rate=48000):self.config = SimpleNamespace(audio_sampling_rate=sampling_rate,audio_hop_length=256,audio_mel_bins=128,audio_vae_mel_compression_ratio=2,audio_vae_temporal_compression_ratio=4,audio_latent_channels=64,in_channels=2,)self.mels: list = []self.encoded: list = []def mel_spectrogram(self, waveform):mel = ("mel", waveform)self.mels.append(waveform)return meldef encode(self, mel):self.encoded.append(mel)latents = SimpleNamespace(shape=(1, 64, 16, 128))return SimpleNamespace(latent_dist=SimpleNamespace(sample=lambda: latents))#: What the stub loader hands back: the shape `load_waveform` really returns.STUB_WAVEFORM = ("waveform", "stub")STUB_SAMPLING_RATE = 48000@pytest.fixturedef audio_input_ready(monkeypatch):"""Make the audio-input path runnable in the offline gate.``load_waveform`` reads a real file with torchaudio, and the gate hasneither the file nor torchaudio. Stubbing only the **loader** leaves the restof the path -- resample, mel front-end, encode, shape assertion -- genuinelyexercised, which is the part that was dead."""from ltx25_studio import audio as audio_modulemonkeypatch.setattr(audio_module, "load_waveform", lambda source: (STUB_WAVEFORM, STUB_SAMPLING_RATE))class FakePipeline:"""Duck-types the bits of an ``LTX2*Pipeline`` that ``lora/apply.py`` touches.8 unmodified lines_lora_loadable_modules = ["transformer", "connectors"]def __init__(self, transformer_paths=None, connector_paths=None, dims=None):# The real pipeline carries one, and `generate._prepared_audio` unwraps# to `.pipeline` to find it. A fake without it made the audio-input# modes look like they had nothing to encode with.self.audio_vae = FakeAudioVae()self.transformer = FakeComponent(TRANSFORMER_MODULE_PATHS if transformer_paths is None else transformer_paths,dims=dims,
37 unmodified lines38394041424342 unmodified lines86878889909137 unmodified linesfrom pathlib import Pathimport pytestfrom ltx25_studio import generate as generate_modulefrom ltx25_studio import modes, outputs42 unmodified linesclass FakePipe:def __init__(self):self.calls: list[dict] = []def __call__(self, **kwargs):self.calls.append(kwargs)37 unmodified lines3839404142434442 unmodified lines87888990919293949537 unmodified linesfrom pathlib import Pathimport pytestfrom conftest import FakeAudioVaefrom ltx25_studio import generate as generate_modulefrom ltx25_studio import modes, outputs42 unmodified linesclass FakePipe:def __init__(self):self.calls: list[dict] = []# The real pipeline has one, and the audio-input modes cannot be# encoded without it. A fake without it made those modes look fine.self.audio_vae = FakeAudioVae()def __call__(self, **kwargs):self.calls.append(kwargs)
29 unmodified lines30313233343537 unmodified lines7374757677787 unmodified lines86878889909192939495206 unmodified lines30230330429 unmodified linesfrom dataclasses import replaceimport pytestfrom test_exports_contract import (MODE_IDS,MODE_TRACK_PAIRS,37 unmodified linesdef __init__(self):self.params: list[dict] = []self.results: list = []@propertydef result(self):7 unmodified linesreal = generate_module.generatewiring = Wiring()def wired_generate(**params):wiring.params.append(params)result = real(pipeline_factory=factory_returning(FakePipe()),encoder=one_muxed_file_encoder,output_root=tmp_path,retention_bytes=10**9,206 unmodified linesassert (video, audio) == (None, None)assert status.strip(), "a failed generation returned an empty status string"assert "Generation failed" in status29 unmodified lines3031323334353637 unmodified lines747576777879807 unmodified lines888990919293949596979899100101102103104105106107108109110111206 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240329 unmodified linesfrom dataclasses import replaceimport pytestfrom conftest import STUB_WAVEFORMfrom test_exports_contract import (MODE_IDS,MODE_TRACK_PAIRS,37 unmodified linesdef __init__(self):self.params: list[dict] = []self.results: list = []self.pipes: list = []@propertydef result(self):7 unmodified linesreal = generate_module.generatewiring = Wiring()# `values_for` hands the audio modes a path-shaped string, exactly as the UI# hands a real filepath. Nothing used to read it -- that was the bug. Now the# loader does, so it is stubbed; everything downstream of it (resample, mel,# encode, shape assertion) runs for real against the fake audio VAE.from conftest import STUB_SAMPLING_RATE, STUB_WAVEFORMfrom ltx25_studio import audio as audio_modulemonkeypatch.setattr(audio_module, "load_waveform", lambda source: (STUB_WAVEFORM, STUB_SAMPLING_RATE))def wired_generate(**params):wiring.params.append(params)pipe = FakePipe()wiring.pipes.append(pipe)result = real(pipeline_factory=factory_returning(pipe),encoder=one_muxed_file_encoder,output_root=tmp_path,retention_bytes=10**9,206 unmodified linesassert (video, audio) == (None, None)assert status.strip(), "a failed generation returned an empty status string"assert "Generation failed" in status# --------------------------------------------------------------------------# the audio a user uploads has to reach the model## There is no `audio=` argument on any LTX2 pipeline: audio enters as# pre-encoded `audio_latents`. The UI wrote `request.audio`, `modes._with_audio`# read `request.audio_latents`, and NOTHING JOINED THEM -- both ends built, the# encoder exported, its importer count zero. So the upload was discarded, the# model generated fresh audio, the run succeeded, the artifact was valid, and# 1926 tests passed. Only the user's own ears would have told them.# --------------------------------------------------------------------------AUDIO_INPUT_MODES = [m for m in MODE_IDS if "audio" in modes.get_mode(m).inputs]@pytest.mark.parametrize("mode_id", AUDIO_INPUT_MODES)def test_the_uploaded_audio_reaches_the_pipeline_as_latents(mode_id, wired, audio_input_ready, tmp_path):"""The whole point: the model must be handed what the user supplied."""handlers.on_generate(mode_id, *values_for(mode_id))pipe = wired.pipes[-1]sent = pipe.calls[-1]assert sent.get("audio_latents") is not None, (f"{mode_id} was given an audio file and the pipeline received "f"audio_latents=None, so the upload was discarded and the model "f"generated audio the user did not ask for: {sorted(sent)}")@pytest.mark.parametrize("mode_id", AUDIO_INPUT_MODES)def test_the_upload_is_encoded_through_the_audio_vae(mode_id, wired, audio_input_ready):"""Not merely present -- produced by the encoder, from the user's waveform.Asserting only that ``audio_latents`` is set would pass if something handedthe pipeline a constant. This follows the value back to the waveform."""handlers.on_generate(mode_id, *values_for(mode_id))audio_vae = wired.pipes[-1].audio_vaeassert audio_vae.encoded, f"{mode_id} never called audio_vae.encode"assert audio_vae.mels and audio_vae.mels[-1] == STUB_WAVEFORM, (f"{mode_id} encoded something other than the loaded waveform: {audio_vae.mels}")@pytest.mark.parametrize("mode_id", [m for m in MODE_IDS if "audio" not in modes.get_mode(m).inputs])def test_a_mode_that_takes_no_audio_encodes_nothing(mode_id, wired, audio_input_ready):"""The guard must not fire where there is nothing to encode."""handlers.on_generate(mode_id, *values_for(mode_id))assert not wired.pipes[-1].audio_vae.encoded, (f"{mode_id} takes no audio input and still ran an encode")def test_an_audio_input_with_no_audio_vae_is_refused_loudly(monkeypatch, tmp_path):"""Silently dropping it is the defect; generating anyway is the worst form."""from conftest import STUB_SAMPLING_RATE, STUB_WAVEFORMfrom ltx25_studio import audio as audio_modulefrom ltx25_studio.errors import GenerationErrormonkeypatch.setattr(audio_module, "load_waveform", lambda source: (STUB_WAVEFORM, STUB_SAMPLING_RATE))pipe = FakePipe()del pipe.audio_vaewith pytest.raises(GenerationError) as excinfo:generate_module.generate(mode="audio_to_audio",seed=7,audio="an-upload.wav",pipeline_factory=factory_returning(pipe),encoder=one_muxed_file_encoder,output_root=tmp_path,retention_bytes=10**9,)assert "audio_vae" in str(excinfo.value), excinfo.valueassert not pipe.calls, "the pipeline ran anyway, so the user got audio they did not ask for"