techfreakworm commited on
Commit
4ebb8b9
·
unverified ·
1 Parent(s): 4804da1

fix: seed the pipeline, and start the schedule where the noise actually is

Browse files

Two defects on the audio-input path, both confirmed on the card.

THE SEED NEVER REACHED THE MODEL. _resolve_seed ran and the number went into
encoder_kwargs as sidecar metadata; there was no generator anywhere in the
package or the harness. So every run was unconditionally random and every
"same seed" comparison was two independent runs -- H10b, the before/after
pixel diffs, H12b, H4b. What survives is everything structural: H14's exact
2x resolution, H15's 97 frames, H17's frequency recovery, and every audio
level, since a 50 dB gap is not run-to-run variation.

decode_kwargs(generator=kwargs.get("generator")) was mine, written during the
stage-2 work with a docstring about the decoder drawing its own noise. It
read a key nothing ever set -- an advertised lever attached to nothing, in
the session I spent removing other people's.

_sampled also called .sample() bare where upstream threads a generator, so
the audio encode drew differently every run. The sampling MODE was always
right; upstream defaults to "sample" too. Both are now fed the same seeded
generator, built on the pipeline's own device for the same reason the dtype
is read off the component.

AND noise_scale IS sigmas[0]. Upstream infers one from the other -- "first
(largest) sigma value if using custom sigmas" -- so a run noised to 0.5 while
the scheduler is told 1.0 has a whole schedule's worth of noise removed from
a half-noised tensor. Measured: agree -10.4 dBFS, disagree -87.7 dBFS, one
variable.

schedule_from() truncates the distilled curve at noise_scale, and BOTH paths
take it. Stage 2 passes noise_scale == sigmas[0] so it returns the three-step
tail unchanged -- it keeps its behaviour by construction rather than by two
branches happening to agree, which is exactly how they diverged. The
reasoning existed in stage_2_kwargs' docstring and never reached the audio
path: a rule written on one branch is not a rule.

Truncation rather than rescaling, because rescaling invents a curve upstream
never publishes.

The usable noise_scale range is NOT set here. The schedule degenerates to one
step below 0.421875 and discards the input entirely at 1.0, but "one step"
and "bad output" are different claims. That range is a measurement and the
sweep will decide it.

Both mutations fail: untruncating names the sigma disagreement and the
measured dBFS, and removing the generator names the seed that never arrived.

Also hardened test_no_sample_rate_is_hardcoded, which assumed every node's
.body is a list -- an IfExp's is a single expression, so any ternary in
audio.py crashed the scan with "'Call' object is not subscriptable".

ltx25_studio/audio.py CHANGED
@@ -512,11 +512,17 @@ def _resampled(waveform, *, from_rate: int, to_rate: int):
512
  return torchaudio.functional.resample(waveform, int(from_rate), int(to_rate))
513
 
514
 
515
- def _sampled(encoded):
516
- """Unwrap whatever ``audio_vae.encode`` returned into a latent tensor."""
 
 
 
 
 
 
517
  distribution = getattr(encoded, "latent_dist", None)
518
  if distribution is not None:
519
- return distribution.sample()
520
  for attribute in ("latents", "sample"):
521
  found = getattr(encoded, attribute, None)
522
  if found is not None:
@@ -748,7 +754,14 @@ def _matched_to_module(tensor, component, *, name: str):
748
 
749
 
750
  def encode_waveform_to_latents(
751
- waveform, *, audio_vae, sampling_rate: int, to_mel=None, notes=None, vocoder=None
 
 
 
 
 
 
 
752
  ):
753
  """waveform -> mel -> ``audio_vae`` latents, ready to pass as ``audio_latents``.
754
 
@@ -792,7 +805,7 @@ def encode_waveform_to_latents(
792
  # explicitly-passed `to_mel=` from a caller who does not know the VAE dtype.
793
  mel = _matched_to_module(mel, audio_vae, name="audio_vae")
794
  _validate_mel_rank(mel)
795
- latents = _sampled(audio_vae.encode(mel))
796
  validate_audio_latents_shape(getattr(latents, "shape", ()))
797
  return latents
798
 
 
512
  return torchaudio.functional.resample(waveform, int(from_rate), int(to_rate))
513
 
514
 
515
+ def _sampled(encoded, generator=None):
516
+ """Unwrap whatever ``audio_vae.encode`` returned into a latent tensor.
517
+
518
+ ``.sample()`` **draws**, so it takes a generator like any other sampler.
519
+ Upstream's ``retrieve_latents`` threads one; we called it bare, which made
520
+ two runs draw different latents regardless of the lever being tested. The
521
+ sampling *mode* was always right -- upstream defaults to ``"sample"`` too.
522
+ """
523
  distribution = getattr(encoded, "latent_dist", None)
524
  if distribution is not None:
525
+ return distribution.sample(generator) if generator is not None else distribution.sample()
526
  for attribute in ("latents", "sample"):
527
  found = getattr(encoded, attribute, None)
528
  if found is not None:
 
754
 
755
 
756
  def encode_waveform_to_latents(
757
+ waveform,
758
+ *,
759
+ audio_vae,
760
+ sampling_rate: int,
761
+ to_mel=None,
762
+ notes=None,
763
+ vocoder=None,
764
+ generator=None,
765
  ):
766
  """waveform -> mel -> ``audio_vae`` latents, ready to pass as ``audio_latents``.
