techfreakworm commited on
Commit
466bbd5
·
unverified ·
1 Parent(s): dfacddd

fix: batch in the product, and put the latents in upstream's layout

Browse files

Four structural defects in the audio-input path, all found by host-runner
varying inputs through the to_mel= seam. audio.py had been untouched.

THE BATCHING WAS IN THE HARNESS, NOT THE PRODUCT. A script commit added it,
so H17 would have passed while a user uploading a wav still got a 3D mel and
a refusal from our own validator. That is the harness-proves-the-model trap,
one layer down from where we last hit it.

Batched inside encode_waveform_to_latents, and AFTER match_channel_count --
the two guards contradict each other in any other order. match_channel_count
reads the channel count off axis 0, so a batched (1, 2, N) stereo clip looked
like mono, was 'widened' by duplication, reached the VAE with batch 2, and
told the user their audio was mono. It now refuses a non-2D waveform rather
than misreading one, and the ordering constraint is documented at both ends.

audio_vae.encode emits [B, C, M, L]; upstream reads [B, C, L, M]. Established
by experiment -- halving the input halves axis 3 while axis 2 stays pinned at
mel_bins / mel_compression_ratio -- and confirmed in upstream's own packer,
latents.transpose(1, 2).flatten(2, 3) # [B, C, L, M] --> [B, L, C * M].

So AUDIO_LATENT_DIMS was RIGHT and must not be 'corrected'. Our constant,
validate_audio_latents_shape, audio_frames_from_latents and upstream's reader
all agree; the missing step was ours. Changing the constant instead would
have made every reader agree with every other reader and all of them wrong,
which is PLAN 5.7 row 5 exactly. The fixed 0.61s reconstruction was this same
defect from the decode end.

validate_audio_latents_shape gets a docstring line saying it is now confirmed
against real weights, because 'never verified' and 'verified' look identical
in code -- and it earned it, rejecting a rank error the VAE itself accepted.

Also recorded: we return un-normalised, un-noised latents deliberately.
prepare_audio_latents packs, normalises and noises them upstream, so doing
any of it here would do it twice.

The fake VAE now emits MEL-MAJOR latents, because a fake emitting the
already-correct order would pass a missing transpose. All three structural
fixes fail offline when mutated away, naming the shape they produced.

