Spaces:
Running on Zero
fix: the audio encoder's mel transform uses the 1024-sample window the audio VAE was built for, so uploaded audio no longer reaches the model about 9 dB too quiet
Browse filesIssue F69. Modes 10 (audio to sound) and 11 (audio to video and sound) turn
the user's audio into audio-VAE latents through a forward mel transform the
app builds, because the checkpoint ships none. It took n_fft and win_length
from the vocoder's config (filter_length = window_length = 512). Those
numbers, with the vocoder's hop_length of 80, configure the vocoder's own mel
stage (MelSTFT in LTX2VocoderWithBWE, computed on its output to feed the
bandwidth extender); they do not describe the audio VAE's input.
Measured by round trip through the pinned audio VAE and vocoder (the app's own
encode_waveform_to_latents and decode_latents_to_waveform, CPU, float32): with
512 / 512, speech, an ocean recording and the model's own output came back
-8.9 / -9.7 / -8.8 dB; with 1024 / 1024 they come back +0.1 / -0.2 / +0.1 dB,
and the transform of the vocoder's output is within 0.11 log units of the mel
the vocoder was given (it was 1.1 to 1.5 below it).
The transform now reads the sample rate, hop and mel bins from
audio_vae.config and declares n_fft = win_length = 1024 in MEL_CONVENTIONS,
next to the other conventions, which the same measurement confirms. Nothing is
read from the vocoder. build_mel_front_end and mel_front_end_for keep their
signatures and the vocoder argument supplies nothing, so mel_front_end_for no
longer refuses to build without one. A missing audio_vae is still a typed
error, now raised before torch is imported.
Tests: the mel-parameter tests in tests/test_audio.py pinned the old design
(n_fft and win_length owned by the vocoder, no build without a vocoder) and
are rewritten to pin the new one; the source scan that bans 1024 in audio.py
now exempts exactly the two declared window values. The new
tests/test_mel_front_end_real.py loads only the pinned audio VAE and vocoder
from the local Hugging Face cache (CPU, float32; it skips when they are absent
or LTX25_SKIP_REAL_COMPONENT_TESTS=1), checks that a synthetic stereo signal
comes back within 1.5 dB and 0.3 log units, and that a 512 window fails both
checks (measured -9.6 dB and -1.12).
- ltx25_studio/audio.py +48 -74
- tests/test_audio.py +169 -46
- tests/test_mel_front_end_real.py +236 -0
|
@@ -436,53 +436,33 @@ def reconcile_waveform_with_video(
|
|
| 436 |
# waveform <-> mel <-> latents
|
| 437 |
# ---------------------------------------------------------------------------
|
| 438 |
|
| 439 |
-
#: Attribute names a loaded ``audio_vae`` may carry its own mel front-end under
|
| 440 |
-
#:
|
| 441 |
-
#:
|
| 442 |
-
#: inventing them would produce a mel spectrogram the VAE was not trained on --
|
| 443 |
-
#: silently, and only audible as degraded audio.
|
| 444 |
MEL_FRONT_END_ATTRS = ("mel_spectrogram", "mel_transform", "_mel_spectrogram")
|
| 445 |
|
| 446 |
|
| 447 |
-
#:
|
| 448 |
-
#: components and agree**, which is what makes this a lookup rather than a
|
| 449 |
-
#: reconstruction: the vocoder's ``num_mel_channels`` is 64 and the VAE's
|
| 450 |
-
#: ``mel_bins`` is 64; the vocoder's ``input_sampling_rate`` is 16000 and the
|
| 451 |
-
#: VAE's ``sample_rate`` is 16000.
|
| 452 |
-
#:
|
| 453 |
-
#: ⚠️ **The hop is the one disagreement, and it is read from the VAE on purpose.**
|
| 454 |
-
#: ``audio_vae.mel_hop_length`` is 160; ``vocoder.hop_length`` is 80. The
|
| 455 |
-
#: vocoder's own ``upsample_factors`` -- ``[5, 2, 2, 2, 2, 2]`` -- multiply to
|
| 456 |
-
#: **160**, matching the VAE rather than the vocoder's own declared 80, so that
|
| 457 |
-
#: 80 refers to something else inside the vocoder. Read ``window_length`` across
|
| 458 |
-
#: from the vocoder; **do NOT read a hop across.** The asymmetry is deliberate
|
| 459 |
-
#: and is exactly the kind of thing a later reader will "tidy" into consistency.
|
| 460 |
-
#:
|
| 461 |
-
#: *Read off vocoder/config.json and audio_vae/config.json at revision
|
| 462 |
-
#: 871165de…, cross-checked against the upsample factors.*
|
| 463 |
MEL_PARAM_SOURCES = MappingProxyType(
|
| 464 |
{
|
| 465 |
-
"
|
| 466 |
-
"
|
| 467 |
-
"
|
| 468 |
-
"n_mels": ("audio_vae", "mel_bins"),
|
| 469 |
-
"sample_rate": ("audio_vae", "sample_rate"),
|
| 470 |
}
|
| 471 |
)
|
| 472 |
|
| 473 |
-
#:
|
| 474 |
-
#:
|
| 475 |
-
#:
|
| 476 |
-
#:
|
| 477 |
-
#:
|
| 478 |
-
#:
|
| 479 |
-
#:
|
| 480 |
-
#: decoration: a wrong window or scaling smears the spectrum and the
|
| 481 |
-
#: reconstruction degrades measurably. If that test fails, these are the
|
| 482 |
-
#: candidates -- in this order.
|
| 483 |
MEL_CONVENTIONS = MappingProxyType(
|
| 484 |
{
|
| 485 |
-
"
|
|
|
|
|
|
|
| 486 |
"f_min": 0.0,
|
| 487 |
"f_max": None, # -> sample_rate / 2
|
| 488 |
"mel_scale": "slaney",
|
|
@@ -512,20 +492,26 @@ MEL_INPUT_DIMS = ("batch", "channels", "time", "mel")
|
|
| 512 |
MEL_LOG_FLOOR = 1e-5
|
| 513 |
|
| 514 |
|
| 515 |
-
def mel_parameters(audio_vae, vocoder):
|
| 516 |
-
"""
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
return values
|
| 530 |
|
| 531 |
|
|
@@ -560,21 +546,18 @@ def encoder_layout(mel):
|
|
| 560 |
return mel.transpose(-2, -1)
|
| 561 |
|
| 562 |
|
| 563 |
-
def build_mel_front_end(audio_vae, vocoder):
|
| 564 |
-
"""
|
| 565 |
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
inverts it -- which is why H5-H9 produce real audio while the audio-INPUT
|
| 569 |
-
modes cannot start. The gap is asymmetric by nature, not by oversight.
|
| 570 |
"""
|
|
|
|
|
|
|
| 571 |
import torch
|
| 572 |
import torchaudio
|
| 573 |
|
| 574 |
-
|
| 575 |
-
conventions = dict(MEL_CONVENTIONS)
|
| 576 |
-
conventions["f_max"] = conventions["f_max"] or params["sample_rate"] / 2
|
| 577 |
-
transform = torchaudio.transforms.MelSpectrogram(**params, **conventions)
|
| 578 |
|
| 579 |
def to_mel(waveform):
|
| 580 |
mel = transform.to(device=waveform.device, dtype=torch.float32)(waveform.float())
|
|
@@ -585,25 +568,16 @@ def build_mel_front_end(audio_vae, vocoder):
|
|
| 585 |
|
| 586 |
|
| 587 |
def mel_front_end_for(audio_vae, vocoder=None):
|
| 588 |
-
"""The callable that turns a waveform into the mel the VAE
|
| 589 |
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
rather than have this module guess an FFT size.
|
| 593 |
"""
|
| 594 |
for attribute in MEL_FRONT_END_ATTRS:
|
| 595 |
found = getattr(audio_vae, attribute, None)
|
| 596 |
if callable(found):
|
| 597 |
return found
|
| 598 |
-
|
| 599 |
-
return build_mel_front_end(audio_vae, vocoder)
|
| 600 |
-
raise LTXStudioError(
|
| 601 |
-
f"the loaded audio_vae carries no mel front-end (looked for "
|
| 602 |
-
f"{', '.join(MEL_FRONT_END_ATTRS)}), and this module will not construct one: the FFT "
|
| 603 |
-
f"and window sizes are not among the parameters audio_vae.config declares, so any "
|
| 604 |
-
f"value chosen here would be a guess that produces a mel spectrogram the VAE was never "
|
| 605 |
-
f"trained on -- audible as degraded audio, reported as nothing. Pass to_mel= explicitly."
|
| 606 |
-
)
|
| 607 |
|
| 608 |
|
| 609 |
def _resampled(waveform, *, from_rate: int, to_rate: int):
|
|
|
|
| 436 |
# waveform <-> mel <-> latents
|
| 437 |
# ---------------------------------------------------------------------------
|
| 438 |
|
| 439 |
+
#: Attribute names a loaded ``audio_vae`` may carry its own mel front-end under,
|
| 440 |
+
#: searched in order. The pinned checkpoint carries none, so
|
| 441 |
+
#: :func:`build_mel_front_end` builds it.
|
|
|
|
|
|
|
| 442 |
MEL_FRONT_END_ATTRS = ("mel_spectrogram", "mel_transform", "_mel_spectrogram")
|
| 443 |
|
| 444 |
|
| 445 |
+
#: Read from ``audio_vae.config``: torchaudio ``MelSpectrogram`` argument -> config key.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
MEL_PARAM_SOURCES = MappingProxyType(
|
| 447 |
{
|
| 448 |
+
"sample_rate": "sample_rate",
|
| 449 |
+
"hop_length": "mel_hop_length",
|
| 450 |
+
"n_mels": "mel_bins",
|
|
|
|
|
|
|
| 451 |
}
|
| 452 |
)
|
| 453 |
|
| 454 |
+
#: Declared, not read: no config describes the audio VAE's analysis window, and
|
| 455 |
+
#: the vocoder's filter_length / window_length / hop_length (512 / 512 / 80) set
|
| 456 |
+
#: up its own internal mel stage, so nothing here comes from the vocoder.
|
| 457 |
+
#: Measured by round trip through the pinned audio VAE and vocoder, 2026-11-16,
|
| 458 |
+
#: CPU float32: with these values speech, an ocean recording and the model's own
|
| 459 |
+
#: output came back at +0.1 / -0.2 / +0.1 dB (mel offset -0.10 / -0.03 / -0.11);
|
| 460 |
+
#: with n_fft = win_length = 512 they lost 8.9 / 9.7 / 8.8 dB.
|
|
|
|
|
|
|
|
|
|
| 461 |
MEL_CONVENTIONS = MappingProxyType(
|
| 462 |
{
|
| 463 |
+
"n_fft": 1024,
|
| 464 |
+
"win_length": 1024,
|
| 465 |
+
"power": 1.0, # magnitude; the log is taken after
|
| 466 |
"f_min": 0.0,
|
| 467 |
"f_max": None, # -> sample_rate / 2
|
| 468 |
"mel_scale": "slaney",
|
|
|
|
| 492 |
MEL_LOG_FLOOR = 1e-5
|
| 493 |
|
| 494 |
|
| 495 |
+
def mel_parameters(audio_vae, vocoder=None):
|
| 496 |
+
"""Every argument the forward transform is built with.
|
| 497 |
+
|
| 498 |
+
The audio VAE's rate, hop and mel bins (:data:`MEL_PARAM_SOURCES`), then
|
| 499 |
+
:data:`MEL_CONVENTIONS` with ``f_max`` resolved. ``vocoder`` is accepted
|
| 500 |
+
from existing callers and supplies nothing.
|
| 501 |
+
"""
|
| 502 |
+
if audio_vae is None:
|
| 503 |
+
raise LTXStudioError(
|
| 504 |
+
"the mel front-end is built from audio_vae.config (sample rate, hop, mel bins), "
|
| 505 |
+
"and no audio_vae was supplied."
|
| 506 |
+
)
|
| 507 |
+
config = _config_of(audio_vae, name="audio_vae")
|
| 508 |
+
values = {
|
| 509 |
+
name: int(_read(config, field, owner="audio_vae.config"))
|
| 510 |
+
for name, field in MEL_PARAM_SOURCES.items()
|
| 511 |
+
}
|
| 512 |
+
values.update(MEL_CONVENTIONS)
|
| 513 |
+
if values["f_max"] is None:
|
| 514 |
+
values["f_max"] = values["sample_rate"] / 2
|
| 515 |
return values
|
| 516 |
|
| 517 |
|
|
|
|
| 546 |
return mel.transpose(-2, -1)
|
| 547 |
|
| 548 |
|
| 549 |
+
def build_mel_front_end(audio_vae, vocoder=None):
|
| 550 |
+
"""The forward transform, waveform -> log-mel in encoder layout, from :func:`mel_parameters`.
|
| 551 |
|
| 552 |
+
Only the encode needs it: on the way out the VAE decoder emits the mel and
|
| 553 |
+
the vocoder inverts it. ``vocoder`` supplies nothing.
|
|
|
|
|
|
|
| 554 |
"""
|
| 555 |
+
# Read before torch is imported, so a missing audio_vae is the same typed error without it.
|
| 556 |
+
params = mel_parameters(audio_vae)
|
| 557 |
import torch
|
| 558 |
import torchaudio
|
| 559 |
|
| 560 |
+
transform = torchaudio.transforms.MelSpectrogram(**params)
|
|
|
|
|
|
|
|
|
|
| 561 |
|
| 562 |
def to_mel(waveform):
|
| 563 |
mel = transform.to(device=waveform.device, dtype=torch.float32)(waveform.float())
|
|
|
|
| 568 |
|
| 569 |
|
| 570 |
def mel_front_end_for(audio_vae, vocoder=None):
|
| 571 |
+
"""The callable that turns a waveform into the mel the audio VAE encodes.
|
| 572 |
|
| 573 |
+
One the VAE carries itself (:data:`MEL_FRONT_END_ATTRS`) is used as is;
|
| 574 |
+
otherwise :func:`build_mel_front_end` builds it. ``vocoder`` supplies nothing.
|
|
|
|
| 575 |
"""
|
| 576 |
for attribute in MEL_FRONT_END_ATTRS:
|
| 577 |
found = getattr(audio_vae, attribute, None)
|
| 578 |
if callable(found):
|
| 579 |
return found
|
| 580 |
+
return build_mel_front_end(audio_vae)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 581 |
|
| 582 |
|
| 583 |
def _resampled(waveform, *, from_rate: int, to_rate: int):
|
|
@@ -124,9 +124,34 @@ SUSPICIOUS_LITERALS = {8000, 16000, 22050, 24000, 32000, 44100, 48000, 1024}
|
|
| 124 |
|
| 125 |
AUDIO_MODULE = PACKAGE_ROOT / "audio.py"
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
def test_no_sample_rate_is_hardcoded():
|
| 129 |
-
"""Comments and docstrings may cite numbers; code may not use them.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
tree = ast.parse(AUDIO_MODULE.read_text())
|
| 131 |
docstring_ids = set()
|
| 132 |
for node in ast.walk(tree):
|
|
@@ -138,6 +163,11 @@ def test_no_sample_rate_is_hardcoded():
|
|
| 138 |
continue
|
| 139 |
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
|
| 140 |
docstring_ids.add(id(body[0].value))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
found = {
|
| 142 |
node.value
|
| 143 |
for node in ast.walk(tree)
|
|
@@ -145,11 +175,13 @@ def test_no_sample_rate_is_hardcoded():
|
|
| 145 |
and isinstance(node.value, int)
|
| 146 |
and not isinstance(node.value, bool)
|
| 147 |
and id(node) not in docstring_ids
|
|
|
|
| 148 |
and node.value in SUSPICIOUS_LITERALS
|
| 149 |
}
|
| 150 |
assert not found, (
|
| 151 |
-
f"audio.py hardcodes {sorted(found)}.
|
| 152 |
-
"audio_vae.config at runtime (PLAN §5.4)
|
|
|
|
| 153 |
)
|
| 154 |
|
| 155 |
|
|
@@ -476,12 +508,12 @@ def test_a_planar_file_is_concatenated_rather_than_reshaped():
|
|
| 476 |
# --------------------------------------------------------------------------
|
| 477 |
# the mel front-end the checkpoint does not ship
|
| 478 |
#
|
| 479 |
-
#
|
| 480 |
-
#
|
| 481 |
-
#
|
| 482 |
-
#
|
| 483 |
-
#
|
| 484 |
-
#
|
| 485 |
# --------------------------------------------------------------------------
|
| 486 |
|
| 487 |
#: The exact key set of ``vocoder/config.json`` at revision 871165de….
|
|
@@ -527,37 +559,65 @@ REAL_VOCODER_CONFIG_KEYS = frozenset(
|
|
| 527 |
}
|
| 528 |
)
|
| 529 |
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
}
|
| 534 |
|
| 535 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
@pytest.mark.parametrize("name", sorted(audio.MEL_PARAM_SOURCES))
|
| 537 |
def test_every_mel_parameter_names_a_key_the_checkpoint_really_has(name):
|
| 538 |
"""The check a fake cannot make, because fakes are built from the mapping."""
|
| 539 |
-
|
| 540 |
|
| 541 |
-
assert field in
|
| 542 |
-
f"{name!r} is read from
|
| 543 |
f"such key -- it would raise on real weights and pass every offline test"
|
| 544 |
)
|
| 545 |
|
| 546 |
|
| 547 |
-
def
|
| 548 |
-
"""
|
| 549 |
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
consistency would halve it.
|
| 554 |
"""
|
| 555 |
-
assert audio.MEL_PARAM_SOURCES
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
|
| 562 |
|
| 563 |
def test_the_vocoders_upsample_factors_corroborate_the_vaes_hop():
|
|
@@ -569,38 +629,101 @@ def test_the_vocoders_upsample_factors_corroborate_the_vaes_hop():
|
|
| 569 |
|
| 570 |
assert product == 160
|
| 571 |
assert product != vocoder.config.hop_length, (
|
| 572 |
-
"the vocoder's
|
| 573 |
-
"
|
| 574 |
)
|
| 575 |
|
| 576 |
|
| 577 |
-
def
|
| 578 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
vae, vocoder = FakeAudioVae(), FakeVocoder()
|
|
|
|
| 580 |
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
assert
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
|
| 585 |
|
| 586 |
def test_the_declared_parameters_are_read_not_defaulted():
|
| 587 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
|
| 589 |
-
assert params == {
|
| 590 |
-
"n_fft": 512,
|
| 591 |
-
"win_length": 512,
|
| 592 |
-
"hop_length": 160,
|
| 593 |
-
"n_mels": 64,
|
| 594 |
-
"sample_rate": 16000,
|
| 595 |
-
}, params
|
| 596 |
|
|
|
|
|
|
|
|
|
|
| 597 |
|
| 598 |
-
def test_building_without_a_vocoder_refuses_rather_than_guessing():
|
| 599 |
-
"""A guessed FFT size produces a mel the VAE was never trained on."""
|
| 600 |
with pytest.raises(LTXStudioError) as excinfo:
|
| 601 |
-
audio.mel_parameters(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
|
| 603 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 604 |
|
| 605 |
|
| 606 |
def test_the_mel_is_cast_to_the_dtype_the_vae_actually_uses():
|
|
|
|
| 124 |
|
| 125 |
AUDIO_MODULE = PACKAGE_ROOT / "audio.py"
|
| 126 |
|
| 127 |
+
#: The only numbers audio.py may write down: the analysis window, declared in
|
| 128 |
+
#: ``MEL_CONVENTIONS`` because no config describes it.
|
| 129 |
+
DECLARED_WINDOW_KEYS = ("n_fft", "win_length")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _declared_window_values(tree) -> set[int]:
|
| 133 |
+
"""The ``id`` of each window value node in the ``MEL_CONVENTIONS`` literal."""
|
| 134 |
+
declared = set()
|
| 135 |
+
for node in ast.walk(tree):
|
| 136 |
+
names = [t.id for t in getattr(node, "targets", ()) if isinstance(t, ast.Name)]
|
| 137 |
+
if not isinstance(node, ast.Assign) or "MEL_CONVENTIONS" not in names:
|
| 138 |
+
continue
|
| 139 |
+
for inner in ast.walk(node.value):
|
| 140 |
+
if isinstance(inner, ast.Dict):
|
| 141 |
+
for key, value in zip(inner.keys, inner.values, strict=True):
|
| 142 |
+
if isinstance(key, ast.Constant) and key.value in DECLARED_WINDOW_KEYS:
|
| 143 |
+
declared.add(id(value))
|
| 144 |
+
return declared
|
| 145 |
+
|
| 146 |
|
| 147 |
def test_no_sample_rate_is_hardcoded():
|
| 148 |
+
"""Comments and docstrings may cite numbers; code may not use them.
|
| 149 |
+
|
| 150 |
+
Except the analysis window, declared once in ``MEL_CONVENTIONS``: no config
|
| 151 |
+
describes the audio VAE's window, and 1024 was measured by round trip
|
| 152 |
+
through the real audio VAE and vocoder (2026-11-16). Anywhere else, a 1024
|
| 153 |
+
is as suspect as a sample rate.
|
| 154 |
+
"""
|
| 155 |
tree = ast.parse(AUDIO_MODULE.read_text())
|
| 156 |
docstring_ids = set()
|
| 157 |
for node in ast.walk(tree):
|
|
|
|
| 163 |
continue
|
| 164 |
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
|
| 165 |
docstring_ids.add(id(body[0].value))
|
| 166 |
+
declared = _declared_window_values(tree)
|
| 167 |
+
assert len(declared) == len(DECLARED_WINDOW_KEYS), (
|
| 168 |
+
f"expected MEL_CONVENTIONS to declare {DECLARED_WINDOW_KEYS} once each, found "
|
| 169 |
+
f"{len(declared)}; this scan exempts exactly those values and nothing else"
|
| 170 |
+
)
|
| 171 |
found = {
|
| 172 |
node.value
|
| 173 |
for node in ast.walk(tree)
|
|
|
|
| 175 |
and isinstance(node.value, int)
|
| 176 |
and not isinstance(node.value, bool)
|
| 177 |
and id(node) not in docstring_ids
|
| 178 |
+
and id(node) not in declared
|
| 179 |
and node.value in SUSPICIOUS_LITERALS
|
| 180 |
}
|
| 181 |
assert not found, (
|
| 182 |
+
f"audio.py hardcodes {sorted(found)}. Rate, hop and mel bins are read from "
|
| 183 |
+
"audio_vae.config at runtime (PLAN §5.4); the only numbers written down are the "
|
| 184 |
+
"declared conventions in MEL_CONVENTIONS."
|
| 185 |
)
|
| 186 |
|
| 187 |
|
|
|
|
| 508 |
# --------------------------------------------------------------------------
|
| 509 |
# the mel front-end the checkpoint does not ship
|
| 510 |
#
|
| 511 |
+
# The forward transform is built here: sample rate, hop and mel bins read from
|
| 512 |
+
# the audio VAE's config, n_fft and win_length declared in MEL_CONVENTIONS.
|
| 513 |
+
# The vocoder's filter_length / window_length / hop_length (512 / 512 / 80) set
|
| 514 |
+
# up its own internal mel stage, so nothing is read from it; taking the window
|
| 515 |
+
# from there made every encoded sound about 9 dB too quiet. The decode needs
|
| 516 |
+
# none of this: the VAE decoder emits a mel and the vocoder inverts it.
|
| 517 |
# --------------------------------------------------------------------------
|
| 518 |
|
| 519 |
#: The exact key set of ``vocoder/config.json`` at revision 871165de….
|
|
|
|
| 559 |
}
|
| 560 |
)
|
| 561 |
|
| 562 |
+
#: Every argument the forward transform is built with, for the pinned checkpoint.
|
| 563 |
+
PINNED_MEL_PARAMETERS = {
|
| 564 |
+
"sample_rate": 16000,
|
| 565 |
+
"hop_length": 160,
|
| 566 |
+
"n_mels": 64,
|
| 567 |
+
"n_fft": 1024,
|
| 568 |
+
"win_length": 1024,
|
| 569 |
+
"power": 1.0,
|
| 570 |
+
"f_min": 0.0,
|
| 571 |
+
"f_max": 8000.0,
|
| 572 |
+
"mel_scale": "slaney",
|
| 573 |
+
"norm": "slaney",
|
| 574 |
+
"center": True,
|
| 575 |
}
|
| 576 |
|
| 577 |
|
| 578 |
+
class UntouchableVocoder:
|
| 579 |
+
"""A vocoder that fails the test the moment anything reads from it."""
|
| 580 |
+
|
| 581 |
+
def __getattr__(self, name):
|
| 582 |
+
raise AssertionError(f"the mel front end read vocoder.{name}")
|
| 583 |
+
|
| 584 |
+
|
| 585 |
@pytest.mark.parametrize("name", sorted(audio.MEL_PARAM_SOURCES))
|
| 586 |
def test_every_mel_parameter_names_a_key_the_checkpoint_really_has(name):
|
| 587 |
"""The check a fake cannot make, because fakes are built from the mapping."""
|
| 588 |
+
field = audio.MEL_PARAM_SOURCES[name]
|
| 589 |
|
| 590 |
+
assert field in REAL_AUDIO_VAE_CONFIG_KEYS, (
|
| 591 |
+
f"{name!r} is read from audio_vae.config[{field!r}] and the real checkpoint has no "
|
| 592 |
f"such key -- it would raise on real weights and pass every offline test"
|
| 593 |
)
|
| 594 |
|
| 595 |
|
| 596 |
+
def test_only_the_rate_hop_and_bins_are_read_and_the_window_is_declared():
|
| 597 |
+
"""n_fft and win_length are conventions, not readings from the vocoder.
|
| 598 |
|
| 599 |
+
The vocoder's 512 / 512 set up its own mel stage; the audio VAE was built
|
| 600 |
+
for 1024 (measured by round trip, 2026-11-16). The hop is the VAE's 160,
|
| 601 |
+
never the vocoder's 80.
|
|
|
|
| 602 |
"""
|
| 603 |
+
assert dict(audio.MEL_PARAM_SOURCES) == {
|
| 604 |
+
"sample_rate": "sample_rate",
|
| 605 |
+
"hop_length": "mel_hop_length",
|
| 606 |
+
"n_mels": "mel_bins",
|
| 607 |
+
}
|
| 608 |
+
assert {key: audio.MEL_CONVENTIONS[key] for key in ("n_fft", "win_length")} == {
|
| 609 |
+
"n_fft": 1024,
|
| 610 |
+
"win_length": 1024,
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def test_nothing_is_read_from_the_vocoder():
|
| 615 |
+
"""A vocoder whose every attribute raises changes nothing, and so does none at all."""
|
| 616 |
+
vae = FakeAudioVae()
|
| 617 |
+
|
| 618 |
+
assert audio.mel_parameters(vae, UntouchableVocoder()) == PINNED_MEL_PARAMETERS
|
| 619 |
+
assert audio.mel_parameters(vae, None) == PINNED_MEL_PARAMETERS
|
| 620 |
+
assert audio.mel_parameters(vae) == PINNED_MEL_PARAMETERS
|
| 621 |
|
| 622 |
|
| 623 |
def test_the_vocoders_upsample_factors_corroborate_the_vaes_hop():
|
|
|
|
| 629 |
|
| 630 |
assert product == 160
|
| 631 |
assert product != vocoder.config.hop_length, (
|
| 632 |
+
"the fake vocoder's hop_length now equals its upsample product; the real config "
|
| 633 |
+
"says 80 against 160, and its 80 is the hop of the vocoder's own mel stage"
|
| 634 |
)
|
| 635 |
|
| 636 |
|
| 637 |
+
def test_the_vocoder_shares_only_the_rate_and_bins_with_the_front_end():
|
| 638 |
+
"""The vocoder takes the VAE's mel, so it agrees on the rate and the bins.
|
| 639 |
+
|
| 640 |
+
Its filter_length / window_length / hop_length -- 512 / 512 / 80 in the
|
| 641 |
+
real config and in the suite's fake -- set up its internal mel stage for
|
| 642 |
+
bandwidth extension, and none of them is what the transform is built with.
|
| 643 |
+
"""
|
| 644 |
vae, vocoder = FakeAudioVae(), FakeVocoder()
|
| 645 |
+
stft_keys = ("filter_length", "window_length", "hop_length")
|
| 646 |
|
| 647 |
+
params = audio.mel_parameters(vae, vocoder)
|
| 648 |
+
|
| 649 |
+
assert set(stft_keys) <= REAL_VOCODER_CONFIG_KEYS
|
| 650 |
+
assert tuple(getattr(vocoder.config, key) for key in stft_keys) == (512, 512, 80)
|
| 651 |
+
assert (params["n_fft"], params["win_length"], params["hop_length"]) == (1024, 1024, 160)
|
| 652 |
+
assert params["n_mels"] == vae.config.mel_bins == vocoder.config.num_mel_channels
|
| 653 |
+
assert params["sample_rate"] == vae.config.sample_rate == vocoder.config.input_sampling_rate
|
| 654 |
|
| 655 |
|
| 656 |
def test_the_declared_parameters_are_read_not_defaulted():
|
| 657 |
+
"""Rate, hop and bins follow the audio VAE's config; the window does not move with them."""
|
| 658 |
+
assert audio.mel_parameters(FakeAudioVae(), FakeVocoder()) == PINNED_MEL_PARAMETERS
|
| 659 |
+
|
| 660 |
+
unusual = FakeAudioVae(sampling_rate=22050)
|
| 661 |
+
unusual.config.mel_hop_length = 256
|
| 662 |
+
unusual.config.mel_bins = 80
|
| 663 |
+
params = audio.mel_parameters(unusual)
|
| 664 |
+
|
| 665 |
+
read = {key: params[key] for key in ("sample_rate", "hop_length", "n_mels", "f_max")}
|
| 666 |
+
assert read == {"sample_rate": 22050, "hop_length": 256, "n_mels": 80, "f_max": 11025.0}
|
| 667 |
+
assert (params["n_fft"], params["win_length"]) == (1024, 1024), params
|
| 668 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 669 |
|
| 670 |
+
def test_a_missing_config_field_is_named_rather_than_defaulted():
|
| 671 |
+
vae = FakeAudioVae()
|
| 672 |
+
del vae.config.mel_hop_length
|
| 673 |
|
|
|
|
|
|
|
| 674 |
with pytest.raises(LTXStudioError) as excinfo:
|
| 675 |
+
audio.mel_parameters(vae)
|
| 676 |
+
|
| 677 |
+
assert "mel_hop_length" in str(excinfo.value), excinfo.value
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@pytest.mark.parametrize(
|
| 681 |
+
"build",
|
| 682 |
+
[audio.mel_parameters, audio.build_mel_front_end, audio.mel_front_end_for],
|
| 683 |
+
ids=["mel_parameters", "build_mel_front_end", "mel_front_end_for"],
|
| 684 |
+
)
|
| 685 |
+
def test_a_missing_audio_vae_is_a_typed_error(build):
|
| 686 |
+
"""Raised before torch is imported, so it is the same error with or without torch."""
|
| 687 |
+
with pytest.raises(LTXStudioError) as excinfo:
|
| 688 |
+
build(None, FakeVocoder())
|
| 689 |
+
|
| 690 |
+
assert "audio_vae" in str(excinfo.value), excinfo.value
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@pytest.mark.parametrize("vocoder", [FakeVocoder(), None], ids=["fake_vocoder", "no_vocoder"])
|
| 694 |
+
def test_the_encode_builds_the_transform_with_the_measured_window(monkeypatch, vocoder):
|
| 695 |
+
"""Through the encode, as ``generate`` calls it, with the real torchaudio class.
|
| 696 |
+
|
| 697 |
+
Like the checkpoint's, this VAE carries no front end, so one is built. The
|
| 698 |
+
fake vocoder's config says 512 / 512 / 80 and changes nothing; neither does
|
| 699 |
+
passing no vocoder at all.
|
| 700 |
+
"""
|
| 701 |
+
torch = pytest.importorskip("torch", reason="needs real torch")
|
| 702 |
+
torchaudio = pytest.importorskip("torchaudio", reason="needs real torchaudio")
|
| 703 |
+
built = []
|
| 704 |
+
|
| 705 |
+
class Recorded(torchaudio.transforms.MelSpectrogram):
|
| 706 |
+
def __init__(self, **kwargs):
|
| 707 |
+
super().__init__(**kwargs)
|
| 708 |
+
built.append(self)
|
| 709 |
+
|
| 710 |
+
class CheckpointLikeVae(FakeAudioVae):
|
| 711 |
+
mel_spectrogram = None
|
| 712 |
+
dtype = torch.float32
|
| 713 |
+
device = torch.device("cpu")
|
| 714 |
+
|
| 715 |
+
monkeypatch.setattr(torchaudio.transforms, "MelSpectrogram", Recorded)
|
| 716 |
+
vae = CheckpointLikeVae()
|
| 717 |
+
|
| 718 |
+
audio.encode_waveform_to_latents(
|
| 719 |
+
torch.zeros((2, 16000)), audio_vae=vae, sampling_rate=16000, vocoder=vocoder
|
| 720 |
+
)
|
| 721 |
|
| 722 |
+
(transform,) = built
|
| 723 |
+
assert (transform.n_fft, transform.win_length, transform.hop_length) == (1024, 1024, 160)
|
| 724 |
+
assert (transform.sample_rate, transform.n_mels, transform.f_max) == (16000, 64, 8000.0)
|
| 725 |
+
assert tuple(transform.mel_scale.fb.shape) == (513, 64)
|
| 726 |
+
assert tuple(vae.encoded[-1].shape) == (1, 2, 101, 64), tuple(vae.encoded[-1].shape)
|
| 727 |
|
| 728 |
|
| 729 |
def test_the_mel_is_cast_to_the_dtype_the_vae_actually_uses():
|
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The forward mel transform against the real audio VAE and vocoder (issue F69).
|
| 2 |
+
|
| 3 |
+
Loads only the pinned ``audio_vae`` and ``vocoder`` (about 350 MB on disk) from
|
| 4 |
+
the local Hugging Face cache, on the CPU in float32, at the revision
|
| 5 |
+
``ltx25_studio.model_files`` pins. Never downloads and never loads anything
|
| 6 |
+
else. Skips, with the reason, when torch, torchaudio or diffusers is missing,
|
| 7 |
+
when either component is not cached, or when
|
| 8 |
+
``LTX25_SKIP_REAL_COMPONENT_TESTS=1``.
|
| 9 |
+
|
| 10 |
+
Two checks, both through the app's own ``encode_waveform_to_latents`` and
|
| 11 |
+
``decode_latents_to_waveform``:
|
| 12 |
+
|
| 13 |
+
- the round trip returns the signal at the level it was given;
|
| 14 |
+
- the transform of the vocoder's output matches the mel the vocoder was given.
|
| 15 |
+
|
| 16 |
+
A transform built with a 512 window fails both, which is what shipped: every
|
| 17 |
+
encoded sound reached the model about 9 dB too quiet.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
|
| 25 |
+
import pytest
|
| 26 |
+
|
| 27 |
+
from ltx25_studio import audio
|
| 28 |
+
|
| 29 |
+
SKIP_ENV = "LTX25_SKIP_REAL_COMPONENT_TESTS"
|
| 30 |
+
|
| 31 |
+
#: The upload: stereo at a common upload rate, so the encode resamples as it does for a user.
|
| 32 |
+
RATE = 48000
|
| 33 |
+
SECONDS = 2.0
|
| 34 |
+
THREADS = 4
|
| 35 |
+
|
| 36 |
+
LEVEL_TOLERANCE_DB = 1.5
|
| 37 |
+
OFFSET_TOLERANCE = 0.3 # natural-log mel units
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class Pair:
|
| 42 |
+
torch: object
|
| 43 |
+
torchaudio: object
|
| 44 |
+
audio_vae: object
|
| 45 |
+
vocoder: object
|
| 46 |
+
waveform: object
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass(frozen=True)
|
| 50 |
+
class Measured:
|
| 51 |
+
level_db: float
|
| 52 |
+
offset: float
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _skip_unless_available():
|
| 56 |
+
if os.environ.get(SKIP_ENV) == "1":
|
| 57 |
+
pytest.skip(f"{SKIP_ENV}=1")
|
| 58 |
+
torch = pytest.importorskip("torch", reason="needs torch")
|
| 59 |
+
torchaudio = pytest.importorskip("torchaudio", reason="needs torchaudio")
|
| 60 |
+
pytest.importorskip("diffusers", reason="needs diffusers")
|
| 61 |
+
return torch, torchaudio
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _cached_dir(name):
|
| 65 |
+
"""The pinned component's folder in the local HF cache, or skip. Never downloads."""
|
| 66 |
+
from ltx25_studio import model_files, preflight
|
| 67 |
+
|
| 68 |
+
spec = model_files.get_component(name)
|
| 69 |
+
folder = model_files.component_dir(name, repo_cache=preflight.cache_repo_dir())
|
| 70 |
+
missing = [filename for filename in spec.files if not (folder / filename).is_file()]
|
| 71 |
+
if missing:
|
| 72 |
+
pytest.skip(
|
| 73 |
+
f"the pinned {name} ({spec.repo_id}@{spec.revision[:8]}) is not in the local "
|
| 74 |
+
f"Hugging Face cache: {folder} lacks {', '.join(missing)}. This test never downloads."
|
| 75 |
+
)
|
| 76 |
+
return folder
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _signal(torch):
|
| 80 |
+
"""Two tones per channel under a tremolo, plus a pink noise burst inside the VAE's band.
|
| 81 |
+
|
| 82 |
+
The noise carries most of the energy and covers 50-7500 Hz, below the audio
|
| 83 |
+
VAE's 8 kHz Nyquist, so the resample to its rate removes nothing. Isolated
|
| 84 |
+
pure tones would not do: even with the 1024 window this vocoder renders them
|
| 85 |
+
11-16 dB low (measured 2026-11-16), which it does not do to speech or noise.
|
| 86 |
+
"""
|
| 87 |
+
samples = int(RATE * SECONDS)
|
| 88 |
+
t = torch.arange(samples, dtype=torch.float64) / RATE
|
| 89 |
+
fades = torch.clamp(torch.minimum(t, SECONDS - t) / 0.05, max=1.0)
|
| 90 |
+
tremolo = fades * (0.65 + 0.35 * torch.sin(2 * torch.pi * 1.5 * t))
|
| 91 |
+
left = 0.05 * torch.sin(2 * torch.pi * 440 * t) + 0.03 * torch.sin(2 * torch.pi * 1320 * t)
|
| 92 |
+
right = 0.05 * torch.sin(2 * torch.pi * 660 * t) + 0.03 * torch.sin(2 * torch.pi * 1760 * t)
|
| 93 |
+
tones = torch.stack([left, right]) * tremolo
|
| 94 |
+
|
| 95 |
+
generator = torch.Generator().manual_seed(69)
|
| 96 |
+
spectrum = torch.fft.rfft(torch.randn((2, samples), generator=generator, dtype=torch.float64))
|
| 97 |
+
freqs = torch.fft.rfftfreq(samples, 1.0 / RATE)
|
| 98 |
+
spectrum = spectrum / torch.clamp(freqs, min=1.0).sqrt() # pink: power falls as 1/f
|
| 99 |
+
spectrum[:, (freqs < 50) | (freqs > 7500)] = 0
|
| 100 |
+
noise = torch.fft.irfft(spectrum, n=samples)
|
| 101 |
+
noise = noise / noise.pow(2).mean().sqrt()
|
| 102 |
+
start, stop = int(0.15 * samples), int(0.85 * samples)
|
| 103 |
+
burst = torch.zeros(samples, dtype=torch.float64)
|
| 104 |
+
burst[start:stop] = torch.hann_window(stop - start, periodic=False, dtype=torch.float64)
|
| 105 |
+
|
| 106 |
+
return (tones + 0.2 * noise * burst).float()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@pytest.fixture(scope="module")
|
| 110 |
+
def pair():
|
| 111 |
+
torch, torchaudio = _skip_unless_available()
|
| 112 |
+
from diffusers import AutoencoderKLLTX2Audio
|
| 113 |
+
from diffusers.pipelines.ltx2.vocoder import LTX2VocoderWithBWE
|
| 114 |
+
|
| 115 |
+
folders = {name: _cached_dir(name) for name in ("audio_vae", "vocoder")}
|
| 116 |
+
threads = torch.get_num_threads()
|
| 117 |
+
torch.set_num_threads(THREADS)
|
| 118 |
+
try:
|
| 119 |
+
loaded = Pair(
|
| 120 |
+
torch=torch,
|
| 121 |
+
torchaudio=torchaudio,
|
| 122 |
+
audio_vae=AutoencoderKLLTX2Audio.from_pretrained(
|
| 123 |
+
folders["audio_vae"], dtype=torch.float32, local_files_only=True
|
| 124 |
+
).eval(),
|
| 125 |
+
vocoder=LTX2VocoderWithBWE.from_pretrained(
|
| 126 |
+
folders["vocoder"], dtype=torch.float32, local_files_only=True
|
| 127 |
+
).eval(),
|
| 128 |
+
waveform=_signal(torch),
|
| 129 |
+
)
|
| 130 |
+
yield loaded
|
| 131 |
+
finally:
|
| 132 |
+
torch.set_num_threads(threads)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class _Recording:
|
| 136 |
+
"""The real vocoder, keeping the mel it was given."""
|
| 137 |
+
|
| 138 |
+
def __init__(self, vocoder):
|
| 139 |
+
self._vocoder = vocoder
|
| 140 |
+
self.config = vocoder.config
|
| 141 |
+
self.given = []
|
| 142 |
+
|
| 143 |
+
def __call__(self, mel):
|
| 144 |
+
self.given.append(mel)
|
| 145 |
+
return self._vocoder(mel)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _rms_db(torch, x):
|
| 149 |
+
return 20 * torch.log10(x.double().pow(2).mean().sqrt()).item()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _mean_offset(mel, given):
|
| 153 |
+
"""Mean of ``mel - given`` in log units, over the frames that carry energy.
|
| 154 |
+
|
| 155 |
+
Per mel band over the frames whose mean exceeds the clip's mean minus one,
|
| 156 |
+
then averaged across bands. 0 means the vocoder's output, put through the
|
| 157 |
+
transform, is the mel it was given.
|
| 158 |
+
"""
|
| 159 |
+
frames = min(mel.shape[-2], given.shape[-2])
|
| 160 |
+
mel, given = mel[..., :frames, :], given[..., :frames, :]
|
| 161 |
+
loud = given.mean(dim=-1, keepdim=True) > given.mean() - 1.0
|
| 162 |
+
per_band = ((mel - given) * loud).sum(dim=(0, 1, 2)) / loud.sum().clamp(min=1)
|
| 163 |
+
return per_band.mean().item()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _round_trip(pair) -> Measured:
|
| 167 |
+
"""Encode the signal the way ``generate`` does, decode it, and measure both checks."""
|
| 168 |
+
torch = pair.torch
|
| 169 |
+
with torch.inference_mode():
|
| 170 |
+
latents = audio.encode_waveform_to_latents(
|
| 171 |
+
pair.waveform, audio_vae=pair.audio_vae, sampling_rate=RATE, vocoder=pair.vocoder
|
| 172 |
+
)
|
| 173 |
+
vocoder = _Recording(pair.vocoder)
|
| 174 |
+
decoded, rate = audio.decode_latents_to_waveform(
|
| 175 |
+
latents, audio_vae=pair.audio_vae, vocoder=vocoder
|
| 176 |
+
)
|
| 177 |
+
to_mel = audio.mel_front_end_for(pair.audio_vae, pair.vocoder)
|
| 178 |
+
vae_rate = audio.audio_params_from(pair.audio_vae).audio_sampling_rate
|
| 179 |
+
resampled = pair.torchaudio.functional.resample(decoded[0], int(rate), int(vae_rate))
|
| 180 |
+
mel = to_mel(audio.batched(resampled))
|
| 181 |
+
(given,) = vocoder.given
|
| 182 |
+
return Measured(
|
| 183 |
+
level_db=_rms_db(torch, decoded) - _rms_db(torch, pair.waveform),
|
| 184 |
+
offset=_mean_offset(mel, given),
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@pytest.fixture(scope="module")
|
| 189 |
+
def as_built(pair):
|
| 190 |
+
"""Both checks on the front end the app builds."""
|
| 191 |
+
return _round_trip(pair)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@pytest.fixture(scope="module")
|
| 195 |
+
def with_512_window(pair):
|
| 196 |
+
"""The same round trip with the front end built with n_fft = win_length = 512."""
|
| 197 |
+
real = pair.torchaudio.transforms.MelSpectrogram
|
| 198 |
+
built = []
|
| 199 |
+
|
| 200 |
+
def narrowed(**kwargs):
|
| 201 |
+
built.append(real(**{**kwargs, "n_fft": 512, "win_length": 512}))
|
| 202 |
+
return built[-1]
|
| 203 |
+
|
| 204 |
+
with pytest.MonkeyPatch.context() as patch:
|
| 205 |
+
patch.setattr(pair.torchaudio.transforms, "MelSpectrogram", narrowed)
|
| 206 |
+
measured = _round_trip(pair)
|
| 207 |
+
assert built, "the 512 arm never built a transform, so it measured the app's own"
|
| 208 |
+
return measured
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_the_round_trip_returns_the_level_it_was_given(as_built):
|
| 212 |
+
assert abs(as_built.level_db) <= LEVEL_TOLERANCE_DB, (
|
| 213 |
+
f"encode -> decode changed the level by {as_built.level_db:+.1f} dB (allowed "
|
| 214 |
+
f"+/-{LEVEL_TOLERANCE_DB}). A 512 window loses about 9 dB: the mel the audio VAE is "
|
| 215 |
+
f"given is too small, so everything encoded reaches the model too quiet."
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_the_vocoders_output_maps_back_to_the_mel_it_was_given(as_built):
|
| 220 |
+
assert abs(as_built.offset) <= OFFSET_TOLERANCE, (
|
| 221 |
+
f"the transform of the vocoder's output is {as_built.offset:+.2f} log units away "
|
| 222 |
+
f"from the mel the vocoder was given (allowed +/-{OFFSET_TOLERANCE}). The forward "
|
| 223 |
+
f"transform is not the one the audio VAE and vocoder agree on."
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_a_512_window_fails_both_checks(with_512_window):
|
| 228 |
+
"""The regression guard: the window the app used to take from the vocoder's config."""
|
| 229 |
+
assert abs(with_512_window.level_db) > LEVEL_TOLERANCE_DB, (
|
| 230 |
+
f"with a 512 window the round trip changed the level by only "
|
| 231 |
+
f"{with_512_window.level_db:+.1f} dB, so the level check no longer tells the windows apart"
|
| 232 |
+
)
|
| 233 |
+
assert abs(with_512_window.offset) > OFFSET_TOLERANCE, (
|
| 234 |
+
f"with a 512 window the offset is only {with_512_window.offset:+.2f} log units, so the "
|
| 235 |
+
f"consistency check no longer tells the windows apart"
|
| 236 |
+
)
|