767
 
 
805
  # explicitly-passed `to_mel=` from a caller who does not know the VAE dtype.
806
  mel = _matched_to_module(mel, audio_vae, name="audio_vae")
807
  _validate_mel_rank(mel)
808
+ latents = _sampled(audio_vae.encode(mel), generator)
809
  validate_audio_latents_shape(getattr(latents, "shape", ()))
810
  return latents
811
 
ltx25_studio/generate.py CHANGED
@@ -277,6 +277,33 @@ def _prepared_conditions(kwargs: dict, request: GenerationRequest) -> None:
277
  )
278
 
279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  def _prepared_audio(kwargs: dict, request: GenerationRequest, pipe) -> tuple[str, ...]:
281
  """Encode the user's audio file into the latents the pipeline actually takes.
282
 
@@ -312,6 +339,10 @@ def _prepared_audio(kwargs: dict, request: GenerationRequest, pipe) -> tuple[str
312
  )
313
 
314
  waveform, rate = audio_module.load_waveform(source)
 
 
 
 
315
  # Anything the encode had to change about the user's file comes back here,
316
  # so it reaches `GenerationResult.warnings` rather than the Space log alone.
317
  notes: list[str] = []
@@ -321,6 +352,7 @@ def _prepared_audio(kwargs: dict, request: GenerationRequest, pipe) -> tuple[str
321
  sampling_rate=rate,
322
  notes=notes,
323
  vocoder=vocoder,
 
324
  )
325
  return tuple(notes)
326
 
@@ -546,6 +578,12 @@ def generate(
546
  kwargs = _pipeline_kwargs(spec, request)
547
  _prepared_conditions(kwargs, request)
548
  _apply_loras(pipe, request)
 
 
 
 
 
 
549
  # After the pipeline exists, because encoding needs its `audio_vae`.
550
  audio_notes = _prepared_audio(kwargs, request, pipe)
551
  size_notes = ()
 
277
  )
278
 
279
 
280
+ def _seeded_generator(pipe, seed: int):
281
+ """A generator on the pipeline's own device, seeded from the request.
282
+
283
+ **The seed used to reach only the sidecar.** ``_resolve_seed`` ran, the
284
+ number went into ``encoder_kwargs`` as metadata, and **nothing was ever
285
+ seeded** -- there was no generator anywhere in the package. So every run was
286
+ unconditionally random and every "same seed" comparison was two independent
287
+ runs: H10b, the before/after pixel diffs, H12b, H4b.
288
+
289
+ The device is read off the pipeline for the same reason the dtype is: a
290
+ CUDA generator is required for CUDA sampling, and ``"cuda"`` hardcoded is
291
+ wrong under offload or a second device.
292
+
293
+ Returns ``None`` when torch is absent, which is only true where there is no
294
+ model to seed -- the offline gate. It is not a fallback on a real path.
295
+ """
296
+ try:
297
+ import torch
298
+ except ImportError:
299
+ return None
300
+
301
+ target = getattr(getattr(pipe, "pipeline", pipe), "device", None)
302
+ generator = torch.Generator(device=target) if target is not None else torch.Generator()
303
+ generator.manual_seed(int(seed))
304
+ return generator
305
+
306
+
307
  def _prepared_audio(kwargs: dict, request: GenerationRequest, pipe) -> tuple[str, ...]:
308
  """Encode the user's audio file into the latents the pipeline actually takes.
309
 
 
339
  )
340
 
341
  waveform, rate = audio_module.load_waveform(source)
342
+ # The same generator the pipeline gets: `audio_vae.encode` returns a
343
+ # distribution and `.sample()` draws from it, so an unseeded draw makes two
344
+ # runs differ regardless of any lever under test. That is the third reason
345
+ # H10b established less than it appeared to.
346
  # Anything the encode had to change about the user's file comes back here,