ltx25_studio/audio.py CHANGED
@@ -71,6 +71,8 @@ __all__ = [
71
  "mel_front_end_for",
72
  "build_mel_front_end",
73
  "encoder_layout",
 
 
74
  "mel_parameters",
75
  "MEL_PARAM_SOURCES",
76
  "MEL_CONVENTIONS",
@@ -258,6 +260,13 @@ def export_sampling_rate_from(vocoder) -> int:
258
  def validate_audio_latents_shape(shape) -> tuple[int, ...]:
259
  """Return the shape unchanged, or raise naming the rank we got.
260
 
 
 
 
 
 
 
 
261
  ``audio_latents`` is **unpacked** ``[B, C, L, M]``. Upstream does not
262
  reliably raise on a wrong rank -- the documented failure is "shape errors,
263
  **or worse, silent misinterpretation**" -- so the assertion lives at our
@@ -404,7 +413,7 @@ def mel_parameters(audio_vae, vocoder):
404
 
405
 
406
  def encoder_layout(mel):
407
- """``[channels, mel, time]`` -> ``[batch, channels, time, mel]``.
408
 
409
  Separated from :func:`build_mel_front_end` so it can be exercised without
410
  torch installed. The transform itself needs real tensors; **this rearrangement
@@ -416,7 +425,7 @@ def encoder_layout(mel):
416
  tensor that satisfies the rank check and is a **transposed spectrogram** --
417
  audio out, silently wrong. See :data:`MEL_INPUT_DIMS`.
418
  """
419
- return mel.transpose(-2, -1).unsqueeze(0)
420
 
421
 
422
  def build_mel_front_end(audio_vae, vocoder):
@@ -595,6 +604,14 @@ def match_channel_count(waveform, *, channels: int):
595
  shape = getattr(waveform, "shape", None)
596
  if not shape:
597
  return waveform, None
 
 
 
 
 
 
 
 
598
  found = int(shape[0])
599
  if found == channels:
600
  return waveform, None
@@ -618,6 +635,49 @@ def match_channel_count(waveform, *, channels: int):
618
  )
619
 
620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
  def _validate_mel_rank(mel) -> None:
622
  """Refuse a mel the encoder would silently misread.
623
 
@@ -680,6 +740,13 @@ def encode_waveform_to_latents(
680
  ``sampling_rate`` is the rate of the *incoming* waveform; the VAE's own rate
681
  comes from its config and wins. The returned shape is asserted before it can
682
  reach the pipeline.
 
 
 
 
 
 
 
683
  """
684
  params = audio_params_from(audio_vae)
685
  prepared = _resampled(waveform, from_rate=sampling_rate, to_rate=params.audio_sampling_rate)
@@ -691,6 +758,8 @@ def encode_waveform_to_latents(
691
  logger.warning(note)
692
  if notes is not None:
693
  notes.append(note)
 
 
694
  mel = (to_mel or mel_front_end_for(audio_vae, vocoder))(prepared)
695
  # ⚠️ Cast HERE, at the hand-off, not inside the transform. The mel is
696
  # computed in float32 on purpose -- an STFT in bf16 would lose precision
@@ -703,7 +772,7 @@ def encode_waveform_to_latents(
703
  # explicitly-passed `to_mel=` from a caller who does not know the VAE dtype.
704
  mel = _matched_dtype(mel, audio_vae, name="audio_vae")
705
  _validate_mel_rank(mel)
706
- latents = _sampled(audio_vae.encode(mel))
707
  validate_audio_latents_shape(getattr(latents, "shape", ()))
708
  return latents
709
 
 
71
  "mel_front_end_for",
72
  "build_mel_front_end",
73
  "encoder_layout",
74
+ "batched",
75
+ "unpacked_latents",
76
  "mel_parameters",
77
  "MEL_PARAM_SOURCES",
78
  "MEL_CONVENTIONS",
 
260
  def validate_audio_latents_shape(shape) -> tuple[int, ...]:
261
  """Return the shape unchanged, or raise naming the rank we got.
262
 
263
+ ✅ **Confirmed against real weights**, and it was right. On its first
264
+ contact with a real encode it rejected a 3-D tensor the VAE itself had
265
+ accepted without complaint -- the batch axis was missing, so ``conv2d``
266
+ silently treated the input as unbatched. The instinct was to loosen this
267
+ check; the check was correct and the input was wrong. See
268
+ :func:`unpacked_latents`.
269
+
270
  ``audio_latents`` is **unpacked** ``[B, C, L, M]``. Upstream does not
271
  reliably raise on a wrong rank -- the documented failure is "shape errors,
272
  **or worse, silent misinterpretation**" -- so the assertion lives at our
 
413
 
414
 
415
  def encoder_layout(mel):
416
+ """``[..., mel, time]`` -> ``[..., time, mel]``.
417
 
418
  Separated from :func:`build_mel_front_end` so it can be exercised without
419
  torch installed. The transform itself needs real tensors; **this rearrangement
 
425
  tensor that satisfies the rank check and is a **transposed spectrogram** --
426
  audio out, silently wrong. See :data:`MEL_INPUT_DIMS`.
427
  """
428
+ return mel.transpose(-2, -1)
429
 
430
 
431
  def build_mel_front_end(audio_vae, vocoder):
 
604
  shape = getattr(waveform, "shape", None)
605
  if not shape:
606
  return waveform, None
607
+ if len(shape) != 2:
608
+ raise LTXStudioError(
609
+ f"the waveform is {len(shape)}D {tuple(shape)} and this expects an UNBATCHED "
610
+ f"(channels, samples). Given a batched one it would read the batch axis as the "
611
+ f"channel count -- a (1, 2, N) stereo clip looks like mono, is 'widened' by "
612
+ f"duplication, and reaches the VAE with a batch of 2 and the user told their "
613
+ f"audio was mono. Batch after this runs, not before."
614
+ )
615
  found = int(shape[0])
616
  if found == channels:
617
  return waveform, None
 
635
  )
636
 
637
 
638
+ def batched(waveform):
639
+ """Add the batch axis the encoder requires, after the channel count is settled.
640
+
641
+ **Order matters and the two guards disagree unless it is respected.**
642
+ :func:`match_channel_count` reads the channel count off axis 0, so it must
643
+ see an unbatched ``(channels, samples)``; the encoder needs 4D, which needs
644
+ a batch. Batching *after* the channel check is the only order that satisfies
645
+ both -- batching first makes a stereo clip look mono, and not batching at
646
+ all makes the latents come back one rank short.
647
+ """
648
+ shape = getattr(waveform, "shape", None)
649
+ if shape is None or len(shape) != 2:
650
+ return waveform
651
+ # `[None]` rather than `.unsqueeze(0)`: it means the same thing in torch and
652
+ # in numpy, and the offline gate has no torch. Same reason as the fancy
653
+ # indexing in `match_channel_count`.
654
+ return waveform[None]
655
+
656
+
657
+ def unpacked_latents(latents):
658
+ """``audio_vae.encode`` output ``[B, C, M, L]`` -> upstream's ``[B, C, L, M]``.
659
+
660
+ ✅ Established by experiment on real weights: halving the input duration
661
+ halves **axis 3** (100 → 50) while axis 2 stays pinned at
662
+ ``mel_bins / mel_compression_ratio`` = 16. So the VAE emits mel-major.
663
+
664
+ 📄 Upstream wants length-major, and says so in
665
+ ``pipeline_ltx2_condition.prepare_audio_latents``: *"latents expected to be
666
+ unpacked (4D) with shape [B, C, L, M]"*, with ``_pack_audio_latents`` doing
667
+ ``latents.transpose(1, 2).flatten(2, 3) # [B, C, L, M] --> [B, L, C * M]``.
668
+
669
+ **This is why :data:`AUDIO_LATENT_DIMS` was right and must not be
670
+ "corrected".** Our constant, ``validate_audio_latents_shape`` and
671
+ ``audio_frames_from_latents`` all agree with upstream; the missing step was
672
+ here. Swapping the constant instead would have made every reader agree with
673
+ every other reader and all of them wrong -- PLAN §5.7 row 5 exactly.
674
+ """
675
+ swap = getattr(latents, "transpose", None)
676
+ if swap is None:
677
+ return latents
678
+ return swap(-2, -1)
679
+
680
+
681
  def _validate_mel_rank(mel) -> None:
682
  """Refuse a mel the encoder would silently misread.
683
 
 
740
  ``sampling_rate`` is the rate of the *incoming* waveform; the VAE's own rate
741
  comes from its config and wins. The returned shape is asserted before it can
742
  reach the pipeline.
743
+
744
+ **Returns unpacked, UN-NORMALISED, un-noised 4D ``[B, C, L, M]``.** That is
745
+ the whole job and stopping there is deliberate:
746
+ ``prepare_audio_latents`` upstream calls ``_pack_audio_latents``,
747
+ ``_normalize_audio_latents`` and ``_create_noised_state`` itself, so
748
+ anything applied here would be applied twice. *"Should this normalise?" is
749
+ the obvious next question and the answer is no.*
750
  """
751
  params = audio_params_from(audio_vae)
752
  prepared = _resampled(waveform, from_rate=sampling_rate, to_rate=params.audio_sampling_rate)
 
758
  logger.warning(note)
759
  if notes is not None:
760
  notes.append(note)
761
+ # AFTER the channel check, never before -- see `batched`.
762
+ prepared = batched(prepared)
763
  mel = (to_mel or mel_front_end_for(audio_vae, vocoder))(prepared)
764
  # ⚠️ Cast HERE, at the hand-off, not inside the transform. The mel is
765
  # computed in float32 on purpose -- an STFT in bf16 would lose precision
 
772
  # explicitly-passed `to_mel=` from a caller who does not know the VAE dtype.
773
  mel = _matched_dtype(mel, audio_vae, name="audio_vae")
774
  _validate_mel_rank(mel)
775
+ latents = unpacked_latents(_sampled(audio_vae.encode(mel)))
776
  validate_audio_latents_shape(getattr(latents, "shape", ()))
777
  return latents
778
 
tests/conftest.py CHANGED
@@ -393,6 +393,40 @@ class FakeComponent(FakeModule):
393
  self.peft_config: dict[str, object] = {}
394
 
395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  class FakeMel:
397
  """A mel that carries a dtype and the rank the encoder requires.
398
 
@@ -455,7 +489,11 @@ class FakeAudioVae:
455
 
456
  def encode(self, mel):
457
  self.encoded.append(mel)
458
- latents = SimpleNamespace(shape=(1, 64, 16, 128))
 
 
 
 
459
  return SimpleNamespace(latent_dist=SimpleNamespace(sample=lambda: latents))
460
 
461
 
 
393
  self.peft_config: dict[str, object] = {}
394
 
395
 
396
+ class ShapedTensor:
397
+ """Enough tensor to follow a rearrangement, with no torch installed.
398
+
399
+ The offline gate has none, so a test of a real transform can only skip --
400
+ and a skipped test of an axis order is how two half-fixes went unnoticed.
401
+ This models exactly the operations the layout steps use.
402
+ """
403
+
404
+ def __init__(self, shape, dtype="float32"):
405
+ self.shape = tuple(shape)
406
+ self.dtype = dtype
407
+
408
+ def transpose(self, a, b):
409
+ axes = list(self.shape)
410
+ axes[a], axes[b] = axes[b], axes[a]
411
+ return ShapedTensor(axes, self.dtype)
412
+
413
+ def unsqueeze(self, axis):
414
+ axes = list(self.shape)
415
+ axes.insert(axis, 1)
416
+ return ShapedTensor(axes, self.dtype)
417
+
418
+ def to(self, dtype):
419
+ return ShapedTensor(self.shape, dtype)
420
+
421
+ def __getitem__(self, key):
422
+ # Models `waveform[None]`, which is how the batch axis is added --
423
+ # `[None]` rather than `.unsqueeze(0)` because it means the same in
424
+ # torch and numpy and the offline gate has no torch.
425
+ if key is None:
426
+ return self.unsqueeze(0)
427
+ raise TypeError(f"ShapedTensor only models [None] indexing, got {key!r}")
428
+
429
+
430
  class FakeMel:
431
  """A mel that carries a dtype and the rank the encoder requires.
432
 
 
489
 
490
  def encode(self, mel):
491
  self.encoded.append(mel)
492
+ # ⚠️ MEL-MAJOR [B, C, M, L], which is what the real VAE emits -- axis 3
493
+ # tracks duration, axis 2 is pinned at mel_bins / mel_compression_ratio.
494
+ # Upstream wants [B, C, L, M], so `unpacked_latents` has to swap them. A
495
+ # fake emitting the already-correct order would pass a missing transpose.
496
+ latents = ShapedTensor((1, 8, 16, 100))
497
  return SimpleNamespace(latent_dist=SimpleNamespace(sample=lambda: latents))
498
 
499
 
tests/test_audio.py CHANGED
@@ -21,6 +21,7 @@ from conftest import (
21
  FakeAudioVae,
22
  FakeMel,
23
  FakeVocoder,
 
24
  code_string_constants,
25
  waveform_of,
26
  )
@@ -248,8 +249,8 @@ def test_a_mono_upload_reaches_the_vae_as_stereo():
248
  waveform_of(1), audio_vae=vae, sampling_rate=vae.config.sample_rate, notes=notes
249
  )
