Skip to content
Python

added ltx 2.3 support

DeepBeepMeepdc1d6968d714
diff --git a/defaults/kiwi_edit.json b/defaults/kiwi_edit.json
index 31ba3fd..e6b8225 100644
--- a/defaults/kiwi_edit.json
+++ b/defaults/kiwi_edit.json
@@ -16,6 +16,5 @@
"prompt": "Change the woman's dress to a vivid red while preserving her pose, face, and the room lighting.",
"video_length": 81,
"flow_shift": 5,
- "num_inference_steps": 30,
- "resolution": "1280x704"
+ "num_inference_steps": 30
}
diff --git a/defaults/kiwi_edit_instruct_only.json b/defaults/kiwi_edit_instruct_only.json
index 66a25bf..ebe0aff 100644
--- a/defaults/kiwi_edit_instruct_only.json
+++ b/defaults/kiwi_edit_instruct_only.json
@@ -16,6 +16,5 @@
"prompt": "Remove the monkey.",
"video_length": 81,
"flow_shift": 5,
- "num_inference_steps": 30,
- "resolution": "1280x704"
+ "num_inference_steps": 30
}
diff --git a/defaults/kiwi_edit_reference_only.json b/defaults/kiwi_edit_reference_only.json
index a01d4a5..a61e1cd 100644
--- a/defaults/kiwi_edit_reference_only.json
+++ b/defaults/kiwi_edit_reference_only.json
@@ -16,6 +16,5 @@
"prompt": "Apply the style from the reference image.",
"video_length": 81,
"flow_shift": 5,
- "num_inference_steps": 30,
- "resolution": "1280x704"
+ "num_inference_steps": 30
}
diff --git a/defaults/ltx2_19B.json b/defaults/ltx2_19B.json
index 65a1d97..1d909ff 100644
--- a/defaults/ltx2_19B.json
+++ b/defaults/ltx2_19B.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Dev 19B",
+ "name": "LTX-2 2.0 Dev 19B",
"architecture": "ltx2_19B",
"description": "LTX-2 generates video up to 20s with an audio soundtrack. Supports start/end keyframes and sliding-window continuation. You can force the audio soundtrack by providing an Audio Prompt.",
"URLs": [
diff --git a/defaults/ltx2_19B_nvfp4.json b/defaults/ltx2_19B_nvfp4.json
index ce32c8a..dab5fa6 100644
--- a/defaults/ltx2_19B_nvfp4.json
+++ b/defaults/ltx2_19B_nvfp4.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Dev 19B NVFP4",
+ "name": "LTX-2 2.0 Dev NVFP4 19B",
"architecture": "ltx2_19B",
"description": "NVFP4-quantized LTX-2 Dev 19B weights. For full speed, a sm120+ GPU is needed (RTX 50xx) and the comfy-kitchen NVFP4 kernels must be installed.",
"URLs": [
diff --git a/defaults/ltx2_22B.json b/defaults/ltx2_22B.json
new file mode 100644
index 0000000..e4ac4b0
--- /dev/null
+++ b/defaults/ltx2_22B.json
@@ -0,0 +1,22 @@
+{
+ "model": {
+ "name": "LTX-2 2.3 Dev 22B",
+ "architecture": "ltx2_22B",
+ "description": "LTX-2.3 dev checkpoint (22B) for video+audio generation with start/end keyframes and sliding-window continuation.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/LTX-2.3/resolve/main/ltx-2.3-22b-dev_diffusion_model.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LTX-2.3/resolve/main/ltx-2.3-22b-dev_diffusion_model_quanto_int8.safetensors"
+ ],
+ "loras": [
+ "https://huggingface.co/DeepBeepMeep/LTX-2.3/resolve/main/ltx-2.3-22b-distilled-lora-384.safetensors"
+ ],
+ "loras_multipliers": [
+ "0;1"
+ ]
+ },
+ "prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",
+ "num_inference_steps": 30,
+ "video_length": 241,
+ "resolution": "1280x720",
+ "guidance_scale": 3.0
+}
diff --git a/defaults/ltx2_22B_distilled.json b/defaults/ltx2_22B_distilled.json
new file mode 100644
index 0000000..a413b8d
--- /dev/null
+++ b/defaults/ltx2_22B_distilled.json
@@ -0,0 +1,17 @@
+{
+ "model": {
+ "name": "LTX-2 2.3 Distilled 22B",
+ "architecture": "ltx2_22B",
+ "description": "LTX-2.3 distilled checkpoint (22B) with faster generation.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/LTX-2.3/resolve/main/ltx-2.3-22b-distilled_diffusion_model.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LTX-2.3/resolve/main/ltx-2.3-22b-distilled_diffusion_model_quanto_int8.safetensors"
+ ],
+ "preload_URLs": "ltx2_22B",
+ "ltx2_pipeline": "distilled"
+ },
+ "prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",
+ "num_inference_steps": 8,
+ "video_length": 241,
+ "resolution": "1280x720"
+}
diff --git a/defaults/ltx2_distilled.json b/defaults/ltx2_distilled.json
index f21f9c9..a59e2a9 100644
--- a/defaults/ltx2_distilled.json
+++ b/defaults/ltx2_distilled.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Distilled 19B",
+ "name": "LTX-2 2.0 Distilled 19B",
"architecture": "ltx2_19B",
"description": "LTX-2 distilled checkpoint with faster generation.",
"URLs": [
diff --git a/defaults/ltx2_distilled_gguf_q4_k_m.json b/defaults/ltx2_distilled_gguf_q4_k_m.json
index ab2b2cb..60863ab 100644
--- a/defaults/ltx2_distilled_gguf_q4_k_m.json
+++ b/defaults/ltx2_distilled_gguf_q4_k_m.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Distilled GGUF Q4_K_M 19B ",
+ "name": "LTX-2 2.0 Distilled GGUF Q4_K_M 19B ",
"architecture": "ltx2_19B",
"description": "LTX-2 distilled GGUF Q4_K_M checkpoint for llama.cpp-backed quantization.",
"URLs": [
diff --git a/defaults/ltx2_distilled_gguf_q6_k.json b/defaults/ltx2_distilled_gguf_q6_k.json
index 979ad5d..cf5ac75 100644
--- a/defaults/ltx2_distilled_gguf_q6_k.json
+++ b/defaults/ltx2_distilled_gguf_q6_k.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Distilled GGUF Q6_K 19B ",
+ "name": "LTX-2 2.0 Distilled GGUF Q6_K 19B ",
"architecture": "ltx2_19B",
"description": "LTX-2 distilled GGUF Q6_K checkpoint for llama.cpp-backed quantization.",
"URLs": [
diff --git a/defaults/ltx2_distilled_gguf_q8_0.json b/defaults/ltx2_distilled_gguf_q8_0.json
index 21edbba..b253429 100644
--- a/defaults/ltx2_distilled_gguf_q8_0.json
+++ b/defaults/ltx2_distilled_gguf_q8_0.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "LTX-2 Distilled GGUF Q8_0 19B ",
+ "name": "LTX-2 2.0 Distilled GGUF Q8_0 19B ",
"architecture": "ltx2_19B",
"description": "LTX-2 distilled GGUF Q8_0 checkpoint for llama.cpp-backed quantization.",
"URLs": [
diff --git a/models/ltx2/configs/ltx2_19b_config.json b/models/ltx2/configs/ltx2_19b_config.json
new file mode 100644
index 0000000..ccf416c
--- /dev/null
+++ b/models/ltx2/configs/ltx2_19b_config.json
@@ -0,0 +1,283 @@
+{
+ "audio_vae": {
+ "model": {
+ "params": {
+ "ddconfig": {
+ "attn_resolutions": [],
+ "causality_axis": "height",
+ "ch": 128,
+ "ch_mult": [
+ 1,
+ 2,
+ 4
+ ],
+ "double_z": true,
+ "downsample_time": false,
+ "dropout": 0.0,
+ "in_channels": 2,
+ "mel_bins": 64,
+ "mid_block_add_attention": false,
+ "norm_type": "pixel",
+ "num_res_blocks": 2,
+ "out_ch": 2,
+ "resolution": 256,
+ "z_channels": 8
+ },
+ "embed_dim": 8,
+ "sampling_rate": 16000
+ }
+ },
+ "preprocessing": {
+ "audio": {
+ "causal_padding": 3,
+ "duration": 5.12,
+ "max_wav_value": 32768.0,
+ "sampling_rate": 16000,
+ "stereo": true
+ },
+ "mel": {
+ "mel_fmax": 8000,
+ "mel_fmin": 0,
+ "n_mel_channels": 64
+ },
+ "stft": {
+ "causal": true,
+ "filter_length": 1024,
+ "hop_length": 160,
+ "win_length": 1024
+ }
+ }
+ },
+ "scheduler": {
+ "_class_name": "RectifiedFlowScheduler",
+ "_diffusers_version": "0.25.1",
+ "base_resolution": null,
+ "num_train_timesteps": 1000,
+ "sampler": "LinearQuadratic",
+ "shifting": null
+ },
+ "transformer": {
+ "_class_name": "AVTransformer3DModel",
+ "_diffusers_version": "0.25.1",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 128,
+ "attention_type": "default",
+ "audio_attention_head_dim": 64,
+ "audio_cross_attention_dim": 2048,
+ "audio_num_attention_heads": 32,
+ "audio_out_channels": 128,
+ "audio_positional_embedding_max_pos": [
+ 20
+ ],
+ "av_ca_timestep_scale_multiplier": 1000.0,
+ "av_cross_ada_norm": true,
+ "caption_channels": 3840,
+ "causal_temporal_positioning": true,
+ "connector_attention_head_dim": 128,
+ "connector_norm_output": true,
+ "connector_num_attention_heads": 30,
+ "connector_num_layers": 2,
+ "connector_num_learnable_registers": 128,
+ "connector_positional_embedding_max_pos": [
+ 4096
+ ],
+ "cross_attention_dim": 4096,
+ "cross_attention_norm": true,
+ "double_self_attention": false,
+ "dropout": 0.0,
+ "frequencies_precision": "float64",
+ "in_channels": 128,
+ "norm_elementwise_affine": false,
+ "norm_eps": 1e-06,
+ "norm_num_groups": 32,
+ "num_attention_heads": 32,
+ "num_embeds_ada_norm": 1000,
+ "num_layers": 48,
+ "num_vector_embeds": null,
+ "only_cross_attention": false,
+ "out_channels": 128,
+ "positional_embedding_max_pos": [
+ 20,
+ 2048,
+ 2048
+ ],
+ "positional_embedding_theta": 10000.0,
+ "positional_embedding_type": "rope",
+ "qk_norm": "rms_norm",
+ "rope_type": "split",
+ "share_ff": false,
+ "standardization_norm": "rms_norm",
+ "timestep_scale_multiplier": 1000,
+ "upcast_attention": false,
+ "use_audio_video_cross_attention": true,
+ "use_embeddings_connector": true,
+ "use_linear_projection": false,
+ "use_middle_indices_grid": true
+ },
+ "vae": {
+ "_class_name": "CausalVideoAutoencoder",
+ "causal_decoder": false,
+ "decoder_base_channels": 128,
+ "decoder_blocks": [
+ [
+ "res_x",
+ {
+ "inject_noise": false,
+ "num_layers": 5
+ }
+ ],
+ [
+ "compress_all",
+ {
+ "multiplier": 2,
+ "residual": true
+ }
+ ],
+ [
+ "res_x",
+ {
+ "inject_noise": false,
+ "num_layers": 5
+ }
+ ],
+ [
+ "compress_all",
+ {
+ "multiplier": 2,
+ "residual": true
+ }
+ ],
+ [
+ "res_x",
+ {
+ "inject_noise": false,
+ "num_layers": 5
+ }
+ ],
+ [
+ "compress_all",
+ {
+ "multiplier": 2,
+ "residual": true
+ }
+ ],
+ [
+ "res_x",
+ {
+ "inject_noise": false,
+ "num_layers": 5
+ }
+ ]
+ ],
+ "dims": 3,
+ "encoder_base_channels": 128,
+ "encoder_blocks": [
+ [
+ "res_x",
+ {
+ "num_layers": 4
+ }
+ ],
+ [
+ "compress_space_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 6
+ }
+ ],
+ [
+ "compress_time_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 6
+ }
+ ],
+ [
+ "compress_all_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ],
+ [
+ "compress_all_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ]
+ ],
+ "in_channels": 3,
+ "latent_channels": 128,
+ "latent_log_var": "uniform",
+ "norm_layer": "pixel_norm",
+ "normalize_latent_channels": false,
+ "out_channels": 3,
+ "patch_size": 4,
+ "scaling_factor": 1.0,
+ "timestep_conditioning": false,
+ "use_quant_conv": false
+ },
+ "vocoder": {
+ "resblock": "1",
+ "resblock_dilation_sizes": [
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ]
+ ],
+ "resblock_kernel_sizes": [
+ 3,
+ 7,
+ 11
+ ],
+ "stereo": true,
+ "upsample_initial_channel": 1024,
+ "upsample_kernel_sizes": [
+ 16,
+ 15,
+ 8,
+ 4,
+ 4
+ ],
+ "upsample_rates": [
+ 6,
+ 5,
+ 2,
+ 2,
+ 2
+ ]
+ }
+}
\ No newline at end of file
diff --git a/models/ltx2/configs/ltx2_22b_config.json b/models/ltx2/configs/ltx2_22b_config.json
new file mode 100644
index 0000000..1485786
--- /dev/null
+++ b/models/ltx2/configs/ltx2_22b_config.json
@@ -0,0 +1,356 @@
+{
+ "audio_vae": {
+ "model": {
+ "params": {
+ "ddconfig": {
+ "attn_resolutions": [],
+ "causality_axis": "height",
+ "ch": 128,
+ "ch_mult": [
+ 1,
+ 2,
+ 4
+ ],
+ "double_z": true,
+ "downsample_time": false,
+ "dropout": 0.0,
+ "in_channels": 2,
+ "mel_bins": 64,
+ "mid_block_add_attention": false,
+ "norm_type": "pixel",
+ "num_res_blocks": 2,
+ "out_ch": 2,
+ "resolution": 256,
+ "z_channels": 8
+ },
+ "sampling_rate": 16000
+ }
+ },
+ "preprocessing": {
+ "audio": {
+ "causal_padding": 3,
+ "duration": 5.12,
+ "max_wav_value": 32768.0,
+ "sampling_rate": 16000,
+ "stereo": true
+ },
+ "mel": {
+ "mel_fmax": 8000,
+ "mel_fmin": 0,
+ "n_mel_channels": 64
+ },
+ "stft": {
+ "causal": true,
+ "filter_length": 1024,
+ "hop_length": 160,
+ "win_length": 1024
+ }
+ }
+ },
+ "scheduler": {
+ "_class_name": "RectifiedFlowScheduler",
+ "_diffusers_version": "0.25.1",
+ "base_resolution": null,
+ "num_train_timesteps": 1000,
+ "sampler": "LinearQuadratic",
+ "shifting": null
+ },
+ "transformer": {
+ "_class_name": "AVTransformer3DModel",
+ "activation_fn": "gelu-approximate",
+ "apply_gated_attention": true,
+ "attention_bias": true,
+ "attention_head_dim": 128,
+ "attention_type": "default",
+ "audio_attention_head_dim": 64,
+ "audio_connector_attention_head_dim": 64,
+ "audio_connector_num_attention_heads": 32,
+ "audio_cross_attention_dim": 2048,
+ "audio_num_attention_heads": 32,
+ "audio_out_channels": 128,
+ "audio_positional_embedding_max_pos": [
+ 20
+ ],
+ "av_ca_timestep_scale_multiplier": 1000.0,
+ "av_cross_ada_norm": true,
+ "caption_channels": 3840,
+ "caption_proj_before_connector": true,
+ "caption_proj_input_norm": false,
+ "caption_projection_first_linear": false,
+ "caption_projection_second_linear": false,
+ "causal_temporal_positioning": true,
+ "connector_apply_gated_attention": true,
+ "connector_attention_head_dim": 128,
+ "connector_learnable_registers_std": 1,
+ "connector_norm_output": true,
+ "connector_num_attention_heads": 32,
+ "connector_num_layers": 8,
+ "connector_num_learnable_registers": 128,
+ "connector_positional_embedding_max_pos": [
+ 4096
+ ],
+ "cross_attention_adaln": true,
+ "cross_attention_dim": 4096,
+ "cross_attention_norm": true,
+ "double_self_attention": false,
+ "dropout": 0.0,
+ "frequencies_precision": "float64",
+ "in_channels": 128,
+ "norm_elementwise_affine": false,
+ "norm_eps": 1e-06,
+ "norm_num_groups": 32,
+ "num_attention_heads": 32,
+ "num_embeds_ada_norm": 1000,
+ "num_layers": 48,
+ "num_vector_embeds": null,
+ "only_cross_attention": false,
+ "out_channels": 128,
+ "positional_embedding_max_pos": [
+ 20,
+ 2048,
+ 2048
+ ],
+ "positional_embedding_theta": 10000.0,
+ "positional_embedding_type": "rope",
+ "qk_norm": "rms_norm",
+ "rope_type": "split",
+ "share_ff": false,
+ "standardization_norm": "rms_norm",
+ "text_encoder_norm_type": "per_token_rms",
+ "timestep_scale_multiplier": 1000,
+ "upcast_attention": false,
+ "use_audio_video_cross_attention": true,
+ "use_embeddings_connector": true,
+ "use_linear_projection": false,
+ "use_middle_indices_grid": true
+ },
+ "vae": {
+ "_class_name": "CausalVideoAutoencoder",
+ "causal_decoder": false,
+ "decoder_base_channels": 128,
+ "decoder_blocks": [
+ [
+ "res_x",
+ {
+ "num_layers": 4
+ }
+ ],
+ [
+ "compress_space",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 6
+ }
+ ],
+ [
+ "compress_time",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 4
+ }
+ ],
+ [
+ "compress_all",
+ {
+ "multiplier": 1
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ],
+ [
+ "compress_all",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ]
+ ],
+ "dims": 3,
+ "encoder_base_channels": 128,
+ "encoder_blocks": [
+ [
+ "res_x",
+ {
+ "num_layers": 4
+ }
+ ],
+ [
+ "compress_space_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 6
+ }
+ ],
+ [
+ "compress_time_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 4
+ }
+ ],
+ [
+ "compress_all_res",
+ {
+ "multiplier": 2
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ],
+ [
+ "compress_all_res",
+ {
+ "multiplier": 1
+ }
+ ],
+ [
+ "res_x",
+ {
+ "num_layers": 2
+ }
+ ]
+ ],
+ "in_channels": 3,
+ "latent_channels": 128,
+ "latent_log_var": "uniform",
+ "norm_layer": "pixel_norm",
+ "normalize_latent_channels": false,
+ "out_channels": 3,
+ "patch_size": 4,
+ "scaling_factor": 1.0,
+ "spatial_padding_mode": "zeros",
+ "timestep_conditioning": false,
+ "use_quant_conv": false
+ },
+ "vocoder": {
+ "bwe": {
+ "activation": "snakebeta",
+ "apply_final_activation": false,
+ "hop_length": 80,
+ "input_sampling_rate": 16000,
+ "n_fft": 512,
+ "num_mels": 64,
+ "output_sampling_rate": 48000,
+ "resblock": "AMP1",
+ "resblock_dilation_sizes": [
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ]
+ ],
+ "resblock_kernel_sizes": [
+ 3,
+ 7,
+ 11
+ ],
+ "stereo": true,
+ "upsample_initial_channel": 512,
+ "upsample_kernel_sizes": [
+ 12,
+ 11,
+ 4,
+ 4,
+ 4
+ ],
+ "upsample_rates": [
+ 6,
+ 5,
+ 2,
+ 2,
+ 2
+ ],
+ "use_bias_at_final": false,
+ "use_tanh_at_final": false,
+ "win_size": 512
+ },
+ "vocoder": {
+ "activation": "snakebeta",
+ "resblock": "AMP1",
+ "resblock_dilation_sizes": [
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ],
+ [
+ 1,
+ 3,
+ 5
+ ]
+ ],
+ "resblock_kernel_sizes": [
+ 3,
+ 7,
+ 11
+ ],
+ "stereo": true,
+ "upsample_initial_channel": 1536,
+ "upsample_kernel_sizes": [
+ 11,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4
+ ],
+ "upsample_rates": [
+ 5,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2
+ ],
+ "use_bias_at_final": false,
+ "use_tanh_at_final": false
+ }
+ }
+}
\ No newline at end of file
diff --git a/models/ltx2/configs/ltx2_rgb_factors.json b/models/ltx2/configs/ltx2_rgb_factors.json
new file mode 100644
index 0000000..783b17e
--- /dev/null
+++ b/models/ltx2/configs/ltx2_rgb_factors.json
@@ -0,0 +1,659 @@
+{
+ "ltx2_22B": {
+ "latent_rgb_factors": [
+ [
+ -0.002637,
+ -0.022435,
+ -0.014525
+ ],
+ [
+ -4e-05,
+ 0.002258,
+ -0.002773
+ ],
+ [
+ 0.017013,
+ 0.019457,
+ 0.01902
+ ],
+ [
+ 0.003543,
+ -0.003552,
+ -0.007818
+ ],
+ [
+ -0.009536,
+ -0.003874,
+ 0.004383
+ ],
+ [
+ 0.004008,
+ -0.006709,
+ -0.004319
+ ],
+ [
+ -0.036751,
+ -0.043466,
+ -0.048329
+ ],
+ [
+ -0.096575,
+ -0.064235,
+ -0.062143
+ ],
+ [
+ 0.011298,
+ 0.014851,
+ 0.011954
+ ],
+ [
+ -0.010023,
+ -0.009218,
+ -0.020513
+ ],
+ [
+ -0.008272,
+ -0.008638,
+ -0.006964
+ ],
+ [
+ -0.020323,
+ -0.015916,
+ -0.013125
+ ],
+ [
+ -0.000465,
+ -0.000317,
+ -0.008137
+ ],
+ [
+ -0.016116,
+ -0.018386,
+ -0.020579
+ ],
+ [
+ -0.006978,
+ -0.000909,
+ 0.007134
+ ],
+ [
+ 0.016408,
+ 0.007682,
+ 0.002734
+ ],
+ [
+ -0.005839,
+ -0.000587,
+ 0.012418
+ ],
+ [
+ -0.004253,
+ 0.000283,
+ 0.000204
+ ],
+ [
+ 0.011091,
+ 0.012431,
+ 0.020362
+ ],
+ [
+ -0.010974,
+ -0.013548,
+ -0.007926
+ ],
+ [
+ 0.008863,
+ -0.002148,
+ -0.014016
+ ],
+ [
+ -0.00136,
+ 0.00142,
+ 0.000509
+ ],
+ [
+ -0.011228,
+ -0.010231,
+ 0.003795
+ ],
+ [
+ -0.003145,
+ -0.01233,
+ -0.000278
+ ],
+ [
+ -0.004863,
+ 0.006857,
+ 0.019429
+ ],
+ [
+ -0.001873,
+ -0.009766,
+ -0.00023
+ ],
+ [
+ -0.01237,
+ -0.005718,
+ -0.009533
+ ],
+ [
+ -0.012286,
+ -0.001246,
+ 0.006019
+ ],
+ [
+ 0.004865,
+ -0.002002,
+ -0.004165
+ ],
+ [
+ -0.004346,
+ -0.005383,
+ -0.004504
+ ],
+ [
+ -0.002492,
+ 0.004697,
+ 0.002858
+ ],
+ [
+ -0.002394,
+ 0.000685,
+ 0.005236
+ ],
+ [
+ 0.007604,
+ 0.007468,
+ 0.009615
+ ],
+ [
+ -0.000106,
+ -0.003317,
+ -0.000438
+ ],
+ [
+ 0.024229,
+ 0.025679,
+ 0.025601
+ ],
+ [
+ 0.00897,
+ 0.005995,
+ 0.006451
+ ],
+ [
+ 0.000735,
+ 0.001644,
+ 0.001438
+ ],
+ [
+ -0.000723,
+ -0.003181,
+ -0.005735
+ ],
+ [
+ -0.007293,
+ -0.006387,
+ -0.004542
+ ],
+ [
+ 0.006823,
+ 0.004482,
+ 0.005263
+ ],
+ [
+ -0.003291,
+ 0.002319,
+ 0.000601
+ ],
+ [
+ -0.019049,
+ -0.022004,
+ -0.01587
+ ],
+ [
+ -0.005866,
+ -0.006257,
+ -0.004923
+ ],
+ [
+ -0.008179,
+ -0.005068,
+ -0.012506
+ ],
+ [
+ 0.016921,
+ 0.010924,
+ 0.008665
+ ],
+ [
+ 0.016727,
+ 0.006363,
+ 0.019086
+ ],
+ [
+ 0.007689,
+ 0.009421,
+ 0.006278
+ ],
+ [
+ 0.000311,
+ 0.004294,
+ 0.00234
+ ],
+ [
+ -0.008876,
+ -0.010579,
+ -0.007904
+ ],
+ [
+ -0.004933,
+ -0.004116,
+ -0.003897
+ ],
+ [
+ -0.00796,
+ -0.007913,
+ -0.005858
+ ],
+ [
+ 0.033702,
+ 0.02998,
+ 0.023054
+ ],
+ [
+ 0.003681,
+ 0.000736,
+ 0.001179
+ ],
+ [
+ 0.011194,
+ 0.009676,
+ 0.008584
+ ],
+ [
+ -0.006748,
+ -0.008025,
+ -0.012712
+ ],
+ [
+ 0.003629,
+ 0.008801,
+ 0.024646
+ ],
+ [
+ -0.005553,
+ -0.003534,
+ 0.000868
+ ],
+ [
+ 0.018373,
+ 0.026107,
+ 0.048515
+ ],
+ [
+ -0.018188,
+ -0.016738,
+ -0.011824
+ ],
+ [
+ -0.005569,
+ -0.002895,
+ -0.000267
+ ],
+ [
+ 0.024878,
+ 0.022724,
+ 0.020622
+ ],
+ [
+ -0.003171,
+ -0.003368,
+ -0.007122
+ ],
+ [
+ 0.016151,
+ 0.019179,
+ 0.016925
+ ],
+ [
+ -0.020461,
+ -0.016825,
+ 0.005923
+ ],
+ [
+ -0.010058,
+ 0.008644,
+ 0.006714
+ ],
+ [
+ -0.030223,
+ -0.028451,
+ -0.028098
+ ],
+ [
+ -0.012519,
+ -0.010286,
+ -0.010658
+ ],
+ [
+ -0.002638,
+ -0.00201,
+ 0.005868
+ ],
+ [
+ 0.009401,
+ 0.010221,
+ 0.01304
+ ],
+ [
+ -0.004573,
+ -0.005399,
+ -0.002189
+ ],
+ [
+ 0.005468,
+ 0.008426,
+ 0.007985
+ ],
+ [
+ 0.004175,
+ 0.001259,
+ 0.002328
+ ],
+ [
+ -0.008226,
+ 0.031092,
+ 0.034302
+ ],
+ [
+ -0.002707,
+ 0.000329,
+ -0.000929
+ ],
+ [
+ -0.017879,
+ -0.011023,
+ -0.008185
+ ],
+ [
+ -0.154098,
+ -0.149095,
+ -0.114443
+ ],
+ [
+ -0.011193,
+ -0.01034,
+ -0.010992
+ ],
+ [
+ 0.008415,
+ 0.009909,
+ 0.006711
+ ],
+ [
+ 0.010234,
+ 0.006162,
+ -0.000474
+ ],
+ [
+ -0.003913,
+ -0.004917,
+ 0.004581
+ ],
+ [
+ 0.009658,
+ -0.004839,
+ -0.002031
+ ],
+ [
+ 0.000503,
+ -0.001236,
+ -0.002399
+ ],
+ [
+ 0.045968,
+ 0.025765,
+ 0.022633
+ ],
+ [
+ -0.015219,
+ -0.026419,
+ -0.025316
+ ],
+ [
+ -0.008027,
+ -0.001555,
+ 0.004266
+ ],
+ [
+ 0.00206,
+ -0.00047,
+ -1.5e-05
+ ],
+ [
+ 0.017509,
+ 0.020194,
+ 0.00659
+ ],
+ [
+ 0.030655,
+ 0.015133,
+ -0.001706
+ ],
+ [
+ 0.005769,
+ 0.002032,
+ -0.001164
+ ],
+ [
+ -0.011608,
+ -0.002177,
+ -0.00019
+ ],
+ [
+ -0.006229,
+ -0.005444,
+ -0.003577
+ ],
+ [
+ 0.000107,
+ 0.005813,
+ -0.001181
+ ],
+ [
+ -0.014333,
+ -0.017095,
+ 0.004329
+ ],
+ [
+ 0.020339,
+ 0.016295,
+ 0.01572
+ ],
+ [
+ 0.019904,
+ 0.013839,
+ 0.007771
+ ],
+ [
+ 0.008964,
+ 0.009021,
+ 0.008781
+ ],
+ [
+ -0.004733,
+ 0.014352,
+ 0.00817
+ ],
+ [
+ -0.082997,
+ -0.146227,
+ -0.177141
+ ],
+ [
+ -0.004424,
+ 0.004261,
+ -0.002953
+ ],
+ [
+ 0.002149,
+ 0.005867,
+ 0.009992
+ ],
+ [
+ 0.009515,
+ 0.01639,
+ 0.019565
+ ],
+ [
+ 0.002039,
+ -0.008968,
+ -0.009913
+ ],
+ [
+ -0.007031,
+ -0.003982,
+ 9.3e-05
+ ],
+ [
+ 0.068442,
+ 0.075373,
+ 0.051207
+ ],
+ [
+ 0.011794,
+ 0.007765,
+ -0.00076
+ ],
+ [
+ 0.001684,
+ -0.003199,
+ 0.009644
+ ],
+ [
+ -0.003405,
+ -0.004217,
+ -0.00665
+ ],
+ [
+ -0.015646,
+ -0.00616,
+ -0.000201
+ ],
+ [
+ -0.060917,
+ -0.058964,
+ -0.050211
+ ],
+ [
+ -0.001947,
+ -0.003689,
+ 0.00299
+ ],
+ [
+ 0.018446,
+ 0.000534,
+ -0.040772
+ ],
+ [
+ -0.001858,
+ 0.008965,
+ 0.015008
+ ],
+ [
+ -0.045379,
+ -0.037718,
+ -0.035154
+ ],
+ [
+ -0.000329,
+ 0.007689,
+ 3.6e-05
+ ],
+ [
+ -0.016536,
+ -0.021012,
+ -0.00465
+ ],
+ [
+ 0.018388,
+ 0.023352,
+ 0.016103
+ ],
+ [
+ -0.086596,
+ -0.07431,
+ -0.078423
+ ],
+ [
+ 0.009143,
+ 0.008548,
+ 0.004895
+ ],
+ [
+ 0.002656,
+ 0.002964,
+ -0.000803
+ ],
+ [
+ -0.008501,
+ -0.008217,
+ -0.001661
+ ],
+ [
+ 0.006445,
+ -0.003139,
+ -0.008694
+ ],
+ [
+ 0.023101,
+ 0.035471,
+ 0.040335
+ ],
+ [
+ 0.005615,
+ 0.007732,
+ 0.007626
+ ],
+ [
+ -0.017656,
+ -0.014044,
+ -0.009303
+ ],
+ [
+ -0.004839,
+ -0.003358,
+ -0.000664
+ ],
+ [
+ -0.007193,
+ -0.005399,
+ -0.008577
+ ],
+ [
+ -0.031276,
+ -0.034591,
+ -0.0364
+ ],
+ [
+ -0.008987,
+ -0.015887,
+ -0.013977
+ ]
+ ],
+ "latent_rgb_factors_bias": [
+ -0.219173,
+ -0.292845,
+ -0.31485
+ ],
+ "regression_stats": {
+ "used_images": 500,
+ "skipped_images": 0,
+ "num_pixels": 609294,
+ "mse": 0.019852999807675988
+ },
+ "image_count_requested": 500,
+ "source_report": "tmp\\ltx2_rgb_regression_22b_picsum\\ltx2_22b_rgb_factors.json"
+ }
+}
\ No newline at end of file
diff --git a/models/ltx2/ltx2.py b/models/ltx2/ltx2.py
index cc116d1..71278c5 100644
--- a/models/ltx2/ltx2.py
+++ b/models/ltx2/ltx2.py
@@ -59,7 +59,7 @@ def _normalize_config(config_value):
return {}
-def _load_config_from_checkpoint(path):
+def _load_config_from_checkpoint(path, fallback_config_path: str | None = None):
from mmgp import quant_router
if isinstance(path, (list, tuple)):
@@ -68,15 +68,31 @@ def _load_config_from_checkpoint(path):
path = path[0]
if not path:
return {}
- _, metadata = quant_router.load_metadata_state_dict(path)
- if not metadata:
+
+ def _read_config_metadata(one_path: str) -> dict:
+ if not one_path:
+ return {}
+ _, metadata = quant_router.load_metadata_state_dict(one_path)
+ if not metadata:
+ return {}
+ return _normalize_config(metadata.get("config"))
+
+ config = _read_config_metadata(path)
+ if config:
+ return config
+ if not fallback_config_path:
+ return {}
+ try:
+ with open(fallback_config_path, "r", encoding="utf-8") as reader:
+ return _normalize_config(json.load(reader))
+ except Exception:
return {}
- return _normalize_config(metadata.get("config"))
def _strip_model_prefix(key: str) -> str:
- if key.startswith("model."):
- return key[len("model.") :]
+ for prefix in ("model.", "velocity_model."):
+ if key.startswith(prefix):
+ return _strip_model_prefix(key[len(prefix) :])
return key
@@ -441,7 +457,13 @@ class LTX2:
gemma_root = text_encoder_filepath if text_encoder_filename is None else text_encoder_filename
if not gemma_root:
raise ValueError("Missing Gemma text encoder path.")
- spatial_upsampler_path = fl.locate_file(_SPATIAL_UPSCALER_FILENAME)
+ if component_paths:
+ spatial_upsampler_path = component_paths.get("spatial_upsampler")
+ else:
+ spatial_upsampler_path = None
+ if not spatial_upsampler_path:
+ spatial_upsampler_name = model_def.get("ltx2_spatial_upscaler_file", _SPATIAL_UPSCALER_FILENAME)
+ spatial_upsampler_path = fl.locate_file(spatial_upsampler_name)
# Internal FP8 handling is disabled; mmgp manages quantization/dtypes.
pipeline_kind = model_def.get("ltx2_pipeline", "two_stage")
@@ -475,7 +497,8 @@ class LTX2:
):
from mmgp import offload as mmgp_offload
- base_config = _load_config_from_checkpoint(transformer_path)
+ fallback_config_path = component_paths.get("model_config") if component_paths else None
+ base_config = _load_config_from_checkpoint(transformer_path, fallback_config_path=fallback_config_path)
if not base_config:
raise ValueError("Missing config in transformer checkpoint.")
@@ -488,7 +511,7 @@ class LTX2:
return transformer_path
def _component_config(path):
- config = _load_config_from_checkpoint(path)
+ config = _load_config_from_checkpoint(path, fallback_config_path=fallback_config_path)
return config or base_config
def _load_component(model, path, sd_ops=None, postprocess=None):
@@ -1037,10 +1060,11 @@ class LTX2:
if audio_np is not None and audio_np.ndim == 2:
if audio_np.shape[0] in (1, 2) and audio_np.shape[1] > audio_np.shape[0]:
audio_np = audio_np.T
+ output_audio_sampling_rate = int(getattr(self.vocoder, "output_sampling_rate", AUDIO_SAMPLE_RATE))
result = {
"x": video_tensor,
"audio": audio_np,
- "audio_sampling_rate": AUDIO_SAMPLE_RATE,
+ "audio_sampling_rate": output_audio_sampling_rate,
}
if latent_slice is not None:
result["latent_slice"] = latent_slice
diff --git a/models/ltx2/ltx2_handler.py b/models/ltx2/ltx2_handler.py
index 443ab53..a7c8159 100644
--- a/models/ltx2/ltx2_handler.py
+++ b/models/ltx2/ltx2_handler.py
@@ -7,35 +7,79 @@ _GEMMA_FOLDER_URL = "https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/gemm
_GEMMA_FOLDER = "gemma-3-12b-it-qat-q4_0-unquantized"
_GEMMA_FILENAME = f"{_GEMMA_FOLDER}.safetensors"
_GEMMA_QUANTO_FILENAME = f"{_GEMMA_FOLDER}_quanto_bf16_int8.safetensors"
-_SPATIAL_UPSCALER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
-_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
-_VIDEO_VAE_FILENAME = "ltx-2-19b_vae.safetensors"
-_AUDIO_VAE_FILENAME = "ltx-2-19b_audio_vae.safetensors"
-_VOCODER_FILENAME = "ltx-2-19b_vocoder.safetensors"
-_TEXT_EMBEDDING_PROJECTION_FILENAME = "ltx-2-19b_text_embedding_projection.safetensors"
-_DEV_EMBEDDINGS_CONNECTOR_FILENAME = "ltx-2-19b-dev_embeddings_connector.safetensors"
-_DISTILLED_EMBEDDINGS_CONNECTOR_FILENAME = "ltx-2-19b-distilled_embeddings_connector.safetensors"
-
-def _get_embeddings_connector_filename(model_def):
+_ARCH_SPECS = {
+ "ltx2_19B": {
+ "repo_id": "DeepBeepMeep/LTX-2",
+ "config_file": "ltx2_19b_config.json",
+ "spatial_upscaler": "ltx-2-spatial-upscaler-x2-1.0.safetensors",
+ "temporal_upscaler": "ltx-2-temporal-upscaler-x2-1.0.safetensors",
+ "distilled_lora": "ltx-2-19b-distilled-lora-384.safetensors",
+ "video_vae": "ltx-2-19b_vae.safetensors",
+ "audio_vae": "ltx-2-19b_audio_vae.safetensors",
+ "vocoder": "ltx-2-19b_vocoder.safetensors",
+ "text_embedding_projection": "ltx-2-19b_text_embedding_projection.safetensors",
+ "dev_embeddings_connector": "ltx-2-19b-dev_embeddings_connector.safetensors",
+ "distilled_embeddings_connector": "ltx-2-19b-distilled_embeddings_connector.safetensors",
+ "profiles_dir": "ltx2_19B",
+ "lora_dir": "ltx2",
+ },
+ "ltx2_22B": {
+ "repo_id": "DeepBeepMeep/LTX-2.3",
+ "config_file": "ltx2_22b_config.json",
+ "spatial_upscaler": "ltx-2.3-spatial-upscaler-x2-1.0.safetensors",
+ "temporal_upscaler": "ltx-2.3-temporal-upscaler-x2-1.0.safetensors",
+ "distilled_lora": "ltx-2.3-22b-distilled-lora-384.safetensors",
+ "video_vae": "ltx-2.3-22b_vae.safetensors",
+ "audio_vae": "ltx-2.3-22b_audio_vae.safetensors",
+ "vocoder": "ltx-2.3-22b_vocoder.safetensors",
+ "text_embedding_projection": "ltx-2.3-22b_text_embedding_projection.safetensors",
+ "embeddings_connector": "ltx-2.3-22b_embeddings_connector.safetensors",
+ "profiles_dir": "ltx2_22B",
+ "lora_dir": "ltx2_22B",
+ },
+}
+
+
+def _get_arch_spec(base_model_type: str | None) -> dict:
+ return _ARCH_SPECS.get(base_model_type or "", _ARCH_SPECS["ltx2_19B"])
+
+
+def _default_slg_layers(base_model_type: str | None) -> list[int]:
+ return [28] if base_model_type == "ltx2_22B" else [29]
+
+
+def _get_embeddings_connector_filename(model_def, base_model_type):
+ spec = _get_arch_spec(base_model_type)
+ shared_connector = spec.get("embeddings_connector")
+ if shared_connector:
+ return shared_connector
pipeline_kind = (model_def or {}).get("ltx2_pipeline", "two_stage")
if pipeline_kind == "distilled":
- return _DISTILLED_EMBEDDINGS_CONNECTOR_FILENAME
- return _DEV_EMBEDDINGS_CONNECTOR_FILENAME
+ return spec["distilled_embeddings_connector"]
+ return spec["dev_embeddings_connector"]
-def _get_multi_file_names(model_def):
+def _get_multi_file_names(model_def, base_model_type):
+ spec = _get_arch_spec(base_model_type)
return {
- "video_vae": _VIDEO_VAE_FILENAME,
- "audio_vae": _AUDIO_VAE_FILENAME,
- "vocoder": _VOCODER_FILENAME,
- "text_embedding_projection": _TEXT_EMBEDDING_PROJECTION_FILENAME,
- "text_embeddings_connector": _get_embeddings_connector_filename(model_def),
+ "video_vae": spec["video_vae"],
+ "audio_vae": spec["audio_vae"],
+ "vocoder": spec["vocoder"],
+ "text_embedding_projection": spec["text_embedding_projection"],
+ "text_embeddings_connector": _get_embeddings_connector_filename(model_def, base_model_type),
}
-def _resolve_multi_file_paths(model_def):
- return {key: fl.locate_file(name) for key, name in _get_multi_file_names(model_def).items()}
+def _resolve_multi_file_paths(model_def, base_model_type):
+ spec = _get_arch_spec(base_model_type)
+ paths = {key: fl.locate_file(name) for key, name in _get_multi_file_names(model_def, base_model_type).items()}
+ paths["spatial_upsampler"] = fl.locate_file(spec["spatial_upscaler"])
+ model_config = os.path.join(os.path.dirname(__file__), "configs", spec["config_file"])
+ if not os.path.isfile(model_config):
+ raise FileNotFoundError(f"Missing LTX config file: {model_config}")
+ paths["model_config"] = model_config
+ return paths
@@ -43,7 +87,7 @@ def _resolve_multi_file_paths(model_def):
class family_handler:
@staticmethod
def query_supported_types():
- return ["ltx2_19B"]
+ return ["ltx2_19B", "ltx2_22B"]
@staticmethod
def query_family_maps():
@@ -59,9 +103,18 @@ class family_handler:
@staticmethod
def query_model_def(base_model_type, model_def):
+ spec = _get_arch_spec(base_model_type)
pipeline_kind = model_def.get("ltx2_pipeline", "two_stage")
+ is_ltx23 = base_model_type == "ltx2_22B"
distilled = pipeline_kind == "distilled"
+ audio_prompt_selection = ["", "A"] if is_ltx23 else ["", "A", "K"]
+ audio_prompt_labels = {
+ "": "Generate Video & Soundtrack based on Text Prompt",
+ "A": "Generate Video based on Soundtrack and Text Prompt",
+ }
+ if not is_ltx23:
+ audio_prompt_labels["K"] = "Generate Video based on Control Video + its Audio Track and Text Prompt"
extra_model_def = {
"text_encoder_folder": _GEMMA_FOLDER,
@@ -82,33 +135,31 @@ class family_handler:
"audio_guide_label": "Audio Prompt (Soundtrack)",
"audio_scale_name": "Prompt Audio Strength",
"audio_prompt_type_sources": {
- "selection": ["", "A", "K"],
- "labels": {
- "": "Generate Video & Soundtrack based on Text Prompt",
- "A": "Generate Video based on Soundtrack and Text Prompt",
- "K": "Generate Video based on Control Video + its Audio Track and Text Prompt",
- },
+ "selection": audio_prompt_selection,
+ "labels": audio_prompt_labels,
"show_label": False,
},
"audio_guide_window_slicing": True,
"output_audio_is_input_audio": True,
"custom_denoising_strength": True,
- "profiles_dir": ["ltx2_19B"],
+ "profiles_dir": [spec["profiles_dir"]],
+ "ltx2_spatial_upscaler_file": spec["spatial_upscaler"],
"self_refiner": True,
"self_refiner_max_plans": 2,
}
extra_model_def["extra_control_frames"] = 1
extra_model_def["dont_cat_preguide"] = True
extra_model_def["input_video_strength"] = "Image / Source Video Strength (you may try values lower value than 1 to get more motion)"
- extra_model_def["guide_preprocessing"] = {
- "selection": ["", "PVG", "DVG", "EVG", "VG"],
- "labels": {
- "PVG": "Transfer Human Motion",
- "DVG": "Transfer Depth",
- "EVG": "Transfer Canny Edges",
- "VG": "Use LTX-2 raw format",
- },
- }
+ if not is_ltx23:
+ extra_model_def["guide_preprocessing"] = {
+ "selection": ["", "PVG", "DVG", "EVG", "VG"],
+ "labels": {
+ "PVG": "Transfer Human Motion",
+ "DVG": "Transfer Depth",
+ "EVG": "Transfer Canny Edges",
+ "VG": "Use LTX-2 raw format",
+ },
+ }
extra_model_def["mask_preprocessing"] = {
"selection": ["", "A", "NA", "XA", "XNA"],
}
@@ -147,7 +198,7 @@ class family_handler:
def get_rgb_factors(base_model_type):
from shared.RGB_factors import get_rgb_factors
- return get_rgb_factors("ltx2")
+ return get_rgb_factors("ltx2", base_model_type)
@staticmethod
def register_lora_cli_args(parser, lora_root):
@@ -157,9 +208,17 @@ class family_handler:
default=None,
help=f"Path to a directory that contains LTX-2 LoRAs (default: {os.path.join(lora_root, 'ltx2')})",
)
+ parser.add_argument(
+ "--lora-dir-ltx2-22b",
+ type=str,
+ default=None,
+ help=f"Path to a directory that contains LTX-2.3 22B LoRAs (default: {os.path.join(lora_root, 'ltx2_22B')})",
+ )
@staticmethod
def get_lora_dir(base_model_type, args, lora_root):
+ if base_model_type == "ltx2_22B":
+ return getattr(args, "lora_dir_ltx2_22b", None) or os.path.join(lora_root, "ltx2_22B")
return getattr(args, "lora_dir_ltx2", None) or os.path.join(lora_root, "ltx2")
@staticmethod
@@ -168,6 +227,7 @@ class family_handler:
@staticmethod
def query_model_files(computeList, base_model_type, model_def=None):
+ spec = _get_arch_spec(base_model_type)
gemma_files = [
"added_tokens.json",
"chat_template.json",
@@ -179,16 +239,16 @@ class family_handler:
"tokenizer.json",
"tokenizer.model",
"tokenizer_config.json",
- ]
+ ]
- file_list = [_SPATIAL_UPSCALER_FILENAME]
- for name in _get_multi_file_names(model_def).values():
+ file_list = [spec["spatial_upscaler"], spec["temporal_upscaler"]]
+ for name in _get_multi_file_names(model_def, base_model_type).values():
if name not in file_list:
file_list.append(name)
download_def = [
{
- "repoId": "DeepBeepMeep/LTX-2",
+ "repoId": spec["repo_id"],
"sourceFolderList": [""],
"fileList": [file_list],
},
@@ -226,8 +286,8 @@ class family_handler:
):
from .ltx2 import LTX2
- checkpoint_paths = _resolve_multi_file_paths(model_def)
- transformer_path = model_filename[0] if isinstance(model_filename, (list, tuple)) else model_filename
+ checkpoint_paths = _resolve_multi_file_paths(model_def, base_model_type)
+ transformer_path = list(model_filename) if isinstance(model_filename, (list, tuple)) else model_filename
checkpoint_paths["transformer"] = transformer_path
ltx2_model = LTX2(
@@ -242,6 +302,19 @@ class family_handler:
checkpoint_paths=checkpoint_paths,
)
+ if save_quantized:
+ from wgp import save_quantized_model
+
+ quantized_source = transformer_path[0] if isinstance(transformer_path, (list, tuple)) else transformer_path
+ quantized_transformer = getattr(ltx2_model.model, "velocity_model", ltx2_model.model)
+ save_quantized_model(
+ quantized_transformer,
+ model_type,
+ quantized_source,
+ dtype,
+ checkpoint_paths["model_config"],
+ )
+
pipe = {
"transformer": ltx2_model.model,
"text_encoder": ltx2_model.text_encoder,
@@ -264,6 +337,7 @@ class family_handler:
@staticmethod
def fix_settings(base_model_type, settings_version, model_def, ui_defaults):
+ default_slg_layers = _default_slg_layers(base_model_type)
pipeline_kind = model_def.get("ltx2_pipeline", "two_stage")
if pipeline_kind != "distilled" and ui_defaults.get("guidance_phases", 0) < 2:
ui_defaults["guidance_phases"] = 2
@@ -280,7 +354,7 @@ class family_handler:
ui_defaults.update(
{
"alt_guidance_scale": 1.0,
- "slg_layers": [29],
+ "slg_layers": default_slg_layers,
}
)
@@ -299,6 +373,7 @@ class family_handler:
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
+ default_slg_layers = _default_slg_layers(base_model_type)
ui_defaults.update(
{
"sliding_window_size": 481,
@@ -307,7 +382,7 @@ class family_handler:
"masking_strength": 0,
"audio_prompt_type": "",
"alt_guidance_scale": 1.0,
- "slg_layers": [29],
+ "slg_layers": default_slg_layers,
}
)
ui_defaults.setdefault("audio_scale", 1.0)
diff --git a/models/ltx2/ltx_core/model/audio_vae/__init__.py b/models/ltx2/ltx_core/model/audio_vae/__init__.py
index 8d12304..ec2d672 100644
--- a/models/ltx2/ltx_core/model/audio_vae/__init__.py
+++ b/models/ltx2/ltx_core/model/audio_vae/__init__.py
@@ -10,7 +10,7 @@ from .model_configurator import (
VocoderConfigurator,
)
from .ops import AudioProcessor
-from .vocoder import Vocoder
+from .vocoder import Vocoder, VocoderWithBWE
__all__ = [
"AUDIO_VAE_DECODER_COMFY_KEYS_FILTER",
@@ -22,6 +22,7 @@ __all__ = [
"AudioEncoderConfigurator",
"AudioProcessor",
"Vocoder",
+ "VocoderWithBWE",
"VocoderConfigurator",
"decode_audio",
]
diff --git a/models/ltx2/ltx_core/model/audio_vae/model_configurator.py b/models/ltx2/ltx_core/model/audio_vae/model_configurator.py
index e652ced..63879bd 100644
--- a/models/ltx2/ltx_core/model/audio_vae/model_configurator.py
+++ b/models/ltx2/ltx_core/model/audio_vae/model_configurator.py
@@ -1,30 +1,86 @@
-from ...loader.sd_ops import SDOps
+import torch
+
+from ...loader.sd_ops import KeyValueOperationResult, SDOps
from .attention import AttentionType
from .audio_vae import AudioDecoder, AudioEncoder
from .causality_axis import CausalityAxis
-from .vocoder import Vocoder
+from .vocoder import MelSTFT, Vocoder, VocoderWithBWE
from ..common.normalization import NormType
from ..model_protocol import ModelConfigurator
+from ...utils import check_config_value
+
+
+def _vocoder_from_config(
+ cfg: dict,
+ apply_final_activation: bool = True,
+ output_sampling_rate: int | None = None,
+) -> Vocoder:
+ return Vocoder(
+ resblock_kernel_sizes=cfg.get("resblock_kernel_sizes", [3, 7, 11]),
+ upsample_rates=cfg.get("upsample_rates", [6, 5, 2, 2, 2]),
+ upsample_kernel_sizes=cfg.get("upsample_kernel_sizes", [16, 15, 8, 4, 4]),
+ resblock_dilation_sizes=cfg.get("resblock_dilation_sizes", [[1, 3, 5], [1, 3, 5], [1, 3, 5]]),
+ upsample_initial_channel=cfg.get("upsample_initial_channel", 1024),
+ resblock=cfg.get("resblock", "1"),
+ output_sampling_rate=(
+ output_sampling_rate if output_sampling_rate is not None else cfg.get("output_sampling_rate", 24000)
+ ),
+ activation=cfg.get("activation", "snake"),
+ use_tanh_at_final=cfg.get("use_tanh_at_final", True),
+ apply_final_activation=apply_final_activation,
+ use_bias_at_final=cfg.get("use_bias_at_final", True),
+ )
class VocoderConfigurator(ModelConfigurator[Vocoder]):
@classmethod
- def from_config(cls: type[Vocoder], config: dict) -> Vocoder:
- config = config.get("vocoder", {})
- return Vocoder(
- resblock_kernel_sizes=config.get("resblock_kernel_sizes", [3, 7, 11]),
- upsample_rates=config.get("upsample_rates", [6, 5, 2, 2, 2]),
- upsample_kernel_sizes=config.get("upsample_kernel_sizes", [16, 15, 8, 4, 4]),
- resblock_dilation_sizes=config.get("resblock_dilation_sizes", [[1, 3, 5], [1, 3, 5], [1, 3, 5]]),
- upsample_initial_channel=config.get("upsample_initial_channel", 1024),
- stereo=config.get("stereo", True),
- resblock=config.get("resblock", "1"),
- output_sample_rate=config.get("output_sample_rate", 24000),
+ def from_config(cls: type[Vocoder], config: dict) -> Vocoder | VocoderWithBWE:
+ cfg = config.get("vocoder", {})
+ if "bwe" not in cfg:
+ check_config_value(cfg, "resblock", "1")
+ check_config_value(cfg, "stereo", True)
+ return _vocoder_from_config(cfg)
+
+ vocoder_cfg = cfg.get("vocoder", {})
+ bwe_cfg = cfg["bwe"]
+
+ check_config_value(vocoder_cfg, "resblock", "AMP1")
+ check_config_value(vocoder_cfg, "stereo", True)
+ check_config_value(vocoder_cfg, "activation", "snakebeta")
+ check_config_value(bwe_cfg, "resblock", "AMP1")
+ check_config_value(bwe_cfg, "stereo", True)
+ check_config_value(bwe_cfg, "activation", "snakebeta")
+
+ vocoder = _vocoder_from_config(vocoder_cfg, output_sampling_rate=bwe_cfg["input_sampling_rate"])
+ bwe_generator = _vocoder_from_config(
+ bwe_cfg,
+ apply_final_activation=False,
+ output_sampling_rate=bwe_cfg["output_sampling_rate"],
+ )
+ mel_stft = MelSTFT(
+ filter_length=bwe_cfg["n_fft"],
+ hop_length=bwe_cfg["hop_length"],
+ win_length=bwe_cfg["n_fft"],
+ n_mel_channels=bwe_cfg["num_mels"],
+ )
+ return VocoderWithBWE(
+ vocoder=vocoder,
+ bwe_generator=bwe_generator,
+ mel_stft=mel_stft,
+ input_sampling_rate=bwe_cfg["input_sampling_rate"],
+ output_sampling_rate=bwe_cfg["output_sampling_rate"],
+ hop_length=bwe_cfg["hop_length"],
)
+def _strip_vocoder_prefix(key: str, value: torch.Tensor) -> list[KeyValueOperationResult]:
+ return [KeyValueOperationResult(key.removeprefix("vocoder."), value)]
+
+
VOCODER_COMFY_KEYS_FILTER = (
- SDOps("VOCODER_COMFY_KEYS_FILTER").with_matching(prefix="vocoder.").with_replacement("vocoder.", "")
+ SDOps("VOCODER_COMFY_KEYS_FILTER")
+ .with_matching(prefix="vocoder.")
+ .with_kv_operation(operation=_strip_vocoder_prefix, key_prefix="vocoder.")
)
diff --git a/models/ltx2/ltx_core/model/audio_vae/vocoder.py b/models/ltx2/ltx_core/model/audio_vae/vocoder.py
index ac4405d..477674f 100644
--- a/models/ltx2/ltx_core/model/audio_vae/vocoder.py
+++ b/models/ltx2/ltx_core/model/audio_vae/vocoder.py
@@ -1,4 +1,4 @@
-import math
+import math
from typing import List
import einops
@@ -6,7 +6,266 @@ import torch
import torch.nn.functional as F
from torch import nn
-from .resnet import LRELU_SLOPE, ResBlock1, ResBlock2
+from .resnet import LRELU_SLOPE, ResBlock1
+
+
+def get_padding(kernel_size: int, dilation: int = 1) -> int:
+ return int((kernel_size * dilation - dilation) / 2)
+
+
+# ---------------------------------------------------------------------------
+# Anti-aliased resampling helpers (kaiser-sinc filters) for BigVGAN v2
+# Adopted from https://github.com/NVIDIA/BigVGAN
+# ---------------------------------------------------------------------------
+
+
+def _sinc(x: torch.Tensor) -> torch.Tensor:
+ return torch.where(
+ x == 0,
+ torch.tensor(1.0, device=x.device, dtype=x.dtype),
+ torch.sin(math.pi * x) / math.pi / x,
+ )
+
+
+def kaiser_sinc_filter1d(cutoff: float, half_width: float, kernel_size: int) -> torch.Tensor:
+ even = kernel_size % 2 == 0
+ half_size = kernel_size // 2
+ delta_f = 4 * half_width
+ amplitude = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
+ if amplitude > 50.0:
+ beta = 0.1102 * (amplitude - 8.7)
+ elif amplitude >= 21.0:
+ beta = 0.5842 * (amplitude - 21) ** 0.4 + 0.07886 * (amplitude - 21.0)
+ else:
+ beta = 0.0
+ window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
+ time = torch.arange(-half_size, half_size) + 0.5 if even else torch.arange(kernel_size) - half_size
+ if cutoff == 0:
+ filter_ = torch.zeros_like(time)
+ else:
+ filter_ = 2 * cutoff * window * _sinc(2 * cutoff * time)
+ filter_ /= filter_.sum()
+ return filter_.view(1, 1, kernel_size)
+
+
+class LowPassFilter1d(nn.Module):
+ def __init__(
+ self,
+ cutoff: float = 0.5,
+ half_width: float = 0.6,
+ stride: int = 1,
+ padding: bool = True,
+ padding_mode: str = "replicate",
+ kernel_size: int = 12,
+ ) -> None:
+ super().__init__()
+ if cutoff < -0.0:
+ raise ValueError("Minimum cutoff must be larger than zero.")
+ if cutoff > 0.5:
+ raise ValueError("A cutoff above 0.5 does not make sense.")
+ self.kernel_size = kernel_size
+ self.even = kernel_size % 2 == 0
+ self.pad_left = kernel_size // 2 - int(self.even)
+ self.pad_right = kernel_size // 2
+ self.stride = stride
+ self.padding = padding
+ self.padding_mode = padding_mode
+ self.register_buffer("filter", kaiser_sinc_filter1d(cutoff, half_width, kernel_size))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ _, n_channels, _ = x.shape
+ if self.padding:
+ x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode)
+ return F.conv1d(x, self.filter.expand(n_channels, -1, -1), stride=self.stride, groups=n_channels)
+
+
+class UpSample1d(nn.Module):
+ def __init__(
+ self,
+ ratio: int = 2,
+ kernel_size: int | None = None,
+ persistent: bool = True,
+ window_type: str = "kaiser",
+ ) -> None:
+ super().__init__()
+ self.ratio = ratio
+ self.stride = ratio
+
+ if window_type == "hann":
+ # Hann-windowed sinc filter equivalent to torchaudio.functional.resample
+ rolloff = 0.99
+ lowpass_filter_width = 6
+ width = math.ceil(lowpass_filter_width / rolloff)
+ self.kernel_size = 2 * width * ratio + 1
+ self.pad = width
+ self.pad_left = 2 * width * ratio
+ self.pad_right = self.kernel_size - ratio
+ time_axis = (torch.arange(self.kernel_size) / ratio - width) * rolloff
+ time_clamped = time_axis.clamp(-lowpass_filter_width, lowpass_filter_width)
+ window = torch.cos(time_clamped * math.pi / lowpass_filter_width / 2) ** 2
+ sinc_filter = (torch.sinc(time_axis) * window * rolloff / ratio).view(1, 1, -1)
+ else:
+ # Kaiser-windowed sinc filter (BigVGAN default).
+ self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
+ self.pad = self.kernel_size // ratio - 1
+ self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
+ self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
+ sinc_filter = kaiser_sinc_filter1d(
+ cutoff=0.5 / ratio,
+ half_width=0.6 / ratio,
+ kernel_size=self.kernel_size,
+ )
+
+ self.register_buffer("filter", sinc_filter, persistent=persistent)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ _, n_channels, _ = x.shape
+ x = F.pad(x, (self.pad, self.pad), mode="replicate")
+ filt = self.filter.to(dtype=x.dtype, device=x.device).expand(n_channels, -1, -1)
+ x = self.ratio * F.conv_transpose1d(x, filt, stride=self.stride, groups=n_channels)
+ return x[..., self.pad_left : -self.pad_right]
+
+
+class DownSample1d(nn.Module):
+ def __init__(self, ratio: int = 2, kernel_size: int | None = None) -> None:
+ super().__init__()
+ self.ratio = ratio
+ self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
+ self.lowpass = LowPassFilter1d(
+ cutoff=0.5 / ratio,
+ half_width=0.6 / ratio,
+ stride=ratio,
+ kernel_size=self.kernel_size,
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.lowpass(x)
+
+
+class Activation1d(nn.Module):
+ def __init__(
+ self,
+ activation: nn.Module,
+ up_ratio: int = 2,
+ down_ratio: int = 2,
+ up_kernel_size: int = 12,
+ down_kernel_size: int = 12,
+ ) -> None:
+ super().__init__()
+ self.act = activation
+ self.upsample = UpSample1d(up_ratio, up_kernel_size)
+ self.downsample = DownSample1d(down_ratio, down_kernel_size)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.upsample(x)
+ x = self.act(x)
+ return self.downsample(x)
+
+
+class Snake(nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ alpha: float = 1.0,
+ alpha_trainable: bool = True,
+ alpha_logscale: bool = True,
+ ) -> None:
+ super().__init__()
+ self.alpha_logscale = alpha_logscale
+ self.alpha = nn.Parameter(torch.zeros(in_features) if alpha_logscale else torch.ones(in_features) * alpha)
+ self.alpha.requires_grad = alpha_trainable
+ self.eps = 1e-9
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1)
+ if self.alpha_logscale:
+ alpha = torch.exp(alpha)
+ return x + (1.0 / (alpha + self.eps)) * torch.sin(x * alpha).pow(2)
+
+
+class SnakeBeta(nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ alpha: float = 1.0,
+ alpha_trainable: bool = True,
+ alpha_logscale: bool = True,
+ ) -> None:
+ super().__init__()
+ self.alpha_logscale = alpha_logscale
+ self.alpha = nn.Parameter(torch.zeros(in_features) if alpha_logscale else torch.ones(in_features) * alpha)
+ self.alpha.requires_grad = alpha_trainable
+ self.beta = nn.Parameter(torch.zeros(in_features) if alpha_logscale else torch.ones(in_features) * alpha)
+ self.beta.requires_grad = alpha_trainable
+ self.eps = 1e-9
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1)
+ beta = self.beta.unsqueeze(0).unsqueeze(-1)
+ if self.alpha_logscale:
+ alpha = torch.exp(alpha)
+ beta = torch.exp(beta)
+ return x + (1.0 / (beta + self.eps)) * torch.sin(x * alpha).pow(2)
+
+
+class AMPBlock1(nn.Module):
+ def __init__(
+ self,
+ channels: int,
+ kernel_size: int = 3,
+ dilation: tuple[int, int, int] = (1, 3, 5),
+ activation: str = "snake",
+ ) -> None:
+ super().__init__()
+ act_cls = SnakeBeta if activation == "snakebeta" else Snake
+ self.convs1 = nn.ModuleList(
+ [
+ nn.Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[0],
+ padding=get_padding(kernel_size, dilation[0]),
+ ),
+ nn.Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[1],
+ padding=get_padding(kernel_size, dilation[1]),
+ ),
+ nn.Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[2],
+ padding=get_padding(kernel_size, dilation[2]),
+ ),
+ ]
+ )
+
+ self.convs2 = nn.ModuleList(
+ [
+ nn.Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1)),
+ nn.Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1)),
+ nn.Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1)),
+ ]
+ )
+
+ self.acts1 = nn.ModuleList([Activation1d(act_cls(channels)) for _ in range(len(self.convs1))])
+ self.acts2 = nn.ModuleList([Activation1d(act_cls(channels)) for _ in range(len(self.convs2))])
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ for c1, c2, a1, a2 in zip(self.convs1, self.convs2, self.acts1, self.acts2, strict=True):
+ xt = a1(x)
+ xt = c1(xt)
+ xt = a2(xt)
+ xt = c2(xt)
+ x = x + xt
+ return x
class Vocoder(torch.nn.Module):
@@ -23,28 +282,33 @@ class Vocoder(torch.nn.Module):
This value is read from the checkpoint at `config.vocoder.resblock_dilation_sizes`.
upsample_initial_channel: Initial number of channels for the upsampling layers.
This value is read from the checkpoint at `config.vocoder.upsample_initial_channel`.
- stereo: Whether to use stereo output.
- This value is read from the checkpoint at `config.vocoder.stereo`.
- resblock: Type of residual block to use.
+ resblock: Type of residual block to use ("1", "2", or "AMP1").
This value is read from the checkpoint at `config.vocoder.resblock`.
- output_sample_rate: Waveform sample rate.
- This value is read from the checkpoint at `config.vocoder.output_sample_rate`.
+ output_sampling_rate: Waveform sample rate.
+ This value is read from the checkpoint at `config.vocoder.output_sampling_rate`.
+ activation: Activation type for BigVGAN v2 ("snake" or "snakebeta"). Only used when resblock="AMP1".
+ use_tanh_at_final: Apply tanh at the output (when apply_final_activation=True).
+ apply_final_activation: Whether to apply the final tanh/clamp activation.
+ use_bias_at_final: Whether to use bias in the final conv layer.
"""
- def __init__(
+ def __init__( # noqa: PLR0913
self,
resblock_kernel_sizes: List[int] | None = None,
upsample_rates: List[int] | None = None,
upsample_kernel_sizes: List[int] | None = None,
resblock_dilation_sizes: List[List[int]] | None = None,
upsample_initial_channel: int = 1024,
- stereo: bool = True,
resblock: str = "1",
- output_sample_rate: int = 24000,
- ):
+ output_sampling_rate: int = 24000,
+ activation: str = "snake",
+ use_tanh_at_final: bool = True,
+ apply_final_activation: bool = True,
+ use_bias_at_final: bool = True,
+ ) -> None:
super().__init__()
- # Initialize default values if not provided. Note that mutable default values are not supported.
+ # Mutable default values are not supported as default arguments.
if resblock_kernel_sizes is None:
resblock_kernel_sizes = [3, 7, 11]
if upsample_rates is None:
@@ -54,36 +318,60 @@ class Vocoder(torch.nn.Module):
if resblock_dilation_sizes is None:
resblock_dilation_sizes = [[1, 3, 5], [1, 3, 5], [1, 3, 5]]
- self.output_sample_rate = output_sample_rate
+ self.output_sampling_rate = output_sampling_rate
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
- in_channels = 128 if stereo else 64
- self.conv_pre = nn.Conv1d(in_channels, upsample_initial_channel, 7, 1, padding=3)
- resblock_class = ResBlock1 if resblock == "1" else ResBlock2
-
- self.ups = nn.ModuleList()
- for i, (stride, kernel_size) in enumerate(zip(upsample_rates, upsample_kernel_sizes, strict=True)):
- self.ups.append(
- nn.ConvTranspose1d(
- upsample_initial_channel // (2**i),
- upsample_initial_channel // (2 ** (i + 1)),
- kernel_size,
- stride,
- padding=(kernel_size - stride) // 2,
- )
+ self.use_tanh_at_final = use_tanh_at_final
+ self.apply_final_activation = apply_final_activation
+ self.is_amp = resblock == "AMP1"
+
+ # All production checkpoints are stereo: 128 input channels (2 stereo channels x 64 mel
+ # bins each), 2 output channels.
+ self.conv_pre = nn.Conv1d(
+ in_channels=128,
+ out_channels=upsample_initial_channel,
+ kernel_size=7,
+ stride=1,
+ padding=3,
+ )
+ resblock_cls = ResBlock1 if resblock == "1" else AMPBlock1
+
+ self.ups = nn.ModuleList(
+ nn.ConvTranspose1d(
+ upsample_initial_channel // (2**i),
+ upsample_initial_channel // (2 ** (i + 1)),
+ kernel_size,
+ stride,
+ padding=(kernel_size - stride) // 2,
)
+ for i, (stride, kernel_size) in enumerate(zip(upsample_rates, upsample_kernel_sizes, strict=True))
+ )
+ final_channels = upsample_initial_channel // (2 ** len(upsample_rates))
self.resblocks = nn.ModuleList()
- for i, _ in enumerate(self.ups):
+
+ for i in range(len(upsample_rates)):
ch = upsample_initial_channel // (2 ** (i + 1))
for kernel_size, dilations in zip(resblock_kernel_sizes, resblock_dilation_sizes, strict=True):
- self.resblocks.append(resblock_class(ch, kernel_size, dilations))
+ if self.is_amp:
+ self.resblocks.append(resblock_cls(ch, kernel_size, dilations, activation=activation))
+ else:
+ self.resblocks.append(resblock_cls(ch, kernel_size, dilations))
- out_channels = 2 if stereo else 1
- final_channels = upsample_initial_channel // (2**self.num_upsamples)
- self.conv_post = nn.Conv1d(final_channels, out_channels, 7, 1, padding=3)
+ if self.is_amp:
+ self.act_post: nn.Module = Activation1d(SnakeBeta(final_channels))
+ else:
+ self.act_post = nn.LeakyReLU()
- self.upsample_factor = math.prod(layer.stride[0] for layer in self.ups)
+ # All production checkpoints are stereo: this final conv maps `final_channels` to 2 output channels (stereo).
+ self.conv_post = nn.Conv1d(
+ in_channels=final_channels,
+ out_channels=2,
+ kernel_size=7,
+ stride=1,
+ padding=3,
+ bias=use_bias_at_final,
+ )
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
@@ -104,7 +392,8 @@ class Vocoder(torch.nn.Module):
x = self.conv_pre(x)
for i in range(self.num_upsamples):
- x = F.leaky_relu(x, LRELU_SLOPE)
+ if not self.is_amp:
+ x = F.leaky_relu(x, LRELU_SLOPE)
x = self.ups[i](x)
start = i * self.num_kernels
end = start + self.num_kernels
@@ -116,8 +405,172 @@ class Vocoder(torch.nn.Module):
[self.resblocks[idx](x) for idx in range(start, end)],
dim=0,
)
-
x = block_outputs.mean(dim=0)
- x = self.conv_post(F.leaky_relu(x))
- return torch.tanh(x)
+ x = self.act_post(x)
+ x = self.conv_post(x)
+
+ if self.apply_final_activation:
+ x = torch.tanh(x) if self.use_tanh_at_final else torch.clamp(x, -1, 1)
+
+ return x
+
+
+class _STFTFn(nn.Module):
+ """Implements STFT as a convolution with precomputed DFT x Hann-window bases.
+ The DFT basis rows (real and imaginary parts interleaved) multiplied by the causal
+ Hann window are stored as buffers and loaded from the checkpoint. Using the exact
+ bfloat16 bases from training ensures the mel values fed to the BWE generator are
+ bit-identical to what it was trained on.
+ """
+
+ def __init__(self, filter_length: int, hop_length: int, win_length: int) -> None:
+ super().__init__()
+ self.hop_length = hop_length
+ self.win_length = win_length
+ n_freqs = filter_length // 2 + 1
+ self.register_buffer("forward_basis", torch.zeros(n_freqs * 2, 1, filter_length))
+ self.register_buffer("inverse_basis", torch.zeros(n_freqs * 2, 1, filter_length))
+
+ def forward(self, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Compute magnitude and phase spectrogram from a batch of waveforms.
+ Applies causal (left-only) padding of win_length - hop_length samples so that
+ each output frame depends only on past and present input no lookahead.
+ Args:
+ y: Waveform tensor of shape (B, T).
+ Returns:
+ magnitude: Linear amplitude spectrogram, shape (B, n_freqs, T_frames).
+ phase: Phase spectrogram in radians, shape (B, n_freqs, T_frames).
+ """
+ if y.dim() == 2:
+ y = y.unsqueeze(1) # (B, 1, T)
+ left_pad = max(0, self.win_length - self.hop_length) # causal: left-only
+ y = F.pad(y, (left_pad, 0))
+ spec = F.conv1d(y, self.forward_basis, stride=self.hop_length, padding=0)
+ n_freqs = spec.shape[1] // 2
+ real, imag = spec[:, :n_freqs], spec[:, n_freqs:]
+ magnitude = torch.sqrt(real**2 + imag**2)
+ phase = torch.atan2(imag.float(), real.float()).to(real.dtype)
+ return magnitude, phase
+
+
+class MelSTFT(nn.Module):
+ """Causal log-mel spectrogram module whose buffers are loaded from the checkpoint.
+ Computes a log-mel spectrogram by running the causal STFT (_STFTFn) on the input
+ waveform and projecting the linear magnitude spectrum onto the mel filterbank.
+ The module's state dict layout matches the 'mel_stft.*' keys stored in the checkpoint
+ (mel_basis, stft_fn.forward_basis, stft_fn.inverse_basis).
+ """
+
+ def __init__(
+ self,
+ filter_length: int,
+ hop_length: int,
+ win_length: int,
+ n_mel_channels: int,
+ ) -> None:
+ super().__init__()
+ self.stft_fn = _STFTFn(filter_length, hop_length, win_length)
+
+ # Initialized to zeros; load_state_dict overwrites with the checkpoint's
+ # exact bfloat16 filterbank (vocoder.mel_stft.mel_basis, shape [n_mels, n_freqs]).
+ n_freqs = filter_length // 2 + 1
+ self.register_buffer("mel_basis", torch.zeros(n_mel_channels, n_freqs))
+
+ def mel_spectrogram(self, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Compute log-mel spectrogram and auxiliary spectral quantities.
+ Args:
+ y: Waveform tensor of shape (B, T).
+ Returns:
+ log_mel: Log-compressed mel spectrogram, shape (B, n_mel_channels, T_frames).
+ magnitude: Linear amplitude spectrogram, shape (B, n_freqs, T_frames).
+ phase: Phase spectrogram in radians, shape (B, n_freqs, T_frames).
+ energy: Per-frame energy (L2 norm over frequency), shape (B, T_frames).
+ """
+ magnitude, phase = self.stft_fn(y)
+ energy = torch.norm(magnitude, dim=1)
+ mel = torch.matmul(self.mel_basis.to(magnitude.dtype), magnitude)
+ log_mel = torch.log(torch.clamp(mel, min=1e-5))
+ return log_mel, magnitude, phase, energy
+
+
+class VocoderWithBWE(nn.Module):
+ """Vocoder with bandwidth extension (BWE) upsampling.
+ Chains a mel-to-wav vocoder with a BWE module that upsamples the output
+ to a higher sample rate. The BWE computes a mel spectrogram from the
+ vocoder output, runs it through a second generator to predict a residual,
+ and adds it to a sinc-resampled skip connection.
+ """
+
+ def __init__(
+ self,
+ vocoder: Vocoder,
+ bwe_generator: Vocoder,
+ mel_stft: MelSTFT,
+ input_sampling_rate: int,
+ output_sampling_rate: int,
+ hop_length: int,
+ ) -> None:
+ super().__init__()
+ self.vocoder = vocoder
+ self.bwe_generator = bwe_generator
+ self.mel_stft = mel_stft
+ self.input_sampling_rate = input_sampling_rate
+ self.output_sampling_rate = output_sampling_rate
+ self.hop_length = hop_length
+ # Compute the resampler on CPU so the sinc filter is materialized even when
+ # the model is constructed on meta device (SingleGPUModelBuilder pattern).
+ # The filter is not stored in the checkpoint (persistent=False).
+ with torch.device("cpu"):
+ self.resampler = UpSample1d(
+ ratio=output_sampling_rate // input_sampling_rate, persistent=False, window_type="hann"
+ )
+
+ @property
+ def conv_pre(self) -> nn.Conv1d:
+ return self.vocoder.conv_pre
+
+ @property
+ def conv_post(self) -> nn.Conv1d:
+ return self.vocoder.conv_post
+
+ def _compute_mel(self, audio: torch.Tensor) -> torch.Tensor:
+ """Compute log-mel spectrogram from waveform using causal STFT bases.
+ Args:
+ audio: Waveform tensor of shape (B, C, T).
+ Returns:
+ mel: Log-mel spectrogram of shape (B, C, n_mels, T_frames).
+ """
+ batch, n_channels, _ = audio.shape
+ flat = audio.reshape(batch * n_channels, -1) # (B*C, T)
+ mel, _, _, _ = self.mel_stft.mel_spectrogram(flat) # (B*C, n_mels, T_frames)
+ return mel.reshape(batch, n_channels, mel.shape[1], mel.shape[2]) # (B, C, n_mels, T_frames)
+
+ def forward(self, mel_spec: torch.Tensor) -> torch.Tensor:
+ """Run the full vocoder + BWE forward pass.
+ Args:
+ mel_spec: Mel spectrogram of shape (B, 2, T, mel_bins) for stereo
+ or (B, T, mel_bins) for mono. Same format as Vocoder.forward.
+ Returns:
+ Waveform tensor of shape (B, out_channels, T_out) clipped to [-1, 1].
+ """
+ x = self.vocoder(mel_spec)
+ _, _, length_low_rate = x.shape
+ output_length = length_low_rate * self.output_sampling_rate // self.input_sampling_rate
+
+ # Pad to multiple of hop_length for exact mel frame count
+ remainder = length_low_rate % self.hop_length
+ if remainder != 0:
+ x = F.pad(x, (0, self.hop_length - remainder))
+
+ # Compute mel spectrogram from vocoder output: (B, C, n_mels, T_frames)
+ mel = self._compute_mel(x)
+
+ # Vocoder.forward expects (B, C, T, mel_bins) transpose before calling bwe_generator
+ mel_for_bwe = mel.transpose(2, 3) # (B, C, T_frames, mel_bins)
+ residual = self.bwe_generator(mel_for_bwe)
+ skip = self.resampler(x)
+ assert residual.shape == skip.shape, f"residual {residual.shape} != skip {skip.shape}"
+
+ return torch.clamp(residual + skip, -1, 1)[..., :output_length]
+
diff --git a/models/ltx2/ltx_core/model/transformer/adaln.py b/models/ltx2/ltx_core/model/transformer/adaln.py
index 8cb70d5..9f1f56e 100644
--- a/models/ltx2/ltx_core/model/transformer/adaln.py
+++ b/models/ltx2/ltx_core/model/transformer/adaln.py
@@ -4,6 +4,16 @@ import torch
from .timestep_embedding import PixArtAlphaCombinedTimestepSizeEmbeddings
+# Number of AdaLN modulation parameters per transformer block.
+# Base: 2 params (shift + scale) x 3 norms (self-attn, feed-forward, output).
+ADALN_NUM_BASE_PARAMS = 6
+# Cross-attention AdaLN adds 3 more (scale, shift, gate) for the CA norm.
+ADALN_NUM_CROSS_ATTN_PARAMS = 3
+
+
+def adaln_embedding_coefficient(cross_attention_adaln: bool) -> int:
+ return ADALN_NUM_BASE_PARAMS + (ADALN_NUM_CROSS_ATTN_PARAMS if cross_attention_adaln else 0)
+
class AdaLayerNormSingle(torch.nn.Module):
r"""
diff --git a/models/ltx2/ltx_core/model/transformer/attention.py b/models/ltx2/ltx_core/model/transformer/attention.py
index 823f650..2c875a3 100644
--- a/models/ltx2/ltx_core/model/transformer/attention.py
+++ b/models/ltx2/ltx_core/model/transformer/attention.py
@@ -180,6 +180,7 @@ class Attention(torch.nn.Module):
norm_eps: float = 1e-6,
rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
attention_function: AttentionCallable | AttentionFunction = AttentionFunction.DEFAULT,
+ apply_gated_attention: bool = False,
) -> None:
super().__init__()
self.rope_type = rope_type
@@ -197,6 +198,7 @@ class Attention(torch.nn.Module):
self.to_q = torch.nn.Linear(query_dim, inner_dim, bias=True)
self.to_k = torch.nn.Linear(context_dim, inner_dim, bias=True)
self.to_v = torch.nn.Linear(context_dim, inner_dim, bias=True)
+ self.to_gate_logits = torch.nn.Linear(query_dim, heads, bias=True) if apply_gated_attention else None
self.to_out = torch.nn.Sequential(torch.nn.Linear(inner_dim, query_dim, bias=True), torch.nn.Identity())
@@ -219,6 +221,7 @@ class Attention(torch.nn.Module):
k_pe: torch.Tensor | None = None,
) -> torch.Tensor:
x = x_list[0]
+ gate_input = x
x_list.clear()
context = None
if context_list is not None:
@@ -252,6 +255,11 @@ class Attention(torch.nn.Module):
version=attention_version,
cross_attn=cross_attn
)
+ if self.to_gate_logits is not None:
+ gate_logits = self.to_gate_logits(gate_input)
+ gates = 2.0 * torch.sigmoid(gate_logits).to(dtype=out.dtype)
+ out.mul_(gates.unsqueeze(-1))
+ gate_input = None
out = out.flatten(2, 3)
out = self.to_out(out)
return out
diff --git a/models/ltx2/ltx_core/model/transformer/modality.py b/models/ltx2/ltx_core/model/transformer/modality.py
index f4b1656..0cf1bfd 100644
--- a/models/ltx2/ltx_core/model/transformer/modality.py
+++ b/models/ltx2/ltx_core/model/transformer/modality.py
@@ -14,6 +14,7 @@ class Modality:
latent: (
torch.Tensor
) # Shape: (B, T, D) where B is the batch size, T is the number of tokens, and D is input dimension
+ sigma: torch.Tensor # Shape: (B,). Current sigma value for prompt/cross-attention AdaLN.
timesteps: torch.Tensor # Shape: (B, T) where T is the number of timesteps
positions: (
torch.Tensor
@@ -21,4 +22,5 @@ class Modality:
context: torch.Tensor
enabled: bool = True
context_mask: torch.Tensor | None = None
+ attention_mask: torch.Tensor | None = None
frame_indices: torch.Tensor | None = None
diff --git a/models/ltx2/ltx_core/model/transformer/model.py b/models/ltx2/ltx_core/model/transformer/model.py
index ac2536c..22f6b96 100644
--- a/models/ltx2/ltx_core/model/transformer/model.py
+++ b/models/ltx2/ltx_core/model/transformer/model.py
@@ -4,11 +4,10 @@ from enum import Enum
import torch
from ...guidance.perturbations import BatchedPerturbationConfig
-from .adaln import AdaLayerNormSingle
+from .adaln import AdaLayerNormSingle, adaln_embedding_coefficient
from .attention import AttentionCallable, AttentionFunction
from .modality import Modality
from .rope import LTXRopeType
-from .text_projection import PixArtAlphaTextProjection
from .transformer import BasicAVTransformerBlock, TransformerConfig, _apply_scale_shift
from .transformer_args import (
MultiModalTransformerArgsPreprocessor,
@@ -62,9 +61,14 @@ class LTXModel(torch.nn.Module):
av_ca_timestep_scale_multiplier: int = 1,
rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
double_precision_rope: bool = False,
+ apply_gated_attention: bool = False,
+ caption_projection: torch.nn.Module | None = None,
+ audio_caption_projection: torch.nn.Module | None = None,
+ cross_attention_adaln: bool = False,
):
super().__init__()
self._enable_gradient_checkpointing = False
+ self.cross_attention_adaln = cross_attention_adaln
self.interrupt_check: Callable[[], bool] | None = None
self.interrupted = False
self.interrupt_check: Callable[[], bool] | None = None
@@ -86,6 +90,7 @@ class LTXModel(torch.nn.Module):
out_channels=out_channels,
caption_channels=caption_channels,
norm_eps=norm_eps,
+ caption_projection=caption_projection,
)
if model_type.is_audio_enabled():
@@ -99,6 +104,7 @@ class LTXModel(torch.nn.Module):
out_channels=audio_out_channels,
caption_channels=caption_channels,
norm_eps=norm_eps,
+ caption_projection=audio_caption_projection,
)
if model_type.is_video_enabled() and model_type.is_audio_enabled():
@@ -117,6 +123,7 @@ class LTXModel(torch.nn.Module):
audio_cross_attention_dim=audio_cross_attention_dim,
norm_eps=norm_eps,
attention_type=attention_type,
+ apply_gated_attention=apply_gated_attention,
)
def _init_video(
@@ -125,17 +132,21 @@ class LTXModel(torch.nn.Module):
out_channels: int,
caption_channels: int,
norm_eps: float,
+ caption_projection: torch.nn.Module | None = None,
) -> None:
"""Initialize video-specific components."""
# Video input components
self.patchify_proj = torch.nn.Linear(in_channels, self.inner_dim, bias=True)
+ if caption_projection is not None:
+ self.caption_projection = caption_projection
- self.adaln_single = AdaLayerNormSingle(self.inner_dim)
+ self.adaln_single = AdaLayerNormSingle(
+ self.inner_dim,
+ embedding_coefficient=adaln_embedding_coefficient(self.cross_attention_adaln),
+ )
- # Video caption projection
- self.caption_projection = PixArtAlphaTextProjection(
- in_features=caption_channels,
- hidden_size=self.inner_dim,
+ self.prompt_adaln_single = (
+ AdaLayerNormSingle(self.inner_dim, embedding_coefficient=2) if self.cross_attention_adaln else None
)
# Video output components
@@ -149,20 +160,22 @@ class LTXModel(torch.nn.Module):
out_channels: int,
caption_channels: int,
norm_eps: float,
+ caption_projection: torch.nn.Module | None = None,
) -> None:
"""Initialize audio-specific components."""
# Audio input components
self.audio_patchify_proj = torch.nn.Linear(in_channels, self.audio_inner_dim, bias=True)
+ if caption_projection is not None:
+ self.audio_caption_projection = caption_projection
self.audio_adaln_single = AdaLayerNormSingle(
self.audio_inner_dim,
+ embedding_coefficient=adaln_embedding_coefficient(self.cross_attention_adaln),
)
- # Audio caption projection
- self.audio_caption_projection = PixArtAlphaTextProjection(
- in_features=caption_channels,
- hidden_size=self.audio_inner_dim,
+ self.audio_prompt_adaln_single = (
+ AdaLayerNormSingle(self.audio_inner_dim, embedding_coefficient=2) if self.cross_attention_adaln else None
)
# Audio output components
@@ -205,7 +218,7 @@ class LTXModel(torch.nn.Module):
self.video_args_preprocessor = MultiModalTransformerArgsPreprocessor(
patchify_proj=self.patchify_proj,
adaln=self.adaln_single,
- caption_projection=self.caption_projection,
+ caption_projection=getattr(self, "caption_projection", None),
cross_scale_shift_adaln=self.av_ca_video_scale_shift_adaln_single,
cross_gate_adaln=self.av_ca_a2v_gate_adaln_single,
inner_dim=self.inner_dim,
@@ -219,11 +232,12 @@ class LTXModel(torch.nn.Module):
positional_embedding_theta=self.positional_embedding_theta,
rope_type=self.rope_type,
av_ca_timestep_scale_multiplier=self.av_ca_timestep_scale_multiplier,
+ prompt_adaln=getattr(self, "prompt_adaln_single", None),
)
self.audio_args_preprocessor = MultiModalTransformerArgsPreprocessor(
patchify_proj=self.audio_patchify_proj,
adaln=self.audio_adaln_single,
- caption_projection=self.audio_caption_projection,
+ caption_projection=getattr(self, "audio_caption_projection", None),
cross_scale_shift_adaln=self.av_ca_audio_scale_shift_adaln_single,
cross_gate_adaln=self.av_ca_v2a_gate_adaln_single,
inner_dim=self.audio_inner_dim,
@@ -237,12 +251,13 @@ class LTXModel(torch.nn.Module):
positional_embedding_theta=self.positional_embedding_theta,
rope_type=self.rope_type,
av_ca_timestep_scale_multiplier=self.av_ca_timestep_scale_multiplier,
+ prompt_adaln=getattr(self, "audio_prompt_adaln_single", None),
)
elif self.model_type.is_video_enabled():
self.video_args_preprocessor = TransformerArgsPreprocessor(
patchify_proj=self.patchify_proj,
adaln=self.adaln_single,
- caption_projection=self.caption_projection,
+ caption_projection=getattr(self, "caption_projection", None),
inner_dim=self.inner_dim,
max_pos=self.positional_embedding_max_pos,
num_attention_heads=self.num_attention_heads,
@@ -251,12 +266,13 @@ class LTXModel(torch.nn.Module):
double_precision_rope=self.double_precision_rope,
positional_embedding_theta=self.positional_embedding_theta,
rope_type=self.rope_type,
+ prompt_adaln=getattr(self, "prompt_adaln_single", None),
)
elif self.model_type.is_audio_enabled():
self.audio_args_preprocessor = TransformerArgsPreprocessor(
patchify_proj=self.audio_patchify_proj,
adaln=self.audio_adaln_single,
- caption_projection=self.audio_caption_projection,
+ caption_projection=getattr(self, "audio_caption_projection", None),
inner_dim=self.audio_inner_dim,
max_pos=self.audio_positional_embedding_max_pos,
num_attention_heads=self.audio_num_attention_heads,
@@ -265,6 +281,7 @@ class LTXModel(torch.nn.Module):
double_precision_rope=self.double_precision_rope,
positional_embedding_theta=self.positional_embedding_theta,
rope_type=self.rope_type,
+ prompt_adaln=getattr(self, "audio_prompt_adaln_single", None),
)
def _refresh_preprocessor_refs(self) -> None:
@@ -288,6 +305,7 @@ class LTXModel(torch.nn.Module):
audio_cross_attention_dim: int,
norm_eps: float,
attention_type: AttentionFunction | AttentionCallable,
+ apply_gated_attention: bool,
) -> None:
"""Initialize transformer blocks for LTX."""
video_config = (
@@ -296,6 +314,8 @@ class LTXModel(torch.nn.Module):
heads=self.num_attention_heads,
d_head=attention_head_dim,
context_dim=cross_attention_dim,
+ apply_gated_attention=apply_gated_attention,
+ cross_attention_adaln=self.cross_attention_adaln,
)
if self.model_type.is_video_enabled()
else None
@@ -306,6 +326,8 @@ class LTXModel(torch.nn.Module):
heads=self.audio_num_attention_heads,
d_head=audio_attention_head_dim,
context_dim=audio_cross_attention_dim,
+ apply_gated_attention=apply_gated_attention,
+ cross_attention_adaln=self.cross_attention_adaln,
)
if self.model_type.is_audio_enabled()
else None
diff --git a/models/ltx2/ltx_core/model/transformer/model_configurator.py b/models/ltx2/ltx_core/model/transformer/model_configurator.py
index 9f47d03..f71ee41 100644
--- a/models/ltx2/ltx_core/model/transformer/model_configurator.py
+++ b/models/ltx2/ltx_core/model/transformer/model_configurator.py
@@ -7,6 +7,7 @@ from ..model_protocol import ModelConfigurator
from .attention import AttentionFunction
from .model import LTXModel, LTXModelType
from .rope import LTXRopeType
+from .text_projection import create_caption_projection
from ...utils import check_config_value
@@ -18,6 +19,7 @@ class LTXModelConfigurator(ModelConfigurator[LTXModel]):
@classmethod
def from_config(cls: type[LTXModel], config: dict) -> LTXModel:
+ caption_projection, audio_caption_projection = _build_caption_projections(config, is_av=True)
config = config.get("transformer", {})
check_config_value(config, "dropout", 0.0)
@@ -63,6 +65,10 @@ class LTXModelConfigurator(ModelConfigurator[LTXModel]):
av_ca_timestep_scale_multiplier=config.get("av_ca_timestep_scale_multiplier", 1),
rope_type=LTXRopeType(config.get("rope_type", "interleaved")),
double_precision_rope=config.get("frequencies_precision", False) == "float64",
+ apply_gated_attention=config.get("apply_gated_attention", False),
+ caption_projection=caption_projection,
+ audio_caption_projection=audio_caption_projection,
+ cross_attention_adaln=config.get("cross_attention_adaln", False),
)
@@ -74,6 +80,7 @@ class LTXVideoOnlyModelConfigurator(ModelConfigurator[LTXModel]):
@classmethod
def from_config(cls: type[LTXModel], config: dict) -> LTXModel:
+ caption_projection, _ = _build_caption_projections(config, is_av=False)
config = config.get("transformer", {})
check_config_value(config, "dropout", 0.0)
@@ -109,9 +116,22 @@ class LTXVideoOnlyModelConfigurator(ModelConfigurator[LTXModel]):
use_middle_indices_grid=config.get("use_middle_indices_grid", True),
rope_type=LTXRopeType(config.get("rope_type", "interleaved")),
double_precision_rope=config.get("frequencies_precision", False) == "float64",
+ apply_gated_attention=config.get("apply_gated_attention", False),
+ caption_projection=caption_projection,
+ cross_attention_adaln=config.get("cross_attention_adaln", False),
)
+def _build_caption_projections(config: dict, is_av: bool) -> tuple[torch.nn.Module | None, torch.nn.Module | None]:
+ transformer_config = config.get("transformer", {})
+ if transformer_config.get("caption_proj_before_connector", False):
+ return None, None
+ with torch.device("meta"):
+ caption_projection = create_caption_projection(transformer_config)
+ audio_caption_projection = create_caption_projection(transformer_config, audio=True) if is_av else None
+ return caption_projection, audio_caption_projection
+
+
def _naive_weight_or_bias_downcast(key: str, value: torch.Tensor) -> list[KeyValueOperationResult]:
"""
Downcast the weight or bias to the float8_e4m3fn dtype.
diff --git a/models/ltx2/ltx_core/model/transformer/text_projection.py b/models/ltx2/ltx_core/model/transformer/text_projection.py
index 788f6c8..844fb38 100644
--- a/models/ltx2/ltx_core/model/transformer/text_projection.py
+++ b/models/ltx2/ltx_core/model/transformer/text_projection.py
@@ -25,3 +25,12 @@ class PixArtAlphaTextProjection(torch.nn.Module):
hidden_states = self.act_1(hidden_states)
hidden_states = self.linear_2(hidden_states)
return hidden_states
+
+
+def create_caption_projection(transformer_config: dict, audio: bool = False) -> PixArtAlphaTextProjection:
+ caption_channels = transformer_config["caption_channels"]
+ if audio:
+ inner_dim = transformer_config["audio_num_attention_heads"] * transformer_config["audio_attention_head_dim"]
+ else:
+ inner_dim = transformer_config["num_attention_heads"] * transformer_config["attention_head_dim"]
+ return PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
diff --git a/models/ltx2/ltx_core/model/transformer/transformer.py b/models/ltx2/ltx_core/model/transformer/transformer.py
index b73b6b4..2641a0d 100644
--- a/models/ltx2/ltx_core/model/transformer/transformer.py
+++ b/models/ltx2/ltx_core/model/transformer/transformer.py
@@ -6,6 +6,7 @@ from dataclasses import dataclass, replace
import torch
from ...guidance.perturbations import BatchedPerturbationConfig, PerturbationType
+from .adaln import adaln_embedding_coefficient
from .attention import Attention, AttentionCallable, AttentionFunction
from .feed_forward import FeedForward
from .rope import LTXRopeType
@@ -21,15 +22,18 @@ def _restore_hidden_states_shape(hidden_states: torch.Tensor) -> torch.Tensor:
return hidden_states.reshape(hidden_states.shape[0], -1, hidden_states.shape[-1])
-def _apply_scale_shift(
- hidden_states: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor
-) -> torch.Tensor:
+def _apply_scale_shift(hidden_states: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor, in_place: bool = True) -> torch.Tensor:
if scale.shape[1] == hidden_states.shape[1]:
- hidden_states.mul_(1 + scale).add_(shift)
- return hidden_states
- hidden_states = _reshape_hidden_states(hidden_states, scale.shape[1])
- hidden_states.mul_(1 + scale.unsqueeze(2)).add_(shift.unsqueeze(2))
- return _restore_hidden_states_shape(hidden_states)
+ if in_place:
+ hidden_states.mul_(1 + scale).add_(shift)
+ return hidden_states
+ return hidden_states * (1 + scale) + shift
+
+ hidden_states_reshaped = _reshape_hidden_states(hidden_states, scale.shape[1])
+ if in_place:
+ hidden_states_reshaped.mul_(1 + scale.unsqueeze(2)).add_(shift.unsqueeze(2))
+ return _restore_hidden_states_shape(hidden_states_reshaped)
+ return _restore_hidden_states_shape(hidden_states_reshaped * (1 + scale.unsqueeze(2)) + shift.unsqueeze(2))
def _apply_gate(hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
@@ -47,6 +51,8 @@ class TransformerConfig:
heads: int
d_head: int
context_dim: int
+ apply_gated_attention: bool = False
+ cross_attention_adaln: bool = False
class BasicAVTransformerBlock(torch.nn.Module):
@@ -71,6 +77,7 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=video.apply_gated_attention,
)
self.attn2 = Attention(
query_dim=video.dim,
@@ -80,9 +87,10 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=video.apply_gated_attention,
)
self.ff = FeedForward(video.dim, dim_out=video.dim)
- self.scale_shift_table = torch.nn.Parameter(torch.empty(6, video.dim))
+ self.scale_shift_table = torch.nn.Parameter(torch.empty(adaln_embedding_coefficient(video.cross_attention_adaln), video.dim))
if audio is not None:
self.audio_attn1 = Attention(
@@ -93,6 +101,7 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=audio.apply_gated_attention,
)
self.audio_attn2 = Attention(
query_dim=audio.dim,
@@ -102,9 +111,10 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=audio.apply_gated_attention,
)
self.audio_ff = FeedForward(audio.dim, dim_out=audio.dim)
- self.audio_scale_shift_table = torch.nn.Parameter(torch.empty(6, audio.dim))
+ self.audio_scale_shift_table = torch.nn.Parameter(torch.empty(adaln_embedding_coefficient(audio.cross_attention_adaln), audio.dim))
if audio is not None and video is not None:
# Q: Video, K,V: Audio
@@ -116,6 +126,7 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=video.apply_gated_attention,
)
# Q: Audio, K,V: Video
@@ -127,11 +138,20 @@ class BasicAVTransformerBlock(torch.nn.Module):
rope_type=rope_type,
norm_eps=norm_eps,
attention_function=attention_function,
+ apply_gated_attention=audio.apply_gated_attention,
)
self.scale_shift_table_a2v_ca_audio = torch.nn.Parameter(torch.empty(5, audio.dim))
self.scale_shift_table_a2v_ca_video = torch.nn.Parameter(torch.empty(5, video.dim))
+ self.cross_attention_adaln = (video is not None and video.cross_attention_adaln) or (
+ audio is not None and audio.cross_attention_adaln
+ )
+ if self.cross_attention_adaln and video is not None:
+ self.prompt_scale_shift_table = torch.nn.Parameter(torch.empty(2, video.dim))
+ if self.cross_attention_adaln and audio is not None:
+ self.audio_prompt_scale_shift_table = torch.nn.Parameter(torch.empty(2, audio.dim))
+
self.norm_eps = norm_eps
self.ff_chunk_min_tokens = 1024
@@ -175,6 +195,34 @@ class BasicAVTransformerBlock(torch.nn.Module):
chunk[...] = ffn(chunk)
return x
+ def _apply_text_cross_attention(
+ self,
+ x: torch.Tensor,
+ context: torch.Tensor,
+ attn: AttentionCallable,
+ scale_shift_table: torch.Tensor,
+ prompt_scale_shift_table: torch.Tensor | None,
+ timestep: torch.Tensor,
+ prompt_timestep: torch.Tensor | None,
+ context_mask: torch.Tensor | None,
+ cross_attention_adaln: bool = False,
+ ) -> torch.Tensor:
+ if not cross_attention_adaln:
+ return attn([rms_norm(x, eps=self.norm_eps)], context_list=[context], mask=context_mask)
+ q_shift, q_scale, q_gate = self.get_ada_values(scale_shift_table, x.shape[0], timestep, slice(6, 9))
+ return apply_cross_attention_adaln(
+ x,
+ context,
+ attn,
+ q_shift,
+ q_scale,
+ q_gate,
+ prompt_scale_shift_table,
+ prompt_timestep,
+ context_mask,
+ self.norm_eps,
+ )
+
def forward( # noqa: PLR0915
self,
video: TransformerArgs | None,
@@ -212,8 +260,17 @@ class BasicAVTransformerBlock(torch.nn.Module):
attn_out.mul_(v_mask)
vx.add_(attn_out)
attn_out = None
- x_list, context_list = [rms_norm(vx, eps=self.norm_eps)], [video.context]
- attn_out = self.attn2(x_list, context_list=context_list, mask=video.context_mask)
+ attn_out = self._apply_text_cross_attention(
+ vx,
+ video.context,
+ self.attn2,
+ self.scale_shift_table,
+ getattr(self, "prompt_scale_shift_table", None),
+ video.timesteps,
+ video.prompt_timestep,
+ video.context_mask,
+ cross_attention_adaln=self.cross_attention_adaln,
+ )
vx.add_(attn_out)
attn_out = None
del vshift_msa, vscale_msa, vgate_msa
@@ -237,8 +294,17 @@ class BasicAVTransformerBlock(torch.nn.Module):
attn_out.mul_(a_mask)
ax.add_(attn_out)
attn_out = None
- x_list, context_list = [rms_norm(ax, eps=self.norm_eps)], [audio.context]
- attn_out = self.audio_attn2(x_list, context_list=context_list, mask=audio.context_mask)
+ attn_out = self._apply_text_cross_attention(
+ ax,
+ audio.context,
+ self.audio_attn2,
+ self.audio_scale_shift_table,
+ getattr(self, "audio_prompt_scale_shift_table", None),
+ audio.timesteps,
+ audio.prompt_timestep,
+ audio.context_mask,
+ cross_attention_adaln=self.cross_attention_adaln,
+ )
ax.add_(attn_out)
attn_out = None
del ashift_msa, ascale_msa, agate_msa
@@ -348,7 +414,7 @@ class BasicAVTransformerBlock(torch.nn.Module):
if run_vx:
vshift_mlp, vscale_mlp, vgate_mlp = self.get_ada_values(
- self.scale_shift_table, vx.shape[0], video.timesteps, slice(3, None)
+ self.scale_shift_table, vx.shape[0], video.timesteps, slice(3, 6)
)
vshift_mlp = vshift_mlp.to(vx.dtype)
vscale_mlp = vscale_mlp.to(vx.dtype)
@@ -364,7 +430,7 @@ class BasicAVTransformerBlock(torch.nn.Module):
if run_ax:
ashift_mlp, ascale_mlp, agate_mlp = self.get_ada_values(
- self.audio_scale_shift_table, ax.shape[0], audio.timesteps, slice(3, None)
+ self.audio_scale_shift_table, ax.shape[0], audio.timesteps, slice(3, 6)
)
ashift_mlp = ashift_mlp.to(ax.dtype)
ascale_mlp = ascale_mlp.to(ax.dtype)
@@ -379,3 +445,28 @@ class BasicAVTransformerBlock(torch.nn.Module):
del ashift_mlp, ascale_mlp, agate_mlp
return replace(video, x=vx) if video is not None else None, replace(audio, x=ax) if audio is not None else None
+
+
+def apply_cross_attention_adaln(
+ x: torch.Tensor,
+ context: torch.Tensor,
+ attn: AttentionCallable,
+ q_shift: torch.Tensor,
+ q_scale: torch.Tensor,
+ q_gate: torch.Tensor,
+ prompt_scale_shift_table: torch.Tensor | None,
+ prompt_timestep: torch.Tensor | None,
+ context_mask: torch.Tensor | None = None,
+ norm_eps: float = 1e-6,
+) -> torch.Tensor:
+ if prompt_scale_shift_table is not None and prompt_timestep is not None:
+ batch_size = x.shape[0]
+ shift_kv, scale_kv = (
+ prompt_scale_shift_table[None, None].to(device=x.device, dtype=x.dtype)
+ + prompt_timestep.reshape(batch_size, prompt_timestep.shape[1], 2, -1)
+ ).unbind(dim=2)
+ # Context is reused across blocks in LTX 2.3 prompt AdaLN, so this call must stay out-of-place.
+ context = _apply_scale_shift(context, scale_kv, shift_kv, in_place=False)
+ attn_input = _apply_scale_shift(rms_norm(x, eps=norm_eps), q_scale.squeeze(2), q_shift.squeeze(2))
+ out = attn([attn_input], context_list=[context], mask=context_mask)
+ return _apply_gate(out, q_gate.squeeze(2))
diff --git a/models/ltx2/ltx_core/model/transformer/transformer_args.py b/models/ltx2/ltx_core/model/transformer/transformer_args.py
index 17e35d4..29cb7f3 100644
--- a/models/ltx2/ltx_core/model/transformer/transformer_args.py
+++ b/models/ltx2/ltx_core/model/transformer/transformer_args.py
@@ -27,6 +27,8 @@ class TransformerArgs:
cross_scale_shift_timestep: torch.Tensor | None
cross_gate_timestep: torch.Tensor | None
enabled: bool
+ prompt_timestep: torch.Tensor | None = None
+ self_attention_mask: torch.Tensor | None = None
def _can_broadcast_timesteps(frame_indices: torch.Tensor | None, frame_count: int) -> bool:
@@ -68,7 +70,7 @@ class TransformerArgsPreprocessor:
self,
patchify_proj: torch.nn.Linear,
adaln: AdaLayerNormSingle,
- caption_projection: PixArtAlphaTextProjection,
+ caption_projection: PixArtAlphaTextProjection | None,
inner_dim: int,
max_pos: list[int],
num_attention_heads: int,
@@ -77,10 +79,12 @@ class TransformerArgsPreprocessor:
double_precision_rope: bool,
positional_embedding_theta: float,
rope_type: LTXRopeType,
+ prompt_adaln: AdaLayerNormSingle | None = None,
) -> None:
self.patchify_proj = patchify_proj
self.adaln = adaln
self.caption_projection = caption_projection
+ self.prompt_adaln = prompt_adaln
self.inner_dim = inner_dim
self.max_pos = max_pos
self.num_attention_heads = num_attention_heads
@@ -93,6 +97,7 @@ class TransformerArgsPreprocessor:
def _prepare_timestep(
self,
timestep: torch.Tensor,
+ adaln: AdaLayerNormSingle,
batch_size: int,
hidden_dtype: torch.dtype,
frame_indices: torch.Tensor | None = None,
@@ -101,13 +106,18 @@ class TransformerArgsPreprocessor:
timestep = timestep * self.timestep_scale_multiplier
timestep = _maybe_compress_timesteps(timestep, frame_indices, batch_size)
- timestep, embedded_timestep = self.adaln(
+ timestep, embedded_timestep = adaln(
timestep.flatten(),
hidden_dtype=hidden_dtype,
)
timestep = timestep.view(batch_size, -1, timestep.shape[-1])
embedded_timestep = embedded_timestep.view(batch_size, -1, embedded_timestep.shape[-1])
+ # Batch-level timesteps (for example prompt sigma in cross-attn AdaLN) are shared
+ # across all tokens and must not be gathered with per-token frame indices.
+ if timestep.shape[1] == 1:
+ return timestep, embedded_timestep
+
if frame_indices is None or _can_broadcast_timesteps(frame_indices, timestep.shape[1]):
return timestep, embedded_timestep
@@ -124,7 +134,8 @@ class TransformerArgsPreprocessor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Prepare context for transformer blocks."""
batch_size = x.shape[0]
- context = self.caption_projection(context)
+ if self.caption_projection is not None:
+ context = self.caption_projection(context)
context = context.view(batch_size, -1, x.shape[-1])
return context, attention_mask
@@ -186,10 +197,20 @@ class TransformerArgsPreprocessor:
x = self.patchify_proj(latent)
timestep, embedded_timestep = self._prepare_timestep(
modality.timesteps,
+ self.adaln,
x.shape[0],
latent_dtype,
frame_indices=modality.frame_indices,
)
+ prompt_timestep = None
+ if self.prompt_adaln is not None:
+ prompt_timestep, _ = self._prepare_timestep(
+ modality.sigma,
+ self.prompt_adaln,
+ x.shape[0],
+ latent_dtype,
+ frame_indices=modality.frame_indices,
+ )
context, attention_mask = self._prepare_context(modality.context, x, modality.context_mask)
attention_mask = self._prepare_attention_mask(attention_mask, latent_dtype)
pe = self._prepare_positional_embeddings(
@@ -212,6 +233,7 @@ class TransformerArgsPreprocessor:
cross_scale_shift_timestep=None,
cross_gate_timestep=None,
enabled=modality.enabled,
+ prompt_timestep=prompt_timestep,
)
@@ -220,7 +242,7 @@ class MultiModalTransformerArgsPreprocessor:
self,
patchify_proj: torch.nn.Linear,
adaln: AdaLayerNormSingle,
- caption_projection: PixArtAlphaTextProjection,
+ caption_projection: PixArtAlphaTextProjection | None,
cross_scale_shift_adaln: AdaLayerNormSingle,
cross_gate_adaln: AdaLayerNormSingle,
inner_dim: int,
@@ -234,6 +256,7 @@ class MultiModalTransformerArgsPreprocessor:
positional_embedding_theta: float,
rope_type: LTXRopeType,
av_ca_timestep_scale_multiplier: int,
+ prompt_adaln: AdaLayerNormSingle | None = None,
) -> None:
self.simple_preprocessor = TransformerArgsPreprocessor(
patchify_proj=patchify_proj,
@@ -247,6 +270,7 @@ class MultiModalTransformerArgsPreprocessor:
double_precision_rope=double_precision_rope,
positional_embedding_theta=positional_embedding_theta,
rope_type=rope_type,
+ prompt_adaln=prompt_adaln,
)
self.cross_scale_shift_adaln = cross_scale_shift_adaln
self.cross_gate_adaln = cross_gate_adaln
diff --git a/models/ltx2/ltx_core/model/video_vae/model_configurator.py b/models/ltx2/ltx_core/model/video_vae/model_configurator.py
index a07fd45..8d22c81 100644
--- a/models/ltx2/ltx_core/model/video_vae/model_configurator.py
+++ b/models/ltx2/ltx_core/model/video_vae/model_configurator.py
@@ -13,7 +13,9 @@ class VideoEncoderConfigurator(ModelConfigurator[VideoEncoder]):
convolution_dimensions = config.get("dims", 3)
in_channels = config.get("in_channels", 3)
latent_channels = config.get("latent_channels", 128)
- encoder_spatial_padding_mode = PaddingModeType(config.get("encoder_spatial_padding_mode", "zeros"))
+ encoder_spatial_padding_mode = PaddingModeType(
+ config.get("spatial_padding_mode", config.get("encoder_spatial_padding_mode", "zeros"))
+ )
encoder_blocks = config.get("encoder_blocks", [])
patch_size = config.get("patch_size", 4)
norm_layer_str = config.get("norm_layer", "pixel_norm")
@@ -39,7 +41,9 @@ class VideoDecoderConfigurator(ModelConfigurator[VideoDecoder]):
config = config.get("vae", {})
convolution_dimensions = config.get("dims", 3)
latent_channels = config.get("latent_channels", 128)
- decoder_spatial_padding_mode = PaddingModeType(config.get("decoder_spatial_padding_mode", "reflect"))
+ decoder_spatial_padding_mode = PaddingModeType(
+ config.get("spatial_padding_mode", config.get("decoder_spatial_padding_mode", "reflect"))
+ )
out_channels = config.get("out_channels", 3)
decoder_blocks = config.get("decoder_blocks", [])
patch_size = config.get("patch_size", 4)
@@ -47,6 +51,7 @@ class VideoDecoderConfigurator(ModelConfigurator[VideoDecoder]):
causal = config.get("causal_decoder", False)
timestep_conditioning = config.get("timestep_conditioning", True)
temporal_chunk_on_gpu = config.get("decode_temporal_chunk_on_gpu", True)
+ base_channels = config.get("decoder_base_channels", 128)
return VideoDecoder(
convolution_dimensions=convolution_dimensions,
@@ -59,6 +64,7 @@ class VideoDecoderConfigurator(ModelConfigurator[VideoDecoder]):
timestep_conditioning=timestep_conditioning,
temporal_chunk_on_gpu=temporal_chunk_on_gpu,
decoder_spatial_padding_mode=decoder_spatial_padding_mode,
+ base_channels=base_channels,
)
diff --git a/models/ltx2/ltx_core/model/video_vae/ops.py b/models/ltx2/ltx_core/model/video_vae/ops.py
index cb0ed2d..8912491 100644
--- a/models/ltx2/ltx_core/model/video_vae/ops.py
+++ b/models/ltx2/ltx_core/model/video_vae/ops.py
@@ -70,9 +70,6 @@ class PerChannelStatistics(nn.Module):
super().__init__()
self.register_buffer("std-of-means", torch.empty(latent_channels))
self.register_buffer("mean-of-means", torch.empty(latent_channels))
- self.register_buffer("mean-of-stds", torch.empty(latent_channels))
- self.register_buffer("mean-of-stds_over_std-of-means", torch.empty(latent_channels))
- self.register_buffer("channel", torch.empty(latent_channels))
def un_normalize(self, x: torch.Tensor) -> torch.Tensor:
return (x * self.get_buffer("std-of-means").view(1, -1, 1, 1, 1).to(x)) + self.get_buffer("mean-of-means").view(
diff --git a/models/ltx2/ltx_core/model/video_vae/video_vae.py b/models/ltx2/ltx_core/model/video_vae/video_vae.py
index 0683cb7..2771c65 100644
--- a/models/ltx2/ltx_core/model/video_vae/video_vae.py
+++ b/models/ltx2/ltx_core/model/video_vae/video_vae.py
@@ -362,17 +362,21 @@ def _make_decoder_block(
spatial_padding_mode=spatial_padding_mode,
)
elif block_name == "compress_time":
+ out_channels = in_channels // block_config.get("multiplier", 1)
block = DepthToSpaceUpsample(
dims=convolution_dimensions,
in_channels=in_channels,
stride=(2, 1, 1),
+ out_channels_reduction_factor=block_config.get("multiplier", 1),
spatial_padding_mode=spatial_padding_mode,
)
elif block_name == "compress_space":
+ out_channels = in_channels // block_config.get("multiplier", 1)
block = DepthToSpaceUpsample(
dims=convolution_dimensions,
in_channels=in_channels,
stride=(1, 2, 2),
+ out_channels_reduction_factor=block_config.get("multiplier", 1),
spatial_padding_mode=spatial_padding_mode,
)
elif block_name == "compress_all":
@@ -433,6 +437,7 @@ class VideoDecoder(nn.Module):
timestep_conditioning: bool = False,
temporal_chunk_on_gpu: bool = True,
decoder_spatial_padding_mode: PaddingModeType = PaddingModeType.REFLECT,
+ base_channels: int = 128,
):
super().__init__()
@@ -463,15 +468,8 @@ class VideoDecoder(nn.Module):
self._mask_cache: dict[tuple[int, torch.device, torch.dtype], tuple[torch.Tensor, torch.Tensor]] = {}
self._mask_cache_limit = 512
- # Compute initial feature_channels by going through blocks in reverse
- # This determines the channel width at the start of the decoder
- feature_channels = in_channels
- for block_name, block_params in list(reversed(decoder_blocks)):
- block_config = block_params if isinstance(block_params, dict) else {}
- if block_name == "res_x_y":
- feature_channels = feature_channels * block_config.get("multiplier", 2)
- if block_name == "compress_all":
- feature_channels = feature_channels * block_config.get("multiplier", 1)
+ # LTX decoder starts from a wider trunk then reduces channels across upsampling blocks.
+ feature_channels = base_channels * 8
self.conv_in = make_conv_nd(
dims=convolution_dimensions,
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py b/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
index ce616ff..024a8a9 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
@@ -19,6 +19,7 @@ class _BasicTransformerBlock1D(torch.nn.Module):
heads: int,
dim_head: int,
rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
+ apply_gated_attention: bool = False,
):
super().__init__()
@@ -27,6 +28,7 @@ class _BasicTransformerBlock1D(torch.nn.Module):
heads=heads,
dim_head=dim_head,
rope_type=rope_type,
+ apply_gated_attention=apply_gated_attention,
)
self.ff = FeedForward(
@@ -101,6 +103,7 @@ class Embeddings1DConnector(torch.nn.Module):
num_learnable_registers: int | None = 128,
rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
double_precision_rope: bool = False,
+ apply_gated_attention: bool = False,
):
super().__init__()
self.num_attention_heads = num_attention_heads
@@ -119,6 +122,7 @@ class Embeddings1DConnector(torch.nn.Module):
heads=num_attention_heads,
dim_head=attention_head_dim,
rope_type=rope_type,
+ apply_gated_attention=apply_gated_attention,
)
for _ in range(num_layers)
]
@@ -197,16 +201,59 @@ class Embeddings1DConnector(torch.nn.Module):
class Embeddings1DConnectorConfigurator(ModelConfigurator[Embeddings1DConnector]):
+ """Configurator for video embeddings connector."""
+
+ @classmethod
+ def from_config(cls: type[Embeddings1DConnector], config: dict) -> Embeddings1DConnector:
+ transformer_config = config.get("transformer", {})
+ rope_type = LTXRopeType(transformer_config.get("rope_type", "interleaved"))
+ double_precision_rope = transformer_config.get("frequencies_precision", False) == "float64"
+ pe_max_pos = transformer_config.get("connector_positional_embedding_max_pos", [1])
+ num_attention_heads = transformer_config.get("connector_num_attention_heads", 30)
+ attention_head_dim = transformer_config.get("connector_attention_head_dim", 128)
+ num_layers = transformer_config.get("connector_num_layers", 2)
+
+ connector = Embeddings1DConnector(
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ num_layers=num_layers,
+ positional_embedding_max_pos=pe_max_pos,
+ rope_type=rope_type,
+ double_precision_rope=double_precision_rope,
+ apply_gated_attention=transformer_config.get("connector_apply_gated_attention", False),
+ )
+ return connector
+
+
+class AudioEmbeddings1DConnectorConfigurator(ModelConfigurator[Embeddings1DConnector]):
+ """Configurator for audio embeddings connector with separate dimensions."""
+
@classmethod
def from_config(cls: type[Embeddings1DConnector], config: dict) -> Embeddings1DConnector:
- config = config.get("transformer", {})
- rope_type = LTXRopeType(config.get("rope_type", "interleaved"))
- double_precision_rope = config.get("frequencies_precision", False) == "float64"
- pe_max_pos = config.get("connector_positional_embedding_max_pos", [1])
+ transformer_config = config.get("transformer", {})
+ rope_type = LTXRopeType(transformer_config.get("rope_type", "interleaved"))
+ double_precision_rope = transformer_config.get("frequencies_precision", False) == "float64"
+ pe_max_pos = transformer_config.get("connector_positional_embedding_max_pos", [1])
+ num_attention_heads = transformer_config.get(
+ "audio_connector_num_attention_heads",
+ transformer_config.get("connector_num_attention_heads", 30),
+ )
+ attention_head_dim = transformer_config.get(
+ "audio_connector_attention_head_dim",
+ transformer_config.get("connector_attention_head_dim", 128),
+ )
+ num_layers = transformer_config.get(
+ "audio_connector_num_layers",
+ transformer_config.get("connector_num_layers", 2),
+ )
connector = Embeddings1DConnector(
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ num_layers=num_layers,
positional_embedding_max_pos=pe_max_pos,
rope_type=rope_type,
double_precision_rope=double_precision_rope,
+ apply_gated_attention=transformer_config.get("connector_apply_gated_attention", False),
)
return connector
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/encoders/av_encoder.py b/models/ltx2/ltx_core/text_encoders/gemma/encoders/av_encoder.py
index eb29c35..17c4dc9 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/encoders/av_encoder.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/encoders/av_encoder.py
@@ -6,6 +6,7 @@ from transformers.models.gemma3 import Gemma3ForConditionalGeneration
from ....loader.sd_ops import SDOps
from ....model.model_protocol import ModelConfigurator
from ..embeddings_connector import (
+ AudioEmbeddings1DConnectorConfigurator,
Embeddings1DConnector,
Embeddings1DConnectorConfigurator,
)
@@ -100,7 +101,7 @@ class AVGemmaTextEncoderModelConfigurator(ModelConfigurator[AVGemmaTextEncoderMo
def from_config(cls: type["AVGemmaTextEncoderModel"], config: dict) -> "AVGemmaTextEncoderModel":
feature_extractor_linear = GemmaFeaturesExtractorProjLinear.from_config(config)
embeddings_connector = Embeddings1DConnectorConfigurator.from_config(config)
- audio_embeddings_connector = Embeddings1DConnectorConfigurator.from_config(config)
+ audio_embeddings_connector = AudioEmbeddings1DConnectorConfigurator.from_config(config)
return AVGemmaTextEncoderModel(
feature_extractor_linear=feature_extractor_linear,
embeddings_connector=embeddings_connector,
@@ -124,7 +125,7 @@ class GemmaTextEmbeddingsConnectorModelConfigurator(ModelConfigurator[GemmaTextE
@classmethod
def from_config(cls: type["GemmaTextEmbeddingsConnectorModel"], config: dict) -> "GemmaTextEmbeddingsConnectorModel":
video_embeddings_connector = Embeddings1DConnectorConfigurator.from_config(config)
- audio_embeddings_connector = Embeddings1DConnectorConfigurator.from_config(config)
+ audio_embeddings_connector = AudioEmbeddings1DConnectorConfigurator.from_config(config)
return GemmaTextEmbeddingsConnectorModel(
video_embeddings_connector=video_embeddings_connector,
audio_embeddings_connector=audio_embeddings_connector,
@@ -150,7 +151,9 @@ AV_GEMMA_TEXT_ENCODER_KEY_OPS = (
TEXT_EMBEDDING_PROJECTION_KEY_OPS = (
SDOps("TEXT_EMBEDDING_PROJECTION_KEY_OPS")
.with_matching(prefix="text_embedding_projection.")
+ .with_matching(prefix="feature_extractor.")
.with_replacement("text_embedding_projection.", "")
+ .with_replacement("feature_extractor.", "")
)
TEXT_EMBEDDINGS_CONNECTOR_KEY_OPS = (
@@ -159,8 +162,12 @@ TEXT_EMBEDDINGS_CONNECTOR_KEY_OPS = (
.with_matching(prefix="model.diffusion_model.video_embeddings_connector.")
.with_matching(prefix="diffusion_model.audio_embeddings_connector.")
.with_matching(prefix="diffusion_model.video_embeddings_connector.")
+ .with_matching(prefix="audio_connector.")
+ .with_matching(prefix="video_connector.")
.with_replacement("model.diffusion_model.audio_embeddings_connector.", "audio_embeddings_connector.")
.with_replacement("model.diffusion_model.video_embeddings_connector.", "video_embeddings_connector.")
.with_replacement("diffusion_model.audio_embeddings_connector.", "audio_embeddings_connector.")
.with_replacement("diffusion_model.video_embeddings_connector.", "video_embeddings_connector.")
+ .with_replacement("audio_connector.", "audio_embeddings_connector.")
+ .with_replacement("video_connector.", "video_embeddings_connector.")
)
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py b/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
index 332c7a8..51543cd 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
@@ -59,15 +59,8 @@ class GemmaTextEncoderModelBase(torch.nn.Module):
) -> torch.Tensor:
if self.feature_extractor_linear is None:
raise ValueError("feature_extractor_linear is not available for this text encoder")
- encoded_text_features = torch.stack(hidden_states, dim=-1)
- encoded_text_features_dtype = encoded_text_features.dtype
-
- sequence_lengths = attention_mask.sum(dim=-1)
- normed_concated_encoded_text_features = _norm_and_concat_padded_batch(
- encoded_text_features, sequence_lengths, padding_side=padding_side
- )
-
- return self.feature_extractor_linear(normed_concated_encoded_text_features.to(encoded_text_features_dtype))
+ video_features, _ = self.feature_extractor_linear(hidden_states, attention_mask, padding_side=padding_side)
+ return video_features
def _convert_to_additive_mask(self, attention_mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
return (attention_mask - 1).to(dtype).reshape(
@@ -190,35 +183,31 @@ def _apply_feature_extractor(
attention_mask: torch.Tensor,
padding_side: str,
feature_extractor_linear: GemmaFeaturesExtractorProjLinear,
-) -> torch.Tensor:
- encoded_text_features = torch.stack(hidden_states, dim=-1)
- encoded_text_features_dtype = encoded_text_features.dtype
- sequence_lengths = attention_mask.sum(dim=-1)
- normed = _norm_and_concat_padded_batch(
- encoded_text_features,
- sequence_lengths,
- padding_side=padding_side,
- )
- return feature_extractor_linear(normed.to(encoded_text_features_dtype))
+) -> tuple[torch.Tensor, torch.Tensor | None]:
+ return feature_extractor_linear(hidden_states, attention_mask, padding_side=padding_side)
def _apply_connectors(
- encoded_input: torch.Tensor,
+ encoded_video_input: torch.Tensor,
+ encoded_audio_input: torch.Tensor | None,
attention_mask: torch.Tensor,
embeddings_connector: Embeddings1DConnector,
audio_embeddings_connector: Embeddings1DConnector,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- connector_attention_mask = (attention_mask - 1).to(encoded_input.dtype).reshape(
+ connector_attention_mask = (attention_mask - 1).to(encoded_video_input.dtype).reshape(
(attention_mask.shape[0], 1, -1, attention_mask.shape[-1])
- ) * torch.finfo(encoded_input.dtype).max
+ ) * torch.finfo(encoded_video_input.dtype).max
encoded, encoded_connector_attention_mask = embeddings_connector(
- encoded_input,
+ encoded_video_input,
connector_attention_mask,
)
attention_mask_out = (encoded_connector_attention_mask < 0.000001).to(torch.int64)
attention_mask_out = attention_mask_out.reshape([encoded.shape[0], encoded.shape[1], 1])
encoded = encoded * attention_mask_out
- encoded_for_audio, _ = audio_embeddings_connector(encoded_input, connector_attention_mask)
+ encoded_for_audio, _ = audio_embeddings_connector(
+ encoded_video_input if encoded_audio_input is None else encoded_audio_input,
+ connector_attention_mask,
+ )
return encoded, encoded_for_audio, attention_mask_out.squeeze(-1)
def _norm_and_concat_padded_batch(
@@ -415,17 +404,18 @@ def postprocess_text_embeddings(
projected = []
for item in embeddings:
attention_mask = item.attention_mask.to("cuda")
- encoded_input = _apply_feature_extractor(
+ encoded_video_input, encoded_audio_input = _apply_feature_extractor(
item.hidden_states,
attention_mask,
item.padding_side,
feature_extractor_linear,
)
- projected.append((encoded_input, attention_mask))
+ projected.append((encoded_video_input, encoded_audio_input, attention_mask))
results = []
- for encoded_input, attention_mask in projected:
+ for encoded_video_input, encoded_audio_input, attention_mask in projected:
video_ctx, audio_ctx, _ = _apply_connectors(
- encoded_input,
+ encoded_video_input,
+ encoded_audio_input,
attention_mask,
embeddings_connector,
audio_embeddings_connector,
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/feature_extractor.py b/models/ltx2/ltx_core/text_encoders/gemma/feature_extractor.py
index 9bf8fec..6ca1561 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/feature_extractor.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/feature_extractor.py
@@ -1,36 +1,120 @@
+import math
+
import torch
+from einops import rearrange
from ...model.model_protocol import ModelConfigurator
+def _norm_and_concat_padded_batch(
+ encoded_text: torch.Tensor,
+ sequence_lengths: torch.Tensor,
+ padding_side: str = "right",
+) -> torch.Tensor:
+ b, t, d, l = encoded_text.shape
+ token_indices = torch.arange(t, device=encoded_text.device)[None, :]
+ if padding_side == "right":
+ mask = token_indices < sequence_lengths[:, None]
+ elif padding_side == "left":
+ start_indices = t - sequence_lengths[:, None]
+ mask = token_indices >= start_indices
+ else:
+ raise ValueError(f"padding_side must be 'left' or 'right', got {padding_side}")
+
+ mask = rearrange(mask, "b t -> b t 1 1")
+ eps = 1e-6
+ masked = encoded_text.masked_fill(~mask, 0.0)
+ denom = (sequence_lengths * d).view(b, 1, 1, 1)
+ mean = masked.sum(dim=(1, 2), keepdim=True) / (denom + eps)
+ x_min = encoded_text.masked_fill(~mask, float("inf")).amin(dim=(1, 2), keepdim=True)
+ x_max = encoded_text.masked_fill(~mask, float("-inf")).amax(dim=(1, 2), keepdim=True)
+ range_ = x_max - x_min
+ normed = 8 * (encoded_text - mean) / (range_ + eps)
+ normed = normed.reshape(b, t, -1)
+ mask_flattened = rearrange(mask, "b t 1 1 -> b t 1").expand(-1, -1, d * l)
+ return normed.masked_fill(~mask_flattened, 0.0)
+
+
+def _norm_and_concat_per_token_rms(encoded_text: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ b, t, d, l = encoded_text.shape
+ variance = torch.mean(encoded_text**2, dim=2, keepdim=True)
+ normed = encoded_text * torch.rsqrt(variance + 1e-6)
+ normed = normed.reshape(b, t, d * l)
+ mask_3d = attention_mask.bool().unsqueeze(-1)
+ return torch.where(mask_3d, normed, torch.zeros_like(normed))
+
+
+def _rescale_norm(x: torch.Tensor, target_dim: int, source_dim: int) -> torch.Tensor:
+ return x * math.sqrt(target_dim / source_dim)
+
+
class GemmaFeaturesExtractorProjLinear(torch.nn.Module, ModelConfigurator["GemmaFeaturesExtractorProjLinear"]):
- """
- Feature extractor module for Gemma models.
- This module applies a single linear projection to the input tensor.
- It expects a flattened feature tensor of shape (batch_size, 3840*49).
- The linear layer maps this to a (batch_size, 3840) embedding.
- Attributes:
- aggregate_embed (torch.nn.Linear): Linear projection layer.
- """
-
- def __init__(self) -> None:
- """
- Initialize the GemmaFeaturesExtractorProjLinear module.
- The input dimension is expected to be 3840 * 49, and the output is 3840.
- """
+ """Supports both 19B (single projection) and 22B/2.3 (dual projections)."""
+
+ def __init__(
+ self,
+ aggregate_embed: torch.nn.Linear | None = None,
+ video_aggregate_embed: torch.nn.Linear | None = None,
+ audio_aggregate_embed: torch.nn.Linear | None = None,
+ embedding_dim: int = 3840,
+ ) -> None:
super().__init__()
- self.aggregate_embed = torch.nn.Linear(3840 * 49, 3840, bias=False)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for the feature extractor.
- Args:
- x (torch.Tensor): Input tensor of shape (batch_size, 3840 * 49).
- Returns:
- torch.Tensor: Output tensor of shape (batch_size, 3840).
- """
- return self.aggregate_embed(x)
+ self.aggregate_embed = aggregate_embed
+ self.video_aggregate_embed = video_aggregate_embed
+ self.audio_aggregate_embed = audio_aggregate_embed
+ self.embedding_dim = embedding_dim
+
+ @property
+ def is_v2(self) -> bool:
+ return self.video_aggregate_embed is not None
+
+ def forward(
+ self,
+ hidden_states: tuple[torch.Tensor, ...] | torch.Tensor,
+ attention_mask: torch.Tensor,
+ padding_side: str = "left",
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ encoded = torch.stack(hidden_states, dim=-1) if isinstance(hidden_states, (list, tuple)) else hidden_states
+ if self.is_v2:
+ normed = _norm_and_concat_per_token_rms(encoded, attention_mask).to(encoded.dtype)
+ v_dim = self.video_aggregate_embed.out_features
+ video = self.video_aggregate_embed(_rescale_norm(normed, v_dim, self.embedding_dim))
+ audio = None
+ if self.audio_aggregate_embed is not None:
+ a_dim = self.audio_aggregate_embed.out_features
+ audio = self.audio_aggregate_embed(_rescale_norm(normed, a_dim, self.embedding_dim))
+ return video, audio
+
+ if self.aggregate_embed is None:
+ raise ValueError("Feature extractor is missing aggregate projection weights.")
+ sequence_lengths = attention_mask.sum(dim=-1)
+ normed = _norm_and_concat_padded_batch(encoded, sequence_lengths, padding_side=padding_side)
+ features = self.aggregate_embed(normed.to(encoded.dtype))
+ return features, features
@classmethod
- def from_config(cls: type["GemmaFeaturesExtractorProjLinear"], _config: dict) -> "GemmaFeaturesExtractorProjLinear":
- return cls()
+ def from_config(cls: type["GemmaFeaturesExtractorProjLinear"], config: dict) -> "GemmaFeaturesExtractorProjLinear":
+ transformer_config = config.get("transformer", {})
+ embedding_dim = 3840
+ num_layers_plus_embed = 49
+ flat_dim = embedding_dim * num_layers_plus_embed
+ if transformer_config.get("caption_proj_before_connector", False):
+ video_inner_dim = transformer_config.get("num_attention_heads", 32) * transformer_config.get(
+ "attention_head_dim", 128
+ )
+ audio_inner_dim = transformer_config.get("audio_num_attention_heads", 32) * transformer_config.get(
+ "audio_attention_head_dim", 64
+ )
+ return cls(
+ aggregate_embed=None,
+ video_aggregate_embed=torch.nn.Linear(flat_dim, video_inner_dim, bias=True),
+ audio_aggregate_embed=torch.nn.Linear(flat_dim, audio_inner_dim, bias=True),
+ embedding_dim=embedding_dim,
+ )
+
+ return cls(
+ aggregate_embed=torch.nn.Linear(flat_dim, embedding_dim, bias=False),
+ video_aggregate_embed=None,
+ audio_aggregate_embed=None,
+ embedding_dim=embedding_dim,
+ )
diff --git a/models/ltx2/ltx_pipelines/utils/helpers.py b/models/ltx2/ltx_pipelines/utils/helpers.py
index 9b84d19..8c62fd8 100644
--- a/models/ltx2/ltx_pipelines/utils/helpers.py
+++ b/models/ltx2/ltx_pipelines/utils/helpers.py
@@ -795,13 +795,23 @@ def modality_from_latent_state(
from the denoise mask and sigma, positions, and the provided context.
"""
timesteps, frame_indices = timesteps_from_mask(state.denoise_mask, sigma, positions=state.positions)
+ sigma_tensor = sigma if torch.is_tensor(sigma) else torch.tensor(sigma, device=state.latent.device)
+ sigma_tensor = sigma_tensor.to(device=state.latent.device, dtype=state.latent.dtype)
+ if sigma_tensor.ndim == 0:
+ sigma_tensor = sigma_tensor.expand(state.latent.shape[0])
+ elif sigma_tensor.ndim == 1 and sigma_tensor.shape[0] == 1:
+ sigma_tensor = sigma_tensor.expand(state.latent.shape[0])
+ elif sigma_tensor.ndim > 1:
+ sigma_tensor = sigma_tensor.reshape(state.latent.shape[0], -1)[:, 0]
return Modality(
enabled=enabled,
latent=state.latent,
+ sigma=sigma_tensor,
timesteps=timesteps,
positions=state.positions,
context=context,
context_mask=None,
+ attention_mask=None,
frame_indices=frame_indices,
)
diff --git a/models/wan/configs/kiwi_edit_reference_only.json b/models/wan/configs/kiwi_edit_reference_only.json
index 3e901f0..adb10ed 100644
--- a/models/wan/configs/kiwi_edit_reference_only.json
+++ b/models/wan/configs/kiwi_edit_reference_only.json
@@ -11,6 +11,6 @@
"num_layers": 30,
"out_dim": 48,
"text_len": 512,
- "any_kiwi_source": false,
+ "any_kiwi_source": true,
"any_kiwi_ref": true
}
diff --git a/models/wan/kiwi/variant_config.py b/models/wan/kiwi/variant_config.py
index fdb54a9..1b93335 100644
--- a/models/wan/kiwi/variant_config.py
+++ b/models/wan/kiwi/variant_config.py
@@ -26,7 +26,7 @@ KIWI_VARIANT_MAP = {
"kiwi_mllm_repo_id": KIWI_REPO_ID,
"kiwi_mllm_folder": "kiwi_mllm_encoder_reference_only",
"kiwi_text_encoder_file": "reference_only_mllm_encoder_bf16.safetensors",
- "kiwi_source_embedder_file": None,
+ "kiwi_source_embedder_file": "wan2.2_kiwi_edit_5B_reference_only_source_embedder.safetensors",
"kiwi_ref_embedder_file": "wan2.2_kiwi_edit_5B_reference_only_ref_embedder.safetensors",
"config_file": "models/wan/configs/kiwi_edit_reference_only.json",
},
diff --git a/shared/RGB_factors.py b/shared/RGB_factors.py
index ec1cf16..38966dd 100644
--- a/shared/RGB_factors.py
+++ b/shared/RGB_factors.py
@@ -141,6 +141,140 @@ def get_rgb_factors(model_family, model_type = None, sub_family = None):
latent_rgb_factors_bias = [-0.0329, -0.0718, -0.0851]
elif model_family == "ltx2":
+ # computed by your very own Deep Beep Meep
+ if model_type == "ltx2_22B":
+ ltx2_22b_rgb_factors = [
+ [-0.002637, -0.022435, -0.014525],
+ [-0.000040, 0.002258, -0.002773],
+ [0.017013, 0.019457, 0.019020],
+ [0.003543, -0.003552, -0.007818],
+ [-0.009536, -0.003874, 0.004383],
+ [0.004008, -0.006709, -0.004319],
+ [-0.036751, -0.043466, -0.048329],
+ [-0.096575, -0.064235, -0.062143],
+ [0.011298, 0.014851, 0.011954],
+ [-0.010023, -0.009218, -0.020513],
+ [-0.008272, -0.008638, -0.006964],
+ [-0.020323, -0.015916, -0.013125],
+ [-0.000465, -0.000317, -0.008137],
+ [-0.016116, -0.018386, -0.020579],
+ [-0.006978, -0.000909, 0.007134],
+ [0.016408, 0.007682, 0.002734],
+ [-0.005839, -0.000587, 0.012418],
+ [-0.004253, 0.000283, 0.000204],
+ [0.011091, 0.012431, 0.020362],
+ [-0.010974, -0.013548, -0.007926],
+ [0.008863, -0.002148, -0.014016],
+ [-0.001360, 0.001420, 0.000509],
+ [-0.011228, -0.010231, 0.003795],
+ [-0.003145, -0.012330, -0.000278],
+ [-0.004863, 0.006857, 0.019429],
+ [-0.001873, -0.009766, -0.000230],
+ [-0.012370, -0.005718, -0.009533],
+ [-0.012286, -0.001246, 0.006019],
+ [0.004865, -0.002002, -0.004165],
+ [-0.004346, -0.005383, -0.004504],
+ [-0.002492, 0.004697, 0.002858],
+ [-0.002394, 0.000685, 0.005236],
+ [0.007604, 0.007468, 0.009615],
+ [-0.000106, -0.003317, -0.000438],
+ [0.024229, 0.025679, 0.025601],
+ [0.008970, 0.005995, 0.006451],
+ [0.000735, 0.001644, 0.001438],
+ [-0.000723, -0.003181, -0.005735],
+ [-0.007293, -0.006387, -0.004542],
+ [0.006823, 0.004482, 0.005263],
+ [-0.003291, 0.002319, 0.000601],
+ [-0.019049, -0.022004, -0.015870],
+ [-0.005866, -0.006257, -0.004923],
+ [-0.008179, -0.005068, -0.012506],
+ [0.016921, 0.010924, 0.008665],
+ [0.016727, 0.006363, 0.019086],
+ [0.007689, 0.009421, 0.006278],
+ [0.000311, 0.004294, 0.002340],
+ [-0.008876, -0.010579, -0.007904],
+ [-0.004933, -0.004116, -0.003897],
+ [-0.007960, -0.007913, -0.005858],
+ [0.033702, 0.029980, 0.023054],
+ [0.003681, 0.000736, 0.001179],
+ [0.011194, 0.009676, 0.008584],
+ [-0.006748, -0.008025, -0.012712],
+ [0.003629, 0.008801, 0.024646],
+ [-0.005553, -0.003534, 0.000868],
+ [0.018373, 0.026107, 0.048515],
+ [-0.018188, -0.016738, -0.011824],
+ [-0.005569, -0.002895, -0.000267],
+ [0.024878, 0.022724, 0.020622],
+ [-0.003171, -0.003368, -0.007122],
+ [0.016151, 0.019179, 0.016925],
+ [-0.020461, -0.016825, 0.005923],
+ [-0.010058, 0.008644, 0.006714],
+ [-0.030223, -0.028451, -0.028098],
+ [-0.012519, -0.010286, -0.010658],
+ [-0.002638, -0.002010, 0.005868],
+ [0.009401, 0.010221, 0.013040],
+ [-0.004573, -0.005399, -0.002189],
+ [0.005468, 0.008426, 0.007985],
+ [0.004175, 0.001259, 0.002328],
+ [-0.008226, 0.031092, 0.034302],
+ [-0.002707, 0.000329, -0.000929],
+ [-0.017879, -0.011023, -0.008185],
+ [-0.154098, -0.149095, -0.114443],
+ [-0.011193, -0.010340, -0.010992],
+ [0.008415, 0.009909, 0.006711],
+ [0.010234, 0.006162, -0.000474],
+ [-0.003913, -0.004917, 0.004581],
+ [0.009658, -0.004839, -0.002031],
+ [0.000503, -0.001236, -0.002399],
+ [0.045968, 0.025765, 0.022633],
+ [-0.015219, -0.026419, -0.025316],
+ [-0.008027, -0.001555, 0.004266],
+ [0.002060, -0.000470, -0.000015],
+ [0.017509, 0.020194, 0.006590],
+ [0.030655, 0.015133, -0.001706],
+ [0.005769, 0.002032, -0.001164],
+ [-0.011608, -0.002177, -0.000190],
+ [-0.006229, -0.005444, -0.003577],
+ [0.000107, 0.005813, -0.001181],
+ [-0.014333, -0.017095, 0.004329],
+ [0.020339, 0.016295, 0.015720],
+ [0.019904, 0.013839, 0.007771],
+ [0.008964, 0.009021, 0.008781],
+ [-0.004733, 0.014352, 0.008170],
+ [-0.082997, -0.146227, -0.177141],
+ [-0.004424, 0.004261, -0.002953],
+ [0.002149, 0.005867, 0.009992],
+ [0.009515, 0.016390, 0.019565],
+ [0.002039, -0.008968, -0.009913],
+ [-0.007031, -0.003982, 0.000093],
+ [0.068442, 0.075373, 0.051207],
+ [0.011794, 0.007765, -0.000760],
+ [0.001684, -0.003199, 0.009644],
+ [-0.003405, -0.004217, -0.006650],
+ [-0.015646, -0.006160, -0.000201],
+ [-0.060917, -0.058964, -0.050211],
+ [-0.001947, -0.003689, 0.002990],
+ [0.018446, 0.000534, -0.040772],
+ [-0.001858, 0.008965, 0.015008],
+ [-0.045379, -0.037718, -0.035154],
+ [-0.000329, 0.007689, 0.000036],
+ [-0.016536, -0.021012, -0.004650],
+ [0.018388, 0.023352, 0.016103],
+ [-0.086596, -0.074310, -0.078423],
+ [0.009143, 0.008548, 0.004895],
+ [0.002656, 0.002964, -0.000803],
+ [-0.008501, -0.008217, -0.001661],
+ [0.006445, -0.003139, -0.008694],
+ [0.023101, 0.035471, 0.040335],
+ [0.005615, 0.007732, 0.007626],
+ [-0.017656, -0.014044, -0.009303],
+ [-0.004839, -0.003358, -0.000664],
+ [-0.007193, -0.005399, -0.008577],
+ [-0.031276, -0.034591, -0.036400],
+ [-0.008987, -0.015887, -0.013977]
+ ]
+ ltx2_22b_rgb_factors_bias = [-0.219173, -0.292845, -0.314850]
+ return ltx2_22b_rgb_factors, ltx2_22b_rgb_factors_bias
# LTX2_RGB_FACTORS_START
latent_rgb_factors = [
[0.034942, 0.025665, 0.019890],
@@ -276,140 +410,141 @@ def get_rgb_factors(model_family, model_type = None, sub_family = None):
# LTX2_RGB_FACTORS_END
elif model_family == "ltxv":
+ # computed by your very own Deep Beep Meep
latent_channels = 128
latent_dimensions = 3
latent_rgb_factors = [
- [ 1.1202e-02, -6.3815e-04, -1.0021e-02],
- [ 8.6031e-02, 6.5813e-02, 9.5409e-04],
- [-1.2576e-02, -7.5734e-03, -4.0528e-03],
- [ 9.4063e-03, -2.1688e-03, 2.6093e-03],
- [ 3.7636e-03, 1.2765e-02, 9.1548e-03],
- [ 2.1024e-02, -5.2973e-03, 3.4373e-03],
- [-8.8896e-03, -1.9703e-02, -1.8761e-02],
- [-1.3160e-02, -1.0523e-02, 1.9709e-03],
- [-1.5152e-03, -6.9891e-03, -7.5810e-03],
- [-1.7247e-03, 4.6560e-04, -3.3839e-03],
- [ 1.3617e-02, 4.7077e-03, -2.0045e-03],
- [ 1.0256e-02, 7.7318e-03, 1.3948e-02],
- [-1.6108e-02, -6.2151e-03, 1.1561e-03],
- [ 7.3407e-03, 1.5628e-02, 4.4865e-04],
- [ 9.5357e-04, -2.9518e-03, -1.4760e-02],
- [ 1.9143e-02, 1.0868e-02, 1.2264e-02],
- [ 4.4575e-03, 3.6682e-05, -6.8508e-03],
- [-4.5681e-04, 3.2570e-03, 7.7929e-03],
- [ 3.3902e-02, 3.3405e-02, 3.7454e-02],
- [-2.3001e-02, -2.4877e-03, -3.1033e-03],
- [ 5.0265e-02, 3.8841e-02, 3.3539e-02],
- [-4.1018e-03, -1.1095e-03, 1.5859e-03],
- [-1.2689e-01, -1.3107e-01, -2.1005e-01],
- [ 2.6276e-02, 1.4189e-02, -3.5963e-03],
- [-4.8679e-03, 8.8486e-03, 7.8029e-03],
- [-1.6610e-03, -4.8597e-03, -5.2060e-03],
- [-2.1010e-03, 2.3610e-03, 9.3796e-03],
- [-2.2482e-02, -2.1305e-02, -1.5087e-02],
- [-1.5753e-02, -1.0646e-02, -6.5083e-03],
- [-4.6975e-03, 5.0288e-03, -6.7390e-03],
- [ 1.1951e-02, 2.0712e-02, 1.6191e-02],
- [-6.3704e-03, -8.4827e-03, -9.5483e-03],
- [ 7.2610e-03, -9.9326e-03, -2.2978e-02],
- [-9.1904e-04, 6.2882e-03, 9.5720e-03],
- [-3.7178e-02, -3.7123e-02, -5.6713e-02],
- [-1.3373e-01, -1.0720e-01, -5.3801e-02],
- [-5.3702e-03, 8.1256e-03, 8.8397e-03],
- [-1.5247e-01, -2.1437e-01, -2.1843e-01],
- [ 3.1441e-02, 7.0335e-03, -9.7541e-03],
- [ 2.1528e-03, -8.9817e-03, -2.1023e-02],
- [ 3.8461e-03, -5.8957e-03, -1.5014e-02],
- [-4.3470e-03, -1.2940e-02, -1.5972e-02],
- [-5.4781e-03, -1.0842e-02, -3.0204e-03],
- [-6.5347e-03, 3.0806e-03, -1.0163e-02],
- [-5.0414e-03, -7.1503e-03, -8.9686e-04],
- [-8.5851e-03, -2.4351e-03, 1.0674e-03],
- [-9.0016e-03, -9.6493e-03, 1.5692e-03],
- [ 5.0914e-03, 1.2099e-02, 1.9968e-02],
- [ 1.3758e-02, 1.1669e-02, 8.1958e-03],
- [-1.0518e-02, -1.1575e-02, -4.1307e-03],
- [-2.8410e-02, -3.1266e-02, -2.2149e-02],
- [ 2.9336e-03, 3.6511e-02, 1.8717e-02],
- [-1.6703e-02, -1.6696e-02, -4.4529e-03],
- [ 4.8818e-02, 4.0063e-02, 8.7410e-03],
- [-1.5066e-02, -5.7328e-04, 2.9785e-03],
- [-1.7613e-02, -8.1034e-03, 1.3086e-02],
- [-9.2633e-03, 1.0803e-02, -6.3489e-03],
- [ 3.0851e-03, 4.7750e-04, 1.2347e-02],
- [-2.2785e-02, -2.3043e-02, -2.6005e-02],
- [-2.4787e-02, -1.5389e-02, -2.2104e-02],
- [-2.3572e-02, 1.0544e-03, 1.2361e-02],
- [-7.8915e-03, -1.2271e-03, -6.0968e-03],
- [-1.1478e-02, -1.2543e-03, 6.2679e-03],
- [-5.4229e-02, 2.6644e-02, 6.3394e-03],
- [ 4.4216e-03, -7.3338e-03, -1.0464e-02],
- [-4.5013e-03, 1.6082e-03, 1.4420e-02],
- [ 1.3673e-02, 8.8877e-03, 4.1253e-03],
- [-1.0145e-02, 9.0072e-03, 1.5695e-02],
- [-5.6234e-03, 1.1847e-03, 8.1261e-03],
- [-3.7171e-03, -5.3538e-03, 1.2590e-03],
- [ 2.9476e-02, 2.1424e-02, 3.0424e-02],
- [-3.4925e-02, -2.4340e-02, -2.5316e-02],
- [-3.4127e-02, -2.2406e-02, -1.0589e-02],
- [-1.7342e-02, -1.3249e-02, -1.0719e-02],
- [-2.1478e-03, -8.6051e-03, -2.9878e-03],
- [ 1.2089e-03, -4.2391e-03, -6.8569e-03],
- [ 9.0411e-04, -6.6886e-03, -6.7547e-05],
- [ 1.6048e-02, -1.0057e-02, -2.8929e-02],
- [ 1.2290e-03, 1.0163e-02, 1.8861e-02],
- [ 1.7264e-02, 2.7257e-04, 1.3785e-02],
- [-1.3482e-02, -3.6427e-03, 6.7481e-04],
- [ 4.6782e-03, -5.2423e-03, 2.4467e-03],
- [-5.9113e-03, -6.2244e-03, -1.8162e-03],
- [ 1.5496e-02, 1.4582e-02, 1.9514e-03],
- [ 7.4958e-03, 1.5886e-03, -8.2305e-03],
- [ 1.9086e-02, 1.6360e-03, -3.9674e-03],
- [-5.7021e-03, -2.7307e-03, -4.1066e-03],
- [ 1.7450e-03, 1.4602e-02, 2.5794e-02],
- [-8.2788e-04, 2.2902e-03, 4.5161e-03],
- [ 1.1632e-02, 8.9193e-03, -7.2813e-03],
- [ 7.5721e-03, 2.6784e-03, 1.1393e-02],
- [ 5.1939e-03, 3.6903e-03, 1.4049e-02],
- [-1.8383e-02, -2.2529e-02, -2.4477e-02],
- [ 5.8842e-04, -5.7874e-03, -1.4770e-02],
- [-1.6125e-02, -8.6101e-03, -1.4533e-02],
- [ 2.0540e-02, 2.0729e-02, 6.4338e-03],
- [ 3.3587e-03, -1.1226e-02, -1.6444e-02],
- [-1.4742e-03, -1.0489e-02, 1.7097e-03],
- [ 2.8130e-02, 2.3546e-02, 3.2791e-02],
- [-1.8532e-02, -1.2842e-02, -8.7756e-03],
- [-8.0533e-03, -1.0771e-02, -1.7536e-02],
- [-3.9009e-03, 1.6150e-02, 3.3359e-02],
- [-7.4554e-03, -1.4154e-02, -6.1910e-03],
- [ 3.4734e-03, -1.1370e-02, -1.0581e-02],
- [ 1.1476e-02, 3.9281e-03, 2.8231e-03],
- [ 7.1639e-03, -1.4741e-03, -3.8066e-03],
- [ 2.2250e-03, -8.7552e-03, -9.5719e-03],
- [ 2.4146e-02, 2.1696e-02, 2.8056e-02],
- [-5.4365e-03, -2.4291e-02, -1.7802e-02],
- [ 7.4263e-03, 1.0510e-02, 1.2705e-02],
- [ 6.2669e-03, 6.2658e-03, 1.9211e-02],
- [ 1.6378e-02, 9.4933e-03, 6.6971e-03],
- [ 1.7173e-02, 2.3601e-02, 2.3296e-02],
- [-1.4568e-02, -9.8279e-03, -1.1556e-02],
- [ 1.4431e-02, 1.4430e-02, 6.6362e-03],
- [-6.8230e-03, 1.8863e-02, 1.4555e-02],
- [ 6.1156e-03, 3.4700e-03, -2.6662e-03],
- [-2.6983e-03, -5.9402e-03, -9.2276e-03],
- [ 1.0235e-02, 7.4173e-03, -7.6243e-03],
- [-1.3255e-02, 1.9322e-02, -9.2153e-04],
- [ 2.4222e-03, -4.8039e-03, -1.5759e-02],
- [ 2.6244e-02, 2.5951e-02, 2.0249e-02],
- [ 1.5711e-02, 1.8498e-02, 2.7407e-03],
- [-2.1714e-03, 4.7214e-03, -2.2443e-02],
- [-7.4747e-03, 7.4166e-03, 1.4430e-02],
- [-8.3906e-03, -7.9776e-03, 9.7927e-03],
- [ 3.8321e-02, 9.6622e-03, -1.9268e-02],
- [-1.4605e-02, -6.7032e-03, 3.9675e-03]
+ [0.035582, 0.025241, 0.019059],
+ [-0.011088, -0.004560, -0.005371],
+ [0.007245, -0.014716, -0.001559],
+ [0.020083, 0.002775, -0.002997],
+ [0.008828, 0.023831, 0.011037],
+ [0.008272, 0.012256, 0.003322],
+ [-0.015408, -0.019657, -0.013805],
+ [-0.012167, -0.010744, -0.040915],
+ [-0.000306, 0.002370, 0.005182],
+ [0.014412, 0.007726, -0.001534],
+ [-0.008717, -0.006287, 0.000956],
+ [-0.006908, -0.004871, 0.001747],
+ [0.013476, 0.019110, 0.016148],
+ [0.006494, -0.002371, -0.006191],
+ [0.034034, 0.018516, 0.023265],
+ [-0.001736, 0.003750, 0.013429],
+ [-0.001662, -0.011720, -0.010040],
+ [-0.013817, -0.002600, -0.006292],
+ [0.034908, 0.034661, 0.041437],
+ [-0.003544, -0.027082, -0.021179],
+ [0.014436, 0.008519, 0.014859],
+ [0.000617, -0.001874, -0.004648],
+ [-0.034923, -0.020644, -0.003953],
+ [-0.003528, -0.001817, 0.000409],
+ [0.007435, 0.016008, 0.024745],
+ [0.008246, -0.015555, -0.030704],
+ [-0.029761, -0.025874, -0.016636],
+ [-0.001359, -0.006993, -0.002812],
+ [0.006954, 0.006185, 0.006284],
+ [-0.004145, 0.002543, 0.000443],
+ [0.026397, 0.011885, 0.011944],
+ [0.011959, 0.006476, 0.004567],
+ [0.011958, 0.003278, 0.005483],
+ [0.000880, 0.006825, -0.000239],
+ [0.003066, 0.002158, 0.001152],
+ [-0.000697, -0.000912, 0.003622],
+ [0.015179, 0.019700, 0.021853],
+ [-0.015571, -0.030838, -0.036792],
+ [0.000705, -0.005045, -0.000780],
+ [0.000676, 0.001296, -0.003527],
+ [-0.005033, 0.002671, -0.001989],
+ [0.014950, 0.013809, 0.011505],
+ [0.004975, 0.004733, 0.017948],
+ [-0.000495, -0.009110, -0.037703],
+ [-0.054368, -0.052336, -0.044666],
+ [-0.003123, -0.015530, -0.011048],
+ [-0.006658, -0.000507, 0.001055],
+ [0.066555, 0.083396, 0.061881],
+ [-0.023717, -0.018802, -0.022264],
+ [-0.001998, -0.006345, -0.004872],
+ [-0.005142, -0.007320, -0.019123],
+ [0.008872, 0.007865, 0.004287],
+ [0.002672, -0.002818, -0.002681],
+ [0.011259, -0.006732, -0.001830],
+ [0.003965, 0.002713, 0.013869],
+ [0.035881, 0.021339, 0.019710],
+ [-0.020165, -0.015751, 0.000726],
+ [-0.016233, -0.004130, -0.008461],
+ [-0.019038, -0.019087, -0.016846],
+ [0.010145, 0.011604, 0.018285],
+ [-0.009972, -0.009455, -0.010444],
+ [0.007420, 0.001248, 0.010543],
+ [-0.017763, -0.024588, -0.018310],
+ [-0.005316, -0.003467, -0.001688],
+ [0.075308, 0.060410, 0.042607],
+ [0.016281, 0.018724, 0.015634],
+ [0.003319, 0.002911, -0.012188],
+ [0.002586, -0.000781, 0.002897],
+ [0.019921, 0.031291, 0.023804],
+ [0.000507, 0.000265, 0.006217],
+ [0.015093, 0.009080, 0.012170],
+ [-0.027553, -0.002317, 0.008801],
+ [0.019748, -0.006231, -0.010628],
+ [-0.000992, 0.014483, 0.006747],
+ [-0.005176, -0.006966, -0.006231],
+ [0.009369, 0.009001, 0.006080],
+ [-0.019502, -0.010986, -0.016263],
+ [0.009622, 0.011231, -0.003507],
+ [0.011710, 0.007743, 0.007796],
+ [0.001709, 0.003981, 0.012354],
+ [0.013475, 0.012501, 0.013031],
+ [0.000135, 0.005721, 0.011183],
+ [-0.017884, -0.031334, -0.028284],
+ [-0.015754, -0.007742, -0.011511],
+ [0.030132, 0.022401, 0.024860],
+ [-0.007276, -0.012084, -0.009154],
+ [0.019716, 0.018651, 0.006074],
+ [-0.006242, -0.005683, -0.005029],
+ [0.019383, 0.016312, 0.017580],
+ [-0.010341, -0.004952, 0.002420],
+ [0.011134, 0.009569, 0.008515],
+ [0.019734, -0.012654, -0.028811],
+ [-0.099568, -0.099130, -0.092332],
+ [-0.008051, -0.004986, -0.003922],
+ [-0.014421, -0.004248, -0.015386],
+ [0.015564, -0.004664, 0.006721],
+ [-0.006878, -0.010097, -0.009609],
+ [0.006329, 0.012266, 0.013791],
+ [-0.004897, -0.006628, -0.011967],
+ [-0.006143, -0.009694, -0.002289],
+ [0.012134, 0.022289, 0.017772],
+ [0.022571, 0.017612, 0.010859],
+ [-0.021120, -0.001161, -0.012361],
+ [-0.005513, 0.005725, 0.002040],
+ [0.009246, 0.004407, 0.005687],
+ [0.008619, 0.006166, 0.007369],
+ [-0.001817, 0.000493, 0.005933],
+ [-0.009593, -0.011080, -0.008062],
+ [0.045089, 0.058717, 0.064705],
+ [0.007387, 0.010615, 0.004683],
+ [-0.014032, -0.009903, -0.011561],
+ [-0.017529, 0.012640, 0.041473],
+ [0.007375, -0.007793, 0.001781],
+ [-0.042459, -0.038817, -0.034248],
+ [0.009118, 0.012473, 0.011103],
+ [-0.024234, -0.019062, -0.029192],
+ [-0.003629, -0.011813, -0.005117],
+ [-0.001368, -0.000385, 0.000487],
+ [-0.001570, -0.000605, -0.012106],
+ [-0.023129, -0.023683, -0.020173],
+ [-0.002227, -0.000535, -0.003988],
+ [0.001467, 0.001789, 0.001113],
+ [-0.010948, -0.000490, -0.003436],
+ [-0.018422, -0.001083, 0.008414],
+ [-0.001576, -0.009604, -0.008839],
+ [-0.000041, -0.001356, -0.001524],
+ [-0.004037, -0.006747, -0.034852],
+ [-0.014760, -0.015261, -0.015292]
]
- latent_rgb_factors_bias = [-0.0571, -0.1657, -0.2512]
+ latent_rgb_factors_bias = [-0.063785, -0.133025, -0.195400]
elif model_family == "hunyuan":
if sub_family == "hunyuan1.5":
diff --git a/wgp.py b/wgp.py
index e400f3b..2bcf627 100644
--- a/wgp.py
+++ b/wgp.py
@@ -95,7 +95,7 @@ AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.7.6"
-WanGP_version = "10.952"
+WanGP_version = "10.98"
settings_version = 2.52
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None