347
  # so it reaches `GenerationResult.warnings` rather than the Space log alone.
348
  notes: list[str] = []
 
352
  sampling_rate=rate,
353
  notes=notes,
354
  vocoder=vocoder,
355
+ generator=kwargs.get("generator"),
356
  )
357
  return tuple(notes)
358
 
 
578
  kwargs = _pipeline_kwargs(spec, request)
579
  _prepared_conditions(kwargs, request)
580
  _apply_loras(pipe, request)
581
+ # Before `_prepared_audio`, because the audio encode samples from a
582
+ # distribution and must draw from the same seeded stream as the pipeline.
583
+ generator = _seeded_generator(pipe, seed)
584
+ if generator is not None:
585
+ kwargs["generator"] = generator
586
+
587
  # After the pipeline exists, because encoding needs its `audio_vae`.
588
  audio_notes = _prepared_audio(kwargs, request, pipe)
589
  size_notes = ()
ltx25_studio/pipelines.py CHANGED
@@ -68,6 +68,7 @@ __all__ = [
68
  "stage_2_size_note",
69
  "STAGE_2_SPATIAL_SCALE",
70
  "distilled_kwargs",
 
71
  "DISTILLED_GUIDANCE",
72
  "stage_2_kwargs",
73
  "upsample_kwargs",
@@ -467,6 +468,45 @@ DISTILLED_GUIDANCE = MappingProxyType(
467
  )
468
 
469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  def distilled_kwargs() -> dict:
471
  """The distilled recipe. **Every** run gets this, single-stage included.
472
 
@@ -557,9 +597,13 @@ def stage_2_kwargs(latents, *, audio_latents=None) -> dict:
557
  kwargs = {
558
  **distilled_kwargs(),
559
  "latents": latents,
560
- # The three-step tail replaces stage 1's schedule; the guidance settings
561
- # above are the same for both stages and come from one place.
562
- "sigmas": list(STAGE_2_DISTILLED_SIGMA_VALUES),
 
 
 
 
563
  "noise_scale": STAGE_2_DISTILLED_SIGMA_VALUES[0],
564
  "output_type": "latent",
565
  }
@@ -645,7 +689,12 @@ class StageRunner:
645
  # The distilled recipe applies here too. It used to apply ONLY on
646
  # the stage-2 path, which is how eleven of twelve host runs were
647
  # generated with a linear schedule and SFT guidance.
648
- return self.pipeline(**kwargs, **distilled_kwargs())
 
 
 
 
 
649
  self._stage_2_ready()
650
 
651
  stage_1 = self.pipeline(**kwargs, **stage_1_kwargs())
 
68
  "stage_2_size_note",
69
  "STAGE_2_SPATIAL_SCALE",
70
  "distilled_kwargs",
71
+ "schedule_from",
72
  "DISTILLED_GUIDANCE",
73
  "stage_2_kwargs",
74
  "upsample_kwargs",
 
468
  )
469
 
470
 
471
+ def schedule_from(noise_scale, sigmas=None) -> list[float]:
472
+ """The sigma schedule for a run that starts **partially** noised.
473
+
474
+ **The invariant is ``sigmas[0] == noise_scale``**, and it is upstream's own
475
+ inference rule, stated in its own comment::
476
+
477
+ # Infer noise scale: first (largest) sigma value if using custom sigmas
478
+ if noise_scale is None:
479
+ noise_scale = sigmas[0] if sigmas is not None else 1.0
480
+
481
+ They are the same quantity. ``noise_scale`` noises the latents to a level and
482
+ the schedule tells the model what level it is looking at; disagreeing means
483
+ the model strips a whole schedule's worth of noise from a partly-noised
484
+ tensor. ✅ Measured: agree -> −10.4 dBFS, disagree -> −87.7 dBFS.
485
+
486
+ **One construction, taken by every path that starts partially noised.** The
487
+ defect was that this reasoning existed in ``stage_2_kwargs``'s docstring --
488
+ *"re-noising to 1.0 would discard stage 1 entirely"* -- and never reached the
489
+ audio-input path. A rule written on one branch is not a rule.
490
+
491
+ Truncation rather than rescaling: rescaling the whole curve would invent a
492
+ schedule upstream never publishes.
493
+
494
+ ⚠️ **Degenerate at both ends.** At ``noise_scale = 1.0`` the supplied latents
495
+ contribute nothing (``1.0 * noise + 0.0 * latents``), so it is unconditional
496
+ generation whatever was passed in. Below the distilled floor of 0.421875 it
497
+ collapses to a single step. **Neither bound is the usable range** -- that is
498
+ a measurement, not arithmetic, and "one step" and "bad output" are different
499
+ claims.
500
+ """
501
+ sigmas = DISTILLED_SIGMA_VALUES if sigmas is None else sigmas
502
+ if noise_scale is None:
503
+ return [float(s) for s in sigmas]
504
+ noise_scale = float(noise_scale)
505
+ if noise_scale >= float(sigmas[0]):
506
+ return [float(s) for s in sigmas]
507
+ return [noise_scale] + [float(s) for s in sigmas if float(s) < noise_scale]
508
+
509
+
510
  def distilled_kwargs() -> dict:
511
  """The distilled recipe. **Every** run gets this, single-stage included.
512
 
 
597
  kwargs = {
598
  **distilled_kwargs(),
599
  "latents": latents,
600
+ # Built by the same function the audio-input path uses. Here
601
+ # noise_scale == sigmas[0] already, so this returns the three-step tail
602
+ # unchanged -- stage 2 keeps its behaviour BY CONSTRUCTION rather than
603
+ # by two branches happening to agree.
604
+ "sigmas": schedule_from(
605
+ STAGE_2_DISTILLED_SIGMA_VALUES[0], STAGE_2_DISTILLED_SIGMA_VALUES
606
+ ),
607
  "noise_scale": STAGE_2_DISTILLED_SIGMA_VALUES[0],
608
  "output_type": "latent",
609
  }
 
689
  # The distilled recipe applies here too. It used to apply ONLY on
690
  # the stage-2 path, which is how eleven of twelve host runs were
691
  # generated with a linear schedule and SFT guidance.
692
+ recipe = distilled_kwargs()
693
+ # A run given `noise_scale` starts partially noised, so its schedule
694
+ # must start where its noise actually is. See `schedule_from`.
695
+ if kwargs.get("noise_scale") is not None:
696
+ recipe["sigmas"] = schedule_from(kwargs["noise_scale"])
697
+ return self.pipeline(**kwargs, **recipe)
698
  self._stage_2_ready()
699
 
700
  stage_1 = self.pipeline(**kwargs, **stage_1_kwargs())
tests/test_audio.py CHANGED
@@ -131,6 +131,11 @@ def test_no_sample_rate_is_hardcoded():
131
  docstring_ids = set()
132
  for node in ast.walk(tree):
133
  body = getattr(node, "body", None)
 
 
 
 
 
134
  if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
135
  docstring_ids.add(id(body[0].value))
136
  found = {
 
131
  docstring_ids = set()
132
  for node in ast.walk(tree):
133
  body = getattr(node, "body", None)
134
+ # `isinstance(body, list)` because an IfExp's `.body` is a single
135
+ # expression, not a block -- a ternary anywhere in the module used to
136
+ # crash this scan with "'Call' object is not subscriptable".
137
+ if not isinstance(body, list):
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 = {
tests/test_stage_graph_contract.py CHANGED
@@ -1051,3 +1051,63 @@ def test_no_advertised_lever_sets_guidance_or_steps():
1051
  f"{key!r} is still a UI field, but the distilled recipe fixes it -- a user "
1052
  f"changing it fights the schedule and gets worse output with no way to know why"
1053
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1051
  f"{key!r} is still a UI field, but the distilled recipe fixes it -- a user "
1052
  f"changing it fights the schedule and gets worse output with no way to know why"
1053
  )
1054
+
1055
+
1056
+ # --------------------------------------------------------------------------
1057
+ # a partially-noised run needs a schedule that starts where its noise is
1058
+ #
1059
+ # `noise_scale` and `sigmas[0]` are the same quantity -- upstream infers one
1060
+ # from the other. Ours disagreed on the audio-input path: latents noised to
1061
+ # 0.5, scheduler told 1.0, so the model stripped a whole schedule's worth of
1062
+ # noise from a half-noised tensor. Measured: agree -10.4 dBFS, disagree -87.7.
1063
+ # --------------------------------------------------------------------------
1064
+
1065
+
1066
+ @pytest.mark.parametrize("noise_scale", [0.05, 0.2, 0.5, 0.725, 0.9, 1.0])
1067
+ def test_the_schedule_starts_at_the_noise_scale(noise_scale):
1068
+ """The invariant, across the whole band rather than at one value."""
1069
+ sigmas = pipelines.schedule_from(noise_scale)
1070
+
1071
+ assert sigmas[0] == pytest.approx(noise_scale), (
1072
+ f"schedule starts at {sigmas[0]} for noise_scale={noise_scale}. The model is told "
1073
+ f"it is looking at {sigmas[0]} noise while the latents carry {noise_scale}."
1074
+ )
1075
+ assert sigmas == sorted(sigmas, reverse=True), f"not descending: {sigmas}"
1076
+
1077
+
1078
+ def test_a_full_strength_run_keeps_the_published_schedule():
1079
+ """At 1.0 nothing is truncated -- the distilled curve is used as published."""
1080
+ assert pipelines.schedule_from(1.0) == list(pipelines.DISTILLED_SIGMA_VALUES)
1081
+ assert pipelines.schedule_from(None) == list(pipelines.DISTILLED_SIGMA_VALUES)
1082
+
1083
+
1084
+ def test_stage_2_keeps_its_schedule_by_construction():
1085
+ """Not by two branches happening to agree, which is how they diverged."""
1086
+ built = pipelines.stage_2_kwargs(object())
1087
+
1088
+ assert built["sigmas"] == list(pipelines.STAGE_2_DISTILLED_SIGMA_VALUES)
1089
+ assert built["sigmas"][0] == built["noise_scale"], (
1090
+ "stage 2's own schedule violates the invariant it taught us"
1091
+ )
1092
+
1093
+
1094
+ def test_a_run_given_a_noise_scale_gets_a_matching_schedule():
1095
+ """The seam: the runner must apply it, not just the helper offer it."""
1096
+ runner, pipeline, _up, _dec = two_stage()
1097
+
1098
+ runner(prompt="a lighthouse", noise_scale=0.5)
1099
+
1100
+ sent = pipeline.kwargs
1101
+ assert sent["sigmas"][0] == pytest.approx(0.5), (
1102
+ f"the pipeline was told sigmas[0]={sent['sigmas'][0]} with noise_scale="
1103
+ f"{sent['noise_scale']}. Disagreement here measured -87.7 dBFS on the card."
1104
+ )
1105
+
1106
+
1107
+ def test_a_run_without_a_noise_scale_is_untouched():
1108
+ """Only partially-noised runs truncate; the other ten modes must not."""
1109
+ runner, pipeline, _up, _dec = two_stage()
1110
+
1111
+ runner(prompt="a lighthouse")
1112
+
1113
+ assert pipeline.kwargs["sigmas"] == list(pipelines.DISTILLED_SIGMA_VALUES)
tests/test_ui_generate_seam.py CHANGED
@@ -435,9 +435,51 @@ def test_a_mono_upload_is_reported_to_the_user_not_only_the_log(monkeypatch, tmp
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
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, "the VAE was handed mono and would have raised"
 
 
439
  assert any("mono" in note for note in result.warnings), (
440
  f"the upload was altered and the result says nothing about it: {result.warnings}"
441
  )
442
+
443
+
444
+ def test_the_seed_reaches_the_pipeline_not_only_the_sidecar(monkeypatch, tmp_path):
445
+ """The seed used to be recorded and never applied.
446
+
447
+ `_resolve_seed` ran, the number went into the encoder kwargs as metadata,
448
+ and there was no generator anywhere in the package -- so every run was
449
+ unconditionally random and every same-seed comparison was two independent
450
+ runs. H10b, the before/after pixel diffs, H12b and H4b all rested on it.
451
+ """
452
+ import sys
453
+ import types
454
+
455
+ seen = {}
456
+
457
+ class Generator:
458
+ def __init__(self, device=None):
459
+ seen["device"] = device
460
+
461
+ def manual_seed(self, value):
462
+ seen["seed"] = value
463
+ return self
464
+
465
+ torch = types.ModuleType("torch")
466
+ torch.Generator = Generator
467
+ monkeypatch.setitem(sys.modules, "torch", torch)
468
+
469
+ pipe = FakePipe()
470
+ generate_module.generate(
471
+ mode="text_to_video",
472
+ seed=1234,
473
+ pipeline_factory=factory_returning(pipe),
474
+ encoder=one_muxed_file_encoder,
475
+ output_root=tmp_path,
476
+ retention_bytes=10**9,
477
+ )
478
+
479
+ assert seen.get("seed") == 1234, (
480
+ f"the pipeline was never seeded: {seen}. The seed reaching only the sidecar is "
481
+ f"why 'same seed' comparisons compared two random runs."
482
+ )
483
+ assert "generator" in pipe.calls[-1], (
484
+ f"no generator reached the pipeline: {sorted(pipe.calls[-1])}"
485
+ )