250
 
251
- assert vae.mels[-1].shape[0] == 2, (
252
- f"the audio VAE was handed {vae.mels[-1].shape[0]} channel(s); it takes 2 and "
253
  f"raises a raw conv2d shape error rather than anything actionable"
254
  )
255
  assert notes, "the audio was altered and nothing was recorded for the user"
@@ -663,36 +664,66 @@ def test_an_explicit_to_mel_is_protected_too():
663
  # --------------------------------------------------------------------------
664
 
665
 
666
- class ShapedTensor:
667
- """Enough tensor to follow a rearrangement, with no torch installed.
668
 
669
- The offline gate has no torch, so a test of the real transform can only
670
- skip -- and a skipped test of the axis order is how both half-fixes went
671
- unnoticed. This models exactly the two operations the layout step uses.
672
  """
 
673
 
674
- def __init__(self, shape):
675
- self.shape = tuple(shape)
 
676
 
677
- def transpose(self, a, b):
678
- axes = list(self.shape)
679
- axes[a], axes[b] = axes[b], axes[a]
680
- return ShapedTensor(axes)
681
 
682
- def unsqueeze(self, axis):
683
- axes = list(self.shape)
684
- axes.insert(axis, 1)
685
- return ShapedTensor(axes)
686
 
 
 
 
 
 
687
 
