Repository navigation
feat: add LTX 2.3 and 2.5 video models and audio support - #107
Conversation
bitgamma
left a comment
There was a problem hiding this comment.
Thanks for the PR, but it is always the same problems, existing facilities are being it ignored and generic concepts are trojan horsed as part of the model
| @@ -0,0 +1,75 @@ | |||
| """LTX downloader manifest and cache checks without network access.""" | |||
| from __future__ import annotations | |||
There was a problem hiding this comment.
no need to test the download script
ef808b6 to
4ff418b
Compare
6aa4fe6 to
be4ff83
Compare
bitgamma
left a comment
There was a problem hiding this comment.
it's getting better but there are still several important issues to solve.
| `THENOISE_LTX_GEMMA_SDPA=math|default` permits A/B validation of an | ||
| affected driver/PyTorch combination without changing installed packages. | ||
| """ | ||
| mode = os.environ.get("THENOISE_LTX_GEMMA_SDPA", "auto").strip().lower() |
There was a problem hiding this comment.
wtf? we don't do that! and we already have attention utils.
|
|
||
| vendor = Path(GEMMA3_LTX_CONFIG_DIR) | ||
| config = Gemma3TextConfig(**json.loads( | ||
| (vendor / "text_config.json").read_text(encoding="utf-8") |
There was a problem hiding this comment.
it loads a file that is not committed...
| of split-half coordinates. Cast back to the query dtype after the FP32 | ||
| rotation, so BF16/FP16 Q,K,V still select a common SDPA kernel. | ||
| """ | ||
| ltx_layout = (cos.ndim == 4 and cos.shape[:3] == xq.shape[:3] |
There was a problem hiding this comment.
the ltx path and the normal path share almost no code. I'd rather have two completely separate functions instead of modifying this one
| # Misc | ||
| .DS_Store | ||
| .pytest_cache/ | ||
| thenoise/utils/text_encoder/configs/gemma3_ltx/tokenizer.model |
| video = sub.add_parser("video", help="run one generation and save a clip") | ||
| _add_model_paths(video) | ||
| _add_dit_low(video) | ||
| _add_auxiliary_paths(video) |
There was a problem hiding this comment.
this one is fine, but please fold _add_dit_low into this one so we have a single function
| self.head_dim = head_dim | ||
| self.norm_q = nn.RMSNorm(inner, eps=1e-6) | ||
| self.norm_k = nn.RMSNorm(inner, eps=1e-6) | ||
| self.to_q = nn.Linear(query_dim, inner, bias=True) |
There was a problem hiding this comment.
we use QuantizedLinear directly in everything we write. replace_linear is only for the text encoders we support through transformers
| VERSION_25 = "2.5" | ||
|
|
||
|
|
||
| def version_from_checkpoint(path: str | Path) -> str | None: |
There was a problem hiding this comment.
I still see a lot of custom loading that doesn't use the existing facilities. What makes ltx so special that it cannot use the existing functions?
|
I refactored model loading in main branch so now it should be easier to reuse and adapt to its new patterns |
f8993d8 to
13a1913
Compare
`resolve_video` refused any step count but the released 8, any `guidance_scale` but 1.0, any negative prompt, and then overwrote the caller's sampler anyway. All four are the request's, not the adapter's. - `sigma_at`/`sigma_ladder` move to `thenoise.samplers`, where H3-Image already had them: a distilled release publishes a sigma grid and a ladder walks it at any step count. `dit/ltx_video/sampling.py` owns the two released LTX grids and resamples both, so `steps=8` reproduces the published recipe exactly and anything else scales from it. The refine pass keeps its published re-noise level and its share of the recipe. - `AVConditioning` grows the `null_*` halves and `denoise_step` runs the shared two-forward CFG over the joined stream, as Wan does. Upstream's separate audio scale, guidance rescale, STG and modality guidance stay out of scope, said rather than raised. - Which half of the clip a step is in comes from the segment's leading sigma instead of a counter, because `stages.run` may replay its prepare callable after a memory squeeze. - The shared schedule contract no longer skips LTX.
I2V encoded the reference frame as fp32 into a BF16 VAE, so the first conv3d of the encode rejected it: "Input type (float) and bias type (c10::BFloat16) should be the same". The decode side already casts to `self.vae.dtype`; the encode now mirrors it, with the half-resolution copy for the refine grid still resampled in fp32 where bilinear is defined on every backend.
The muxer hardcoded AAC and refused anything else, and the controller refused a WebM clip with sound in it, so the one model with a soundtrack could only deliver it in MP4. - `AUDIO_CODECS` maps container to codec and the frame length that encoder consumes: the framing loop had AAC's 1024 samples baked in, while Opus wants 20 ms. Both formats now round-trip through a real PyAV container in the tests, not just through the fake. - `decode_audio` answers a `Waveform`, so the sample rate travels with the PCM as the vocoder's own number instead of a literal beside a tuple. - `LATENT_TOKENS_PER_SECOND` replaces the `25.0` in `init_latents`. The audio codec's `sample_rate`, `mel_hop_length` and `is_causal` arguments were accepted and ignored, and went with that literal.
--audio-vae, --spatial-upscaler and --text-projection name a part; each part is taken from whichever file the request gave that holds its tensors. Pointing at the released all-in-one LTX 2.3 checkpoint is therefore --dit plus its upscaler and its text encoder, and a codec packaged apart takes that part from a monolith instead of colliding with it. A part no given file holds is refused by name, with the flag that supplies it -- the old message blamed --dit for a missing codec. Component files travel as ModelPaths.extra_paths by role, an adapter declares which roles it reads (COMPONENT_ROLES) and is refused any other before a load, and ModelConfig reads every file the request named: headers are parsed once per resolved file, which is what makes a multi-role checkpoint one open. The LTX loader says where each part came from, and --dit-low returns to the CLI help.
An all-in-one checkpoint that carries its video codec, its audio codec and its vocoder beside the transformer names their blocks the original way, where the released files that hold one codec alone use the module's names. `split_ltx_key` strips the codec prefix and stopped there, so those tensors reached a strict load under names the module does not have and the load refused weights the checkpoint does carry: `unexpected vae tensor ... up_blocks.0.res_blocks.0...`. Route them through the codec's own key map, the one a component's own file already goes through, and both packagings fill the same parameters.
Only the file the request gave for a component is held to fitting it exactly. Where the engine went looking for a part inside the files it was given, a tensor that does not fit is now skipped instead of ending the load, so a checkpoint carrying more than this engine reads still answers the parts it does fit. A part no given file answers says so with the flag that supplies it and, when some file spelled that part without fitting it, the count and an example: "pass --vae" is no help to a request that already passed a file with vae all over it. A part that is only partly filled names the files it read from. named becomes a required argument of load_ltx_component, since which file is held to this standard is the caller's decision, not a default.
…eside it `load_ltx_component` re-implemented the engine's loader: its own quantization suffix tuple, marker skipping, unexpected-key diagnosis, shape checking, dtype casting and meta-leftover detection, with subtly different answers. The thing it needed and the engine lacked was one thing -- read a file once and sort it by role -- so that is what `utils/loader.py` gains: `partition_keys` walks a header once for every part it answers and reports what was spelled as a part without fitting it, and `load_selected_state` fills one module from the keys chosen across several files. Quantized or plain stays decided per part rather than per file: a checkpoint packing a quantized transformer with full-precision codecs is mixed, and the file-level answer is wrong for half of it. One header walk replaces one per component, and the adapter hands the loader the runtime's own parsed headers by role instead of building a dict of paths. What is left in the LTX loader is LTX: the key map, which file answers which part, and the message naming the flag for a part nothing filled.
load_selected_state takes a device, so a component the memory manager wants resident is read onto it instead of being staged on CPU and copied. The device is answered per part from the files that part arrives from, which is the manager's call, made on their bytes -- so EngineModel grows _load_target_all for a component that comes from more than one file, and the adapter stops moving things afterwards. Loading also stops pretending it can be interrupted: no other loader in the engine takes a cancel callback, and every caller of these passed a function that did nothing.
detect was a set comprehension over every key in the file, comparing a bool to a class attribute; Signature already states keys and absences, and 2.5's whole difference to 2.3 is one embedding, so requiring the other version's answer is what stops a file being claimed by the loader that would build it wrong. version_from_checkpoint is gone with it: it opened a file the caller had opened already and re-derived the version from metadata, a third source of truth next to the two declarations. Metadata survives as a cross-check in validate_paths, where it can say "this file states 2.5.0, which LTX-2.3-Distilled is not" to a request that named the model itself.
make_transformer carried the released geometry as a literal dict and the loader then shape-checked the file against it, so a re-export of another width or depth was a refusal rather than a model. detect_params reads the trunks, the depth, the cross-attention widths and the four optional halves -- feed-forward biases, gated attention, prompt modulation, the keyframe embedding -- through the same key map the load uses, so a rename is written once. What a checkpoint cannot state stays where it belongs: the head split, the RoPE base and causal offset, the timestep multipliers, the fitted positional grid. The constructor lost the twelve knobs that only existed to be validated against their own defaults, and the recipe it implements is now stated in its docstring instead of in a chain of rejections. make_connectors also stops branching on the version for a number that came out the same either way: both released Gemmas are 3840 wide and 48 deep, so the Gemma config answers it, and the connectors' hidden dims are the transformer's widths rather than a copy of them.
encode returned a SimpleNamespace around a posterior and decode returned a one-tuple behind return_dict=False, while the statistics that turn a checkpoint's latents into the run's lived in the adapter as free functions reaching into vae.config for a scaling_factor nothing varies. The codec now has encode/decode returning tensors, encode_pixels_to_latents/decode_to_pixels either side of them, and to_canonical/from_canonical for the one thing trained on the checkpoint's own scale -- the spatial upscaler at the stage boundary. The audio side gets decode_to_mel, so the flat token layout (its channels and bins, both stated by the codec) is no longer two literals in the middle of a decode, and the statistics buffer is sized by that layout rather than by base_channels, which only happened to be the same number. The transformer's forward loses return_dict with it: it existed to refuse True. The latent grid stops being 8, 32 and 64 in the adapter too -- the codec says how far it folds, and the pre-upscaler stage is that again divided by the upscaler's gain. Same numbers for the released codec; a codec that folded differently would now say so.
Ninety lines patched HF internals -- its buffer dicts, re-instantiating the rotary
module and swapping it out -- to rebuild the embedding scale and the RoPE
frequencies, because those came back from the build as meta tensors. They came
back that way because the build asked for torch.device("meta"), which patches
everything; init_empty_weights patches parameter registration only, so the
buffers no checkpoint carries are created for real by the library that owns them.
Both functions and their fake-Rotary, fake-Embedding tests are gone, and a tiny
real Gemma now pins the property, so an accelerate or transformers change that
breaks it fails a test rather than a load.
Dropping the LM head needed no helper either: the Qwen builder deletes it inline.
Every prompt was left-padded to 1024 ids and run through 48 layers with a mask, because the released pipeline batches the prompt and its negative into one pass. One pass was cheaper to write than to reason about: the width is a property of the connectors' learned registers, not of the tokenizer, and the connector re-aligns the valid rows itself, so the padding moved behind the encoder where it is one copy instead of a thousand mostly-pad positions attended forty-eight times. Each prompt now goes alone, dense, no mask -- two dozen tokens twice. THENOISE_LTX_GEMMA_SDPA went with it, and with it the arch list naming gfx1100 and gfx1151 as needing the math backend. An escape hatch that only the maintainer's card can justify is not a config surface: if masked attention turns out broken there, the fix belongs in utils/attention, where every model shares it, and not in a switch beside one encoder. Needs a measurement on the deployment card. Tokenizing moved to the module that builds the encoder, as a prompter beside Wan's.
Thirty-three megabytes of vendored Gemma-3 tokenizer, larger than the other three vendored tokenizers combined, for a tokenizer the checkpoint already carries: the single-file Gemma 3 files keep their SentencePiece proto under `spiece_model`, four megabytes of it, in the ComfyUI BF16 file and the INT8 ConvRot one alike. On the bytes from the released file, SentencePiece plus a BOS gives the same ids as the JSON did on every probe -- CJK, Cyrillic, emoji ZWJ sequences, byte-level digit runs, control characters, the empty prompt. `spiece_model` moves next to the loader, since UMT5 had been reading the same kind of tensor on its own. What is left of the vendored directory was a config file. The ComfyUI Gemma 3 checkpoints carry no metadata at all -- not a text config, not a tokenizer description -- so the architecture stays vendored, as a dict beside the code that builds it, where a diff can be read. Measured while here, because the mapper that translates 2.5 keys was written against layouts nobody had counted: the three released 2.5 text encoders spell their keys identically, and four prefixes cover all of them, so fifty lines of candidate spellings for vision towers and audio towers no file uses are gone. Every one of the 677 parameters the built encoder expects is filled from both the BF16 and the INT8 file either way; a fifth spelling now refuses the load instead of quietly skipping tensors.
`frame_grid` in the LTX adapter and `wan_frame_grid` in Wan's sampling module were the same nine lines: the same (wanted-1)/compression, the same round-up for explicit counts and nearest-for-a-duration, the same minimum of one group. LTX's copy had also quietly dropped the check on the requested count, so a NaN duration reached the kernels there and was refused here. The helper now sits with the request contract it serves, and takes the compression rather than assuming eight -- which is how Wan's 4n+1 variant and the tiny codec in the tests keep their own grids without either adapter restating the arithmetic. The ratio itself stays the video codec's, as a named constant behind its constructor defaults, so `resolve_video` reads it off the codec instead of remembering it.
Two bare nn.RMSNorms where the engine keeps a QKNorm -- and #111 was specifically about using it. Before swapping it in, the width was measured rather than assumed: the released norm weight spans heads*head_dim, so the RMS runs over the whole projection and mixes heads, which is not the same operation as the per-head norm the shared module's docstring implied. A test now pins the width and, with it, that the norm runs before the split into heads; a future tidying that reshapes first would change pixels while keeping every key name. Which leaves the layout worth writing down where it is owed: heads-first is what the attention kernels read, so weights and norms should materialise that way when they can, and a checkpoint that normalises the concatenated projection pays for the transpose instead. The shared QKNorm says as much without naming whose checkpoint does; the copy is attention's business, so that note went into attention. The load keeps both released spellings of the norm names through the one helper other models already use for the same rename.
A second copy of the module, exec'd from its file path, was the only way these tests could monkeypatch the factories -- which meant the patches were landing on an object production never uses, and an import error inside that module would have shown up as a missing attribute here rather than as itself. Every other test in the suite imports normally; this one now does too, and the patches go where they are felt.
Reference latents for two stages, which stage is running, and the request geometry were four attributes with a hand-written reset that had to be kept in step by two places -- `clear_video_state` on failure and `finalize_latent` on success, which agree today and will not forever. Wan solved the same problem with one frozen struct and one assignment; this is that shape, and the geometry it now carries says out loud why it is there: the joined stream cannot be cut back into video and audio tokens without it, and the step and decode hooks are never handed the params that say what it is. Handing them over is the shared contract's business -- the controller has them -- not something one adapter fixes by itself. Dropping the reference frames after the last step also stopped recomputing the low-stage geometry twice to compare a shape against itself.
`checkpoint.py` had become half loader and half table of every spelling the releases and the packers use -- three generations of name for one transformer, the codecs' renumbered block lists, two spellings of a QK norm. Every other model in the engine keeps that table in `keys.py` beside the loader, which is also where a fourth spelling would go; now LTX does too, and what is left in the loader is the loading. Two signatures moved with it, since they are declarations about checkpoint names rather than about a model, and one dropped out entirely: `_upscaler_key` answered "the upscaler, unchanged" and had no caller but a test, which now asks the real question of the mapper that does have one.
The joined audio+video stream cannot be cut back into its two modalities without knowing how big a frame of latents is, and neither `denoise_step` nor the decoders were given that: the numbers were parked on the model in one hook and read out in three, which survives a swap only by remembering to clear them. The schedule already arrives as segments built from the request, so the request comes with them, and the decoders are handed it at the call site that always had it. A segment's own place in the schedule stays `steps`; `params` is what the latents it walks are a picture of. What the model still holds between hooks is then one clip's reference frames -- written and dropped together, which is what the struct is for.
Every stage was sized by one frame, on the argument that frames leave the codec as they are decoded and so nothing in a run grows with the clip. That holds for a codec causal along time and not for one that pads both ends of it: there the clip's pixels are live before the first frame is handed to the muxer, and the stage that runs the decoder was left to survive on its out-of-memory retry. Chunked decoding would be the other answer and was measured against: changing any one latent frame moves every output frame, so no halo of overlap makes a per-chunk decode agree with the whole. The headroom is therefore what the model declares, with a frame as the default.
Two appliers existed: the shared one, whose phases duplicate the frequency band to the rotation width and are laid out [L, 1, 1, rot], and LTX's, whose phases hold each angle once and broadcast per head. They differ only in how the band is spelled -- half-width phases turn the same channels -- so there is one function now, taking the half-width form and rotating the first 2*band channels of a head, leaving a narrower head's idle tail as it was handed over. The layout is why it is worth unifying. An elementwise op takes its output layout from its operand, so a packed [B, L, H, D] projection multiplied by a full band comes back packed, and attention copies it to L-major at every call. Written as two slices through one cat, the answer arrives L-major: two copies per video attention became one. Measured on the 890M at 32 heads of 128, rope plus attention went from 30.0 to 20.7 ms at 1920 tokens and 130 to 101 at 6144, with the projections alongside going 72 to 62 and 270 to 240. Every value is bit-equal to what the two appliers and the four builders produced before. Phases come back half-width from split_half_rope_1d/3d/4d/axes, and callers that sliced the token axis of a table now slice -2. LTX's coordinate construction, which was a class inside its transformer, moved to ltx_video/rope.py as AVRope with one entry point per grid, and caches the phases it builds against that geometry: the build costs milliseconds per forward and a render asks for the same table at every step. Two things about LTX's positions were only visible once the construction was in one place. Cross-modal attention rotates on the time coordinate alone -- the old call sliced the axis dimension, not the frame -- because time is the only coordinate a video and a sound share. And the cross-attention rope modules now carry their stream's scale factors: coordinates used to be built by the stream's module and rotated by the cross one, which left the cross module's geometry unused, and wrong as soon as it built its own.
`@torch.compile(fullgraph=True)` on `_AVBlock.forward`, as every other DiT's block carries it, and `mark_token_axis` once per step for the two streams, the prompt states, the masks and the AdaLN rows -- the axes resolution, prompt length and reference count move along. Phase tables are inputs rather than something the block builds, so their token axis is declared at -2 and nothing inside the graph reconstructs them. Traced on CPU at a tiny config: no graph breaks, and after one promotion each for the audio stream and the audio prompt every further shape is served by the same graph -- video tokens 16 to 64, 144, 70 and audio 5 to 21 cost no recompile. The isolate variant is its own graph, being a different branch rather than a different shape.
`ltx/av` and `ltx/av_i2v` at 22B: video trunk 4096 over 32 heads of 128, audio trunk 2048 over 32 of 64, each stream's prompt width equal to its trunk -- the numbers `detect_params` reads off `ltx-2.3-22b-distilled-1.1.safetensors`. A rung is a clip, so the video grid keeps its temporal axis at 16 latent frames and the audio stream is the 126 tokens the same five seconds costs the audio codec, which does not follow the resolution. The reciprocal cross-modal attentions get their phases at `audio_cross_attention_dim`, where both sides run on the audio heads of 64, and the i2v case carries the per-video-token timestep a reference-conditioned step pins its first frame with.
The unification (3735aad) wrote the rotation as the two halves of the head recombined by a `cat`, on the theory that this avoided a layout copy. On gfx1151 that cost 220% on anima and 58% on moss_image at 16k tokens. Measured there with a harness that swaps the contract whole -- applier and the band its builders emit -- over five formulations, wan22 as a control (it uses no split-half rope, so its spread is the session floor): anima@16k fused 153.7 dup 146.4 slices 496.1 no-tail 469.6 stack 474.0 moss@16k fused 211.0 dup 210.1 slices 336.3 no-tail 337.1 stack 343.5 h3@16k fused 592.5 dup 593.7 slices 914.8 no-tail 588.1 stack 589.3 wan22 (control) within 0.5% throughout Which separates by the shape of the last op before SDPA, not by band width or by `cat` alone: - elementwise chain fast - `cat` of one computed operand and a view fast (h3's idle tail) - `cat` of two computed operands 1.6-3.4x slower So the sin was joining two computed operands, which the two-slice form always does and which h3's tail form does not. gfx1150 emits two kernels either way and shows only +5%, which is why it was missed here. The fix is `dup`: builders keep handing over each angle once, and the applier doubles that band itself -- O(L*rot) rather than O(B*H*L*rot) -- so the head is rotated by one expression and only an idle tail is concatenated. It is the fastest of the five on anima, at par on moss and h3, and it keeps phases at half width, which is what made the unification worth doing. Verified bit-identical to both the two-slice form and the pre-unification expression uncompiled. The test that pinned the output as L-major now pins the opposite, and correct, property: an elementwise op hands back the query's layout, and attention is what puts its operands in one layout.
Measured on gfx1151 against the concatenation it replaces: 5.6% and 6.5% ahead at 9216 tokens, 5.6% and 5.5% at 16384, on the two-stream AV block where the band is per-head and therefore as wide as the rotation it feeds. That is the unfavourable case for doubling, and it still wins, so the applier does not need a per-model escape.
The encoder was the last component in the engine read onto CPU and carried back to the card afterwards: `_load_ltx_text_weights` passed `device="cpu"` to the shared text-encoder loader — the only caller of that function to do so, where Wan, Ming and the four `utils/text_encoder` loaders all pass the target — and the adapter then did `text_encoder.to(_load_target(path))`. For a 15-26 GB file that holds all of it in host RAM while the 22 GB transformer is being read at the same time, on hardware where host RAM and VRAM are the same pool. `183d5aa` removed this round trip from every other part. The `.to()` cannot simply go away, which is why the change is inside the loader rather than a deletion in the adapter: Gemma is built under `init_empty_weights()`, which blanks parameters and leaves `transformers`' own buffers — the rotary frequencies, `embed_scale` — materialised on CPU. The sweep is kept, now beside the build, where it moves those buffers and nothing else, since every parameter is already where it belongs. R41's other half, loading the encoder after the transformer, is dropped. The order is cosmetic and it is not free either: `load_original_components` needs `gemma_text_config`, so swapping them means splitting the config out of the weight load for churn with no measured effect. Unverified on hardware: the quantised encoder takes a path the tests cannot reach here. Peak host RSS during load should drop by roughly the size of the encoder, and a device mismatch at the first prompt would mean a buffer this sweep missed.
Every sixth Gemma 4 attention is head_dim 512, and the fused ROCm SDPA backends return NaN at that width -- over rows, layers and sequence lengths that move from run to run, so a short prompt arrives at the connectors as NaN and the DiT conditions on nothing. Gemma 3 measures clean at head_dim 256 on the same kernels and keeps them.
Summary
Adds native LTX 2.3 (free access) and LTX 2.5 (gated access) video generation with synchronized audio support.
Testing