688
- def test_the_mel_reaches_the_encoder_batched_and_time_major():
689
- """torchaudio gives [channels, mel, time]; the encoder wants [B, C, time, mel]."""
690
- laid_out = audio.encoder_layout(ShapedTensor((2, 64, 401)))
 
691
 
692
- assert laid_out.shape == (1, 2, 401, 64), (
693
- f"got {laid_out.shape}, expected (1, 2, 401, 64) = {audio.MEL_INPUT_DIMS}. "
694
- f"(1, 2, 64, 401) is the batch-only half-fix: 4D, passes every rank check, and is "
695
- f"a transposed spectrogram the encoder reads as 64 time steps of 401 bins."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
696
  )
697
 
698
 
 
21
  FakeAudioVae,
22
  FakeMel,
23
  FakeVocoder,
24
+ ShapedTensor,
25
  code_string_constants,
26
  waveform_of,
27
  )
 
249
  waveform_of(1), audio_vae=vae, sampling_rate=vae.config.sample_rate, notes=notes
250
  )
251
 
252
+ assert vae.mels[-1].shape[-2] == 2, (
253
+ f"the audio VAE was handed {vae.mels[-1].shape[-2]} channel(s); it takes 2 and "
254
  f"raises a raw conv2d shape error rather than anything actionable"
255
  )
256
  assert notes, "the audio was altered and nothing was recorded for the user"
 
664
  # --------------------------------------------------------------------------
665
 
666
 
667
+ def test_the_mel_reaches_the_encoder_time_major():
668
+ """A batched waveform gives [B, C, mel, time]; the encoder wants [B, C, time, mel].
669
 
670
+ `(1, 2, 64, 401)` is the shape that hides: it is 4D, passes every rank check
671
+ downstream, and is a transposed spectrogram the encoder reads as 64 time
672
+ steps of 401 mel bins.
673
  """
674
+ laid_out = audio.encoder_layout(ShapedTensor((1, 2, 64, 401)))
675
 
676
+ assert laid_out.shape == (1, 2, 401, 64), (
677
+ f"got {laid_out.shape}, expected (1, 2, 401, 64) = {audio.MEL_INPUT_DIMS}"
678
+ )
679
 
 
 
 
 
680
 
681
+ def test_the_waveform_is_batched_only_after_the_channel_count_is_settled():
682
+ """The two guards contradict each other in any other order.
 
 
683
 
684
+ `match_channel_count` reads channels off axis 0 and the encoder needs 4D.
685
+ Batching first makes a stereo clip look mono; not batching leaves the
686
+ latents one rank short.
687
+ """
688
+ batched = audio.batched(ShapedTensor((2, 4096)))
689
 
690
+ assert batched.shape == (1, 2, 4096), batched.shape
691
+ assert audio.batched(batched).shape == (1, 2, 4096), (
692
+ "an already-batched waveform was batched again"
693
+ )
694
 
695
+
696
+ def test_a_batched_waveform_is_refused_by_the_channel_check():
697
+ """It used to read the batch axis as the channel count and 'widen' stereo."""
698
+ with pytest.raises(LTXStudioError) as excinfo:
699
+ audio.match_channel_count(ShapedTensor((1, 2, 64000)), channels=2)
700
+
701
+ message = str(excinfo.value)
702
+ assert "3D" in message and "UNBATCHED" in message, message
703
+
704
+
705
+ def test_the_encode_output_is_put_into_upstreams_latent_layout():
706
+ """The VAE emits [B, C, M, L]; upstream reads [B, C, L, M].
707
+
708
+ Established by experiment: halving the input halves axis 3 while axis 2
709
+ stays at mel_bins / mel_compression_ratio. Upstream's own packer says
710
+ `[B, C, L, M] --> [B, L, C * M]`.
711
+ """
712
+ swapped = audio.unpacked_latents(ShapedTensor((1, 8, 16, 100)))
713
+
714
+ assert swapped.shape == (1, 8, 100, 16), (
715
+ f"got {swapped.shape}; the frames axis must be axis 2, which is where "
716
+ f"audio_frames_from_latents and upstream both read it"
717
+ )
718
+
719
+
720
+ def test_the_frame_count_is_read_from_the_axis_the_transpose_produces():
721
+ """The transpose and AUDIO_LATENT_DIMS have to agree, or both are wrong."""
722
+ swapped = audio.unpacked_latents(ShapedTensor((1, 8, 16, 100)))
723
+
724
+ assert audio.audio_frames_from_latents(swapped.shape) == 100, (
725
+ "the frame count does not come back as the axis that tracks duration; "
726
+ "AUDIO_LATENT_DIMS and unpacked_latents disagree"
727
  )
728
 
729
 
tests/test_ui_generate_seam.py CHANGED
@@ -361,9 +361,10 @@ def test_the_upload_is_encoded_through_the_audio_vae(mode_id, wired, audio_input
361
  audio_vae = wired.pipes[-1].audio_vae
362
  assert audio_vae.encoded, f"{mode_id} never called audio_vae.encode"
363
  assert audio_vae.mels, f"{mode_id} never ran the mel front-end"
364
- assert audio_vae.mels[-1].shape == STUB_WAVEFORM.shape, (
 
365
  f"{mode_id} encoded something other than the loaded waveform: "
366
- f"{audio_vae.mels[-1].shape} vs {STUB_WAVEFORM.shape}"
367
  )
368
 
369
 
@@ -432,7 +433,11 @@ def test_a_mono_upload_is_reported_to_the_user_not_only_the_log(monkeypatch, tmp
432
  retention_bytes=10**9,
433
  )
434
 
435
- assert pipe.audio_vae.mels[-1].shape[0] == 2, "the VAE was handed mono and would have raised"
 
 
 
 
436
  assert any("mono" in note for note in result.warnings), (
437
  f"the upload was altered and the result says nothing about it: {result.warnings}"
438
  )
 
361
  audio_vae = wired.pipes[-1].audio_vae
362
  assert audio_vae.encoded, f"{mode_id} never called audio_vae.encode"
363
  assert audio_vae.mels, f"{mode_id} never ran the mel front-end"
364
+ # Batched by the time it reaches the transform: (batch, channels, samples).
365
+ assert audio_vae.mels[-1].shape == (1, *STUB_WAVEFORM.shape), (
366
  f"{mode_id} encoded something other than the loaded waveform: "
367
+ f"{audio_vae.mels[-1].shape} vs {(1, *STUB_WAVEFORM.shape)}"
368
  )
369
 
370
 
 
433
  retention_bytes=10**9,
434
  )
435
 
436
+ # -2 is the channel axis once the waveform is batched; reading axis 0 here
437
+ # would read the batch and pass whatever the channel count actually was.
438
+ assert pipe.audio_vae.mels[-1].shape[-2] == 2, (
439
+ "the VAE was handed mono and would have raised"
440
+ )
441
  assert any("mono" in note for note in result.warnings), (
442
  f"the upload was altered and the result says nothing about it: {result.warnings}"
443
  )