Official Python inference and LoRA trainer package for the LTX-2 audio–video generative model.
Automated PR - 2026-08-25
github-actions[bot]a95ab856bf29
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 652b3fa..55eb929 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,48 @@# Changelog+## 1.3.0 - 2026-08-25++### Added++- DFR can finish 4K in a tiled spatial epilogue instead of denoising the full canvas in stage 2. `--spatial-upscalings 2` keeps stage 2 at half resolution and upscales in that epilogue, which is the path for better-quality 4K (use `3840x2176`; `3840x2160` is not on the size grid). Default `--spatial-upscalings 1` is unchanged.+- Added `ltx_pipelines.dfr_mgpu`, a multi-GPU DFR runner with the same flags as `ltx_pipelines.dfr_pipeline`.+- Added keyframe-aware diffusion-VAE decoding, which sharpens detail at the frames a generator anchored on. Pass keyframe latents into `VideoDecoder.decode_video(..., keyframes=)`. Needs a keyframe-trained video VAE; older checkpoints decode as before.+- `--compile max_video_tokens=N max_audio_tokens=N` (and the matching `CompilationConfig` fields) cap CUDA-graph input memory when `capture=true`, so several captured shapes share one buffer sized for the largest instead of paying for each separately.+- `DiffusionStage.with_model_wrapper()` runs a callable on each built transformer before denoising, and still composes with block streaming and quantization.+- `VideoDecoder.decode_single_frames()` decodes independent one-frame latents without neighbouring frames bleeding into each other.+- `DecodeKeyframes.for_frame_span()` and `.crop_spatial()` crop keyframe planes to a decode window, keeping the nearest anchors outside the window so a tiled decode matches a whole one.+- `DiffusionStage.__call__` accepts optional `audio_fps=` when audio should be sized from a different frame rate than the video RoPE time base.++### Changed++- `DFRPipeline` and `ltx_pipelines.dfr_mgpu` take a distilled checkpoint (`--distilled-checkpoint-path`) instead of a full checkpoint plus a distilled LoRA. Detailing IC-LoRA and optional user LoRAs are unchanged.+- DFR temporal rounds use `--temporal-upscalings` instead of `--temporal-upsample-rounds`.+- DFR snaps transformer conditioning fps to 60 whenever playback fps is above 30 (previously only values above 60 were capped), so 48 and 50 fps stay in the trained range. Playback fps is unchanged.+- `--diffvae-optimization combined_compile` no longer requires the `natten` extra. Without it the mode falls back to Triton, or to PyTorch when Triton is unavailable.+- Automatic decode tiling sizes tiles for keyframe-aware decoding as well as plain decoding, so a keyframe decode is less likely to run out of memory on a clip a plain decode fits.+- Video pipelines now return a named `PipelineOutput` instead of a 3- or 4-tuple. Extra fields are `keyframes` and `video_latent`. Existing unpacking must switch to `result.video`, `result.audio`, and so on.+- `VideoDecoder.decode_video()` takes `keyframes=` on every implementation. The diffusion decoder uses them; conv logs a warning and decodes without them; distributed splits them across ranks. Callers that never pass keyframes are unaffected; decoder implementations must accept the keyword.+- NVFP4 quantization and CuTe DSL DiffVAE kernels (`blackwell_dsl`) now support Jetson Thor. Build NVFP4 with the arch-specific `110a` target.++### Removed++- `DiffusionVideoDecoder.decode_video_with_keyframes`; use `decode_video(..., keyframes=)`.+- `DFROutput`; use `PipelineOutput`.+- `--checkpoint-path` and `--distilled-lora` on `ltx_pipelines.dfr_pipeline` and `ltx_pipelines.dfr_mgpu`; pass `--distilled-checkpoint-path` instead.+- `--num-generated-keyframes` on DFR; slot positions come from DFR's segment grid.+- `--temporal-upsample-rounds` on DFR; use `--temporal-upscalings`.++### Fixed++- Automatic decode tiling no longer OOMs in colour conversion on clips that looked like they had spare VRAM. The budget now reserves encoder memory for each chunk, so long videos decode in temporal pieces instead of as one oversize frame dump.+- A pipelines-only install (`ltx-core` / `ltx-pipelines`, no trainer) no longer fails to load Gemma 4 for missing torchvision.+- `uv sync` on macOS no longer fails looking for CUDA-only torch wheels. Macs use PyPI (MPS on Apple Silicon); Linux and Windows still use the CUDA 13.2 indexes.+- `--quantization fp8-cast` with a LoRA no longer crashes on pre-Ada GPUs such as RTX 3060 or A100.+- Blockwise FP8/FP6 quantization no longer fails on very long sequences or token counts that are not a multiple of 4.+- Multi-GPU DFR no longer crashes at tiling resolve, during carry-keyframe decode, or by dropping context at a temporal tile boundary.+- DFR image-to-video stills land on the correct frame after temporal upsampling (opening-frame `frame_idx=0` was already correct).+- `AUTO_TILING` is recognised after it crosses a process boundary, so multi-GPU pipelines resolve automatic tiling instead of rejecting the sentinel.+## 1.2.0 - 2026-08-11Support for LTX 2.5@@ -50,6 +93,7 @@ Support for LTX 2.5- Fixed diffusion-VAE tiled decoding and multi-GPU blending to use checkpoint-specific geometry with lower peak host memory.- Fixed 8-bit Gemma loading to resolve standard tokenizer assets and use architecture-agnostic Hugging Face model loading.- Fixed CUDA builds using mismatched system toolkits or cuDNN sublibraries.+- Fixed diffusion-VAE decode tiling on Apple Silicon. The decode memory budget was probed only on CUDA, so on other backends it reported zero bytes available and no decode tile could ever fit, at any resolution. Automatic tiling now sizes itself from the Metal working set on MPS.### Removeddiff --git a/LICENSE b/LICENSEindex aa1e32a..d88acd7 100644--- a/LICENSE+++ b/LICENSE@@ -1,580 +1,7 @@- LTX-2.x Community License Agreement- License date: August 11, 2026+LTX Community License Agreements+LTX-2.x Community License Agreement [https://github.com/Lightricks/LTX-2/blob/main/LICENSE-2_x] Dated August 11, 2026.+This license is applicable to all LTX-2.5 versions released since August 11, 2026, and all future releases of LTX-2.x under this license.- By downloading, using, accessing or distributing any portion or- element of LTX-2.x, you agree that you have read and accepted to be- bound by this Agreement.-- 1. Definitions-- 1.1 "Agreement" means the terms and conditions for this LTX-2.x- Community License Agreement and the exhibits, attachments, and- Complementary Materials, as specified in this document.-- 1.2 "Complementary Materials" means the accompanying- documentation, tutorials, examples, configuration files and- other materials made available by Licensor together with the- LTX-2.x model weights and parameters, in each case as- distributed by Licensor.-- 1.3 "Control" means the direct or indirect ownership of more than- fifty percent (50%) of the voting securities or other- ownership interests, or the power to direct the management and- policies of such Entity through voting rights, contract, or- otherwise.-- 1.4 "Data" means a collection of information and/or content- extracted from the dataset used with LTX-2.x, including to- train, pretrain, or otherwise evaluate LTX-2.x. The Data is- not licensed under this Agreement.-- 1.5 "Derivatives of LTX-2.x" means all modifications to LTX-2.x,- works based on LTX-2.x, or any other model which is created or- initialized by transfer of patterns of the weights,- parameters, activations or output of LTX-2.x, to the other- model, in order to cause the other model to perform similarly- to LTX-2.x, including - but not limited to - distillation- methods entailing the use of intermediate data representations- or methods based on the generation of synthetic data by- LTX-2.x for training the other model. For clarity, Derivatives- of LTX-2.x include: (i) any fine-tuned or adapted weights,- parameters, or checkpoints derived from LTX-2.x; (ii)- derivative model architectures that incorporate or are based- upon LTX-2.x's architecture; and (iii) any modified or- extended versions of the Complementary Materials.-- 1.6 "Entity" means any individual, corporation, partnership,- limited liability company, or other legal entity. For purposes- of this Agreement, an Entity shall be deemed to include, on an- aggregative basis, all subsidiaries, affiliates, and other- companies under common Control with such Entity. When- determining whether an Entity meets any threshold under this- Agreement (including revenue thresholds in Section 2.1), all- subsidiaries, affiliates, and companies under common Control- shall be considered collectively.-- 1.7 "Harm" includes but is not limited to physical, mental,- psychological, financial and reputational damage, pain, or- loss.-- 1.8 "Licensor" or "LTX" means the owner that is granting the- license under this Agreement. For the purposes of this- Agreement, the Licensor is Lightricks Ltd.-- 1.9 "LTX-2.x" means the large generative models,- text/image/video/audio/3D generation models, and multimodal- large language models and their software and algorithms,- including trained model weights, parameters (including- optimizer states), machine-learning model code,- inference-enabling code, training-enabling code, fine-tuning- enabling code, accompanying source code, scripts, and all- other elements of the foregoing distributed and made publicly- available by LTX (including, for example, at- https://github.com/Lightricks/LTX-2). This license is- applicable to all LTX-2.5 versions released since August 11,- 2026, and all future releases of LTX-2.x under this license.-- 1.10 "Output" means the results of operating LTX-2.x as embodied- in informational content resulting therefrom.-- 1.11 "you" (or "your") means an individual or legal Entity- licensing LTX-2.x in accordance with this Agreement and/or- otherwise downloading, accessing, distributing or using- LTX-2.x for whichever purpose and in any field of use,- including usage of LTX-2.x in an end-use application - e.g.- chatbot, translator, image generator.-- 2. Grant of License.-- 2.1 Subject to your compliance with the terms and conditions of- this Agreement, you are granted a non-exclusive, worldwide,- non-transferable and royalty-free limited license under- Licensor's intellectual property or other rights owned by- Licensor embodied in LTX-2.x to use, reproduce, prepare,- distribute, publicly display, publicly perform, sublicense,- copy, create derivative works of, and make modifications to- LTX-2.x, for any purpose, subject to the restrictions set- forth in Attachment A; provided however, that Entities with- annual revenues of at least $10,000,000 (the "Commercial- Entities") are required to obtain a paid license for any use- (excluding use solely for a Non-Commercial Purpose as set- forth in Section 2.2) of LTX-2.x and Derivatives of LTX-2.x- (such paid license referred to herein as a "Commercial Use- Agreement"), as will be provided by the Licensor. Commercial- Entities interested in such a commercial license are required- to contact Licensor ([email protected]). Any use- of LTX-2.x or Derivatives of LTX-2.x by Commercial Entities- not in accordance with this Agreement and/or the Commercial- Use Agreement is strictly prohibited and shall be deemed a- material breach of this Agreement. In the event of such- material breach, and without limiting Licensor's right to- terminate the Agreement or to pursue any other remedies- available at law or in equity, you shall pay Licensor the- license fees owed for the period such Commercial Entity used- LTX-2.x (calculated at Licensor's standard commercial license- fees, in effect during the relevant period or, absent- published standard fees, a reasonable market rate for a- comparable license), within thirty (30) days of Licensor's- written demand.-- 2.2 Notwithstanding the foregoing or anything to the contrary in- this Agreement, a Commercial Entity may download and use- LTX-2.x and Derivatives of LTX-2.x without obtaining the- Commercial Use Agreement solely for a Non-Commercial Purpose.- "Non-Commercial Purpose" means any of the following uses, but- only so far as such Commercial Entity does not receive any- direct or indirect payment arising from the use of LTX-2.x or- Derivatives of LTX-2.x: (i) use by an individual acting in a- personal capacity for research, experimentation, learning,- private study, hobby or recreational projects, or personal- entertainment, in each case where such use is not connected,- directly or indirectly, to any commercial activity, business- operation, or the performance of duties for an employer or any- other Entity; and (ii) use by a Commercial Entity for testing,- evaluation, or non-commercial research and development in a- non-production or development environment. For clarity, use- (a) for revenue-generating activity in any manner, whether- direct or indirect, (b) in direct interactions with or that- has impact on end users, or (c) to train, fine-tune, or- distill any model (including any Derivative of LTX-2.x) for- commercial use, in each case, is not a Non-Commercial Purpose- and requires all Commercial Entities to obtain a paid license- under the Commercial Use Agreement prior to such use. For the- avoidance of doubt, the permission granted under this Section- 2.2 is a limited right of use only and does not convey or- transfer any ownership right, title, or interest in or to- LTX-2.x or any Derivatives of LTX-2.x, and all Derivatives of- LTX-2.x created or used pursuant to this Section 2.2 remain- subject to the terms of this Agreement, including Section 1.5.-- 3. Distribution and Redistribution. You may host for third parties- remote access purposes (e.g. software-as-a-service), reproduce and- distribute copies of LTX-2.x or Derivatives of LTX-2.x thereof in- any medium, with or without modifications, provided that you meet- the following conditions:-- 3.1 Use-based restrictions as referenced in Section 4 and all- provisions of Attachment A MUST be included as an enforceable- provision by you in any type of legal agreement (e.g. a- license) governing the use and/or distribution of LTX-2.x or- Derivatives of LTX-2.x, and you shall give notice to- subsequent users you distribute to, that LTX-2.x or- Derivatives of LTX-2.x are subject to Section 4 and Attachment- A in their entirety, including all use restrictions and- acceptable use policies;-- 3.2 You must provide any third-party recipients of LTX-2.x or- Derivatives of LTX-2.x a copy of this Agreement, including all- attachments and use policies. Any Derivative of LTX-2.x (as- defined in Section 1.5, including but not limited to- fine-tuned weights, modified training code, models trained on- Outputs, or any other derivative) must be distributed- exclusively under the terms of this Agreement, subject to- Section 3.6, with a complete copy of this Agreement included;-- 3.3 You must cause any modified files to carry prominent notices- stating that you changed the files;-- 3.4 You must retain all copyright, patent, trademark, and- attribution notices excluding those notices that do not- pertain to any part of LTX-2.x, Derivatives of LTX-2.x.-- 3.5 Transfer of Derivatives. No transfer of any Derivative of- LTX-2.x (including any fine-tuned weights, LoRA adapters, or- similar adaptations) to a third party shall grant such third- party any right, title, license, or authorization to access,- use, reproduce, distribute, or exploit LTX-2.x, or any- Derivative of LTX-2.x beyond the rights granted under this- Agreement. If the transferee is a Commercial Entity (as- defined in Section 2), it must obtain a paid license from- Licensor prior to any use of any Derivative of LTX-2.x,- regardless of who created such Derivative. Prior to or at the- time of any such transfer, you shall notify the transferee in- writing that (i) use of such Derivative of LTX-2.x is subject- to the terms of this Agreement, and (ii) if the transferee is- a Commercial Entity, it must obtain a separate paid license to- LTX-2.x from Licensor. You shall not transfer any Derivative- of LTX-2.x to a Commercial Entity unless such Commercial- Entity has obtained the required paid license from Licensor- prior to any use, and unless the proposed transferee has been- so informed. You and the transferee shall each be responsible- for ensuring the transferee obtains the required license from- Licensor prior to any use of LTX-2.x or Derivative of LTX-2.x.- Nothing in this Section 3.5 shall require a Commercial Entity- to obtain a paid license for use solely for a Non-Commercial- Purpose as permitted under Section 2.2.-- 3.6 You may add your own copyright statement to your modifications- and may provide additional license terms and conditions -- respecting Section 3.1 - for use, reproduction, or- distribution of your modifications, or for any such- Derivatives of LTX-2.x as a whole, provided your use,- reproduction, and distribution of LTX-2.x otherwise complies- with the conditions stated in this Agreement, and you provide- a complete copy of this Agreement with any such use,- reproduction and distribution of LTX-2.x and any Derivatives- thereof; provided that any such additional terms shall be- additive only and shall not derogate from, conflict with,- waive, or purport to modify any term of this Agreement, and- this Agreement shall govern in the event of any conflict.-- 4. Use-based restrictions. The restrictions set forth in Attachment A- are considered Use-based restrictions. Therefore, you cannot use- LTX-2.x and the Derivatives of LTX-2.x in violation of the- specified restricted uses. You may use LTX-2.x subject to this- Agreement, only for lawful purposes and in accordance with the- Agreement. "Use" may include creating any content with,- fine-tuning, updating, running, training, evaluating and/or- re-parametrizing LTX-2.x. You shall require all of your users who- use LTX-2.x or a Derivative of LTX-2.x to comply with the terms of- this Section 4.-- 5. The Output You Generate. Except as set forth herein, Licensor- claims no rights in the Output you generate using LTX-2.x. You are- accountable for input you insert into LTX-2.x, the Output you- generate and its subsequent uses. No use of the Output can- contravene any provision as stated in the Agreement.-- 6. Updates and Runtime Restrictions; AI Regulations. To the maximum- extent permitted by law, Licensor reserves the right to restrict- (remotely or otherwise) usage of LTX-2.x in violation of this- Agreement, update LTX-2.x through electronic means, or modify the- Output of LTX-2.x based on updates. You shall undertake reasonable- efforts to use the latest version of LTX-2.x. Any use of the- non-current version of LTX-2.x is done solely at your risk. To the- extent applicable to you, you shall comply with all laws and- regulations governing artificial intelligence that apply to your- use, deployment, or distribution of LTX-2.x, Derivatives of- LTX-2.x, or Outputs, including Regulation (EU) 2024/1689 (the "EU- AI Act") and the California AI Transparency Act (Cal. Bus. & Prof.- Code § 22757 et seq.), each as amended from time to time and any- other applicable laws, regulations, or binding guidance relating- to artificial intelligence, transparency, content provenance, or- synthetic media, together with any documentation made available by- Licensor regarding compliance with the same (collectively, "AI- Regulations"). You shall maintain (including within any- application or service through which LTX-2.x, any Derivative of- LTX-2.x, or any Output is made available), and shall not remove,- disable, alter, or circumvent, any safety or security measures,- disclosures, metadata, watermarking, content provenance, latent- disclosure, or other transparency features or functionalities- included or embedded within LTX-2.x or any Derivative of LTX-2.x,- or applied to any Output, in furtherance of AI Regulations,- including any capability of LTX-2.x to include latent disclosures- in Outputs, and you shall include equivalent obligations in any- agreement governing your distribution of LTX-2.x or any Derivative- of LTX-2.x. You are solely responsible for any transparency,- disclosure, marking, or labeling obligations applicable to you- under AI Regulations as a provider or deployer of LTX-2.x, any- Derivative of LTX-2.x, or any system incorporating any of the- foregoing, including any obligation to disclose that content is- artificially generated or manipulated. If Licensor knows or- reasonably believes that you have modified LTX-2.x or any- Derivative of LTX-2.x such that it is no longer capable of- including any disclosure required by AI Regulations in Outputs, or- that you have otherwise removed, disabled, or circumvented any- feature or functionality described in this Section, Licensor may- in its sole discretion revoke the license granted under this- Agreement effective immediately upon notice to you, and upon such- revocation you shall immediately cease all use of LTX-2.x and- Derivatives of LTX-2.x. Licensor makes no representation or- warranty that LTX-2.x, any Derivative of LTX-2.x, or any Output- complies with any AI Regulations applicable to your specific use- case or deployment, and you are solely responsible for determining- the applicability of, and ensuring your compliance with, all AI- Regulations. You shall indemnify, defend, and hold harmless- Licensor and its affiliates from and against any and all claims,- liabilities, losses, damages, costs, and expenses (including- reasonable attorneys' fees) arising out of or relating to your- use, deployment, distribution, or modification of LTX-2.x, any- Derivative of LTX-2.x, or any Output in violation of, or your- other failure to comply with, any AI Regulations.-- For purposes of the EU AI Act, Licensor makes LTX-2.x openly- available under this community license and intends that LTX-2.x be- treated as a free and open-source general purpose AI model within- the meaning of Article 53(2) of the EU AI Act. You acknowledge and- agree that (a) to the extent the free and open source derogations- under Article 53(2) of the EU AI Act apply, Licensor's obligations- under the EU AI Act with respect to LTX-2.x are limited to those- applicable to providers of free and open source general purpose AI- models (it being acknowledged that such derogations do not extend- to the obligations under Article 53(1)(c) and (d)), (b) you- acknowledge that LTX-2.x is not intended to be integrated into a- high risk AI system, and shall be fully and solely responsible for- any obligation resulting from such integration, (c) if you- integrate LTX-2.x or any Derivative of LTX-2.x into a high-risk AI- system you shall be solely responsible for all provider- obligations that would otherwise apply to Licensor under the EU AI- Act, and (d) you shall not take any action, or omit to take any- action, that would cause Licensor to lose the benefit of the free- and open source derogations under the EU AI Act, and you shall- indemnify and hold Licensor harmless from any liability, costs, or- expenses arising from your breach of this Section.-- 7. Export Controls and Sanctions Compliance. You acknowledge that- LTX-2.x, Derivatives of LTX-2.x may be subject to export control- laws and regulations, including but not limited to the U.S. Export- Administration Regulations and sanctions programs administered by- the Office of Foreign Assets Control (OFAC). You represent and- warrant that you and any users of LTX-2.x are not (i) located in,- organized under the laws of, or ordinarily resident in any country- or territory subject to comprehensive sanctions; (ii) identified- on any U.S. government restricted party list, including the- Specially Designated Nationals and Blocked Persons List; or (iii)- otherwise prohibited from receiving LTX-2.x under applicable law.- You shall not export, re-export, or transfer LTX-2.x, directly or- indirectly, in violation of any applicable export control or- sanctions laws or regulations. You agree to comply with all- applicable trade control laws and shall indemnify and hold- Licensor harmless from any claims arising from your failure to- comply with such laws.-- 8. Trademarks; Reservation of Rights. Nothing in this Agreement- permits you to make use of Licensor's trademarks, trade names,- logos or to otherwise suggest endorsement or misrepresent the- relationship between the parties; and any rights not expressly- granted herein are reserved by the Licensor. Except as expressly- set forth in this Agreement, Licensor does not grant, directly or- by implication, estoppel, statute or otherwise, any right or- license in its, or its affiliates', intellectual property rights- or other proprietary rights. For avoidance of doubt, all- intellectual property rights in Derivatives of LTX-2.x shall be- subject to the terms of this Agreement, and you acquire no right,- title, or interest in or to LTX-2.x itself, which is and remains- the exclusive property of Licensor. You shall not assert any- ownership or other right in LTX-2.x or any Derivative of LTX-2.x- in any manner that restricts, encumbers, or is inconsistent with- the rights retained by Licensor or granted to other licensees- under this Agreement.-- 9. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides LTX-2.x on an "AS IS"- BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either- express or implied, including, without limitation, any warranties- or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or- FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for- determining the appropriateness of using or redistributing LTX-2.x- and Derivatives of LTX-2.x and assume any risks associated with- your exercise of permissions under this Agreement.-- 10. Limitation of Liability. To the fullest extent permitted by- applicable law, in no event and under no legal theory, whether in- tort (including negligence), contract, or otherwise, unless- required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall Licensor be liable- to you or any other individual or Entity for damages, including- any direct, indirect, special, incidental, or consequential- damages of any character arising as a result of this Agreement or- out of the use of, or inability to use LTX-2.x or any Derivative- of LTX-2.x (including but not limited to damages for loss of- goodwill, work stoppage, computer failure or malfunction, or any- and all other commercial damages or losses), even if Licensor has- been advised of the possibility of such damages.-- 11. Accepting Warranty or Additional Liability. While redistributing- LTX-2.x and Derivatives of LTX-2.x, you may, provided you do not- violate the terms of this Agreement, choose to offer and charge a- fee for, acceptance of support, warranty, indemnity, or other- liability obligations. However, in accepting such obligations,- you may act only on your own behalf and on your sole- responsibility, not on behalf of Licensor, and only if you agree- to indemnify, defend, and hold Licensor harmless for any- liability incurred by, or claims asserted against Licensor, by- reason of your accepting any such warranty or additional- liability.-- 12. Governing Law. This Agreement and all relations, disputes, claims- and other matters arising hereunder (including non-contractual- disputes or claims) will be governed exclusively by, and- construed exclusively in accordance with, the laws of the State- of New York and applicable U.S. federal law. To the extent- permitted by law, choice of laws rules and the United Nations- Convention on Contracts for the International Sale of Goods will- not apply. The prevailing party in any claim or dispute between- the parties under this Agreement will be entitled to- reimbursement of its reasonable attorneys' fees and costs.-- 13. Term and Termination. This Agreement is effective upon your- acceptance and continues until terminated. Licensor may terminate- this Agreement immediately upon written notice to you if you- breach any provision of this Agreement, including but not limited- to violations of the use restrictions in Attachment A or- unauthorized commercial use. This Agreement also terminates- immediately and automatically, without notice, upon any material- breach of this Agreement, including any use in violation of- applicable AI Regulations or any unauthorized commercial use of- LTX-2.x or Derivatives of LTX-2.x by a Commercial Entity. Upon- termination: (a) all rights granted to you under this Agreement- will immediately cease; (b) you must immediately cease all use of- LTX-2.x and Derivatives of LTX-2.x; (c) you must delete or- destroy all copies of LTX-2.x and Derivatives of LTX-2.x in your- possession or control; and (d) you must notify any third parties- to whom you distributed LTX-2.x or Derivatives of LTX-2.x of the- termination. Sections 2, 3, 4, 6-16 and Attachment A shall- survive termination of this Agreement. Termination does not- relieve you of any obligations incurred prior to termination,- including payment obligations under Section 2 and adhering to the- restrictions under Section 3. In addition, if You commence a- lawsuit or other proceedings (including a cross-claim or- counterclaim in a lawsuit) against Licensor or any person or- entity alleging that LTX-2.x or any Output, or any portion of any- of the foregoing, infringe any intellectual property or other- right owned or licensable by you, then all licenses granted to- you under this Agreement shall terminate as of the date such- lawsuit or other proceeding is filed.-- 14. Disputes and Arbitration; Waiver of Jury Trial; Class Action- Waiver. IF YOU ARE NOT ACTING AS A CONSUMER UNDER APPLICABLE LAW,- YOU HEREBY WAIVE THE RIGHT TO A TRIAL BY JURY, TO PARTICIPATE IN- A CLASS OR REPRESENTATIVE ACTION (INCLUDING IN ARBITRATION), OR- TO COMBINE INDIVIDUAL PROCEEDINGS IN COURT OR IN ARBITRATION- WITHOUT THE CONSENT OF ALL PARTIES. All disputes arising in- connection with this Agreement shall be finally settled by- arbitration under the Rules of Arbitration of the International- Chamber of Commerce ("ICC Rules"), by one (1) arbitrator- appointed in accordance with the ICC Rules. The seat of- arbitration shall be New York, NY, USA, and the proceedings shall- be conducted in English. The arbitrator shall be empowered to- grant any relief that a court could grant. Judgment on the- arbitration award may be entered by any court having jurisdiction- thereof. Notwithstanding the foregoing, either party may seek- injunctive or other equitable relief in respect of any actual or- threatened breach of the license restrictions under this- Agreement (including Attachment A and the Acceptable Use Policy)- or any actual or threatened infringement, misappropriation, or- violation of Licensor's intellectual property rights, in the- state or federal courts located in the County of New York, State- of New York, and each party irrevocably consents to the- jurisdiction of, and venue in, such courts for that limited- purpose. The foregoing waivers do not apply to, and are not- enforceable against, any licensee acting as a consumer under the- mandatory consumer-protection laws of its jurisdiction of- residence (including, without limitation, the European Union, the- United Kingdom, and the State of California), and nothing in this- Agreement limits any rights under such laws that cannot be waived- or limited by contract. If any waiver in this Section is held- invalid or unenforceable as to a particular licensee or dispute,- such waiver shall be severed to that extent only and shall not- affect the validity or enforceability of the remainder of this- Section.-- 15. In the event of any exception to the application of binding- arbitration, all disputes, claims, and other matters arising- hereunder shall be brought exclusively in the state or federal- courts located in the County of New York, State of New York. You- waive all defenses of lack of personal jurisdiction and forum non- conveniens with respect to venue and jurisdiction in such courts,- and consent to their exclusive jurisdiction and venue.-- 16. Severability. If any provision of this Agreement is held to be- invalid, illegal or unenforceable, the remaining provisions shall- be unaffected thereby and remain valid as if such provision had- not been set forth herein.-- END OF TERMS AND CONDITIONS-- Attachment A- Use Restrictions-- When using the Outputs, LTX-2.x and any Derivatives thereof, you- agree to comply with the Acceptable Use Policy- (https://static.lightricks.com/legal/ltx-acceptable-use-policy.pdf)- which is hereby incorporated into and made part of this Agreement by- reference. Licensor may update it from time to time, and the version- in effect at the time of your use governs; continued use after an- update constitutes acceptance. Licensor shall post each version of- the Acceptable Use Policy with its effective date, and no update- shall apply retroactively to use occurring before that effective- date. In addition, you agree not to use the Outputs, LTX-2.x or its- Derivatives in any of the following ways:-- 1) In any way that violates any applicable national, federal,- state, local or international law or regulation;-- 2) For the purpose of exploiting, Harming or attempting to exploit- or Harm minors in any way;-- 3) Knowingly generate or disseminate verifiably false information- and/or content with the intent to deceive, defraud, or- otherwise unlawfully Harm others;-- 4) To generate or disseminate personal identifiable information- that can be used to Harm an individual;-- 5) To generate or disseminate information and/or content (e.g.- images, code, posts, articles), and place the information- and/or content in any context (e.g. bot generating tweets)- without expressly and intelligibly disclaiming that the- information and/or content is machine generated;-- 6) To defame others, or to engage in the unlawful harassment of- others;-- 7) To impersonate or attempt to impersonate (e.g. deepfakes)- others without their consent;-- 8) For fully automated decision making that adversely impacts an- individual's legal rights or otherwise creates or modifies a- binding, enforceable obligation;-- 9) For any use intended to or which has the effect of- discriminating against or Harming individuals or groups based- on online or offline social behavior or known or predicted- personal or personality characteristics;-- 10) To exploit any of the vulnerabilities of a specific group of- persons based on their age, social, physical or mental- characteristics, in order to materially distort the behavior- of a person pertaining to that group in a manner that causes- or is likely to cause that person or another person physical- or psychological Harm;-- 11) For any use intended to or which has the effect of- discriminating against individuals or groups based on legally- protected characteristics or categories;-- 12) To provide medical advice and medical results interpretation;-- 13) To generate or disseminate information for the purpose to be- used for administration of justice, law enforcement,- immigration or asylum processes, such as predicting an- individual will commit fraud/crime commitment (e.g. by text- profiling, drawing causal relationships between assertions- made in documents, indiscriminate and arbitrarily-targeted- use);-- 14) To generate and/or disseminate malware (including - but not- limited to - ransomware) or any other content to be used for- the purpose of harming electronic systems;-- 15) To engage in, promote, incite, or facilitate discrimination or- other unlawful or harmful conduct in the provision of- employment, employment benefits, credit, housing, or other- essential goods and services;-- 16) To engage in, promote, incite, or facilitate the harassment,- abuse, threatening, or bullying of individuals or groups of- individuals;-- 17) For military, warfare, nuclear industries or applications,- weapons development, or any use in connection with activities- that may cause death, personal injury, or severe physical or- environmental damage;-- 18) For commercial use only: To train, improve, or fine-tune any- other machine learning model, artificial intelligence system,- or competing model, except for Derivatives of LTX-2.x as- expressly permitted under this Agreement;-- 19) To circumvent, disable, or interfere with any technical- limitations, safety features, content filters, watermarking,- content provenance or latent disclosure functionalities, or- use restrictions implemented in LTX-2.x by Licensor;-- 20) To use LTX-2.x or Derivatives of LTX-2.x in any product,- service, or application that directly competes with Licensor's- commercial products or services, or is designed to replace or- substitute Licensor's offerings in the market, without- obtaining a separate commercial license from Licensor.+LTX-2 Community License Agreement [https://github.com/Lightricks/LTX-2/blob/main/LICENSE-2] Dated January 5, 2026.+This license is applicable to all LTX-2 versions released since January 5, 2026, including LTX-2.3 until August 11, 2026.diff --git a/LICENSE-2 b/LICENSE-2new file mode 100644index 0000000..283c394--- /dev/null+++ b/LICENSE-2@@ -0,0 +1,381 @@+LTX-2 Community License Agreement+License date: January 5, 2026+++By using or distributing any portion or element of LTX-2, you agree+to be bound by this Agreement.++1. Definitions.++"Agreement" means the terms and conditions for the license, use,+reproduction, and distribution of LTX-2 and the Complementary+Materials, as specified in this document.++"Control" means the direct or indirect ownership of more than+fifty percent (50%) of the voting securities or other ownership+interests, or the power to direct the management and policies of+such Entity through voting rights, contract, or otherwise.++"Data" means a collection of information and/or content extracted+from the dataset used with LTX-2, including to train, pretrain,+or otherwise evaluate LTX-2. The Data is not licensed under this+Agreement.++"Derivatives of LTX-2" means all modifications to LTX-2, works+based on LTX-2, or any other model which is created or initialized+by transfer of patterns of the weights, parameters, activations or+output of LTX-2, to the other model, in order to cause the other+model to perform similarly to LTX-2, including – but not limited+to - distillation methods entailing the use of intermediate data+representations or methods based on the generation of synthetic+data by LTX-2 for training the other model. For clarity, Derivatives+of LTX-2 include: (i) any fine-tuned or adapted weights, parameters,+or checkpoints derived from LTX-2; (ii) derivative model architectures+that incorporate or are based upon LTX-2's architecture; and+(iii) any modified or extended versions of the Complementary+Materials. All intellectual property rights in Derivatives of LTX-2+shall be subject to the terms of this Agreement, and you may not+claim exclusive ownership rights in any Derivatives of LTX-2 that+would restrict the rights granted herein.++"Entity" means any individual, corporation, partnership, limited+liability company, or other legal entity. For purposes of this+Agreement, an Entity shall be deemed to include, on an aggregative+basis, all subsidiaries, affiliates, and other companies under+common Control with such Entity. When determining whether an Entity+meets any threshold under this Agreement (including revenue+thresholds), all subsidiaries, affiliates, and companies under+common Control shall be considered collectively.++"Harm" includes but is not limited to physical, mental,+psychological, financial and reputational damage, pain, or loss.++"Licensor" or "Lightricks" means the owner that is granting the+license under this Agreement. For the purposes of this Agreement,+the Licensor is Lightricks Ltd.++"LTX-2" means the large language models, text/image/video/audio/3D+generation models, and multimodal large language models and their+software and algorithms, including trained model weights, parameters+(including optimizer states), machine-learning model code,+inference-enabling code, training-enabling code, fine-tuning+enabling code, accompanying source code, scripts, documentation,+tutorials, examples, and all other elements of the foregoing+distributed and made publicly available by Lightricks (including,+for example, at https://github.com/Lightricks/LTX-2) for the LTX-2+model released on January 5, 2026. This license is applicable to+all LTX-2 versions released since January 5, 2026, and all future+releases of LTX-2 under this license.++"Output" means the results of operating LTX-2 as embodied in+informational content resulting therefrom.++"you" (or "your") means an individual or legal Entity licensing+LTX-2 in accordance with this Agreement and/or making use of LTX-2+for whichever purpose and in any field of use, including usage of+LTX-2 in an end-use application - e.g. chatbot, translator, image+generator.++2. Grant of License. Subject to the terms and conditions of this+Agreement, you are granted a non-exclusive, worldwide,+non-transferable and royalty-free limited license under Licensor's+intellectual property or other rights owned by Licensor embodied+in LTX-2 to use, reproduce, prepare, distribute, publicly display,+publicly perform, sublicense, copy, create derivative works of,+and make modifications to LTX-2, for any purpose, subject to the+restrictions set forth in Attachment A; provided however, that+Entities with annual revenues of at least $10,000,000 (the+"Commercial Entities") are required to obtain a paid commercial+use license in order to use LTX-2 and Derivatives of LTX-2,+subject to the terms and provisions of a different license (the+"Commercial Use Agreement"), as will be provided by the Licensor.+Commercial Entities interested in such a commercial license are+required to contact Licensor. Any commercial use of LTX-2 or+Derivatives of LTX-2 by the Commercial Entities not in accordance+with this Agreement and/or the Commercial Use Agreement is strictly+prohibited and shall be deemed a material breach of this Agreement.+Such material breach will be subject, in addition to any license+fees owed to Licensor for the period such Commercial Entity used+LTX-2 (as will be determined by Licensor), to liquidated damages,+which will be paid to Licensor immediately upon demand, in an+amount equal to double the amount that would otherwise have been+paid by you for the relevant period of time. Such amount reflects+a reasonable estimation of the losses and administrative costs+incurred due to such breach. You agree and understand that this+remedy does not limit the Licensor's right to pursue other remedies+available at law or equity.++3. Distribution and Redistribution. You may host for third parties+remote access purposes (e.g. software-as-a-service), reproduce+and distribute copies of LTX-2 or Derivatives of LTX-2 thereof in+any medium, with or without modifications, provided that you meet+the following conditions:++(a) Use-based restrictions as referenced in paragraph 4 and all+provisions of Attachment A MUST be included as an enforceable+provision by you in any type of legal agreement (e.g. a+license) governing the use and/or distribution of LTX-2 or+Derivatives of LTX-2, and you shall give notice to subsequent+users you distribute to, that LTX-2 or Derivatives of LTX-2+are subject to paragraph 4 and Attachment A in their entirety,+including all use restrictions and acceptable use policies;++(b) You must provide any third party recipients of LTX-2 or+Derivatives of LTX-2 a copy of this Agreement, including all+attachments and use policies. Any Derivative of LTX-2 (as+defined in Section 1.5, including but not limited to fine-tuned+weights, modified training code, models trained on Outputs, or+any other derivative) must be distributed exclusively under+the terms of this Agreement with a complete copy of this+license included;++(c) You must cause any modified files to carry prominent notices+stating that you changed the files;++(d) You must retain all copyright, patent, trademark, and+attribution notices excluding those notices that do not+pertain to any part of LTX-2, Derivatives of LTX-2.++You may add your own copyright statement to your modifications and+may provide additional or different license terms and conditions -+respecting paragraph 3.1 - for use, reproduction, or distribution+of your modifications, or for any such Derivatives of LTX-2 as a+whole, provided your use, reproduction, and distribution of LTX-2+otherwise complies with the conditions stated in this Agreement,+and you provide a complete copy of this Agreement with any such+use, reproduction and distribution of LTX-2 and any Derivatives+thereof.++4. Use-based restrictions. The restrictions set forth in Attachment A+are considered Use-based restrictions. Therefore, you cannot use+LTX-2 and the Derivatives of LTX-2 in violation of the specified+restricted uses. You may use LTX-2 subject to this Agreement,+including only for lawful purposes and in accordance with the+Agreement. "Use" may include creating any content with, fine-tuning,+updating, running, training, evaluating and/or re-parametrizing+LTX-2. You shall require all of your users who use LTX-2 or a+Derivative of LTX-2 to comply with the terms of this paragraph 4.++5. The Output You Generate. Except as set forth herein, Licensor+claims no rights in the Output you generate using LTX-2. You are+accountable for input you insert into LTX-2, the Output you+generate and its subsequent uses. No use of the Output can+contravene any provision as stated in the Agreement.++6. Updates and Runtime Restrictions. To the maximum extent permitted+by law, Licensor reserves the right to restrict (remotely or+otherwise) usage of LTX-2 in violation of this Agreement, update+LTX-2 through electronic means, or modify the Output of LTX-2+based on updates. You shall undertake reasonable efforts to use+the latest version of LTX-2. Any use of the non-current version+of LTX-2 is done solely at your risk.++7. Export Controls and Sanctions Compliance. You acknowledge that+LTX-2, Derivatives of LTX-2 may be subject to export control laws+and regulations, including but not limited to the U.S. Export+Administration Regulations and sanctions programs administered by+the Office of Foreign Assets Control (OFAC). You represent and+warrant that you and any users of LTX-2 are not (i) located in,+organized under the laws of, or ordinarily resident in any country+or territory subject to comprehensive sanctions; (ii) identified+on any U.S. government restricted party list, including the+Specially Designated Nationals and Blocked Persons List; or+(iii) otherwise prohibited from receiving LTX-2 under applicable+law. You shall not export, re-export, or transfer LTX-2, directly+or indirectly, in violation of any applicable export control or+sanctions laws or regulations. You agree to comply with all+applicable trade control laws and shall indemnify and hold+Licensor harmless from any claims arising from your failure to+comply with such laws.++8. Trademarks and related. Nothing in this Agreement permits you to+make use of Licensor's trademarks, trade names, logos or to+otherwise suggest endorsement or misrepresent the relationship+between the parties; and any rights not expressly granted herein+are reserved by the Licensor.++9. Disclaimer of Warranty. Unless required by applicable law or+agreed to in writing, Licensor provides LTX-2 on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+implied, including, without limitation, any warranties or+conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS+FOR A PARTICULAR PURPOSE. You are solely responsible for+determining the appropriateness of using or redistributing LTX-2+and Derivatives of LTX-2 and assume any risks associated with+your exercise of permissions under this Agreement.++10. Limitation of Liability. In no event and under no legal theory,+whether in tort (including negligence), contract, or otherwise,+unless required by applicable law (such as deliberate and grossly+negligent acts) or agreed to in writing, shall Licensor be liable+to you for damages, including any direct, indirect, special,+incidental, or consequential damages of any character arising as+a result of this Agreement or out of the use or inability to use+LTX-2 (including but not limited to damages for loss of goodwill,+work stoppage, computer failure or malfunction, or any and all+other commercial damages or losses), even if Licensor has been+advised of the possibility of such damages.++11. Accepting Warranty or Additional Liability. While redistributing+LTX-2 and Derivatives of LTX-2, you may, provided you do not+violate the terms of this Agreement, choose to offer and charge+a fee for, acceptance of support, warranty, indemnity, or other+liability obligations. However, in accepting such obligations,+you may act only on your own behalf and on your sole+responsibility, not on behalf of Licensor, and only if you agree+to indemnify, defend, and hold Licensor harmless for any liability+incurred by, or claims asserted against Licensor, by reason of+your accepting any such warranty or additional liability.++12. Governing Law. This Agreement and all relations, disputes, claims+and other matters arising hereunder (including non-contractual+disputes or claims) will be governed exclusively by, and construed+exclusively in accordance with, the laws of the State of New York.+To the extent permitted by law, choice of laws rules and the+United Nations Convention on Contracts for the International Sale+of Goods will not apply. For the purposes of adjudicating any+action or proceeding to enforce the terms of this Agreement, you+hereby irrevocably consent to the exclusive jurisdiction of, and+venue in, the federal and state courts located in the County of+New York within the State of New York. The prevailing party in+any claim or dispute between the parties under this Agreement+will be entitled to reimbursement of its reasonable attorneys'+fees and costs. You hereby waive the right to a trial by jury,+to participate in a class or representative action (including in+arbitration), or to combine individual proceedings in court or+in arbitration without the consent of all parties.++13. Term and Termination. This Agreement is effective upon your+acceptance and continues until terminated. Licensor may terminate+this Agreement immediately upon written notice to you if you+breach any provision of this Agreement, including but not limited+to violations of the use restrictions in Attachment A or+unauthorized commercial use. Upon termination: (a) all rights+granted to you under this Agreement will immediately cease;+(b) you must immediately cease all use of LTX-2 and Derivatives+of LTX-2; (c) you must delete or destroy all copies of LTX-2+and Derivatives of LTX-2 in your possession or control; and+(d) you must notify any third parties to whom you distributed+LTX-2 or Derivatives of LTX-2 of the termination. Sections 8-13,+and Section 15 shall survive termination of this Agreement.+Termination does not relieve you of any obligations incurred+prior to termination, including payment obligations under+Section 2. In addition, if You commence a lawsuit or other+proceedings (including a cross-claim or counterclaim in a lawsuit)+against Licensor or any person or entity alleging that LTX-2 or+any Output, or any portion of any of the foregoing, infringe any+intellectual property or other right owned or licensable by you,+then all licenses granted to you under this Agreement shall+terminate as of the date such lawsuit or other proceeding is filed.++14. Disputes and Arbitration. All disputes arising in connection with+this Agreement shall be finally settled by arbitration under the+Rules of Arbitration of the International Chamber of Commerce+("ICC Rules"), by one (1) arbitrator appointed in accordance with+the ICC Rules. The seat of arbitration shall be New York, NY, USA,+and the proceedings shall be conducted in English. The arbitrator+shall be empowered to grant any relief that a court could grant.+Judgment on the arbitration award may be entered by any court+having jurisdiction thereof. Each party waives its right to a+trial by jury and to participate in any class or representative+action.++15. If any provision of this Agreement is held to be+invalid, illegal+or unenforceable, the remaining provisions shall be unaffected+thereby and remain valid as if such provision had not been set+forth herein.++END OF TERMS AND CONDITIONS++ATTACHMENT A: Use Restrictions++When using the Outputs, LTX-2 and any Derivatives thereof, you+will comply with the Acceptable Use Policy. In addition, you+agree not to use the Outputs, LTX-2 or its Derivatives in any+of the following ways:++1. In any way that violates any applicable national, federal,+state, local or international law or regulation;++2. For the purpose of exploiting, Harming or attempting to+exploit or Harm minors in any way;++3. To generate or disseminate false information and/or content+with the purpose of Harming others;++4. To generate or disseminate personal identifiable information+that can be used to Harm an individual;++5. To generate or disseminate information and/or content (e.g.+images, code, posts, articles), and place the information+and/or content in any context (e.g. bot generating tweets)+without expressly and intelligibly disclaiming that the+information and/or content is machine generated;++6. To defame, disparage or otherwise harass others;++7. To impersonate or attempt to impersonate (e.g. deepfakes)+others without their consent;++8. For fully automated decision making that adversely impacts an+individual's legal rights or otherwise creates or modifies a+binding, enforceable obligation;++9. For any use intended to or which has the effect of+discriminating against or Harming individuals or groups based+on online or offline social behavior or known or predicted+personal or personality characteristics;++10. To exploit any of the vulnerabilities of a specific group of+persons based on their age, social, physical or mental+characteristics, in order to materially distort the behavior+of a person pertaining to that group in a manner that causes+or is likely to cause that person or another person physical+or psychological Harm;++11. For any use intended to or which has the effect of+discriminating against individuals or groups based on legally+protected characteristics or categories;++12. To provide medical advice and medical results interpretation;++13. To generate or disseminate information for the purpose to be+used for administration of justice, law enforcement,+immigration or asylum processes, such as predicting an+individual will commit fraud/crime commitment (e.g. by text+profiling, drawing causal relationships between assertions+made in documents, indiscriminate and arbitrarily-targeted use);++14. To generate and/or disseminate malware (including – but not+limited to – ransomware) or any other content to be used for+the purpose of harming electronic systems;++15. To engage in, promote, incite, or facilitate discrimination+or other unlawful or harmful conduct in the provision of+employment, employment benefits, credit, housing, or other+essential goods and services;++16. To engage in, promote, incite, or facilitate the harassment,+abuse, threatening, or bullying of individuals or groups of+individuals;++17. For military, warfare, nuclear industries or applications,+weapons development, or any use in connection with activities+that may cause death, personal injury, or severe physical or+environmental damage;++18. For commercial use only: To train, improve, or fine-tune any+other machine learning model, artificial intelligence system,+or competing model, except for Derivatives of LTX-2 as+expressly permitted under this Agreement;++19. To circumvent, disable, or interfere with any technical+limitations, safety features, content filters, or use+restrictions implemented in LTX-2 by Licensor;++20. To use LTX-2 or Derivatives of LTX-2 in any product, service,+or application that directly competes with Licensor's+commercial products or services, or is designed to replace or+substitute Licensor's offerings in the market, without+obtaining a separate commercial license from Licensor.diff --git a/LICENSE-2_x b/LICENSE-2_xnew file mode 100644index 0000000..e982a92--- /dev/null+++ b/LICENSE-2_x@@ -0,0 +1,580 @@+LTX-2.x Community License Agreement+License date: August 11, 2026+++By downloading, using, accessing or distributing any portion or+element of LTX-2.x, you agree that you have read and accepted to be+bound by this Agreement.++1. Definitions++1.1 "Agreement" means the terms and conditions for this LTX-2.x+Community License Agreement and the exhibits, attachments, and+Complementary Materials, as specified in this document.++1.2 "Complementary Materials" means the accompanying+documentation, tutorials, examples, configuration files and+other materials made available by Licensor together with the+LTX-2.x model weights and parameters, in each case as+distributed by Licensor.++1.3 "Control" means the direct or indirect ownership of more than+fifty percent (50%) of the voting securities or other+ownership interests, or the power to direct the management and+policies of such Entity through voting rights, contract, or+otherwise.++1.4 "Data" means a collection of information and/or content+extracted from the dataset used with LTX-2.x, including to+train, pretrain, or otherwise evaluate LTX-2.x. The Data is+not licensed under this Agreement.++1.5 "Derivatives of LTX-2.x" means all modifications to LTX-2.x,+works based on LTX-2.x, or any other model which is created or+initialized by transfer of patterns of the weights,+parameters, activations or output of LTX-2.x, to the other+model, in order to cause the other model to perform similarly+to LTX-2.x, including - but not limited to - distillation+methods entailing the use of intermediate data representations+or methods based on the generation of synthetic data by+LTX-2.x for training the other model. For clarity, Derivatives+of LTX-2.x include: (i) any fine-tuned or adapted weights,+parameters, or checkpoints derived from LTX-2.x; (ii)+derivative model architectures that incorporate or are based+upon LTX-2.x's architecture; and (iii) any modified or+extended versions of the Complementary Materials.++1.6 "Entity" means any individual, corporation, partnership,+limited liability company, or other legal entity. For purposes+of this Agreement, an Entity shall be deemed to include, on an+aggregative basis, all subsidiaries, affiliates, and other+companies under common Control with such Entity. When+determining whether an Entity meets any threshold under this+Agreement (including revenue thresholds in Section 2.1), all+subsidiaries, affiliates, and companies under common Control+shall be considered collectively.++1.7 "Harm" includes but is not limited to physical, mental,+psychological, financial and reputational damage, pain, or+loss.++1.8 "Licensor" or "LTX" means the owner that is granting the+license under this Agreement. For the purposes of this+Agreement, the Licensor is Lightricks Ltd.++1.9 "LTX-2.x" means the large generative models,+text/image/video/audio/3D generation models, and multimodal+large language models and their software and algorithms,+including trained model weights, parameters (including+optimizer states), machine-learning model code,+inference-enabling code, training-enabling code, fine-tuning+enabling code, accompanying source code, scripts, and all+other elements of the foregoing distributed and made publicly+available by LTX (including, for example, at+https://github.com/Lightricks/LTX-2). This license is+applicable to all LTX-2.5 versions released since August 11,+2026, and all future releases of LTX-2.x under this license.++1.10 "Output" means the results of operating LTX-2.x as embodied+in informational content resulting therefrom.++1.11 "you" (or "your") means an individual or legal Entity+licensing LTX-2.x in accordance with this Agreement and/or+otherwise downloading, accessing, distributing or using+LTX-2.x for whichever purpose and in any field of use,+including usage of LTX-2.x in an end-use application - e.g.+chatbot, translator, image generator.++2. Grant of License.++2.1 Subject to your compliance with the terms and conditions of+this Agreement, you are granted a non-exclusive, worldwide,+non-transferable and royalty-free limited license under+Licensor's intellectual property or other rights owned by+Licensor embodied in LTX-2.x to use, reproduce, prepare,+distribute, publicly display, publicly perform, sublicense,+copy, create derivative works of, and make modifications to+LTX-2.x, for any purpose, subject to the restrictions set+forth in Attachment A; provided however, that Entities with+annual revenues of at least $10,000,000 (the "Commercial+Entities") are required to obtain a paid license for any use+(excluding use solely for a Non-Commercial Purpose as set+forth in Section 2.2) of LTX-2.x and Derivatives of LTX-2.x+(such paid license referred to herein as a "Commercial Use+Agreement"), as will be provided by the Licensor. Commercial+Entities interested in such a commercial license are required+to contact Licensor ([email protected]). Any use+of LTX-2.x or Derivatives of LTX-2.x by Commercial Entities+not in accordance with this Agreement and/or the Commercial+Use Agreement is strictly prohibited and shall be deemed a+material breach of this Agreement. In the event of such+material breach, and without limiting Licensor's right to+terminate the Agreement or to pursue any other remedies+available at law or in equity, you shall pay Licensor the+license fees owed for the period such Commercial Entity used+LTX-2.x (calculated at Licensor's standard commercial license+fees, in effect during the relevant period or, absent+published standard fees, a reasonable market rate for a+comparable license), within thirty (30) days of Licensor's+written demand.++2.2 Notwithstanding the foregoing or anything to the contrary in+this Agreement, a Commercial Entity may download and use+LTX-2.x and Derivatives of LTX-2.x without obtaining the+Commercial Use Agreement solely for a Non-Commercial Purpose.+"Non-Commercial Purpose" means any of the following uses, but+only so far as such Commercial Entity does not receive any+direct or indirect payment arising from the use of LTX-2.x or+Derivatives of LTX-2.x: (i) use by an individual acting in a+personal capacity for research, experimentation, learning,+private study, hobby or recreational projects, or personal+entertainment, in each case where such use is not connected,+directly or indirectly, to any commercial activity, business+operation, or the performance of duties for an employer or any+other Entity; and (ii) use by a Commercial Entity for testing,+evaluation, or non-commercial research and development in a+non-production or development environment. For clarity, use+(a) for revenue-generating activity in any manner, whether+direct or indirect, (b) in direct interactions with or that+has impact on end users, or (c) to train, fine-tune, or+distill any model (including any Derivative of LTX-2.x) for+commercial use, in each case, is not a Non-Commercial Purpose+and requires all Commercial Entities to obtain a paid license+under the Commercial Use Agreement prior to such use. For the+avoidance of doubt, the permission granted under this Section+2.2 is a limited right of use only and does not convey or+transfer any ownership right, title, or interest in or to+LTX-2.x or any Derivatives of LTX-2.x, and all Derivatives of+LTX-2.x created or used pursuant to this Section 2.2 remain+subject to the terms of this Agreement, including Section 1.5.++3. Distribution and Redistribution. You may host for third parties+remote access purposes (e.g. software-as-a-service), reproduce and+distribute copies of LTX-2.x or Derivatives of LTX-2.x thereof in+any medium, with or without modifications, provided that you meet+the following conditions:++3.1 Use-based restrictions as referenced in Section 4 and all+provisions of Attachment A MUST be included as an enforceable+provision by you in any type of legal agreement (e.g. a+license) governing the use and/or distribution of LTX-2.x or+Derivatives of LTX-2.x, and you shall give notice to+subsequent users you distribute to, that LTX-2.x or+Derivatives of LTX-2.x are subject to Section 4 and Attachment+A in their entirety, including all use restrictions and+acceptable use policies;++3.2 You must provide any third-party recipients of LTX-2.x or+Derivatives of LTX-2.x a copy of this Agreement, including all+attachments and use policies. Any Derivative of LTX-2.x (as+defined in Section 1.5, including but not limited to+fine-tuned weights, modified training code, models trained on+Outputs, or any other derivative) must be distributed+exclusively under the terms of this Agreement, subject to+Section 3.6, with a complete copy of this Agreement included;++3.3 You must cause any modified files to carry prominent notices+stating that you changed the files;++3.4 You must retain all copyright, patent, trademark, and+attribution notices excluding those notices that do not+pertain to any part of LTX-2.x, Derivatives of LTX-2.x.++3.5 Transfer of Derivatives. No transfer of any Derivative of+LTX-2.x (including any fine-tuned weights, LoRA adapters, or+similar adaptations) to a third party shall grant such third+party any right, title, license, or authorization to access,+use, reproduce, distribute, or exploit LTX-2.x, or any+Derivative of LTX-2.x beyond the rights granted under this+Agreement. If the transferee is a Commercial Entity (as+defined in Section 2), it must obtain a paid license from+Licensor prior to any use of any Derivative of LTX-2.x,+regardless of who created such Derivative. Prior to or at the+time of any such transfer, you shall notify the transferee in+writing that (i) use of such Derivative of LTX-2.x is subject+to the terms of this Agreement, and (ii) if the transferee is+a Commercial Entity, it must obtain a separate paid license to+LTX-2.x from Licensor. You shall not transfer any Derivative+of LTX-2.x to a Commercial Entity unless such Commercial+Entity has obtained the required paid license from Licensor+prior to any use, and unless the proposed transferee has been+so informed. You and the transferee shall each be responsible+for ensuring the transferee obtains the required license from+Licensor prior to any use of LTX-2.x or Derivative of LTX-2.x.+Nothing in this Section 3.5 shall require a Commercial Entity+to obtain a paid license for use solely for a Non-Commercial+Purpose as permitted under Section 2.2.++3.6 You may add your own copyright statement to your modifications+and may provide additional license terms and conditions -+respecting Section 3.1 - for use, reproduction, or+distribution of your modifications, or for any such+Derivatives of LTX-2.x as a whole, provided your use,+reproduction, and distribution of LTX-2.x otherwise complies+with the conditions stated in this Agreement, and you provide+a complete copy of this Agreement with any such use,+reproduction and distribution of LTX-2.x and any Derivatives+thereof; provided that any such additional terms shall be+additive only and shall not derogate from, conflict with,+waive, or purport to modify any term of this Agreement, and+this Agreement shall govern in the event of any conflict.++4. Use-based restrictions. The restrictions set forth in Attachment A+are considered Use-based restrictions. Therefore, you cannot use+LTX-2.x and the Derivatives of LTX-2.x in violation of the+specified restricted uses. You may use LTX-2.x subject to this+Agreement, only for lawful purposes and in accordance with the+Agreement. "Use" may include creating any content with,+fine-tuning, updating, running, training, evaluating and/or+re-parametrizing LTX-2.x. You shall require all of your users who+use LTX-2.x or a Derivative of LTX-2.x to comply with the terms of+this Section 4.++5. The Output You Generate. Except as set forth herein, Licensor+claims no rights in the Output you generate using LTX-2.x. You are+accountable for input you insert into LTX-2.x, the Output you+generate and its subsequent uses. No use of the Output can+contravene any provision as stated in the Agreement.++6. Updates and Runtime Restrictions; AI Regulations. To the maximum+extent permitted by law, Licensor reserves the right to restrict+(remotely or otherwise) usage of LTX-2.x in violation of this+Agreement, update LTX-2.x through electronic means, or modify the+Output of LTX-2.x based on updates. You shall undertake reasonable+efforts to use the latest version of LTX-2.x. Any use of the+non-current version of LTX-2.x is done solely at your risk. To the+extent applicable to you, you shall comply with all laws and+regulations governing artificial intelligence that apply to your+use, deployment, or distribution of LTX-2.x, Derivatives of+LTX-2.x, or Outputs, including Regulation (EU) 2024/1689 (the "EU+AI Act") and the California AI Transparency Act (Cal. Bus. & Prof.+Code § 22757 et seq.), each as amended from time to time and any+other applicable laws, regulations, or binding guidance relating+to artificial intelligence, transparency, content provenance, or+synthetic media, together with any documentation made available by+Licensor regarding compliance with the same (collectively, "AI+Regulations"). You shall maintain (including within any+application or service through which LTX-2.x, any Derivative of+LTX-2.x, or any Output is made available), and shall not remove,+disable, alter, or circumvent, any safety or security measures,+disclosures, metadata, watermarking, content provenance, latent+disclosure, or other transparency features or functionalities+included or embedded within LTX-2.x or any Derivative of LTX-2.x,+or applied to any Output, in furtherance of AI Regulations,+including any capability of LTX-2.x to include latent disclosures+in Outputs, and you shall include equivalent obligations in any+agreement governing your distribution of LTX-2.x or any Derivative+of LTX-2.x. You are solely responsible for any transparency,+disclosure, marking, or labeling obligations applicable to you+under AI Regulations as a provider or deployer of LTX-2.x, any+Derivative of LTX-2.x, or any system incorporating any of the+foregoing, including any obligation to disclose that content is+artificially generated or manipulated. If Licensor knows or+reasonably believes that you have modified LTX-2.x or any+Derivative of LTX-2.x such that it is no longer capable of+including any disclosure required by AI Regulations in Outputs, or+that you have otherwise removed, disabled, or circumvented any+feature or functionality described in this Section, Licensor may+in its sole discretion revoke the license granted under this+Agreement effective immediately upon notice to you, and upon such+revocation you shall immediately cease all use of LTX-2.x and+Derivatives of LTX-2.x. Licensor makes no representation or+warranty that LTX-2.x, any Derivative of LTX-2.x, or any Output+complies with any AI Regulations applicable to your specific use+case or deployment, and you are solely responsible for determining+the applicability of, and ensuring your compliance with, all AI+Regulations. You shall indemnify, defend, and hold harmless+Licensor and its affiliates from and against any and all claims,+liabilities, losses, damages, costs, and expenses (including+reasonable attorneys' fees) arising out of or relating to your+use, deployment, distribution, or modification of LTX-2.x, any+Derivative of LTX-2.x, or any Output in violation of, or your+other failure to comply with, any AI Regulations.++For purposes of the EU AI Act, Licensor makes LTX-2.x openly+available under this community license and intends that LTX-2.x be+treated as a free and open-source general purpose AI model within+the meaning of Article 53(2) of the EU AI Act. You acknowledge and+agree that (a) to the extent the free and open source derogations+under Article 53(2) of the EU AI Act apply, Licensor's obligations+under the EU AI Act with respect to LTX-2.x are limited to those+applicable to providers of free and open source general purpose AI+models (it being acknowledged that such derogations do not extend+to the obligations under Article 53(1)(c) and (d)), (b) you+acknowledge that LTX-2.x is not intended to be integrated into a+high risk AI system, and shall be fully and solely responsible for+any obligation resulting from such integration, (c) if you+integrate LTX-2.x or any Derivative of LTX-2.x into a high-risk AI+system you shall be solely responsible for all provider+obligations that would otherwise apply to Licensor under the EU AI+Act, and (d) you shall not take any action, or omit to take any+action, that would cause Licensor to lose the benefit of the free+and open source derogations under the EU AI Act, and you shall+indemnify and hold Licensor harmless from any liability, costs, or+expenses arising from your breach of this Section.++7. Export Controls and Sanctions Compliance. You acknowledge that+LTX-2.x, Derivatives of LTX-2.x may be subject to export control+laws and regulations, including but not limited to the U.S. Export+Administration Regulations and sanctions programs administered by+the Office of Foreign Assets Control (OFAC). You represent and+warrant that you and any users of LTX-2.x are not (i) located in,+organized under the laws of, or ordinarily resident in any country+or territory subject to comprehensive sanctions; (ii) identified+on any U.S. government restricted party list, including the+Specially Designated Nationals and Blocked Persons List; or (iii)+otherwise prohibited from receiving LTX-2.x under applicable law.+You shall not export, re-export, or transfer LTX-2.x, directly or+indirectly, in violation of any applicable export control or+sanctions laws or regulations. You agree to comply with all+applicable trade control laws and shall indemnify and hold+Licensor harmless from any claims arising from your failure to+comply with such laws.++8. Trademarks; Reservation of Rights. Nothing in this Agreement+permits you to make use of Licensor's trademarks, trade names,+logos or to otherwise suggest endorsement or misrepresent the+relationship between the parties; and any rights not expressly+granted herein are reserved by the Licensor. Except as expressly+set forth in this Agreement, Licensor does not grant, directly or+by implication, estoppel, statute or otherwise, any right or+license in its, or its affiliates', intellectual property rights+or other proprietary rights. For avoidance of doubt, all+intellectual property rights in Derivatives of LTX-2.x shall be+subject to the terms of this Agreement, and you acquire no right,+title, or interest in or to LTX-2.x itself, which is and remains+the exclusive property of Licensor. You shall not assert any+ownership or other right in LTX-2.x or any Derivative of LTX-2.x+in any manner that restricts, encumbers, or is inconsistent with+the rights retained by Licensor or granted to other licensees+under this Agreement.++9. Disclaimer of Warranty. Unless required by applicable law or+agreed to in writing, Licensor provides LTX-2.x on an "AS IS"+BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either+express or implied, including, without limitation, any warranties+or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or+FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for+determining the appropriateness of using or redistributing LTX-2.x+and Derivatives of LTX-2.x and assume any risks associated with+your exercise of permissions under this Agreement.++10. Limitation of Liability. To the fullest extent permitted by+applicable law, in no event and under no legal theory, whether in+tort (including negligence), contract, or otherwise, unless+required by applicable law (such as deliberate and grossly+negligent acts) or agreed to in writing, shall Licensor be liable+to you or any other individual or Entity for damages, including+any direct, indirect, special, incidental, or consequential+damages of any character arising as a result of this Agreement or+out of the use of, or inability to use LTX-2.x or any Derivative+of LTX-2.x (including but not limited to damages for loss of+goodwill, work stoppage, computer failure or malfunction, or any+and all other commercial damages or losses), even if Licensor has+been advised of the possibility of such damages.++11. Accepting Warranty or Additional Liability. While redistributing+LTX-2.x and Derivatives of LTX-2.x, you may, provided you do not+violate the terms of this Agreement, choose to offer and charge a+fee for, acceptance of support, warranty, indemnity, or other+liability obligations. However, in accepting such obligations,+you may act only on your own behalf and on your sole+responsibility, not on behalf of Licensor, and only if you agree+to indemnify, defend, and hold Licensor harmless for any+liability incurred by, or claims asserted against Licensor, by+reason of your accepting any such warranty or additional+liability.++12. Governing Law. This Agreement and all relations, disputes, claims+and other matters arising hereunder (including non-contractual+disputes or claims) will be governed exclusively by, and+construed exclusively in accordance with, the laws of the State+of New York and applicable U.S. federal law. To the extent+permitted by law, choice of laws rules and the United Nations+Convention on Contracts for the International Sale of Goods will+not apply. The prevailing party in any claim or dispute between+the parties under this Agreement will be entitled to+reimbursement of its reasonable attorneys' fees and costs.++13. Term and Termination. This Agreement is effective upon your+acceptance and continues until terminated. Licensor may terminate+this Agreement immediately upon written notice to you if you+breach any provision of this Agreement, including but not limited+to violations of the use restrictions in Attachment A or+unauthorized commercial use. This Agreement also terminates+immediately and automatically, without notice, upon any material+breach of this Agreement, including any use in violation of+applicable AI Regulations or any unauthorized commercial use of+LTX-2.x or Derivatives of LTX-2.x by a Commercial Entity. Upon+termination: (a) all rights granted to you under this Agreement+will immediately cease; (b) you must immediately cease all use of+LTX-2.x and Derivatives of LTX-2.x; (c) you must delete or+destroy all copies of LTX-2.x and Derivatives of LTX-2.x in your+possession or control; and (d) you must notify any third parties+to whom you distributed LTX-2.x or Derivatives of LTX-2.x of the+termination. Sections 2, 3, 4, 6-16 and Attachment A shall+survive termination of this Agreement. Termination does not+relieve you of any obligations incurred prior to termination,+including payment obligations under Section 2 and adhering to the+restrictions under Section 3. In addition, if You commence a+lawsuit or other proceedings (including a cross-claim or+counterclaim in a lawsuit) against Licensor or any person or+entity alleging that LTX-2.x or any Output, or any portion of any+of the foregoing, infringe any intellectual property or other+right owned or licensable by you, then all licenses granted to+you under this Agreement shall terminate as of the date such+lawsuit or other proceeding is filed.++14. Disputes and Arbitration; Waiver of Jury Trial; Class Action+Waiver. IF YOU ARE NOT ACTING AS A CONSUMER UNDER APPLICABLE LAW,+YOU HEREBY WAIVE THE RIGHT TO A TRIAL BY JURY, TO PARTICIPATE IN+A CLASS OR REPRESENTATIVE ACTION (INCLUDING IN ARBITRATION), OR+TO COMBINE INDIVIDUAL PROCEEDINGS IN COURT OR IN ARBITRATION+WITHOUT THE CONSENT OF ALL PARTIES. All disputes arising in+connection with this Agreement shall be finally settled by+arbitration under the Rules of Arbitration of the International+Chamber of Commerce ("ICC Rules"), by one (1) arbitrator+appointed in accordance with the ICC Rules. The seat of+arbitration shall be New York, NY, USA, and the proceedings shall+be conducted in English. The arbitrator shall be empowered to+grant any relief that a court could grant. Judgment on the+arbitration award may be entered by any court having jurisdiction+thereof. Notwithstanding the foregoing, either party may seek+injunctive or other equitable relief in respect of any actual or+threatened breach of the license restrictions under this+Agreement (including Attachment A and the Acceptable Use Policy)+or any actual or threatened infringement, misappropriation, or+violation of Licensor's intellectual property rights, in the+state or federal courts located in the County of New York, State+of New York, and each party irrevocably consents to the+jurisdiction of, and venue in, such courts for that limited+purpose. The foregoing waivers do not apply to, and are not+enforceable against, any licensee acting as a consumer under the+mandatory consumer-protection laws of its jurisdiction of+residence (including, without limitation, the European Union, the+United Kingdom, and the State of California), and nothing in this+Agreement limits any rights under such laws that cannot be waived+or limited by contract. If any waiver in this Section is held+invalid or unenforceable as to a particular licensee or dispute,+such waiver shall be severed to that extent only and shall not+affect the validity or enforceability of the remainder of this+Section.++15. In the event of any exception to the application of binding+arbitration, all disputes, claims, and other matters arising+hereunder shall be brought exclusively in the state or federal+courts located in the County of New York, State of New York. You+waive all defenses of lack of personal jurisdiction and forum non+conveniens with respect to venue and jurisdiction in such courts,+and consent to their exclusive jurisdiction and venue.++16. Severability. If any provision of this Agreement is held to be+invalid, illegal or unenforceable, the remaining provisions shall+be unaffected thereby and remain valid as if such provision had+not been set forth herein.++ END OF TERMS AND CONDITIONS++ Attachment A+ Use Restrictions++When using the Outputs, LTX-2.x and any Derivatives thereof, you+agree to comply with the Acceptable Use Policy+(https://static.lightricks.com/legal/ltx-acceptable-use-policy.pdf)+which is hereby incorporated into and made part of this Agreement by+reference. Licensor may update it from time to time, and the version+in effect at the time of your use governs; continued use after an+update constitutes acceptance. Licensor shall post each version of+the Acceptable Use Policy with its effective date, and no update+shall apply retroactively to use occurring before that effective+date. In addition, you agree not to use the Outputs, LTX-2.x or its+Derivatives in any of the following ways:++1) In any way that violates any applicable national, federal,+state, local or international law or regulation;++2) For the purpose of exploiting, Harming or attempting to exploit+or Harm minors in any way;++3) Knowingly generate or disseminate verifiably false information+and/or content with the intent to deceive, defraud, or+otherwise unlawfully Harm others;++4) To generate or disseminate personal identifiable information+that can be used to Harm an individual;++5) To generate or disseminate information and/or content (e.g.+images, code, posts, articles), and place the information+and/or content in any context (e.g. bot generating tweets)+without expressly and intelligibly disclaiming that the+information and/or content is machine generated;++6) To defame others, or to engage in the unlawful harassment of+others;++7) To impersonate or attempt to impersonate (e.g. deepfakes)+others without their consent;++8) For fully automated decision making that adversely impacts an+individual's legal rights or otherwise creates or modifies a+binding, enforceable obligation;++9) For any use intended to or which has the effect of+discriminating against or Harming individuals or groups based+on online or offline social behavior or known or predicted+personal or personality characteristics;++10) To exploit any of the vulnerabilities of a specific group of+persons based on their age, social, physical or mental+characteristics, in order to materially distort the behavior+of a person pertaining to that group in a manner that causes+or is likely to cause that person or another person physical+or psychological Harm;++11) For any use intended to or which has the effect of+discriminating against individuals or groups based on legally+protected characteristics or categories;++12) To provide medical advice and medical results interpretation;++13) To generate or disseminate information for the purpose to be+used for administration of justice, law enforcement,+immigration or asylum processes, such as predicting an+individual will commit fraud/crime commitment (e.g. by text+profiling, drawing causal relationships between assertions+made in documents, indiscriminate and arbitrarily-targeted+use);++14) To generate and/or disseminate malware (including - but not+limited to - ransomware) or any other content to be used for+the purpose of harming electronic systems;++15) To engage in, promote, incite, or facilitate discrimination or+other unlawful or harmful conduct in the provision of+employment, employment benefits, credit, housing, or other+essential goods and services;++16) To engage in, promote, incite, or facilitate the harassment,+abuse, threatening, or bullying of individuals or groups of+individuals;++17) For military, warfare, nuclear industries or applications,+weapons development, or any use in connection with activities+that may cause death, personal injury, or severe physical or+environmental damage;++18) For commercial use only: To train, improve, or fine-tune any+other machine learning model, artificial intelligence system,+or competing model, except for Derivatives of LTX-2.x as+expressly permitted under this Agreement;++19) To circumvent, disable, or interfere with any technical+limitations, safety features, content filters, watermarking,+content provenance or latent disclosure functionalities, or+use restrictions implemented in LTX-2.x by Licensor;++20) To use LTX-2.x or Derivatives of LTX-2.x in any product,+service, or application that directly competes with Licensor's+commercial products or services, or is designed to replace or+substitute Licensor's offerings in the market, without+obtaining a separate commercial license from Licensor.diff --git a/LICENSE.md b/LICENSE.mddeleted file mode 100644index 8858b29..0000000--- a/LICENSE.md+++ /dev/null@@ -1,125 +0,0 @@-# LTX-2.x Community License Agreement--*License date: August 11, 2026*--**By downloading, using, accessing or distributing any portion or element of LTX-2.x, you agree that you have read and accepted to be bound by this Agreement.**--**1. Definitions.**--> **1.1** **“Agreement”** means the terms and conditions for this LTX-2.x Community License Agreement and the exhibits, attachments, and Complementary Materials, as specified in this document.--> **1.2** **“Complementary Materials”** means the accompanying documentation, tutorials, examples, configuration files and other materials made available by Licensor together with the LTX-2.x model weights and parameters, in each case as distributed by Licensor.--> **1.3** **“Control”** means the direct or indirect ownership of more than fifty percent (50%) of the voting securities or other ownership interests, or the power to direct the management and policies of such Entity through voting rights, contract, or otherwise.--> **1.4** **“Data”** means a collection of information and/or content extracted from the dataset used with LTX-2.x, including to train, pretrain, or otherwise evaluate LTX-2.x. The Data is not licensed under this Agreement.--> **1.5** **“Derivatives of LTX-2.x”** means all modifications to LTX-2.x, works based on LTX-2.x, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of LTX-2.x, to the other model, in order to cause the other model to perform similarly to LTX-2.x, including – but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by LTX-2.x for training the other model. For clarity, Derivatives of LTX-2.x include: (i) any fine-tuned or adapted weights, parameters, or checkpoints derived from LTX-2.x; (ii) derivative model architectures that incorporate or are based upon LTX-2.x’s architecture; and (iii) any modified or extended versions of the Complementary Materials.--> **1.6** **“Entity”** means any individual, corporation, partnership, limited liability company, or other legal entity. For purposes of this Agreement, an Entity shall be deemed to include, on an aggregative basis, all subsidiaries, affiliates, and other companies under common Control with such Entity. When determining whether an Entity meets any threshold under this Agreement (including revenue thresholds in Section 2.1), all subsidiaries, affiliates, and companies under common Control shall be considered collectively.--> **1.7** **“Harm”** includes but is not limited to physical, mental, psychological, financial and reputational damage, pain, or loss.--> **1.8** **“Licensor”** or **“LTX”** means the owner that is granting the license under this Agreement. For the purposes of this Agreement, the Licensor is Lightricks Ltd.--> **1.9** **“LTX-2.x”** means the large generative models, text/image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code, accompanying source code, scripts, and all other elements of the foregoing distributed and made publicly available by LTX (including, for example, at [https://github.com/Lightricks/LTX-2](https://github.com/Lightricks/LTX-2)). This license is applicable to all LTX-2.5 versions released since August 11, 2026, and all future releases of LTX-2.x under this license.--> **1.10** **“Output”** means the results of operating LTX-2.x as embodied in informational content resulting therefrom.--> **1.11** **“you”** (or **“your”**) means an individual or legal Entity licensing LTX-2.x in accordance with this Agreement and/or otherwise downloading, accessing, distributing or using LTX-2.x for whichever purpose and in any field of use, including usage of LTX-2.x in an end-use application - e.g. chatbot, translator, image generator.--**2. Grant of License.**--> **2.1** Subject to your compliance with the terms and conditions of this Agreement, you are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Licensor’s intellectual property or other rights owned by Licensor embodied in LTX-2.x to use, reproduce, prepare, distribute, publicly display, publicly perform, sublicense, copy, create derivative works of, and make modifications to LTX-2.x, for any purpose, subject to the restrictions set forth in Attachment A; **provided however, that Entities with annual revenues of at least $10,000,000 (the “Commercial Entities”) are required to obtain a paid license for any use (excluding use solely for a Non-Commercial Purpose as set forth in Section 2.2) of LTX-2.x and Derivatives of LTX-2.x (such paid license referred to herein as a “Commercial Use Agreement”), as will be provided by the Licensor. Commercial Entities interested in such a commercial license are required to [contact Licensor](mailto:[email protected]). Any use of LTX-2.x or Derivatives of LTX-2.x by Commercial Entities not in accordance with this Agreement and/or the Commercial Use Agreement is strictly prohibited and shall be deemed a material breach of this Agreement. In the event of such material breach, and without limiting Licensor’s right to terminate the Agreement or to pursue any other remedies available at law or in equity, you shall pay Licensor the license fees owed for the period such Commercial Entity used LTX-2.x (calculated at Licensor’s standard commercial license fees, in effect during the relevant period or, absent published standard fees, a reasonable market rate for a comparable license), within thirty (30) days of Licensor’s written demand.**--> **2.2** Notwithstanding the foregoing or anything to the contrary in this Agreement, a Commercial Entity may download and use LTX-2.x and Derivatives of LTX-2.x without obtaining the Commercial Use Agreement solely for a Non-Commercial Purpose. **“Non-Commercial Purpose”** means any of the following uses, but only so far as such Commercial Entity does not receive any direct or indirect payment arising from the use of LTX-2.x or Derivatives of LTX-2.x: (i) use by an individual acting in a personal capacity for research, experimentation, learning, private study, hobby or recreational projects, or personal entertainment, in each case where such use is not connected, directly or indirectly, to any commercial activity, business operation, or the performance of duties for an employer or any other Entity; and (ii) use by a Commercial Entity for testing, evaluation, or non-commercial research and development in a non-production or development environment. For clarity, use (a) for revenue-generating activity in any manner, whether direct or indirect, (b) in direct interactions with or that has impact on end users, or (c) to train, fine-tune, or distill any model (including any Derivative of LTX-2.x) for commercial use, in each case, is not a Non-Commercial Purpose and requires all Commercial Entities to obtain a paid license under the Commercial Use Agreement prior to such use. For the avoidance of doubt, the permission granted under this Section 2.2 is a limited right of use only and does not convey or transfer any ownership right, title, or interest in or to LTX-2.x or any Derivatives of LTX-2.x, and all Derivatives of LTX-2.x created or used pursuant to this Section 2.2 remain subject to the terms of this Agreement, including Section 1.5.--**3. Distribution and Redistribution.** You may host for third parties remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of LTX-2.x or Derivatives of LTX-2.x thereof in any medium, with or without modifications, provided that you meet the following conditions:--> **3.1** Use-based restrictions as referenced in Section 4 and all provisions of Attachment A MUST be included as an enforceable provision by you in any type of legal agreement (e.g. a license) governing the use and/or distribution of LTX-2.x or Derivatives of LTX-2.x, and you shall give notice to subsequent users you distribute to, that LTX-2.x or Derivatives of LTX-2.x are subject to Section 4 and Attachment A in their entirety, including all use restrictions and acceptable use policies;--> **3.2** You must provide any third-party recipients of LTX-2.x or Derivatives of LTX-2.x a copy of this Agreement, including all attachments and use policies. Any Derivative of LTX-2.x (as defined in Section 1.5, including but not limited to fine-tuned weights, modified training code, models trained on Outputs, or any other derivative) must be distributed exclusively under the terms of this Agreement, subject to Section 3.6, with a complete copy of this Agreement included;--> **3.3** You must cause any modified files to carry prominent notices stating that you changed the files;--> **3.4** You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of LTX-2.x, Derivatives of LTX-2.x.--> **3.5** Transfer of Derivatives. No transfer of any Derivative of LTX-2.x (including any fine-tuned weights, LoRA adapters, or similar adaptations) to a third party shall grant such third party any right, title, license, or authorization to access, use, reproduce, distribute, or exploit LTX-2.x, or any Derivative of LTX-2.x beyond the rights granted under this Agreement. If the transferee is a Commercial Entity (as defined in Section 2), it must obtain a paid license from Licensor prior to any use of any Derivative of LTX-2.x, regardless of who created such Derivative. Prior to or at the time of any such transfer, you shall notify the transferee in writing that (i) use of such Derivative of LTX-2.x is subject to the terms of this Agreement, and (ii) if the transferee is a Commercial Entity, it must obtain a separate paid license to LTX-2.x from Licensor. You shall not transfer any Derivative of LTX-2.x to a Commercial Entity unless such Commercial Entity has obtained the required paid license from Licensor prior to any use, and unless the proposed transferee has been so informed. You and the transferee shall each be responsible for ensuring the transferee obtains the required license from Licensor prior to any use of LTX-2.x or Derivative of LTX-2.x. Nothing in this Section 3.5 shall require a Commercial Entity to obtain a paid license for use solely for a Non-Commercial Purpose as permitted under Section 2.2.--> **3.6** You may add your own copyright statement to your modifications and may provide additional license terms and conditions - **respecting Section 3.1** - for use, reproduction, or distribution of your modifications, or for any such Derivatives of LTX-2.x as a whole, provided your use, reproduction, and distribution of LTX-2.x otherwise complies with the conditions stated in this Agreement, and you provide a complete copy of this Agreement with any such use, reproduction and distribution of LTX-2.x and any Derivatives thereof; provided that any such additional terms shall be additive only and shall not derogate from, conflict with, waive, or purport to modify any term of this Agreement, and this Agreement shall govern in the event of any conflict.--**4. Use-based restrictions.** The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore, you cannot use LTX-2.x and the Derivatives of LTX-2.x in violation of the specified restricted uses. You may use LTX-2.x subject to this Agreement, only for lawful purposes and in accordance with the Agreement. **“Use”** may include creating any content with, fine-tuning, updating, running, training, evaluating and/or re-parametrizing LTX-2.x. You shall require all of your users who use LTX-2.x or a Derivative of LTX-2.x to comply with the terms of this Section 4.--**5. The Output You Generate.** Except as set forth herein, Licensor claims no rights in the Output you generate using LTX-2.x. You are accountable for input you insert into LTX-2.x, the Output you generate and its subsequent uses. No use of the Output can contravene any provision as stated in the Agreement.--**6. Updates and Runtime Restrictions; AI Regulations.** To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of LTX-2.x in violation of this Agreement, update LTX-2.x through electronic means, or modify the Output of LTX-2.x based on updates. You shall undertake reasonable efforts to use the latest version of LTX-2.x. Any use of the non-current version of LTX-2.x is done solely at your risk. To the extent applicable to you, you shall comply with all laws and regulations governing artificial intelligence that apply to your use, deployment, or distribution of LTX-2.x, Derivatives of LTX-2.x, or Outputs, including Regulation (EU) 2024/1689 (the “EU AI Act”) and the California AI Transparency Act (Cal. Bus. & Prof. Code § 22757 et seq.), each as amended from time to time and any other applicable laws, regulations, or binding guidance relating to artificial intelligence, transparency, content provenance, or synthetic media, together with any documentation made available by Licensor regarding compliance with the same (collectively, “AI Regulations”). You shall maintain (including within any application or service through which LTX-2.x, any Derivative of LTX-2.x, or any Output is made available), and shall not remove, disable, alter, or circumvent, any safety or security measures, disclosures, metadata, watermarking, content provenance, latent disclosure, or other transparency features or functionalities included or embedded within LTX-2.x or any Derivative of LTX-2.x, or applied to any Output, in furtherance of AI Regulations, including any capability of LTX-2.x to include latent disclosures in Outputs, and you shall include equivalent obligations in any agreement governing your distribution of LTX-2.x or any Derivative of LTX-2.x. You are solely responsible for any transparency, disclosure, marking, or labeling obligations applicable to you under AI Regulations as a provider or deployer of LTX-2.x, any Derivative of LTX-2.x, or any system incorporating any of the foregoing, including any obligation to disclose that content is artificially generated or manipulated. If Licensor knows or reasonably believes that you have modified LTX-2.x or any Derivative of LTX-2.x such that it is no longer capable of including any disclosure required by AI Regulations in Outputs, or that you have otherwise removed, disabled, or circumvented any feature or functionality described in this Section, Licensor may in its sole discretion revoke the license granted under this Agreement effective immediately upon notice to you, and upon such revocation you shall immediately cease all use of LTX-2.x and Derivatives of LTX-2.x. Licensor makes no representation or warranty that LTX-2.x, any Derivative of LTX-2.x, or any Output complies with any AI Regulations applicable to your specific use case or deployment, and you are solely responsible for determining the applicability of, and ensuring your compliance with, all AI Regulations. You shall indemnify, defend, and hold harmless Licensor and its affiliates from and against any and all claims, liabilities, losses, damages, costs, and expenses (including reasonable attorneys’ fees) arising out of or relating to your use, deployment, distribution, or modification of LTX-2.x, any Derivative of LTX-2.x, or any Output in violation of, or your other failure to comply with, any AI Regulations.--> For purposes of the EU AI Act, Licensor makes LTX-2.x openly available under this community license and intends that LTX-2.x be treated as a free and open-source general purpose AI model within the meaning of Article 53(2) of the EU AI Act. You acknowledge and agree that (a) to the extent the free and open source derogations under Article 53(2) of the EU AI Act apply, Licensor’s obligations under the EU AI Act with respect to LTX-2.x are limited to those applicable to providers of free and open source general purpose AI models (it being acknowledged that such derogations do not extend to the obligations under Article 53(1)(c) and (d)), (b) you acknowledge that LTX-2.x is not intended to be integrated into a high risk AI system, and shall be fully and solely responsible for any obligation resulting from such integration, (c) if you integrate LTX-2.x or any Derivative of LTX-2.x into a high-risk AI system you shall be solely responsible for all provider obligations that would otherwise apply to Licensor under the EU AI Act, and (d) you shall not take any action, or omit to take any action, that would cause Licensor to lose the benefit of the free and open source derogations under the EU AI Act, and you shall indemnify and hold Licensor harmless from any liability, costs, or expenses arising from your breach of this Section.--**7. Export Controls and Sanctions Compliance.** You acknowledge that LTX-2.x, Derivatives of LTX-2.x may be subject to export control laws and regulations, including but not limited to the U.S. Export Administration Regulations and sanctions programs administered by the Office of Foreign Assets Control (OFAC). You represent and warrant that you and any users of LTX-2.x are not (i) located in, organized under the laws of, or ordinarily resident in any country or territory subject to comprehensive sanctions; (ii) identified on any U.S. government restricted party list, including the Specially Designated Nationals and Blocked Persons List; or (iii) otherwise prohibited from receiving LTX-2.x under applicable law. You shall not export, re-export, or transfer LTX-2.x, directly or indirectly, in violation of any applicable export control or sanctions laws or regulations. You agree to comply with all applicable trade control laws and shall indemnify and hold Licensor harmless from any claims arising from your failure to comply with such laws.--**8. Trademarks; Reservation of Rights.** Nothing in this Agreement permits you to make use of Licensor’s trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensor. Except as expressly set forth in this Agreement, Licensor does not grant, directly or by implication, estoppel, statute or otherwise, any right or license in its, or its affiliates’, intellectual property rights or other proprietary rights. For avoidance of doubt, all intellectual property rights in Derivatives of LTX-2.x shall be subject to the terms of this Agreement, and you acquire no right, title, or interest in or to LTX-2.x itself, which is and remains the exclusive property of Licensor. You shall not assert any ownership or other right in LTX-2.x or any Derivative of LTX-2.x in any manner that restricts, encumbers, or is inconsistent with the rights retained by Licensor or granted to other licensees under this Agreement.--**9. Disclaimer of Warranty.** Unless required by applicable law or agreed to in writing, Licensor provides LTX-2.x on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing LTX-2.x and Derivatives of LTX-2.x and assume any risks associated with your exercise of permissions under this Agreement.--**10. Limitation of Liability.** To the fullest extent permitted by applicable law, in no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall Licensor be liable to you or any other individual or Entity for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this Agreement or out of the use of, or inability to use LTX-2.x or any Derivative of LTX-2.x (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if Licensor has been advised of the possibility of such damages.--**11. Accepting Warranty or Additional Liability.** While redistributing LTX-2.x and Derivatives of LTX-2.x, you may, provided you do not violate the terms of this Agreement, choose to offer and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations. However, in accepting such obligations, you may act only on your own behalf and on your sole responsibility, not on behalf of Licensor, and only if you agree to indemnify, defend, and hold Licensor harmless for any liability incurred by, or claims asserted against Licensor, by reason of your accepting any such warranty or additional liability.--**12. Governing Law.** This Agreement and all relations, disputes, claims and other matters arising hereunder (including non-contractual disputes or claims) will be governed exclusively by, and construed exclusively in accordance with, the laws of the State of New York and applicable U.S. federal law. To the extent permitted by law, choice of laws rules and the United Nations Convention on Contracts for the International Sale of Goods will not apply. The prevailing party in any claim or dispute between the parties under this Agreement will be entitled to reimbursement of its reasonable attorneys’ fees and costs.--**13. Term and Termination.** This Agreement is effective upon your acceptance and continues until terminated. Licensor may terminate this Agreement immediately upon written notice to you if you breach any provision of this Agreement, including but not limited to violations of the use restrictions in Attachment A or unauthorized commercial use. This Agreement also terminates immediately and automatically, without notice, upon any material breach of this Agreement, including any use in violation of applicable AI Regulations or any unauthorized commercial use of LTX-2.x or Derivatives of LTX-2.x by a Commercial Entity. Upon termination: (a) all rights granted to you under this Agreement will immediately cease; (b) you must immediately cease all use of LTX-2.x and Derivatives of LTX-2.x; (c) you must delete or destroy all copies of LTX-2.x and Derivatives of LTX-2.x in your possession or control; and (d) you must notify any third parties to whom you distributed LTX-2.x or Derivatives of LTX-2.x of the termination. Sections 2, 3, 4, 6-16 and Attachment A shall survive termination of this Agreement. Termination does not relieve you of any obligations incurred prior to termination, including payment obligations under Section 2 and adhering to the restrictions under Section 3. In addition, if You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Licensor or any person or entity alleging that LTX-2.x or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licenses granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed.--**14. Disputes and Arbitration; Waiver of Jury Trial; Class Action Waiver.** **IF YOU ARE NOT ACTING AS A CONSUMER UNDER APPLICABLE LAW, YOU HEREBY WAIVE THE RIGHT TO A TRIAL BY JURY, TO PARTICIPATE IN A CLASS OR REPRESENTATIVE ACTION (INCLUDING IN ARBITRATION), OR TO COMBINE INDIVIDUAL PROCEEDINGS IN COURT OR IN ARBITRATION WITHOUT THE CONSENT OF ALL PARTIES.** All disputes arising in connection with this Agreement shall be finally settled by arbitration under the Rules of Arbitration of the International Chamber of Commerce (“ICC Rules”), by one (1) arbitrator appointed in accordance with the ICC Rules. The seat of arbitration shall be New York, NY, USA, and the proceedings shall be conducted in English. The arbitrator shall be empowered to grant any relief that a court could grant. Judgment on the arbitration award may be entered by any court having jurisdiction thereof. Notwithstanding the foregoing, either party may seek injunctive or other equitable relief in respect of any actual or threatened breach of the license restrictions under this Agreement (including Attachment A and the Acceptable Use Policy) or any actual or threatened infringement, misappropriation, or violation of Licensor’s intellectual property rights, in the state or federal courts located in the County of New York, State of New York, and each party irrevocably consents to the jurisdiction of, and venue in, such courts for that limited purpose. The foregoing waivers do not apply to, and are not enforceable against, any licensee acting as a consumer under the mandatory consumer-protection laws of its jurisdiction of residence (including, without limitation, the European Union, the United Kingdom, and the State of California), and nothing in this Agreement limits any rights under such laws that cannot be waived or limited by contract. If any waiver in this Section is held invalid or unenforceable as to a particular licensee or dispute, such waiver shall be severed to that extent only and shall not affect the validity or enforceability of the remainder of this Section.--**15.** In the event of any exception to the application of binding arbitration, all disputes, claims, and other matters arising hereunder shall be brought exclusively in the state or federal courts located in the County of New York, State of New York. You waive all defenses of lack of personal jurisdiction and forum non conveniens with respect to venue and jurisdiction in such courts, and consent to their exclusive jurisdiction and venue.--**16. Severability.** If any provision of this Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.--**END OF TERMS AND CONDITIONS**--# Attachment A--*Use Restrictions*--When using the Outputs, LTX-2.x and any Derivatives thereof, you agree to comply with the [Acceptable Use Policy](https://static.lightricks.com/legal/ltx-acceptable-use-policy.pdf) which is hereby incorporated into and made part of this Agreement by reference. Licensor may update it from time to time, and the version in effect at the time of your use governs; continued use after an update constitutes acceptance. Licensor shall post each version of the Acceptable Use Policy with its effective date, and no update shall apply retroactively to use occurring before that effective date. In addition, you agree not to use the Outputs, LTX-2.x or its Derivatives in any of the following ways:--> **1)** In any way that violates any applicable national, federal, state, local or international law or regulation;--> **2)** For the purpose of exploiting, Harming or attempting to exploit or Harm minors in any way;--> **3)** Knowingly generate or disseminate verifiably false information and/or content with the intent to deceive, defraud, or otherwise unlawfully Harm others;--> **4)** To generate or disseminate personal identifiable information that can be used to Harm an individual;--> **5)** To generate or disseminate information and/or content (e.g. images, code, posts, articles), and place the information and/or content in any context (e.g. bot generating tweets) without expressly and intelligibly disclaiming that the information and/or content is machine generated;--> **6)** To defame others, or to engage in the unlawful harassment of others;--> **7)** To impersonate or attempt to impersonate (e.g. deepfakes) others without their consent;--> **8)** For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;--> **9)** For any use intended to or which has the effect of discriminating against or Harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;--> **10)** To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological Harm;--> **11)** For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;--> **12)** To provide medical advice and medical results interpretation;--> **13)** To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use);--> **14)** To generate and/or disseminate malware (including – but not limited to – ransomware) or any other content to be used for the purpose of harming electronic systems;--> **15)** To engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, or other essential goods and services;--> **16)** To engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals;--> **17)** For military, warfare, nuclear industries or applications, weapons development, or any use in connection with activities that may cause death, personal injury, or severe physical or environmental damage;--> **18)** For commercial use only: To train, improve, or fine-tune any other machine learning model, artificial intelligence system, or competing model, except for Derivatives of LTX-2.x as expressly permitted under this Agreement;--> **19)** To circumvent, disable, or interfere with any technical limitations, safety features, content filters, watermarking, content provenance or latent disclosure functionalities, or use restrictions implemented in LTX-2.x by Licensor;--> **20)** To use LTX-2.x or Derivatives of LTX-2.x in any product, service, or application that directly competes with Licensor’s commercial products or services, or is designed to replace or substitute Licensor’s offerings in the market, without obtaining a separate commercial license from Licensor.diff --git a/README.md b/README.mdindex b0a82d3..4e0b923 100644--- a/README.md+++ b/README.md@@ -61,7 +61,35 @@ uv run python -m ltx_pipelines.distilled \In cases of GPU memory constraints, consider `--quantization fp8-cast --offload {cpu, disk}`. See [additional flags](packages/ltx-pipelines/docs/installation.md#common-cli-flags).-This uses the distilled model and pipeline for fast results. For better quality or other capabilities, see [Models](#full-model-list) and [Pipelines](#available-pipelines).+This is **DistilledPipeline**: the fast starting point. For **production quality** (slower, more VRAM), run [DFR](#dfr-production-quality) below. For other capabilities, see [Models](#full-model-list) and [Pipelines](#available-pipelines).++### DFR (production quality)++**DFR** (Diffusion Fidelity Rendering) is the production-quality text/image-to-video path. It uses the **same distilled transformer** as the command above, plus a detailing IC-LoRA — extra generated keyframes and a spatial detailing pass. Expect longer runtime and more VRAM, not a different prompting style. Do not pass the full (dev) transformer.++Reuse the text encoder, VAEs, spatial upscaler, and distilled transformer from the first download; add the detailing IC-LoRA (separate repository):++```bash+hf download Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler \+ ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors \+ --local-dir models/ltx-2.5/loras+```++```bash+uv run python -m ltx_pipelines.dfr_pipeline \+ --transformer-path models/ltx-2.5/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors \+ --text-encoder-path models/ltx-2.5/text_encoders/gemma4-12b-with-proj-ltx-2.5-bf16.safetensors \+ --video-vae-path models/ltx-2.5/vae/ltx-2.5-video-vae-bf16.safetensors \+ --audio-vae-path models/ltx-2.5/vae/ltx-2.5-audio-vae-bf16.safetensors \+ --detailing-lora models/ltx-2.5/loras/ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors \+ --spatial-upsampler-path models/ltx-2.5/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors \+ --num-frames 121 \+ --seed 42 \+ --output-path output_dfr.mp4 \+ --prompt "A medium close-up shot features a Caucasian man with a beard, wearing a green and white baseball cap without any letters on the front, and a light blue shirt over a white t-shirt. He is positioned in the center of the frame, looking intently directly at the camera, his eyes focused on camera. His facial expression is one of deep concentration, with his brow slightly raised. As he looks straight at the camera, a quick sniff sound is heard, and then he speaks with a deep male voice and a satisfied tone, saying, 'I think it's so good.' The camera remains static throughout, maintaining a shallow depth of field, which keeps the man in sharp focus while the background is softly blurred, showing a beige wall behind him. After a brief pause, another short, audible sniff is heard. The man then continues to speak, his voice maintaining the same quality, as he states, 'So good. So good.' He elaborates further, emphasizing his point with a final statement, 'This got to be, it's got to be the best tool I've ever seen.'"+```++Defaults are 1024×1536 at 24 fps (`--temporal-upscalings 0`). UHD 4K is `--width 3840 --height 2176` (not 2160). `--temporal-upscalings 1` or `2` needs the [temporal upscaler](#full-model-list). Size, fps, and memory notes: [Running DFR](packages/ltx-pipelines/docs/pipelines.md#running-dfr).### Full Model List@@ -70,8 +98,8 @@ LTX-2.5 is the recommended model, and what the [Quick Start](#-quick-start) usesDownload from the [LTX-2.5 HuggingFace repository](https://huggingface.co/Lightricks/LTX-2.5):**Transformer** (choose and download one of the following)- * [`ltx-2.5-22b-dev-transformer-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/diffusion_models/ltx-2.5-22b-dev-transformer-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/diffusion_models/ltx-2.5-22b-dev-transformer-bf16.safetensors) - the full model; used by the guided two-stage pipelines- * [`ltx-2.5-22b-distilled-transformer-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors) - runs in far fewer steps; what `DistilledPipeline`, `ICLoraPipeline` and `DubItPipeline` expect+ * [`ltx-2.5-22b-dev-transformer-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/diffusion_models/ltx-2.5-22b-dev-transformer-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/diffusion_models/ltx-2.5-22b-dev-transformer-bf16.safetensors) - the full model; used by the guided two-stage pipelines (TI2Vid, Keyframe, A2Vid)+ * [`ltx-2.5-22b-distilled-transformer-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors) - runs in far fewer steps; what `DistilledPipeline`, [`DFRPipeline`](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py), `ICLoraPipeline` and `DubItPipeline` expect**Text Encoder** - Gemma 4 12B, fine-tuned for LTX, with the text projection bundled in; required by every pipeline. It is bundled with the model, so no separate Gemma download is needed. Google's stock Gemma 4 release is not a substitute: loading checks the encoder's version against the one the checkpoint was trained with (`gemma4-12b-ltx-v1`)* [`gemma4-12b-with-proj-ltx-2.5-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/text_encoders/gemma4-12b-with-proj-ltx-2.5-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/text_encoders/gemma4-12b-with-proj-ltx-2.5-bf16.safetensors)@@ -86,13 +114,13 @@ Download from the [LTX-2.5 HuggingFace repository](https://huggingface.co/Lightr**Spatial Upscaler** - required by the two-stage pipeline implementations in this repository* [`ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors)-**Temporal Upscaler** - required by [`DFRPipeline`](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py) when running temporal refine rounds (`--temporal-upsample-rounds`)+**Temporal Upscaler** - required by [`DFRPipeline`](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py) when running temporal refine rounds (`--temporal-upscalings`)* [`ltx-2.5-latent-temporal-upscaler-x2-bf16-1.0.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/latent_upscale_models/ltx-2.5-latent-temporal-upscaler-x2-bf16-1.0.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/latent_upscale_models/ltx-2.5-latent-temporal-upscaler-x2-bf16-1.0.safetensors)-**Distilled LoRA** - required by the two-stage pipeline implementations that run the full model in stage 1 (all except DistilledPipeline, ICLoraPipeline and DubItPipeline)+**Distilled LoRA** - required by the two-stage pipeline implementations that run the full model in stage 1 (TI2Vid two-stage / HQ, Keyframe, A2Vid; not DistilledPipeline, DFRPipeline, ICLoraPipeline, or DubItPipeline)* [`ltx-2.5-22b-distilled-lora-450-bf16.safetensors`](https://huggingface.co/Lightricks/LTX-2.5/blob/main/loras/ltx-2.5-22b-distilled-lora-450-bf16.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5/resolve/main/loras/ltx-2.5-22b-distilled-lora-450-bf16.safetensors)-**Detailing IC-LoRA** - optional; the 2x spatial detailing LoRA for [`DFRPipeline`](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py)'s refinement stage (`--detailing-lora`). It lives in its own repository, [`LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler`](https://huggingface.co/Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler)+**Detailing IC-LoRA** - required by [`DFRPipeline`](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py)'s refinement stage (`--detailing-lora`). It lives in its own repository, [`LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler`](https://huggingface.co/Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler)* [`ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors`](https://huggingface.co/Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler/blob/main/ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors) - [Download](https://huggingface.co/Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler/resolve/main/ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors)**Duration Head** - optional; lets you omit `--num-frames` and have the clip length predicted from the prompt@@ -109,10 +137,10 @@ See **[LTX-2.3 models](MODELS-LTX-2.3.md)** for the full list.### Available Pipelines-* **[DistilledPipeline](packages/ltx-pipelines/src/ltx_pipelines/distilled.py)** - Fastest inference with 8 predefined sigmas (recommended)-* **[DFRPipeline](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py)** - Detail-fidelity rendering: generated keyframes and a spatial detailing pass, with optional temporal 2x/4x refinement-* **[TI2VidTwoStagesPipeline](packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py)** - Production-quality text/image-to-video with 2x upsampling-* **[TI2VidTwoStagesHQPipeline](packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py)** - Same two-stage flow as above but uses the res_2s second-order sampler (fewer steps, better quality)+* **[DistilledPipeline](packages/ltx-pipelines/src/ltx_pipelines/distilled.py)** - Fastest text/image-to-video (starting point)+* **[DFRPipeline](packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py)** - Production-quality text/image-to-video (slower, more VRAM): same distilled transformer, generated keyframes, spatial detailing, optional 2x/4x fps. How to run: [DFR in Quick Start](#dfr-production-quality) and [Running DFR](packages/ltx-pipelines/docs/pipelines.md#running-dfr)+* **[TI2VidTwoStagesPipeline](packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py)** - Guided two-stage text/image-to-video with CFG/STG and 2x upsampling+* **[TI2VidTwoStagesHQPipeline](packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py)** - Same guided two-stage flow with the res_2s sampler (fewer steps)* **[TI2VidOneStagePipeline](packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py)** - Single-stage generation for quick prototyping* **[ICLoraPipeline](packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py)** - Video-to-video and image-to-video transformations (uses distilled model.)* **[KeyframeInterpolationPipeline](packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py)** - Interpolate between keyframe images@@ -124,7 +152,7 @@ See **[LTX-2.3 models](MODELS-LTX-2.3.md)** for the full list.### ⚡ Optimization Tips-* **Use DistilledPipeline** - Fastest inference with only 8 predefined sigmas (8 steps stage 1, 4 steps stage 2)+* **Use DistilledPipeline for speed** - Fastest inference with only 8 predefined sigmas (8 steps stage 1, 4 steps stage 2). For production quality, use [DFR](#dfr-production-quality) instead.* **Enable FP8 quantization** - Enables lower memory footprint: `--quantization fp8-cast` (CLI) or `quantization=QuantizationPolicy.fp8_cast()` (Python). Fp8-cast should be used with bf16 checkpoints, it shall downcast them on the fly. On Hopper+ GPUs with native FP8 support, use `--quantization fp8-scaled-mm` for FP8 scaled matrix multiplication. Fp8-scaled-mm should be used with fp8 checkpoints.* **Install attention optimizations** - On datacenter Blackwell GPUs (B200), install FlashAttention 4 manually: `uv pip install 'flash-attn-4==4.0.0b9'` (this specific revision is the one we have verified against torch 2.9.1+cu128; newer betas have known issues on consumer Blackwell). On Hopper GPUs, install the FlashAttention 3 wheel. On other CUDA GPUs, PyTorch SDPA is used automatically. An installed backend is selected automatically at runtime; forcing a specific one is a Python-API option (`AttentionFunction.FLASH_ATTENTION_3`/`FLASH_ATTENTION_4`), not a CLI flag.* **Use gradient estimation** - Reduce inference steps from 40 to 20-30 while maintaining quality (see [pipeline documentation](packages/ltx-pipelines/docs/optimization.md#denoising-loop-optimization))diff --git a/packages/ltx-core/README.md b/packages/ltx-core/README.mdindex 752c5b0..3d290b0 100644--- a/packages/ltx-core/README.md+++ b/packages/ltx-core/README.md@@ -438,7 +438,8 @@ Here's how all the components work together conceptually ([`src/ltx_core/compone6. **Unpatchification**: Convert sequence back to spatial format7. **VAE Decoding**: Decode latents to pixel space (with optional upsampling for two-stage)-- [`TI2VidTwoStagesPipeline`](../ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py) - Two-stage text-to-video (recommended)+- [`DFRPipeline`](../ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py) - Production-quality text/image-to-video+- [`TI2VidTwoStagesPipeline`](../ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py) - Guided two-stage text-to-video- [`ICLoraPipeline`](../ltx-pipelines/src/ltx_pipelines/ic_lora.py) - Video-to-video with IC-LoRA control- [`DistilledPipeline`](../ltx-pipelines/src/ltx_pipelines/distilled.py) - Fast inference with distilled model- [`KeyframeInterpolationPipeline`](../ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py) - Keyframe-based interpolationdiff --git a/packages/ltx-core/pyproject.toml b/packages/ltx-core/pyproject.tomlindex 4f8dacc..8254e7e 100644--- a/packages/ltx-core/pyproject.toml+++ b/packages/ltx-core/pyproject.toml@@ -1,12 +1,15 @@[project]name = "ltx-core"-version = "1.2.0"+version = "1.3.0"description = "Core implementation of Lightricks' LTX-2 model"readme = "README.md"requires-python = ">=3.10"dependencies = ["torch~=2.7","torchaudio",+ # Gemma 4's processor imports torchvision; without this, `uv sync --package+ # ltx-pipelines` (no trainer) fails with Could not import Gemma4UnifiedProcessor.+ "torchvision","einops","numpy","av",@@ -37,8 +40,10 @@ natten = [][tool.uv.sources]-torch = { index = "torch" }-torchaudio = { index = "torch-test" }+# macOS: the cu132 indexes ship no darwin wheels, so fall back to PyPI there.+torch = [{ index = "torch", marker = "sys_platform != 'darwin'" }]+torchaudio = [{ index = "torch-test", marker = "sys_platform != 'darwin'" }]+torchvision = [{ index = "torch", marker = "sys_platform != 'darwin'" }]natten = { index = "natten" }[[tool.uv.index]]diff --git a/packages/ltx-core/src/ltx_core/color/yuv.py b/packages/ltx-core/src/ltx_core/color/yuv.pyindex d3185a5..b92c00e 100644--- a/packages/ltx-core/src/ltx_core/color/yuv.py+++ b/packages/ltx-core/src/ltx_core/color/yuv.py@@ -79,17 +79,78 @@ _COLOR_SPACE_MATRICES = {}+# cuBLAS GEMM dims are int32. PyTorch folds ``(F, H*W, 3) @ (3, 3)`` into one+# ``mm`` of size ``F*H*W``, reported as ``n`` in column-major. ``n`` must be+# strictly less than this value (see ``at::cuda::blas::gemm``).+_CUBLAS_INT32_MAX = 2**31 - 1++def _require_rgb_chw(image: torch.Tensor) -> None:if image.ndim < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")+def _max_frames_per_gemm(height: int, width: int) -> int:+ """Largest ``F`` with ``F * H * W < 2**31 - 1``.+ ``int_max // H // W`` is that exclusive upper bound: a GEMM may use strictly+ fewer frames than this so the flattened ``n`` stays below the cuBLAS limit.+ """+ if height <= 0 or width <= 0:+ return _CUBLAS_INT32_MAX+ return _CUBLAS_INT32_MAX // height // width+++def frames_per_yuv_gemm(height: int, width: int) -> int:+ """Frames :func:`rgb_to_yuv` converts per GEMM at ``height x width``.+ Above this many frames it converts in chunks and writes YUV back over the RGB+ storage, so only a chunk-sized temporary is newly allocated. Memory planners+ (see ``diffusion_tiling.emit_convert_bytes``) need that split to size a reserve.+ """+ limit = _max_frames_per_gemm(height, width)+ return 1 if limit <= 1 else limit - 1++def rgb_to_yuv(image: torch.Tensor, color_space: ColorSpace) -> torch.Tensor:- """RGB ``[0, 1]`` ``(*, 3, H, W)`` → YUV ``(*, 3, H, W)``."""+ """RGB ``[0, 1]`` ``(*, 3, H, W)`` → YUV ``(*, 3, H, W)``.+ Long clips are converted in frame chunks of size ``< (2**31 - 1) // H // W``+ so each 3x3 GEMM stays inside cuBLAS int32. When chunking, YUV is written+ back over the RGB storage; otherwise chunks are concatenated.+ """_require_rgb_chw(image)mat = _COLOR_SPACE_MATRICES[color_space].to(device=image.device, dtype=image.dtype)- pixels = image.movedim(-3, -1)- return (pixels @ mat.T).movedim(-1, -3)+ orig_shape = image.shape+ height, width = orig_shape[-2], orig_shape[-1]+ frames = image.reshape(-1, 3, height, width)+ n_frames = frames.shape[0]+ limit = _max_frames_per_gemm(height, width)+ if limit < 1:+ raise ValueError(+ f"Frame {height}x{width} exceeds the cuBLAS int32 GEMM limit "+ f"({_CUBLAS_INT32_MAX}); cannot convert even one frame."+ )+ # Strictly fewer than ``int_max // H // W`` so ``F*H*W < 2**31 - 1``.+ chunk_f = 1 if limit == 1 else limit - 1++ def _gemm(rgb: torch.Tensor) -> torch.Tensor:+ pixels = rgb.movedim(-3, -1)+ yuv = pixels.flatten(-3, -2) @ mat.T+ return yuv.unflatten(-2, (height, width)).movedim(-1, -3)++ if n_frames <= chunk_f:+ return _gemm(frames).reshape(orig_shape)++ # Overwrite RGB in place when ``reshape`` is a view; otherwise collect.+ writeback = frames.untyped_storage().data_ptr() == image.untyped_storage().data_ptr()+ chunks: list[torch.Tensor] = []+ for start in range(0, n_frames, chunk_f):+ yuv = _gemm(frames[start : start + chunk_f])+ if writeback:+ frames[start : start + chunk_f].copy_(yuv)+ else:+ chunks.append(yuv)+ if writeback:+ return frames.reshape(orig_shape)+ return torch.cat(chunks, dim=0).reshape(orig_shape)def apply_color_range_(diff --git a/packages/ltx-core/src/ltx_core/devices.py b/packages/ltx-core/src/ltx_core/devices.pyindex 3e4af2f..faf0665 100644--- a/packages/ltx-core/src/ltx_core/devices.py+++ b/packages/ltx-core/src/ltx_core/devices.py@@ -100,6 +100,44 @@ def cuda_activation_budget_bytes(device: DeviceSpec = None) -> int:return min(int(free_raw), under_fraction)+def mps_activation_budget_bytes(device: DeviceSpec = None) -> int:+ """Bytes still available for new MPS allocations in this process.+ ``recommended_max_memory`` is Metal's recommended working-set size, which is+ below physical RAM (unified memory is shared with the rest of the system), so it+ is the conservative ceiling to plan against. ``driver_allocated_memory`` -- not+ ``current_allocated_memory`` -- is subtracted because it counts blocks the+ allocator is holding in its cache, mirroring the CUDA path's use of+ ``memory_reserved``.+ Unlike the CUDA ceiling this one is advisory: exceeding Metal's recommendation+ degrades to swapping rather than raising, so callers get a budget that errs+ small instead of a hard limit.+ """+ if not is_mps_available():+ return 0+ if resolve_device(device).type != "mps":+ return 0+ recommended = int(torch.mps.recommended_max_memory())+ allocated = int(torch.mps.driver_allocated_memory())+ return max(0, recommended - allocated)+++def activation_budget_bytes(device: DeviceSpec = None) -> int:+ """Bytes available for new activations on *device*, across backends.+ Use this rather than the per-backend helpers when sizing work to fit in memory+ (e.g. DiffVAE decode tiling): a CUDA-only probe silently yields a zero budget+ elsewhere, which reads as "nothing fits" instead of "unknown".+ Returns 0 on CPU. Host RAM is not probed, so callers that support CPU execution+ must treat 0 as "no budget information" and pick their own fallback rather than+ concluding that no work fits.+ """+ resolved = resolve_device(device)+ if resolved.type == "cuda":+ return cuda_activation_budget_bytes(resolved)+ if resolved.type == "mps":+ return mps_activation_budget_bytes(resolved)+ return 0++def cleanup_accelerator_memory(device: DeviceSpec = None) -> None:"""Run Python GC and release CUDA/MPS allocator caches."""gc.collect()diff --git a/packages/ltx-core/src/ltx_core/modality_tiling.py b/packages/ltx-core/src/ltx_core/modality_tiling.pyindex c269b97..f5ecf5c 100644--- a/packages/ltx-core/src/ltx_core/modality_tiling.py+++ b/packages/ltx-core/src/ltx_core/modality_tiling.py@@ -8,15 +8,28 @@ primitives are required.from __future__ import annotations+import logging+from collections.abc import Sequencefrom dataclasses import dataclass, replace+from functools import partialimport torchfrom ltx_core.model.transformer.modality import Modality-from ltx_core.tiling import Tile, TileCountConfig, create_tiles, identity_mapping_operation+from ltx_core.tiling import (+ DimensionTilingConfig,+ SplitOperation,+ Tile,+ TileCountConfig,+ create_tiles,+ identity_mapping_operation,+ split_at_seams,+)from ltx_core.tools import VideoLatentToolsfrom ltx_core.types import VideoLatentShape+logger = logging.getLogger(__name__)+@dataclass(frozen=True)class TilingContext:@@ -35,12 +48,43 @@ class TilingContext:there are no conditioning tokens."""+def seam_split(+ seams: Sequence[int],+ latent_frames: int,+ frames: DimensionTilingConfig,+) -> SplitOperation | None:+ """A temporal split cut on ``seams``, or ``None`` when they cannot carry one.+ ``seams`` are interior latent-frame indices supplied by the caller. A boundary there needs no+ blending: the overlap is denoised for context and dropped (:func:`~ltx_core.tiling.split_at_seams`).+ Leftover segments go to the leading tiles. Missing or non-interior seams fall back to the+ requested overlap split, which blends.+ """+ if frames.num_tiles < 2:+ return None+ interior = sorted({cell for cell in seams if 0 < cell < latent_frames - 1})+ if not interior:+ if seams:+ logger.info(+ "Temporal tiling: seams %s are not interior to %d latent frames; keeping blended tiles",+ list(seams),+ latent_frames,+ )+ return None+ boundaries = [0, *interior, latent_frames - 1]+ logger.info("Temporal tiling: %d tiles cut on seams %s", frames.num_tiles, boundaries)+ return split_at_seams(boundaries, frames.num_tiles, overlap=frames.overlap)++class VideoModalityTilingHelper:"""Stateless helper that tiles and blends video :class:`Modality` sequences.Constructed once with a :class:`TileCountConfig` and:class:`VideoLatentTools`. Tiles are computed at construction andavailable via the :attr:`tiles` property. Use :meth:`tile_modality`and :meth:`blend` with any tile from that list.+ Passing ``seams`` (interior latent-frame indices) lets a temporal split land on those+ cells instead of blended overlaps (:func:`seam_split`); leftover segments go to the+ leading tiles. Missing or non-interior seams keep the blended split. A regular keyframe+ belongs in that list only at strength 0; generated keyframe slots never do.Usage::helper = VideoModalityTilingHelper(tiling, video_tools)for tile in helper.tiles:@@ -49,14 +93,24 @@ class VideoModalityTilingHelper:helper.blend(result, tile, ctx, output=output)"""- def __init__(self, tiling: TileCountConfig, video_tools: VideoLatentTools) -> None:+ def __init__(+ self,+ tiling: TileCountConfig,+ video_tools: VideoLatentTools,+ seams: Sequence[int] = (),+ ) -> None:self._patchifier = video_tools.patchifierself._latent_shape = video_tools.target_shapeself._num_generated_tokens = self._patchifier.get_token_count(self._latent_shape)+ frames, height, width = tiling.to_splitters(video_tools.scale_factors, causal_temporal=False)+ frames_mapper = identity_mapping_operation+ seam_op = seam_split(seams, self._latent_shape.frames, tiling.frames)+ if seam_op is not None:+ frames, frames_mapper = seam_op, partial(identity_mapping_operation, rectangular=True)self._tiles = create_tiles(torch.Size([self._latent_shape.frames, self._latent_shape.height, self._latent_shape.width]),- splitters=list(tiling.to_splitters(video_tools.scale_factors, causal_temporal=False)),- mappers=[identity_mapping_operation] * 3,+ splitters=[frames, height, width],+ mappers=[frames_mapper, identity_mapping_operation, identity_mapping_operation],)@propertydiff --git a/packages/ltx-core/src/ltx_core/model/transformer/compiling.py b/packages/ltx-core/src/ltx_core/model/transformer/compiling.pyindex f312436..aa4d2dd 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/compiling.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/compiling.py@@ -44,6 +44,26 @@ class CompilationConfig:# than reduce-overhead's 48-block cudagraph tree. Requires GPU-resident weights# (keeps_gpu_resident_weights).capture: bool = False+ # Largest video / audio token count the job denoises, used ONLY under `capture` to size the+ # static input buffers every CUDA-graph capture shares, so their cost is that of the largest+ # shape instead of the sum over shapes. Counts are per rank and taken as given: whatever a+ # multi-GPU split (sequence parallel, TDP) leaves this rank with, overlap included -- in a+ # single-GPU run, the whole thing. 0 gives each capture private static buffers; set only the+ # modalities the job actually denoises (a modality that shows up without a budget raises).+ max_video_tokens: int = 0+ max_audio_tokens: int = 0++ def __post_init__(self) -> None:+ # A budget only reaches the buffer pool as an allocation size, where a negative or fractional+ # count fails as an opaque bad-size error well after the config was written.+ for name in ("max_video_tokens", "max_audio_tokens"):+ budget = getattr(self, name)+ if not isinstance(budget, int) or budget < 0:+ raise ValueError(+ f"CompilationConfig.{name} must be a non-negative token count, got {budget!r}. "+ f"Set it to the largest count this rank denoises, or leave it 0 to give each "+ f"capture its own static buffers."+ )class CompiledBlockPerturbationsProcessor(BlockPerturbationsProcessor):@@ -200,7 +220,12 @@ def compile_transformer_captured(model: LTXModel, config: CompilationConfig) ->with _compile_config_patches(config):return original_block_loop(video, audio, perturbations)- model._process_transformer_blocks = CudaGraphRunner(patched_block_loop, model.block_input_processor)+ model._process_transformer_blocks = CudaGraphRunner(+ patched_block_loop,+ model.block_input_processor,+ max_video_tokens=config.max_video_tokens,+ max_audio_tokens=config.max_audio_tokens,+ )return modeldiff --git a/packages/ltx-core/src/ltx_core/model/transformer/cudagraph_capture.py b/packages/ltx-core/src/ltx_core/model/transformer/cudagraph_capture.pyindex 6f3adbd..25f55c6 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/cudagraph_capture.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/cudagraph_capture.py@@ -1,6 +1,9 @@"""Self-managed CUDA-graph capture of the transformer block loop.Captures ``_process_transformer_blocks`` as one CUDA graph per (shape, perturbation signature)and replays it from persistent static buffers. RoPE prepare / output projection stay eager.+Given a max token count per modality, captures across all runners share static input buffers sized+for that count (see :class:`_InputBufferPool`). Their cost is therefore bounded by the largest+shape, rather than growing with the number of captured shapes or runners.Not thread-safe: :class:`CudaGraphRunner` (including the shared graph mempool) assumes a singlecaller; concurrent capture/replay is unsupported."""@@ -8,6 +11,7 @@ caller; concurrent capture/replay is unsupported.from __future__ import annotationsimport dataclasses+import mathfrom collections.abc import Callable, Hashablefrom typing import TYPE_CHECKING@@ -35,10 +39,10 @@ _CaptureKey = tuple[_ShapeKey, Hashable]@dataclasses.dataclassclass _Capture:graph: torch.cuda.CUDAGraph- # Persistent static buffers the graph reads/writes. Inputs are copied in, outputs cloned out.- static_video: TransformerArgs | None- static_audio: TransformerArgs | None- static_perturbations: BatchedPerturbationConfig # wraps the static block_masks buffer read in-graph+ video_pool: _InputBufferPool+ audio_pool: _InputBufferPool+ perturbations_pool: _InputBufferPool+ # Outputs live in the shared CUDA graph mempool, not in the static input buffer pools above.static_video_out: TransformerArgs | Nonestatic_audio_out: TransformerArgs | None@@ -48,39 +52,108 @@ def _shape_key(video: TransformerArgs | None, audio: TransformerArgs | None, bloreturn tuple(tuple(t.shape) for t in tensors if isinstance(t, torch.Tensor))-def _clone_value(value: object) -> object:- """Clone a ``TransformerArgs`` field. Tensors and the rope ``(cos, sin)`` tuples are copied;- bools and ``None`` are immutable and shared as-is."""- if isinstance(value, torch.Tensor):- return value.clone()- if isinstance(value, tuple):- return tuple(t.clone() for t in value)- return value[email protected](frozen=True)+class _BufferKey:+ """Identity of one allocation in an input buffer pool.+ ``field`` is a ``TransformerArgs`` field such as ``x`` or ``positional_embeddings.0``.+ """++ field: str+ shape: tuple[int, ...]+ dtype: torch.dtype+ device: torch.device-def _copy_value(dst: object, src: object) -> None:- """Copy ``src`` into ``dst`` in place. Non-tensor fields (bools/None) are baked into the captured- graph and need no copy; tensors and the rope ``(cos, sin)`` tuples are copied element-wise."""- if isinstance(dst, torch.Tensor):- dst.copy_(src, non_blocking=True)- elif isinstance(dst, tuple):- for d, s in zip(dst, src, strict=True):- d.copy_(s, non_blocking=True)+class _InputBufferPool:+ """Own static input buffers shared by CUDA-graph captures.+ Each key maps to one flat allocation sized for a field at its token budget. Captures of smaller+ shapes use contiguous prefixes of that allocation. This is safe because every replay first+ overwrites its inputs.+ The budget shape is part of the key, so genuinely different footprints (for example,+ key-only and dense attention masks) receive separate allocations. Allocations never move after+ creation because captured graphs retain their addresses.+ """++ def __init__(self, max_tokens: int | None = None) -> None:+ self._max_tokens = max_tokens+ self._buffers: dict[_BufferKey, torch.Tensor] = {}+ @property+ def max_tokens(self) -> int | None:+ return self._max_tokens-def _clone_args(args: TransformerArgs | None) -> TransformerArgs | None:- """Clone args into fresh persistent buffers -- the one-time static-INPUT allocation in ``_capture``."""- if args is None:- return None- return dataclasses.replace(args, **{f.name: _clone_value(getattr(args, f.name)) for f in dataclasses.fields(args)})+ def _max_shape(self, shape: torch.Size, tokens: int | None, *, spans_sequence: bool) -> tuple[int, ...]:+ """Return the tensor shape at this pool's token limit.+ For ordinary ``TransformerArgs`` fields, dimensions equal to the current token count are+ sequence dimensions and grow to ``max_tokens``. ``self_attention_mask`` is different under+ sequence parallelism: ``x`` contains a local token shard while the mask spans the global+ sequence on every rank, so its dimensions after batch and head are scaled by the token+ ratio instead. ``tokens=None`` marks inputs with no token dimension, such as block masks.+ """+ if tokens is None:+ return tuple(shape)+ max_tokens = self.max_tokens or tokens+ if spans_sequence:+ batch_and_heads = shape[:2]+ sequence = (+ -(-dim * max_tokens // tokens) if dim > 1 else dim # ceil, so rounded-up shards fit+ for dim in shape[2:]+ )+ return (*batch_and_heads, *sequence)+ return tuple(max_tokens if dim == tokens else dim for dim in shape)+ def _get_buffer(self, field: str, template: torch.Tensor, max_shape: tuple[int, ...]) -> torch.Tensor:+ """Get a view shaped like ``template``, allocating its buffer on first use.+ Reshaping a flat prefix preserves canonical contiguous strides. Slicing a preallocated+ ``(B, T_max, D)`` tensor along its sequence dimension would not.+ """+ key = _BufferKey(field, max_shape, template.dtype, template.device)+ buffer = self._buffers.get(key)+ if buffer is None:+ buffer = torch.empty(math.prod(max_shape), dtype=template.dtype, device=template.device)+ self._buffers[key] = buffer+ if template.numel() > buffer.numel():+ raise ValueError(+ f"CUDA-graph static buffer {field!r} was sized for {max_shape} but this capture "+ f"supplies {tuple(template.shape)}, which does not fit. The buffers are sized by "+ f"the configured token budget and cannot grow without invalidating the graphs "+ f"already captured -- raise CompilationConfig.max_video_tokens / max_audio_tokens "+ f"to the largest count this rank denoises."+ )+ return buffer[: template.numel()].view(template.shape)++ def copy_value_to_buffer(+ self, field: str, value: object, tokens: int | None, *, spans_sequence: bool = False+ ) -> object:+ """Copy a field into pool storage and return its static representation."""+ if isinstance(value, torch.Tensor):+ static = self._get_buffer(field, value, self._max_shape(value.shape, tokens, spans_sequence=spans_sequence))+ static.copy_(value)+ return static+ if isinstance(value, tuple):+ return tuple(self.copy_value_to_buffer(f"{field}.{i}", t, tokens) for i, t in enumerate(value))+ return value++ def copy_args_to_buffers(self, args: TransformerArgs) -> TransformerArgs:+ """Copy ``TransformerArgs`` fields into persistent buffers."""+ tokens = int(args.x.shape[1])+ return dataclasses.replace(+ args,+ **{+ f.name: self.copy_value_to_buffer(+ f.name,+ getattr(args, f.name),+ tokens,+ spans_sequence=f.name == "self_attention_mask",+ )+ for f in dataclasses.fields(args)+ },+ )-def _copy_args(dst: TransformerArgs | None, src: TransformerArgs | None) -> None:- """Copy ``src``'s tensors into ``dst``'s persistent static buffers, field by field, in place."""- if dst is None:- return- for f in dataclasses.fields(dst):- _copy_value(getattr(dst, f.name), getattr(src, f.name))+ def copy_perturbations_to_buffers(self, perturbations: BatchedPerturbationConfig) -> BatchedPerturbationConfig:+ static_block_masks = self.copy_value_to_buffer("block_masks", perturbations.block_masks, tokens=None)+ assert isinstance(static_block_masks, torch.Tensor)+ return BatchedPerturbationConfig.from_masks(static_block_masks, perturbations.block_masks_cpu)class CudaGraphRunner:@@ -90,6 +163,10 @@ class CudaGraphRunner:copied into the static inputs, the graph replayed, and the static OUTPUT buffers returneddirectly (standard CUDA-graph idiom -- the caller reads them, via the eager output projection,before the next replay overwrites them).+ Perturbation inputs always use a process-wide :class:`_InputBufferPool`. With+ ``max_video_tokens`` / ``max_audio_tokens``, modality inputs also use process-wide pools sized+ for those per-rank limits. Without a modality budget, each capture owns a private pool sized for+ its input shape.Not thread-safe. Capture dict mutation, static-buffer copy-in/out, and the class-level sharedmempool all assume a single-threaded caller; do not share a runner (or concurrent first-timecaptures across runners) across threads.@@ -97,9 +174,18 @@ class CudaGraphRunner:# Shared mempool across runners so captures reuse intermediate memory (lazy init; not locked)._shared_pool: _POOL_HANDLE | None = None+ # Budgeted static inputs are process-wide, like the graph mempool (lazy init; not locked).+ _shared_video_pool: _InputBufferPool | None = None+ _shared_audio_pool: _InputBufferPool | None = None+ _shared_perturbations_pool = _InputBufferPool()def __init__(- self, block_loop_fn: _BlockLoopFn, block_input_processor: BlockPerturbationsProcessor, warmup_iters: int = 3+ self,+ block_loop_fn: _BlockLoopFn,+ block_input_processor: BlockPerturbationsProcessor,+ warmup_iters: int = 3,+ max_video_tokens: int = 0,+ max_audio_tokens: int = 0,) -> None:self._block_loop = block_loop_fn# Keys the capture on the block's perturbation graph signature -- the SAME processor the@@ -108,6 +194,16 @@ class CudaGraphRunner:self._block_input_processor = block_input_processorself._warmup_iters = warmup_itersself._captures: dict[_CaptureKey, _Capture] = {}+ self._max_video_tokens = max_video_tokens+ self._max_audio_tokens = max_audio_tokens+ if max_video_tokens:+ CudaGraphRunner._shared_video_pool = self._configure_shared_input_pool(+ CudaGraphRunner._shared_video_pool, max_video_tokens+ )+ if max_audio_tokens:+ CudaGraphRunner._shared_audio_pool = self._configure_shared_input_pool(+ CudaGraphRunner._shared_audio_pool, max_audio_tokens+ )def __call__(self, video: TransformerArgs | None, audio: TransformerArgs | None, perturbations: BatchedPerturbationConfig@@ -118,10 +214,12 @@ class CudaGraphRunner:cap = self._capture(video, audio, perturbations) # static inputs already hold this call's valuesself._captures[key] = capelse:- # Copy this call's inputs into the static buffers the graph reads.- _copy_args(cap.static_video, video)- _copy_args(cap.static_audio, audio)- cap.static_perturbations.block_masks.copy_(perturbations.block_masks, non_blocking=True)+ # Rebind this call to the same pool buffers used during capture.+ if video is not None:+ cap.video_pool.copy_args_to_buffers(video)+ if audio is not None:+ cap.audio_pool.copy_args_to_buffers(audio)+ cap.perturbations_pool.copy_perturbations_to_buffers(perturbations)# Always replay (even right after capture); never return the capture-run outputs.cap.graph.replay()return cap.static_video_out, cap.static_audio_out@@ -135,15 +233,28 @@ class CudaGraphRunner:shape = _shape_key(video, audio, perturbations.block_masks)return shape, self._block_input_processor.graph_signature(perturbations)+ @staticmethod+ def _configure_shared_input_pool(pool: _InputBufferPool | None, max_tokens: int) -> _InputBufferPool:+ if pool is None:+ return _InputBufferPool(max_tokens)+ if pool.max_tokens != max_tokens:+ raise ValueError(+ f"Shared input pool is already sized for {pool.max_tokens} tokens, "+ f"but another CUDA-graph runner requested {max_tokens}."+ )+ return pool+def _capture(self, video: TransformerArgs | None, audio: TransformerArgs | None, perturbations: BatchedPerturbationConfig) -> _Capture:- static_video = _clone_args(video)- static_audio = _clone_args(audio)- # Device masks are in-graph inputs; host mirror feeds eager any/all during warmup (may be None).- static_perturbations = BatchedPerturbationConfig.from_masks(- perturbations.block_masks.clone(), perturbations.block_masks_cpu- )+ video_pool = self._shared_video_pool if self._max_video_tokens else _InputBufferPool()+ audio_pool = self._shared_audio_pool if self._max_audio_tokens else _InputBufferPool()+ perturbations_pool = self._shared_perturbations_pool++ static_video = video_pool.copy_args_to_buffers(video) if video is not None else None+ static_audio = audio_pool.copy_args_to_buffers(audio) if audio is not None else None+ static_perturbations = perturbations_pool.copy_perturbations_to_buffers(perturbations)+# Warmup on a side stream so any (first-shape) Dynamo/Inductor compile, autotune, cuBLAS# workspace, and IPC-kernel residency land OUTSIDE the capture. All ranks run this lockstep.side = torch.cuda.Stream()@@ -154,14 +265,23 @@ class CudaGraphRunner:torch.cuda.current_stream().wait_stream(side)torch.cuda.synchronize()torch._C._cuda_clearCublasWorkspaces() # avoid double-counting cuBLAS workspace into the pool+# Restore this call's inputs (warmup may have written into the static buffers) so the capture# records with correct values and the post-capture replay yields this call's output.- _copy_args(static_video, video)- _copy_args(static_audio, audio)- static_perturbations.block_masks.copy_(perturbations.block_masks, non_blocking=True)+ static_video = video_pool.copy_args_to_buffers(video) if video is not None else None+ static_audio = audio_pool.copy_args_to_buffers(audio) if audio is not None else None+ static_perturbations = perturbations_pool.copy_perturbations_to_buffers(perturbations)if CudaGraphRunner._shared_pool is None:CudaGraphRunner._shared_pool = torch.cuda.graph_pool_handle()graph = torch.cuda.CUDAGraph()with torch.cuda.graph(graph, pool=CudaGraphRunner._shared_pool, capture_error_mode="global"):video_out, audio_out = self._block_loop(static_video, static_audio, static_perturbations)- return _Capture(graph, static_video, static_audio, static_perturbations, video_out, audio_out)++ return _Capture(+ graph=graph,+ video_pool=video_pool,+ audio_pool=audio_pool,+ perturbations_pool=perturbations_pool,+ static_video_out=video_out,+ static_audio_out=audio_out,+ )diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py b/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.pyindex ebc98e8..93693c2 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py@@ -3,6 +3,7 @@from __future__ import annotationsimport logging+from collections.abc import Sequencefrom typing import Any, Iterator, List, Tupleimport torch@@ -16,11 +17,13 @@ from ltx_core.model.transformer.timestep_embedding import PixArtAlphaCombinedTimfrom ltx_core.model.video_vae.attention import AttnBlock3Dfrom ltx_core.model.video_vae.convolution import make_conv_ndfrom ltx_core.model.video_vae.enums import NormLayerType, PaddingModeType+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.ops import PerChannelStatistics, unpatchifyfrom ltx_core.model.video_vae.resnet import ResnetBlock3D, UNetMidBlock3Dfrom ltx_core.model.video_vae.sampling import DepthToSpaceUpsamplefrom ltx_core.model.video_vae.video_vae import (VideoDecoder,+ iter_decoded_single_frames,map_spatial_slice,map_temporal_slice,to_mapping_operation,@@ -488,11 +491,23 @@ class ConvVideoDecoder(nn.Module, Disposable, VideoDecoder):latent: torch.Tensor,tiling_config: TilingConfig | None = None,generator: torch.Generator | None = None,+ *,+ keyframes: DecodeKeyframes | None = None,) -> Iterator[torch.Tensor]:"""Decode a video latent tensor, yielding float chunks ``[f, h, w, c]`` in ``[0, 1]``.Subclasses (e.g. ``DistributedVideoDecoder``) may override this tocontrol eagerness or distribution across ranks.+ ``keyframes`` is accepted for signature parity with the diffusion decoder and ignored:+ anchoring on keyframe planes is a diffusion-decode feature. Ignoring is deliberate --+ raising would mean every caller has to branch on which VAE it was handed -- but it is+ logged, because a silent drop looks exactly like a keyframe decode that did nothing."""+ if keyframes is not None:+ logger.warning(+ "Conv video decoder ignores the %d keyframe plane(s) it was given; keyframe-anchored "+ "decoding needs a diffusion VAE. Decoding without them.",+ keyframes.num_planes,+ )def to_rgb(frames: torch.Tensor) -> torch.Tensor:video = rearrange(frames[0], "c f h w -> f h w c")@@ -505,6 +520,14 @@ class ConvVideoDecoder(nn.Module, Disposable, VideoDecoder):decoded = self(latent, generator=generator)yield to_rgb(decoded)+ def decode_single_frames(+ self,+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,+ ) -> Iterator[torch.Tensor]:+ """Decode each latent as its own one-frame clip, yielding one RGB tensor per latent."""+ yield from iter_decoded_single_frames(self, latents, generator)+def _accumulate_temporal_group_into_buffer(self,group_tiles: List[Tile],diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_tiling.py b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_tiling.pyindex db9242c..3f9523e 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_tiling.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_tiling.py@@ -12,6 +12,7 @@ from typing import List, Literal, Sequence, Tupleimport torch+from ltx_core.color.yuv import frames_per_yuv_gemmfrom ltx_core.model.video_vae.transformer.apply import resolve_attention_for_hostfrom ltx_core.model.video_vae.transformer.config import DiffVAEMode, NAttentionKindfrom ltx_core.tiling import (@@ -31,6 +32,8 @@ from ltx_core.types import VIDEO_SCALE_FACTORS, SpatioTemporalScaleFactorsResizeAxisMode = Literal["repeat_last", "symmetric"]+_GIB: int = 1 << 30+# Peak-activation heuristic (bytes):# hard (resident for whole tiled decode):# stage-4 input feature (stages 1-3 output): s4_txs4_hxs4_wxstage4_channelsxbf16@@ -41,44 +44,164 @@ ResizeAxisMode = Literal["repeat_last", "symmetric"]# matches decode: fp16 when features are bf16, else feature dtype)# stage-5: stage5_tokens x stage5_channels x bf16 x coef# where stage5_tokens = F x (H/patch) x (W/patch) and coef folds NA working-set multiplicity.-_MEM_COEF_BY_MODE: dict[DiffVAEMode, float] = {- DiffVAEMode.COMBINED_COMPILE: 11,- DiffVAEMode.CHUNKED_COMPILE: 7, # natten backend; Triton/eager use CHUNKED_EAGER- DiffVAEMode.CHUNKED_EAGER: 5,- DiffVAEMode.BLACKWELL_DSL: 2.5,+++@dataclass(frozen=True, slots=True)+class _StageFiveBudget:+ """One mode's stage-5 multiplicity and withheld reserve, with and without keyframes."""++ coef: float+ coef_keyframes: float+ reserve_bytes: int+++# Keyframe decode is *not* compiled: ``compile_diffusion_decoder`` wraps ``forward_attn_mlp`` /+# ``forward_combined``, while the keyframe pathway runs ``*_with_keyframes``. So with keyframes the+# diff blocks are eager whatever the mode asked for, and the budget follows the block shape rather+# than the compile setting:+# - chunked: eager already, so keyframes change nothing (5) and CHUNKED_COMPILE's 7 -- which buys+# its extra headroom from Inductor fusing the attn+mlp region -- falls back to 5.+# - combined: keeps its combined ``context_and_x`` buffer and full-volume attention, but without+# the fusion it holds several live full-volume intermediates instead of one Inductor buffer,+# measured as 11 -> 15.+# - BLACKWELL_DSL: the CuTe kernel has its own joint entry point, so the fused path serves+# keyframes too and nothing changes.+_BUDGET_BY_MODE: dict[DiffVAEMode, _StageFiveBudget] = {+ DiffVAEMode.COMBINED_COMPILE: _StageFiveBudget(coef=11, coef_keyframes=15, reserve_bytes=2 * _GIB),+ DiffVAEMode.CHUNKED_COMPILE: _StageFiveBudget(coef=7, coef_keyframes=5, reserve_bytes=2 * _GIB),+ DiffVAEMode.CHUNKED_EAGER: _StageFiveBudget(coef=5, coef_keyframes=5, reserve_bytes=1 * _GIB),+ DiffVAEMode.BLACKWELL_DSL: _StageFiveBudget(coef=2.5, coef_keyframes=2.5, reserve_bytes=2 * _GIB),}_DEFAULT_ELEMENT_SIZE: int = 2 # bf16 features → fp16 accumulator / bf16 stage-5_ACCUMULATOR_CHANNELS: int = 3 # RGB pixel blend buffer (decoder out_channels)_MIN_MODEL_BYTES_FLOOR: int = 1 << 30 # never assume a free DiffVAE weight footprint-_BUDGET_SAFETY_BYTES_EAGER: int = 1 << 30-_BUDGET_SAFETY_BYTES_COMPILED: int = 2 << 30+_BUDGET_SAFETY_BYTES_EAGER: int = 1 * _GIB+#: Keyframe decode runs eager blocks, so it takes the eager reserve -- unless the joint attention+#: ends up on torch's MATH SDPA kernel, which materializes its score block and wants one more GiB.+_BUDGET_SAFETY_BYTES_JOINT_MATERIALIZED: int = 2 * _GIB++def _falls_back_to_eager_na(mode: DiffVAEMode) -> bool:+ """True when this host has no natten and the mode's NA remaps to Triton/eager.+ For chunked modes that remap also switches ``compile_blocks`` off, so the peak is the eager+ one; :func:`resolve_attention_for_host` is the single owner of that decision.+ """+ resolved = resolve_attention_for_host(mode.resolve())+ return resolved.attention in (NAttentionKind.TRITON, NAttentionKind.EAGER_SDPA) and not resolved.compile_blocks-def stage5_mem_coef(mode: DiffVAEMode) -> float:++def stage5_mem_coef(mode: DiffVAEMode, *, keyframes: bool = False) -> float:"""Stage-5 working-set multiplicity for auto tiling, after host NA resolve.- ``CHUNKED_COMPILE``'s coef 7 assumes natten. When the host remaps chunked- modes to Triton/eager fallback, use the ``CHUNKED_EAGER`` coef (5) instead.- ``COMBINED_COMPILE`` requires natten and keeps coef 11.+ Args:+ mode: the decode preset.+ keyframes: whether this decode carries a keyframe stream, which runs eager blocks."""try:- base = _MEM_COEF_BY_MODE[mode]+ budget = _BUDGET_BY_MODE[mode]except KeyError as exc:raise ValueError(f"Unsupported DiffVAEMode for tiling budget: {mode!r}") from exc- resolved = resolve_attention_for_host(mode.resolve())- if resolved.attention in (NAttentionKind.TRITON, NAttentionKind.EAGER_SDPA):- return _MEM_COEF_BY_MODE[DiffVAEMode.CHUNKED_EAGER]- return base+ if keyframes:+ return budget.coef_keyframes+ if _falls_back_to_eager_na(mode):+ return _BUDGET_BY_MODE[DiffVAEMode.CHUNKED_EAGER].coef+ return budget.coef+++# Peak of the SDR encode sink, per emitted pixel, on top of the chunk itself (which the+# accumulator term already covers). Measured at 11.50 B/px for bf16 RGB at 3840x2176.+# Two peaks compete, and which one wins depends on whether ``rgb_to_yuv`` converts the+# chunk in one GEMM or in write-back chunks (see ``color.yuv.frames_per_yuv_gemm``):+# one GEMM (chunk <= limit) a full new YUV tensor, kept alive afterwards by the+# ``y`` view into it+# write-back (chunk > limit) YUV overwrites the RGB storage the accumulator already+# charges, so only a GEMM-sized temporary is new+# On top of that, both paths allocate ``uv_full`` (2 ch, freed before the pack), the+# pooled 4:2:0 ``uv`` (0.5 ch), and then in ``pack_i420`` a concatenated float plane+# (1.5 ch) plus its uint8 copy (1.5 B/px, which does not scale with dtype).+# Halves are carried doubled so the arithmetic stays integral.+_CONVERT_PEAK_UV_CHANNELS_X2 = 5 # uv_full (2) + pooled uv (0.5)+_PACK_PEAK_UV_CHANNELS_X2 = 4 # pooled uv (0.5) + packed float (1.5)+_PACK_PEAK_UINT8_BYTES_X2 = 3 # 1.5 B/px+++def max_emitted_frames(*, num_frames: int, tile_frames: int, overlap_frames: int) -> int:+ """Longest chunk the tiled decode yields, in pixel frames.+ ``_decode_groups_with_keyframes`` yields only a group's *exclusive* span -- one+ stride -- and keeps the trailing overlap as a stub for the next group. Only the+ final group yields its whole buffer. Charging ``tile_frames`` for every chunk+ therefore roughly doubles the estimate on long clips, which blocks layouts that+ would have fit. ``+1`` covers the causal shift, which moves each group after the+ first back by one frame.+ """+ if tile_frames >= num_frames:+ return num_frames+ stride = tile_frames - overlap_frames+ if stride <= 0:+ return tile_frames+ n_tiles = 1 + -(-(num_frames - tile_frames) // stride)+ last_group = num_frames - (n_tiles - 1) * stride+ return min(tile_frames, max(stride, last_group + 1))-def budget_safety_bytes(mode: DiffVAEMode) -> int:- """Extra bytes withheld from the recommend budget (eager 1 GiB, compiled 2 GiB)."""- if mode is DiffVAEMode.CHUNKED_EAGER:- return _BUDGET_SAFETY_BYTES_EAGER- # Chunked compile that remaps to fallback NA is effectively eager for peak VRAM.- resolved = resolve_attention_for_host(mode.resolve())- if resolved.attention in (NAttentionKind.TRITON, NAttentionKind.EAGER_SDPA):+def emit_convert_bytes(+ *,+ tile_frames: int,+ height: int,+ width: int,+ out_channels: int,+ element_size: int,+) -> int:+ """Downstream bytes a yielded chunk costs while the encoder consumes it.+ The decode budget alone is not enough to size a tile: whatever ``_emit`` yields is+ handed straight to the video encoder, and that peak overlaps the decode because the+ decoder is a generator -- it stays suspended holding stage-4 features and the+ accumulator while the consumer converts the chunk it just yielded. A layout that+ decodes comfortably can therefore still die in the encoder, and because the+ recommender spends spare VRAM on *larger* temporal tiles, more free memory used to+ make that failure more likely rather than less.+ ``out_channels`` is the width of the intermediate **YUV** tensor, not a second copy+ of the emitted RGB: the chunk itself is charged by the accumulator term. On the+ write-back path YUV lands in that same RGB storage, so it is not charged here at all+ and only the GEMM temporary is.+ """+ frames = int(tile_frames)+ gemm_frames = min(frames, frames_per_yuv_gemm(height, width))+ # Write-back reuses the RGB storage, so no full YUV tensor survives into the pack.+ resident_yuv_frames = frames if gemm_frames == frames else 0+ yuv_channels_x2 = 2 * int(out_channels)++ convert_peak_x2 = element_size * (yuv_channels_x2 * gemm_frames + _CONVERT_PEAK_UV_CHANNELS_X2 * frames)+ pack_peak_x2 = (+ element_size * (yuv_channels_x2 * resident_yuv_frames + _PACK_PEAK_UV_CHANNELS_X2 * frames)+ + _PACK_PEAK_UINT8_BYTES_X2 * frames+ )++ return int(height) * int(width) * max(convert_peak_x2, pack_peak_x2) // 2+++def budget_safety_bytes(+ mode: DiffVAEMode,+ *,+ keyframes: bool = False,+ joint_sdpa_materializes: bool = False,+) -> int:+ """Extra bytes withheld from the recommend budget.+ Args:+ mode: the decode preset.+ keyframes: whether this decode carries a keyframe stream.+ joint_sdpa_materializes: whether the joint attention will run on torch's MATH SDPA kernel+ (see ``fallback_na.joint_eager.sdpa_materializes_scores``). Ignored without keyframes,+ and irrelevant when a fused joint kernel serves the decode.+ """+ try:+ budget = _BUDGET_BY_MODE[mode]+ except KeyError as exc:+ raise ValueError(f"Unsupported DiffVAEMode for tiling budget: {mode!r}") from exc+ if keyframes and mode is not DiffVAEMode.BLACKWELL_DSL:+ return _BUDGET_SAFETY_BYTES_JOINT_MATERIALIZED if joint_sdpa_materializes else _BUDGET_SAFETY_BYTES_EAGER+ if _falls_back_to_eager_na(mode):return _BUDGET_SAFETY_BYTES_EAGER- return _BUDGET_SAFETY_BYTES_COMPILED+ return budget.reserve_bytesdef accumulator_element_size(feature_dtype: torch.dtype) -> int:@@ -153,6 +276,8 @@ def recommended_decode_tiling_config( # noqa: PLR0913element_size: int = _DEFAULT_ELEMENT_SIZE,natten_trailing_pad_latent_frames: int = 0,out_channels: int = _ACCUMULATOR_CHANNELS,+ keyframes: bool = False,+ joint_sdpa_materializes: bool = False,) -> TileSizeConfig:"""Pick DiffVAE decode tiling from stage-4/5 halos and free VRAM.Always enables both spatial and temporal tiling (temporal-only full-frame slabs@@ -164,8 +289,8 @@ def recommended_decode_tiling_config( # noqa: PLR0913counts from :func:`~ltx_core.tiling.split_by_size` (same as decode).2. Drop triples whose peak-bytes estimate exceeds ``usable`` bytes(``free - max(model, 1 GiB) - safety - stage4_feature``; safety is- 1 GiB eager / 2 GiB compiled). Stage-4 input features stay resident- for the whole tiled decode.+ 1 GiB eager / 2 GiB compiled, see :func:`budget_safety_bytes`).+ Stage-4 input features stay resident for the whole tiled decode.3. Among feasible triples, pick minimal :func:`volumetric_overlap_waste`.Peak-bytes estimate::stage4_feature_bytes(...) # hard, full volume@@ -177,7 +302,13 @@ def recommended_decode_tiling_config( # noqa: PLR0913RGBx``element_size`` by default. ``element_size`` is the activation width:production bf16 features use fp16 accumulators (2), matching:func:`accumulator_element_size`. Stage-5 uses the same element size x- ``stage5_channels`` x ``coef`` (11 / 7 / 5 / 2.5 by mode).+ ``stage5_channels`` x ``coef``, which :func:`stage5_mem_coef` reads off the+ mode and ``keyframes`` (11 / 7 / 5 / 2.5 by mode; 15 / 5 / 5 / 2.5 with a+ keyframe stream, which runs eager blocks).+ Args beyond the geometry:+ keyframes: this decode carries a keyframe stream (joint attention, eager blocks).+ joint_sdpa_materializes: the joint attention will run on torch's MATH SDPA kernel;+ costs one more GiB of reserve. See :func:`budget_safety_bytes`."""if height < 1 or width < 1 or num_frames < 1:raise ValueError(f"height/width/num_frames must be >= 1, got {height}x{width}x{num_frames}")@@ -213,7 +344,7 @@ def recommended_decode_tiling_config( # noqa: PLR0913)model_cost = max(int(model_bytes), _MIN_MODEL_BYTES_FLOOR)- coef = stage5_mem_coef(mode)+ coef = stage5_mem_coef(mode, keyframes=keyframes)s4_feat_bytes = stage4_feature_bytes(height=height,width=width,@@ -223,7 +354,8 @@ def recommended_decode_tiling_config( # noqa: PLR0913element_size=element_size,natten_trailing_pad_latent_frames=natten_trailing_pad_latent_frames,)- usable = max(0, int(free_bytes) - model_cost - budget_safety_bytes(mode) - s4_feat_bytes)+ reserve = budget_safety_bytes(mode, keyframes=keyframes, joint_sdpa_materializes=joint_sdpa_materializes)+ usable = max(0, int(free_bytes) - model_cost - reserve - s4_feat_bytes)s5_bytes_per_token = max(1.0, float(stage5_channels) * float(element_size) * coef)acc_bytes_per_pixel = int(out_channels) * int(element_size)@@ -237,9 +369,17 @@ def recommended_decode_tiling_config( # noqa: PLR0913# Current group buffer + still-live emit/stub during temporal handoff.acc_frames = 2 * int(tile_t)acc_bytes = acc_frames * int(height) * int(width) * acc_bytes_per_pixel- if acc_bytes >= usable:+ # The consumer converts each yielded chunk while this decode is suspended.+ downstream_bytes = emit_convert_bytes(+ tile_frames=max_emitted_frames(num_frames=num_frames, tile_frames=tile_t, overlap_frames=overlap_t),+ height=height,+ width=width,+ out_channels=out_channels,+ element_size=element_size,+ )+ if acc_bytes + downstream_bytes >= usable:continue- s5_budget_bytes = usable - acc_bytes+ s5_budget_bytes = usable - acc_bytes - downstream_bytesmax_s5_tokens = int(s5_budget_bytes // s5_bytes_per_token)for tile_h, n_h in h_cands:for tile_w, n_w in w_cands:@@ -263,9 +403,10 @@ def recommended_decode_tiling_config( # noqa: PLR0913"Cannot fit a DiffVAE decode tile under the memory budget: "f"min tile ~{min_t_px}f x {min_h_px}x{min_w_px}px "f"(overlaps T={overlap_t}, HW={overlap_hw}), "- f"mode={mode.value}, coef={coef}, stage5_channels={stage5_channels}, "+ f"mode={mode.value}, keyframes={keyframes}, coef={coef}, stage5_channels={stage5_channels}, "f"stage4_feature_bytes={s4_feat_bytes}, usable_bytes={usable}. "- "Reduce resolution or free GPU memory."+ "Reduce resolution, reduce num_frames (stage-4 features and the per-chunk "+ "encode buffers both scale with it), or free GPU memory.")scored.sort()diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.pyindex b9cc41e..2dfb3d4 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py@@ -2,15 +2,25 @@from __future__ import annotations+import dataclasses+import logging+from collections.abc import Sequencefrom typing import Iterator, List, Literal, Tupleimport torchfrom torch import nn-from ltx_core.devices import cuda_activation_budget_bytesfrom ltx_core.model.disposable import Disposablefrom ltx_core.model.transformer.timestep_embedding import PixArtAlphaCombinedTimestepSizeEmbeddingsfrom ltx_core.model.video_vae import diffusion_tiling+from ltx_core.model.video_vae.keyframes import (+ DecodeKeyframes,+ KeyframeStream,+ keyframe_clip_times,+ planes_for_tile,+ remaining_time_strides,+ upsample_keyframe_planes,+)from ltx_core.model.video_vae.ops import PerChannelStatistics, patchify, unpatchifyfrom ltx_core.model.video_vae.transformer import (AdaLNZero,@@ -19,11 +29,9 @@ from ltx_core.model.video_vae.transformer import (LinearPixelShuffleUpsample,NABlock,)-from ltx_core.model.video_vae.transformer.config import DiffVAEMode-from ltx_core.model.video_vae.video_vae import VideoDecoder+from ltx_core.model.video_vae.video_vae import VideoDecoder, iter_decoded_single_framesfrom ltx_core.tiling import (Tile,- TileSizeConfig,TilingConfig,group_tiles_by_temporal_slice,masks_are_complementary,@@ -32,6 +40,8 @@ from ltx_core.tiling import (from ltx_core.types import SpatioTemporalScaleFactors, VideoLatentShapefrom ltx_core.utils import to_velocity+logger: logging.Logger = logging.getLogger(__name__)+# Production CausalVideoAutoencoderL decoder layout: channel width per stage.# Mirrors the (non-diffusion) NA decoder's stage spec._L_STAGE_CHANNELS: Tuple[int, ...] = (1024, 512, 256, 256, 128)@@ -123,6 +133,12 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):self.per_channel_statistics = PerChannelStatistics(latent_channels=in_channels)self.conv_in = ChannelLinear(in_channels, stage_channels[0], bias=True)+ # Keyframe-stream tag, added to un-normalized keyframe latents before the shared+ # ``conv_in`` and nowhere else. It is the only keyframe-specific weight in the+ # whole feature. Checkpoints predating the keyframe training have no such key, so+ # ``video_decoder_sd_ops_for_checkpoint`` synthesizes zeros -- a missing key would+ # otherwise leave the parameter on the meta device under ``strict=False`` load.+ self.type_emb = nn.Parameter(torch.zeros(in_channels))self.det_stages = nn.ModuleList()self.upsamples = nn.ModuleList()@@ -198,6 +214,9 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):# Default False = combined pathway (``CombinedDiffusionNABlock``). Chunked DiffVAE# modes flip this via ``apply_diffvae_config``.self.deferred_stage4_upsample = False+ # Remaining temporal upsampling per stage input, plus 1 for stage 5: the divisor in+ # ``keyframe_stage_times``. (8, 8, 4, 2, 1) for the production ladder.+ self._keyframe_time_strides: Tuple[int, ...] = remaining_time_strides(self.upsamples)def _run_det_stage(self, x: torch.Tensor, stage_i: int, drop_leading_frame: bool) -> torch.Tensor:"""One deterministic stage: NA blocks + upsample."""@@ -225,6 +244,214 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):x = self._run_det_stage(x, stage_i, drop_leading_frame)return x+ def _keyframe_stream_from_latents(+ self,+ keyframes: DecodeKeyframes,+ *,+ valid: torch.Tensor | None = None,+ ) -> KeyframeStream:+ """Keyframe latents to a stage-1-input stream: un-normalize, tag, ``conv_in``, mask.+ Stages 1-3 always run on the whole volume, so times stay in the global stage-1+ origin. Tile-local rebasing happens later, at stage 4.+ Unlike upstream we un-normalize first, because our ``conv_in`` consumes+ un-normalized latents (``forward_stages_1_to_3`` does the same for video) while+ upstream un-normalizes above the decoder. ``type_emb`` still lands in exactly the+ same place: on the latents, immediately before the shared ``conv_in``.+ """+ latents = self.per_channel_statistics.un_normalize(keyframes.latents)+ x = latents.permute(0, 2, 3, 4, 1)+ x = x + self.type_emb.view(1, 1, 1, 1, -1)+ x = self.conv_in(x)+ planes = x.shape[1]+ if valid is None:+ valid = torch.ones(planes, dtype=torch.bool, device=x.device)+ times = keyframe_clip_times(+ keyframes.pixel_frame_indices,+ self._keyframe_time_strides[0],+ keyframes.clip_start_frame,+ )+ return KeyframeStream(x=x, times=times.to(device=x.device), valid=valid.to(device=x.device)).masked()++ def _run_det_stage_with_keyframes(+ self,+ x: torch.Tensor,+ keyframes: KeyframeStream,+ stage_i: int,+ drop_leading_frame: bool,+ pixel_frame_indices: torch.Tensor,+ next_time_origin: float,+ clip_start_frame: int = 0,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """One deterministic stage over both streams: joint NA blocks + upsample.+ The keyframe upsample is spatial-only and always drops its leading frame; the video+ stream's ``drop_leading_frame`` is a tiling property and must not leak into it.+ Times are rebuilt from the *next* stage's remaining stride after upsampling.+ ``next_time_origin`` is in the **next** stage's temporal units, because that is the+ scale the times it rebases are expressed in. Zero everywhere except the stage-4 hop of+ a tiled decode, whose next stage is 5 and whose origin is therefore a pixel frame.+ ``clip_start_frame`` is the first global pixel of *this* video latent (0 for a full+ clip; Dist's tile origin for a slice).+ """+ if self.mark_dynamic_shapes:+ for dim in (1, 2, 3):+ torch._dynamo.mark_dynamic(x, dim)+ for block in self.det_stages[stage_i]:+ x, keyframes = block.forward_with_keyframes(x, keyframes)+ x = self.upsamples[stage_i](x, drop_leading_frame=drop_leading_frame)+ keyframe_x = upsample_keyframe_planes(self.upsamples[stage_i], keyframes.x)+ next_times = keyframe_clip_times(+ pixel_frame_indices,+ self._keyframe_time_strides[stage_i + 1],+ clip_start_frame,+ extra_origin=next_time_origin,+ )+ return x, KeyframeStream(+ x=keyframe_x,+ times=next_times.to(device=keyframe_x.device),+ valid=keyframes.valid,+ ).masked()++ def forward_stages_1_to_3_with_keyframes(+ self,+ z_noisy: torch.Tensor,+ keyframes: DecodeKeyframes,+ drop_leading_frame: bool = True,+ *,+ keyframe_valid: torch.Tensor | None = None,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """Dual-stream stages 1-3: video latent + keyframe planes to stage-4 inputs.+ Keyframe counterpart of :meth:`forward_stages_1_to_3`. ``z_noisy`` and+ ``keyframes.latents`` must already carry identical spatial padding -- the pad is+ applied symmetrically, so padding only one stream would offset every keyframe plane+ from the video by half the pad and read as ghosting rather than a failure.+ Times are relative to :attr:`DecodeKeyframes.clip_start_frame`. For a full-clip decode+ that is 0, so they match global ``t_s``. For a Dist slice they are ``t_s(index) -+ t_s(clip_start)`` from stage 1, because this path's "whole volume" *is* the slice.+ Additional in-volume tile origins are applied in :meth:`forward_stage_4_with_keyframes`.+ """+ keyframes.validate()+ if z_noisy.shape[-2:] != keyframes.latents.shape[-2:]:+ raise ValueError(+ f"keyframe latents must share the video latent's H/W (identical padding), got "+ f"{tuple(keyframes.latents.shape[-2:])} vs {tuple(z_noisy.shape[-2:])}"+ )+ stream = self._keyframe_stream_from_latents(keyframes, valid=keyframe_valid)+ x = self.per_channel_statistics.un_normalize(z_noisy).permute(0, 2, 3, 4, 1)+ x = self.conv_in(x)+ for stage_i in range(3):+ x, stream = self._run_det_stage_with_keyframes(+ x,+ stream,+ stage_i,+ drop_leading_frame,+ keyframes.pixel_frame_indices,+ 0.0,+ clip_start_frame=keyframes.clip_start_frame,+ )+ return x, stream++ def forward_stage_4_with_keyframes(+ self,+ x: torch.Tensor,+ keyframes: KeyframeStream,+ pixel_frame_indices: torch.Tensor,+ drop_leading_frame: bool = True,+ pad_trailing: bool = True,+ *,+ stage4_time_origin: float = 0.0,+ pixel_time_origin: float = 0.0,+ clip_start_frame: int = 0,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """Dual-stream stage 4 to stage-5 context. Keyframe counterpart of+ :meth:`forward_stage_4`.+ The ghost-pad crop applies to the video stream only: the trailing replicate is a+ temporal-border workaround and the keyframe planes have no temporal extent to pad.+ On the deferred (chunked) pathway neither stream is upsampled here: each stage-5+ block folds ``upsamples[3]`` into its own context inject. The returned stream's+ ``times`` are nonetheless the *stage-5* times, because that is where they are+ consumed -- the same asymmetry the video stream already has, whose returned+ ``x`` is a pre-upsample feature rather than stage-5 context.+ **Two origins, at two scales.** The video stream's RoPE is tile-local 0-based at every+ stage, so keyframe times must be rebased to whatever the tile's frame 0 is -- and this+ method spans two different temporal resolutions. ``stage4_time_origin`` is the tile's+ start in stage-4 input units (for the blocks); ``pixel_time_origin`` is its first+ global pixel frame (for stage 5). They are taken separately from the tile rather than+ derived from one another: ``drop_leading_frame`` and the causal first frame make+ ``pixel_origin == stride_t * stage4_origin`` an off-by-one trap, not an identity. Both+ are 0.0 for an untiled full-clip decode. ``clip_start_frame`` is subtracted in stage+ units as well, so a Dist slice whose first pixel is 56 still sees ``t_s(48) - t_s(56)``.+ """+ # Rebuild from global indices rather than trusting the caller's stream: stages 1-3 of a+ # full-clip decode are global, and Dist has already folded clip_start into clip times.+ keyframes = dataclasses.replace(+ keyframes,+ times=keyframe_clip_times(+ pixel_frame_indices,+ self._keyframe_time_strides[3],+ clip_start_frame,+ extra_origin=stage4_time_origin,+ ).to(device=keyframes.x.device),+ )+ if self.deferred_stage4_upsample:+ return self._forward_stage_4_deferred_with_keyframes(+ x, keyframes, pixel_frame_indices, pad_trailing, pixel_time_origin, clip_start_frame+ )+ x, keyframes = self._run_det_stage_with_keyframes(+ x,+ keyframes,+ 3,+ drop_leading_frame,+ pixel_frame_indices,+ pixel_time_origin,+ clip_start_frame=clip_start_frame,+ )+ if pad_trailing:+ x = diffusion_tiling.crop_trailing_context_natten_pad(+ x,+ n_latent_frames=self._natten_trailing_pad_latent_frames,+ time_scale=self.video_downscale_factors.time,+ stage5_kernel_t=self.stage5_kernel[0],+ )+ return x, keyframes++ def _forward_stage_4_deferred_with_keyframes(+ self,+ x: torch.Tensor,+ keyframes: KeyframeStream,+ pixel_frame_indices: torch.Tensor,+ pad_trailing: bool,+ pixel_time_origin: float,+ clip_start_frame: int = 0,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """Stage-4 blocks only, both streams, for the deferred (chunked) pathway.+ Mirrors :meth:`forward_stage_4`'s deferred branch: no ``upsamples[3]`` on either+ stream, ghost cropped at pre-upsample temporal resolution (video only).+ """+ if self.mark_dynamic_shapes:+ for dim in (1, 2, 3):+ torch._dynamo.mark_dynamic(x, dim)+ for block in self.det_stages[3]:+ x, keyframes = block.forward_with_keyframes(x, keyframes)+ if pad_trailing:+ up_t = int(self.upsamples[3].stride[0])+ x = diffusion_tiling.crop_trailing_context_natten_pad(+ x,+ n_latent_frames=self._natten_trailing_pad_latent_frames,+ time_scale=self.video_downscale_factors.time // up_t,+ stage5_kernel_t=max(1, -(-self.stage5_kernel[0] // up_t)),+ )+ stage5_times = keyframe_clip_times(+ pixel_frame_indices,+ self._keyframe_time_strides[4],+ clip_start_frame,+ extra_origin=pixel_time_origin,+ )+ return x, KeyframeStream(+ x=keyframes.x,+ times=stage5_times.to(device=keyframes.x.device),+ valid=keyframes.valid,+ ).masked()+def forward_stage_4(self,x: torch.Tensor,@@ -269,11 +496,34 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):x = self.conv_in_x_t(noised_pixels_patched.permute(0, 2, 3, 4, 1))return torch.cat([context, x], dim=-1)+ def _keyframe_context_and_x_for_diff_step(+ self,+ keyframe_context: torch.Tensor,+ keyframe_x_t: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> torch.Tensor:+ """Keyframe ``[context | conv_in_x_t(patched x)]``, mask-zeroed.+ ``keyframe_x_t`` is ``(B, C_pix, P, H_pix, W_pix)`` -- the keyframe planes' own noised+ pixels, one pixel frame per plane, through the *shared* ``conv_in_x_t``.+ """+ patched = patchify(keyframe_x_t, patch_size_hw=self.patch_size, patch_size_t=1)+ x = self.conv_in_x_t(patched.permute(0, 2, 3, 4, 1))+ x = x * keyframe_valid[None, :, None, None, None]+ return torch.cat([keyframe_context, x], dim=-1)+def _x_for_diff_step(self, x_t: torch.Tensor) -> torch.Tensor:"""Conv-processed noised pixels only (deferred-context path)."""noised_pixels_patched = patchify(x_t, patch_size_hw=self.patch_size, patch_size_t=1)return self.conv_in_x_t(noised_pixels_patched.permute(0, 2, 3, 4, 1))+ def _keyframe_x_for_diff_step(self, keyframe_x_t: torch.Tensor, keyframe_valid: torch.Tensor) -> torch.Tensor:+ """Mask-zeroed keyframe noised pixels only (deferred-context path).+ Contiguous by construction: the chunked pathway mutates this buffer in place.+ """+ patched = patchify(keyframe_x_t, patch_size_hw=self.patch_size, patch_size_t=1)+ x = self.conv_in_x_t(patched.permute(0, 2, 3, 4, 1))+ return (x * keyframe_valid[None, :, None, None, None]).contiguous()+def forward_diff_step(self,context_and_x: torch.Tensor,@@ -296,8 +546,55 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):for block in self.diff_blocks:x_half.copy_(block.forward_combined(context_and_x, modulation))- x = x_half+ return self._pixels_from_stage5(x_half)+ def forward_diff_step_with_keyframes(+ self,+ context_and_x: torch.Tensor,+ keyframe_context_and_x: torch.Tensor,+ t: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """One dual-stream stage-5 step. Returns ``(video_pred, keyframe_pred)`` in pixel space.+ The keyframe stream at stage 5 is a genuine second *pixel* diffusion stream -- its own+ noised pixels through the shared ``conv_in_x_t``, its own per-block+ ``context_proj(keyframe_context)``, the same AdaLN modulation -- not a zero tensor and+ not the context. It is evolved through the same Euler loop as video so the hidden+ state the joint attention reads sits at the noise level it was trained to see, then+ discarded: callers use the video prediction only.+ Both buffers follow ``forward_diff_step``'s ``[context | x]`` layout and the same+ ``copy_``-into-a-view discipline. Video T/H/W stay dynamic; the keyframe plane axis is+ specialized, since ``keyframe_times`` / ``keyframe_valid`` pin it.+ """+ x_half = context_and_x[..., self.context_channels :]+ keyframe_half = keyframe_context_and_x[..., self.context_channels :]+ t_emb = self.t_embedder(self.timestep_scale_multiplier * t, hidden_dtype=x_half.dtype)+ modulation = self.shared_adaln(t_emb)++ if self.mark_dynamic_shapes:+ for dim in (1, 2, 3):+ torch._dynamo.mark_dynamic(context_and_x, dim)+ # Keyframe dim 1 is the plane count, not T, and keyframe_times / keyframe_valid pin it.+ # Marking it dynamic and then specializing to P raises ConstraintViolationError.+ for dim in (2, 3):+ torch._dynamo.mark_dynamic(keyframe_context_and_x, dim)++ for block in self.diff_blocks:+ x_out, keyframe_out = block.forward_combined_with_keyframes(+ context_and_x,+ keyframe_context_and_x,+ modulation,+ keyframe_times,+ keyframe_valid,+ )+ x_half.copy_(x_out)+ keyframe_half.copy_(keyframe_out)++ return self._pixels_from_stage5(x_half), self._pixels_from_stage5(keyframe_half)++ def _pixels_from_stage5(self, x: torch.Tensor) -> torch.Tensor:+ """Shared stage-5 tail: ``norm_out`` -> ``conv_out`` -> channels-first -> unpatchify."""x = self.norm_out(x)x = self.conv_out(x)x = x.permute(0, 4, 1, 2, 3).contiguous()@@ -340,6 +637,68 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):x = x.permute(0, 4, 1, 2, 3).contiguous()return unpatchify(x, patch_size_hw=self.patch_size, patch_size_t=1)+ def forward_diff_step_deferred_with_keyframes(+ self,+ x: torch.Tensor,+ stage4_feat: torch.Tensor,+ keyframe_x: torch.Tensor,+ keyframe_stage4_feat: torch.Tensor,+ t: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ *,+ drop_leading_frame: bool = True,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Dual-stream stage-5 step with deferred context. Keyframe counterpart of+ :meth:`forward_diff_step_deferred`.+ Each stream carries its own pre-upsample stage-4 feature and injects it per block,+ so full-resolution context is never materialised for either. ``drop_leading_frame``+ is the video stream's tiling property; the keyframe inject always collapses its+ temporal stride.+ """+ t_emb = self.t_embedder(self.timestep_scale_multiplier * t, hidden_dtype=x.dtype)+ modulation = self.shared_adaln(t_emb)++ if self.mark_dynamic_shapes:+ for dim in (1, 2, 3):+ torch._dynamo.mark_dynamic(x, dim)+ torch._dynamo.mark_dynamic(stage4_feat, dim)+ # Plane count, not T -- see the note in the combined path above.+ for dim in (2, 3):+ torch._dynamo.mark_dynamic(keyframe_x, dim)+ torch._dynamo.mark_dynamic(keyframe_stage4_feat, dim)++ # The DSL chain drives itself, so both streams recycle output buffers instead of+ # allocating a volume per block per stream; the chunked blocks expose the same+ # ``forward_x_ctx_with_keyframes``, so the fallback loop drives those.+ from ltx_core.model.video_vae.transformer.dsl_kernels import DSLDiffusionBlockChain # noqa: PLC0415++ if isinstance(self.diff_blocks, DSLDiffusionBlockChain):+ x, keyframe_x = self.diff_blocks.forward_x_ctx_with_keyframes(+ x,+ stage4_feat,+ keyframe_x,+ keyframe_stage4_feat,+ modulation,+ keyframe_times,+ keyframe_valid,+ drop_leading_frame=drop_leading_frame,+ )+ else:+ for block in self.diff_blocks:+ x, keyframe_x = block.forward_x_ctx_with_keyframes(+ x,+ stage4_feat,+ keyframe_x,+ keyframe_stage4_feat,+ modulation,+ keyframe_times,+ keyframe_valid,+ drop_leading_frame=drop_leading_frame,+ )++ return self._pixels_from_stage5(x), self._pixels_from_stage5(keyframe_x)+def _euler_step(self, x_t: torch.Tensor, model_out: torch.Tensor, t_now: torch.Tensor, t_next: torch.Tensor) -> torch.Tensor:@@ -394,6 +753,508 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):return model_outreturn self._euler_step(x_t, model_out.to(torch.float32), t_now, torch.zeros_like(t_now))+ def _stage5_canvas_from_context(+ self,+ context_tile: torch.Tensor,+ *,+ drop_leading_frame: bool,+ ) -> tuple[int, int, int]:+ """``(T, H_pix, W_pix)`` of the stage-5 pixel canvas a context tile implies.+ On the combined pathway the context is already at stage-5 resolution and+ ``_context_and_x_for_diff_step`` patchifies ``x_t`` by ``patch_size``, so the canvas+ is just ``(T, H * patch_size, W * patch_size)``. On the deferred pathway the tile is+ still pre-upsample: each stage-5 block folds ``upsamples[3]`` into its inject, so+ apply that stride here -- including the leading-frame drop the fold performs when the+ temporal stride is 2.+ """+ t, h, w = context_tile.shape[1], context_tile.shape[2], context_tile.shape[3]+ if self.deferred_stage4_upsample:+ # Context is still pre-upsample, so this is the same geometry as a stage-4+ # input. Ghost crop already ran, so do not re-apply the kernel-T floor.+ return diffusion_tiling.stage5_pixel_shape_from_stage4(+ t,+ h,+ w,+ upsample_stride=tuple(self.upsamples[3].stride), # type: ignore[arg-type]+ patch_size=self.patch_size,+ stage5_kernel_t=self.stage5_kernel[0],+ drop_leading_frame=drop_leading_frame,+ pad_trailing=False,+ )+ return t, h * self.patch_size, w * self.patch_size++ def _decode_one_tile_with_keyframes( # noqa: PLR0913+ self,+ feat_tile: torch.Tensor,+ keyframes: KeyframeStream,+ pixel_frame_indices: torch.Tensor,+ *,+ is_origin: bool,+ timestep: torch.Tensor,+ pad_trailing: bool,+ generator: torch.Generator | None,+ compute_dtype: torch.dtype,+ x_t_tile_init: torch.Tensor | None = None,+ stage4_time_origin: float = 0.0,+ pixel_time_origin: float = 0.0,+ clip_start_frame: int = 0,+ ) -> torch.Tensor:+ """Stage 4 + dual-stream diffusion on one stage-4 feature tile.+ Both streams are Euler-stepped together; only the video pixels are returned. The+ keyframe pixel stream exists so the hidden state the joint attention reads stays at+ the noise level it was trained on, and is discarded here (upstream exposes it only+ through its explicit per-step entry points, which the trainer uses).+ Noise is sized from the stage-5 context rather than from a re-derived tile geometry;+ see :meth:`_stage5_canvas_from_context` for the deferred-pathway correction. The+ keyframe canvas differs only in its frame count -- one pixel frame per plane, since+ keyframe upsampling collapses its temporal stride.+ ``x_t_tile_init`` lets a tiled decode share one global noise field across tiles (edge+ policy applied by the caller, as the plain path does); ``None`` draws fresh noise. The+ keyframe stream always draws its own -- its planes are not part of the video canvas.+ """+ context_tile, keyframes = self.forward_stage_4_with_keyframes(+ feat_tile,+ keyframes,+ pixel_frame_indices,+ drop_leading_frame=is_origin,+ pad_trailing=pad_trailing,+ stage4_time_origin=stage4_time_origin,+ pixel_time_origin=pixel_time_origin,+ clip_start_frame=clip_start_frame,+ )++ batch = context_tile.shape[0]+ canvas_t, canvas_h, canvas_w = self._stage5_canvas_from_context(context_tile, drop_leading_frame=is_origin)+ randn_device = generator.device if generator is not None else feat_tile.device++ def _noise(frames: int) -> torch.Tensor:+ return torch.randn(+ (batch, self.out_channels, frames, canvas_h, canvas_w),+ dtype=compute_dtype,+ generator=generator,+ device=randn_device,+ ).to(feat_tile.device)++ x_t = _noise(canvas_t) if x_t_tile_init is None else x_t_tile_init+ keyframe_x_t = _noise(keyframes.num_planes)++ def _step(t_now: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ if self.deferred_stage4_upsample:+ return self.forward_diff_step_deferred_with_keyframes(+ self._x_for_diff_step(x_t),+ context_tile,+ self._keyframe_x_for_diff_step(keyframe_x_t, keyframes.valid),+ keyframes.x,+ t_now,+ keyframes.times,+ keyframes.valid,+ drop_leading_frame=is_origin,+ )+ context_and_x = self._context_and_x_for_diff_step(context_tile, x_t)+ keyframe_context_and_x = self._keyframe_context_and_x_for_diff_step(+ keyframes.x, keyframe_x_t, keyframes.valid+ )+ return self.forward_diff_step_with_keyframes(+ context_and_x, keyframe_context_and_x, t_now, keyframes.times, keyframes.valid+ )++ _, num_steps = timestep.shape+ for i in range(num_steps - 1):+ t_now = timestep[:, i]+ t_next = timestep[:, i + 1]+ video_out, keyframe_out = _step(t_now)+ x_t = self._euler_step(x_t, video_out.to(torch.float32), t_now, t_next)+ keyframe_x_t = self._euler_step(keyframe_x_t, keyframe_out.to(torch.float32), t_now, t_next)++ t_now = timestep[:, -1]+ video_out, _ = _step(t_now)+ if self.model_output_type == "x0":+ return video_out+ return self._euler_step(x_t, video_out.to(torch.float32), t_now, torch.zeros_like(t_now))++ def _decode_temporal_group_isolated_with_keyframes( # noqa: PLR0913+ self,+ tiles: List[Tile],+ feat_s4: torch.Tensor,+ stream: KeyframeStream,+ pixel_frame_indices: torch.Tensor,+ content_s4_frames: int,+ x_t_init: torch.Tensor | None,+ timestep: torch.Tensor,+ full_video_shape: VideoLatentShape,+ curr_temporal_slice: slice,+ generator: torch.Generator | None,+ *,+ complementary: bool,+ clip_start_frame: int = 0,+ ) -> Tuple[torch.Tensor, torch.Tensor | None]:+ """Decode one temporal group's tiles with keyframes and blend into a group buffer.+ Keyframe counterpart of :meth:`_decode_temporal_group_isolated`. Each tile carries+ only the planes near it -- those inside its pixel-frame span plus the nearest plane on+ each *side* of it (:func:`planes_for_tile`) -- and the two origins that plane set has+ to be rebased against come from the tile, never from each other.+ Tile ``out_coords`` are local to this latent. Dist slices keep global+ ``pixel_frame_indices`` and pass ``clip_start_frame`` so selection lines up.+ """+ group_temporal_len = curr_temporal_slice.stop - curr_temporal_slice.start+ group_shape = full_video_shape._replace(frames=group_temporal_len)+ full_torch_shape = full_video_shape.to_torch_shape()+ accum_dtype = torch.float16 if feat_s4.dtype == torch.bfloat16 else feat_s4.dtype+ buffer = torch.zeros(group_shape.to_torch_shape(), device=feat_s4.device, dtype=accum_dtype)+ weights: torch.Tensor | None = None if complementary else torch.zeros_like(buffer)+ local_temporal_slice = slice(0, group_temporal_len)++ compute_dtype = feat_s4.dtype+ up3_stride = tuple(self.upsamples[3].stride)++ for tile_index, tile in enumerate(tiles):+ feat_tile, is_origin, pad_trailing, content_thw = diffusion_tiling.slice_stage4_tile(+ feat_s4, tile, content_frames=content_s4_frames+ )+ # Two origins at two scales -- see forward_stage_4_with_keyframes.+ stage4_origin = tile.in_coords[1].indices(content_s4_frames)[0]+ pixel_lo, pixel_hi, _ = tile.out_coords[2].indices(full_torch_shape[2])++ # ``out_coords`` are local to this latent. Dist slices keep global indices and+ # ``clip_start_frame`` as the origin, so a local ``[0, 72)`` still has to select+ # global ``[56, 127]``.+ keep = planes_for_tile(pixel_frame_indices, pixel_lo, pixel_hi - 1, clip_start_frame=clip_start_frame)+ if not bool(keep.any()):+ raise RuntimeError(+ f"tile covering pixel frames [{pixel_lo + clip_start_frame}, "+ f"{pixel_hi - 1 + clip_start_frame}] selected no keyframe planes "+ f"out of {int(pixel_frame_indices.shape[0])}; planes_for_tile always keeps at least one"+ )+ tile_stream = stream.select_planes(keep.to(stream.valid.device)).crop_spatial(+ tile.in_coords[2], tile.in_coords[3]+ )+ # Not debug-only: the decode below needs this tile's plane positions.+ tile_indices = pixel_frame_indices[keep.to(pixel_frame_indices.device)]+ if logger.isEnabledFor(logging.INFO):+ logger.info(+ "keyframe decode: tile %d/%d frames [%d, %d), stage-4 extent %dx%dx%d, %d of %d planes at %s",+ tile_index + 1,+ len(tiles),+ pixel_lo,+ pixel_hi,+ feat_tile.shape[1],+ feat_tile.shape[2],+ feat_tile.shape[3],+ tile_stream.num_planes,+ int(pixel_frame_indices.shape[0]),+ tile_indices.tolist(),+ )++ x_t_tile_init: torch.Tensor | None = None+ if x_t_init is not None:+ stage5_f, stage5_h, stage5_w = diffusion_tiling.stage5_pixel_shape_from_stage4(+ content_thw[0],+ content_thw[1],+ content_thw[2],+ upsample_stride=up3_stride, # type: ignore[arg-type]+ patch_size=self.patch_size,+ stage5_kernel_t=self.stage5_kernel[0],+ drop_leading_frame=is_origin,+ pad_trailing=pad_trailing,+ )+ # Same edge policy as the plain path: expand/crop the shared noise field+ # rather than drawing fresh noise, since NA mixes padded values inward.+ x_t_tile_init = x_t_init[tile.out_coords]+ x_t_tile_init, _ = diffusion_tiling.resize_axis(x_t_tile_init, 2, stage5_f, mode="repeat_last")+ x_t_tile_init, _ = diffusion_tiling.resize_axis(x_t_tile_init, 3, stage5_h, mode="symmetric")+ x_t_tile_init, _ = diffusion_tiling.resize_axis(x_t_tile_init, 4, stage5_w, mode="symmetric")++ pixel_tile = self._decode_one_tile_with_keyframes(+ feat_tile,+ tile_stream,+ tile_indices,+ is_origin=is_origin,+ timestep=timestep,+ pad_trailing=pad_trailing,+ generator=generator,+ compute_dtype=compute_dtype,+ x_t_tile_init=x_t_tile_init,+ stage4_time_origin=float(stage4_origin),+ pixel_time_origin=float(pixel_lo),+ clip_start_frame=clip_start_frame,+ )+ content_pixel_shape = diffusion_tiling.pixel_tile_shape(full_torch_shape, tile.out_coords)+ pixel_tile = diffusion_tiling.crop_pixels_to_content(+ pixel_tile,+ content_pixel_shape[2],+ content_pixel_shape[3],+ content_pixel_shape[4],+ ).to(buffer.dtype)++ masks = tuple(m.to(device=buffer.device, dtype=torch.float32) for m in tile.masks_1d)+ local_coords = (+ tile.out_coords[0],+ tile.out_coords[1],+ local_temporal_slice,+ tile.out_coords[3],+ tile.out_coords[4],+ )+ buffer[local_coords] += scale_by_masks_1d(pixel_tile, masks)+ if weights is not None:+ strength = torch.ones(pixel_tile.shape, device=buffer.device, dtype=buffer.dtype)+ weights[local_coords] += scale_by_masks_1d(strength, masks)++ return buffer, weights++ def _decode_groups_with_keyframes( # noqa: PLR0913, PLR0915+ self,+ feat_s4: torch.Tensor,+ stream: KeyframeStream,+ pixel_frame_indices: torch.Tensor,+ latent: torch.Tensor,+ tiling_config: TilingConfig,+ timestep: torch.Tensor,+ generator: torch.Generator | None,+ *,+ content_pixel: VideoLatentShape,+ h_pad: diffusion_tiling.AxisPad | None,+ w_pad: diffusion_tiling.AxisPad | None,+ as_fhwc: bool,+ clip_start_frame: int = 0,+ ) -> Iterator[torch.Tensor]:+ """Tiled keyframe decode, streaming one temporal group at a time.+ Same shape as :meth:`_decode_pixels`: only the trailing overlap of the previous group+ is retained between iterations, and a group's exclusive frames are yielded before the+ next group decodes. That keeps residency at roughly two tile extents rather than a+ whole video, which matters more here than on the plain path -- a keyframe decode also+ carries a second pixel stream through stage 5.+ """+ full_video_shape = (+ VideoLatentShape.from_torch_shape(latent.shape)+ .upscale(self.video_downscale_factors)+ ._replace(channels=self.out_channels)+ )+ target_shape = full_video_shape.to_torch_shape()+ strides = [tuple(u.stride) for u in self.upsamples]+ s4_t, s4_h, s4_w = diffusion_tiling.stage4_thw_from_latent(+ strides, latent.shape[2], latent.shape[3], latent.shape[4], drop_leading_frame=True+ )+ tiles = diffusion_tiling.prepare_tile_schedule(+ torch.Size([latent.shape[0], latent.shape[1], s4_t, s4_h, s4_w]),+ tiling_config,+ upsample3_stride=tuple(self.upsamples[3].stride), # type: ignore[arg-type]+ patch_size=self.patch_size,+ min_tile_size=self.tile_min_sizes,+ tile_halos=self.tile_halos,+ )+ complementary = masks_are_complementary(tiles, target_shape)+ groups = group_tiles_by_temporal_slice(tiles)+ group_slices = [slice(*group[0].out_coords[2].indices(target_shape[2])[:2]) for group in groups]++ single_step_x0 = timestep.shape[1] == 1 and self.model_output_type == "x0"+ x_t_init: torch.Tensor | None = None+ if not single_step_x0:+ randn_device = generator.device if generator is not None else latent.device+ x_t_init = torch.randn(+ tuple(target_shape), dtype=latent.dtype, generator=generator, device=randn_device+ ).to(latent.device)++ logger.info(+ "keyframe decode: %d tile(s) in %d temporal group(s), %d frames at %dx%d, %d planes",+ len(tiles),+ len(groups),+ content_pixel.frames,+ content_pixel.height,+ content_pixel.width,+ int(pixel_frame_indices.shape[0]),+ )++ scaled_h_pad = diffusion_tiling.scale_axis_pad(h_pad, self.video_downscale_factors.height)+ scaled_w_pad = diffusion_tiling.scale_axis_pad(w_pad, self.video_downscale_factors.width)+ overlap_stub: torch.Tensor | None = None+ overlap_stub_weights: torch.Tensor | None = None++ def _emit(buf: torch.Tensor, wts: torch.Tensor | None, global_start: int) -> torch.Tensor | None:+ """Finalize, crop to content, and lay out one emitted run of frames."""+ if global_start >= content_pixel.frames or buf.shape[2] < 1:+ return None+ frames_keep = min(buf.shape[2], content_pixel.frames - global_start)+ if frames_keep < 1:+ return None+ chunk = buf[:, :, :frames_keep]+ if wts is not None:+ floor = diffusion_tiling._weight_floor(wts.dtype)+ chunk = chunk / wts[:, :, :frames_keep].clamp(min=floor)+ chunk = diffusion_tiling.crop_pixels_to_content(+ chunk.to(latent.dtype),+ frames_keep,+ content_pixel.height,+ content_pixel.width,+ h_pad=scaled_h_pad,+ w_pad=scaled_w_pad,+ )+ return chunk[0].permute(1, 2, 3, 0).contiguous() if as_fhwc else chunk++ for group_index, group in enumerate(groups):+ curr_temporal_slice = group_slices[group_index]+ logger.info(+ "keyframe decode: group %d/%d, frames [%d, %d)",+ group_index + 1,+ len(groups),+ curr_temporal_slice.start,+ curr_temporal_slice.stop,+ )+ buffer, weights = self._decode_temporal_group_isolated_with_keyframes(+ group,+ feat_s4,+ stream,+ pixel_frame_indices,+ s4_t,+ x_t_init,+ timestep,+ full_video_shape,+ curr_temporal_slice,+ generator,+ complementary=complementary,+ clip_start_frame=clip_start_frame,+ )++ if overlap_stub is not None:+ overlap_len = int(overlap_stub.shape[2])+ if overlap_len > 0:+ overlap_stub += buffer[:, :, :overlap_len]+ buffer[:, :, :overlap_len] = overlap_stub+ if not complementary:+ assert overlap_stub_weights is not None+ assert weights is not None+ overlap_stub_weights += weights[:, :, :overlap_len]+ weights[:, :, :overlap_len] = overlap_stub_weights+ overlap_stub = None+ overlap_stub_weights = None++ if group_index + 1 < len(groups):+ next_start = group_slices[group_index + 1].start+ exclusive_len = min(max(0, next_start - curr_temporal_slice.start), buffer.shape[2])+ emitted = _emit(+ buffer[:, :, :exclusive_len],+ None if weights is None else weights[:, :, :exclusive_len],+ curr_temporal_slice.start,+ )+ if emitted is not None:+ yield emitted+ # Retain only the trailing overlap for the next group's handoff.+ overlap_stub = buffer[:, :, exclusive_len:].clone()+ if not complementary:+ assert weights is not None+ overlap_stub_weights = weights[:, :, exclusive_len:].clone()+ del buffer, weights+ else:+ emitted = _emit(buffer, weights, curr_temporal_slice.start)+ if emitted is not None:+ yield emitted++ def _decode_pixels_with_keyframes(+ self,+ latent: torch.Tensor,+ keyframes: DecodeKeyframes,+ tiling_config: TilingConfig | None = None,+ generator: torch.Generator | None = None,+ *,+ as_fhwc: bool = False,+ ) -> Iterator[torch.Tensor]:+ """Keyframe-aware decode, yielding one chunk of ``(B, C, F, H, W)`` in ``[-1, 1]``.+ Stages 1-3 run once on the whole volume for both streams -- so the keyframe stream+ reaches stage 4 with *global* times -- then stages 4-5 run per tile with pixel blend.+ With ``tiling_config=None`` that is a single tile and the whole thing is one pass.+ """+ content_shape = VideoLatentShape.from_torch_shape(latent.shape)+ content_pixel = content_shape.upscale(self.video_downscale_factors)._replace(channels=self.out_channels)+ keyframes.validate(num_frames=content_pixel.frames)++ latent, (_t_pad, h_pad, w_pad) = diffusion_tiling.ensure_min_latent_shape(latent, self.stage_min_tile_sizes)+ # Same spatial floor for the keyframe planes, with the plane axis pinned by a+ # temporal minimum of 1. The pad is symmetric, so padding only one stream would+ # offset every plane from the video by half of it.+ _min_t, min_h, min_w = self.stage_min_tile_sizes+ keyframe_latents, (_, keyframe_h_pad, keyframe_w_pad) = diffusion_tiling.ensure_min_latent_shape(+ keyframes.latents, (1, min_h, min_w)+ )+ if (keyframe_h_pad, keyframe_w_pad) != (h_pad, w_pad):+ raise RuntimeError(+ f"keyframe spatial pad {(keyframe_h_pad, keyframe_w_pad)} != video pad {(h_pad, w_pad)}; "+ "the two streams must share one spatial origin"+ )+ padded_keyframes = dataclasses.replace(keyframes, latents=keyframe_latents)++ # Ghost pad is a temporal-border workaround for the video stream; keyframe planes have+ # no temporal extent to pad. The appendix is cropped off context before stage 5.+ latent_padded = diffusion_tiling.pad_trailing_latent_for_natten_border(+ latent, self._natten_trailing_pad_latent_frames+ )+ feat_s4, stream = self.forward_stages_1_to_3_with_keyframes(+ latent_padded, padded_keyframes, drop_leading_frame=True+ )++ batch = latent.shape[0]+ timestep = self.default_inference_timesteps.to(latent.device).unsqueeze(0).expand(batch, -1)+ if tiling_config is not None:+ yield from self._decode_groups_with_keyframes(+ feat_s4,+ stream,+ keyframes.pixel_frame_indices,+ latent,+ tiling_config,+ timestep,+ generator,+ content_pixel=content_pixel,+ h_pad=h_pad,+ w_pad=w_pad,+ as_fhwc=as_fhwc,+ clip_start_frame=keyframes.clip_start_frame,+ )+ return++ logger.info("keyframe decode: untiled, %d frames, %d planes", content_pixel.frames, stream.num_planes)+ pixels = self._decode_one_tile_with_keyframes(+ feat_s4,+ stream,+ keyframes.pixel_frame_indices,+ is_origin=True,+ timestep=timestep,+ pad_trailing=True,+ generator=generator,+ compute_dtype=latent.dtype,+ clip_start_frame=keyframes.clip_start_frame,+ )+ pixels = diffusion_tiling.crop_pixels_to_content(+ pixels,+ content_pixel.frames,+ content_pixel.height,+ content_pixel.width,+ h_pad=diffusion_tiling.scale_axis_pad(h_pad, self.video_downscale_factors.height),+ w_pad=diffusion_tiling.scale_axis_pad(w_pad, self.video_downscale_factors.width),+ ).to(latent.dtype)+ if as_fhwc:+ yield pixels[0].permute(1, 2, 3, 0).contiguous()+ else:+ yield pixels++ def _decode_video_with_keyframes(+ self,+ latent: torch.Tensor,+ keyframes: DecodeKeyframes,+ tiling_config: TilingConfig | None = None,+ generator: torch.Generator | None = None,+ ) -> Iterator[torch.Tensor]:+ """Keyframe-aware decode, yielding float chunk(s) ``[f, h, w, c]`` in ``[0, 1]``.+ Implementation of :meth:`decode_video` when ``keyframes`` is set. ``keyframes`` carries+ single-frame latents plus their global pixel frame indices; every video token then+ attends to the nearest planes through a joint neighborhood-attention window.+ """++ def to_rgb(frames: torch.Tensor) -> torch.Tensor:+ return frames.add_(1).mul_(0.5).clamp_(0, 1)++ for chunk in self._decode_pixels_with_keyframes(+ latent, keyframes, tiling_config, generator=generator, as_fhwc=True+ ):+ yield to_rgb(chunk)+def _decode_temporal_group_isolated(self,tiles: List[Tile],@@ -686,39 +1547,6 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):"""Decode via ``_decode_pixels`` with ``tiling_config=None`` (single full tile)."""return next(self._decode_pixels(sample, tiling_config=None, generator=generator))- def recommended_tiling_config(- self,- *,- height: int,- width: int,- num_frames: int,- mode: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,- free_bytes: int | None = None,- model_bytes: int | None = None,- ) -> TileSizeConfig:- """DiffVAE-aware tiling: stage-4/5 overlaps + memory-capped tile sizes."""- if free_bytes is None:- device = next(self.parameters()).device- free_bytes = cuda_activation_budget_bytes(device) if device.type == "cuda" else 0- if model_bytes is None:- model_bytes = sum(p.numel() * p.element_size() for p in self.parameters())- pixel_scale = diffusion_tiling.stage4_to_pixel_scale_factors(- tuple(self.upsamples[3].stride), # type: ignore[arg-type]- self.patch_size,- )- return diffusion_tiling.recommended_decode_tiling_config(- tile_halos=self.tile_halos,- pixel_scale=pixel_scale,- min_tile_size_s4=self.tile_min_sizes,- patch_size=self.patch_size,- height=height,- width=width,- num_frames=num_frames,- mode=mode,- free_bytes=free_bytes,- model_bytes=model_bytes,- )-def tiled_decode(self,latent: torch.Tensor,@@ -733,16 +1561,31 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):latent: torch.Tensor,tiling_config: TilingConfig | None = None,generator: torch.Generator | None = None,+ *,+ keyframes: DecodeKeyframes | None = None,) -> Iterator[torch.Tensor]:"""Decode latent video, yielding float chunk(s) ``[f, h, w, c]`` in ``[0, 1]``.Untiled and tiled both go through ``_decode_pixels``. Tiled decode may yieldmultiple times when ``tiling_config.frames`` splits the video.+ With ``keyframes`` this is :meth:`_decode_video_with_keyframes`; the argument exists on+ every decoder so a caller can pass planes without first asking which VAE it holds.Layout is packed once to contiguous FHWC on emit; ``to_rgb`` only doesinplace ``[-1, 1]→[0, 1]`` (no second realloc)."""+ if keyframes is not None:+ yield from self._decode_video_with_keyframes(latent, keyframes, tiling_config, generator)+ returndef to_rgb(frames: torch.Tensor) -> torch.Tensor:return frames.add_(1).mul_(0.5).clamp_(0, 1)for chunk in self._decode_pixels(latent, tiling_config, generator=generator, as_fhwc=True):yield to_rgb(chunk)++ def decode_single_frames(+ self,+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,+ ) -> Iterator[torch.Tensor]:+ """Decode each latent as its own one-frame clip, yielding one RGB tensor per latent."""+ yield from iter_decoded_single_frames(self, latents, generator)diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/keyframes.py b/packages/ltx-core/src/ltx_core/model/video_vae/keyframes.pynew file mode 100644index 0000000..565dfcd--- /dev/null+++ b/packages/ltx-core/src/ltx_core/model/video_vae/keyframes.py@@ -0,0 +1,325 @@+"""Keyframe (dual-stream) inputs and coordinate math for DiffVAE decode.+A keyframe-aware decode carries two streams through the decoder: the video volume+``(B, T, H, W, C)`` and a stack of keyframe *planes* ``(B, P, H, W, C)`` whose plane+axis occupies video's temporal slot. Weights are fully shared; the streams only ever+mix inside one joint attention softmax (see ``transformer/fallback_na/joint_eager.py``).+Everything here is pure coordinate/geometry math with no module state, so the eager and+triton backends can share it and therefore agree exactly on slot selection.+Deviation from upstream worth knowing: upstream carries per-sample keyframe times and+masks (``(B, n_kf)``). Here they are batch-shared 1-D ``(P,)`` tensors, because our+decode path is single-sample and ``rope_math.rot_abs_axis_impl`` takes a 1-D position+vector per axis. That keeps the RoPE call and the slot tables batch-independent.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Sequence++import torch+from einops import rearrange++#: Keyframe planes visible to one video query (and video frames visible to one keyframe+#: query). Fixed at 2 upstream -- its backward kernel hardcodes at most two slots.+KEYFRAME_CONTEXT_SLOTS = 2+++@dataclass(frozen=True)+class DecodeKeyframes:+ """Caller-facing keyframe input to a DiffVAE decode.+ Attributes:+ latents: ``(B, C, P, H, W)`` per-channel-normalized latents, exactly one latent+ frame per keyframe. Each plane must have been encoded as a standalone+ one-pixel-frame clip -- the VAE is causal, so a ``P``-frame encode would+ blend planes that were never temporally adjacent.+ pixel_frame_indices: ``(P,)`` int64 **global** pixel frame index of each plane.+ Never rebased onto a tile. A Dist slice whose first pixel is 56 still carries+ a plane at 48 as ``48``; :attr:`clip_start_frame` is how DiffVAE learns the+ 8-frame gap.+ clip_start_frame: first global pixel frame of the video latent in this decode+ call. ``0`` for a full-clip decode. Dist sets it to the tile origin so stage+ times are ``t_s(index) - t_s(clip_start)``.+ """++ latents: torch.Tensor+ pixel_frame_indices: torch.Tensor+ clip_start_frame: int = 0++ def validate(self, *, num_frames: int | None = None) -> None:+ """Raise if shapes/indices are inconsistent (optionally against a frame count)."""+ if self.latents.ndim != 5:+ raise ValueError(f"keyframe latents must be (B, C, P, H, W), got {tuple(self.latents.shape)}")+ if self.pixel_frame_indices.ndim != 1:+ raise ValueError(f"pixel_frame_indices must be 1-D (P,), got {tuple(self.pixel_frame_indices.shape)}")+ if self.clip_start_frame < 0:+ raise ValueError(f"clip_start_frame must be non-negative, got {self.clip_start_frame}")+ planes = self.latents.shape[2]+ if planes != self.pixel_frame_indices.shape[0]:+ raise ValueError(+ f"keyframe plane count {planes} != len(pixel_frame_indices) {self.pixel_frame_indices.shape[0]}"+ )+ if planes == 0:+ # An empty stack is a plain decode wearing a keyframe decode's costs, and every+ # backend has to special-case it (the slot tables are all -1, and gathering plane 0+ # of an empty axis is an out-of-bounds read). Say so here instead.+ raise ValueError("keyframe decode needs at least one plane; use decode_video() for a plain decode")+ if planes and int(self.pixel_frame_indices.min()) < 0:+ raise ValueError("pixel_frame_indices must be non-negative (global pixel frames)")+ if num_frames is not None and num_frames < 1:+ raise ValueError(f"num_frames must be positive, got {num_frames}")+ # Planes may sit outside [clip_start_frame, clip_start_frame + num_frames): Dist tiles+ # keep the nearest plane on each side so |dt| matches a whole-clip decode. A far plane+ # on a full clip is the same geometry -- joint attention ranks it by distance.++ def for_frame_span(self, frame_lo: int, frame_hi: int) -> "DecodeKeyframes":+ """Keep the planes a decode of pixel frames ``[lo, hi]`` needs; indices stay global.+ Selection is :func:`planes_for_tile`: every plane inside the span **plus the nearest+ plane on each side outside it**. Those two are not optional. DiffVAE's joint attention+ picks a frame's anchors by ``|dt|``, so a window ending at frame 64 whose last inside+ plane is 48 still has to carry the plane at 96 -- drop it and frames near the boundary+ anchor on 48 alone, which is exactly how a split decode stops matching a whole one.+ ``pixel_frame_indices`` are not rewritten. :attr:`clip_start_frame` becomes ``frame_lo``+ so the decoder subtracts ``t_s(48) - t_s(56)`` rather than treating the slice as a new+ clip that starts at pixel 0.+ """+ keep = planes_for_tile(self.pixel_frame_indices, frame_lo, frame_hi)+ return DecodeKeyframes(+ latents=self.latents[:, :, keep.to(self.latents.device)],+ pixel_frame_indices=self.pixel_frame_indices[keep.to(self.pixel_frame_indices.device)],+ clip_start_frame=frame_lo,+ )++ def crop_spatial(self, height: slice, width: slice) -> "DecodeKeyframes":+ """Crop the planes to a spatial window, with the *same* latent slices the video used.+ For a decode that splits the latent across workers (see+ :class:`~ltx_core.multigpu.vae.distributed_decoder.DistributedVideoDecoder`): each worker+ holds a crop of the video latent, so it must hold the matching crop of every keyframe+ plane. Cropping one and not the other offsets every plane from the video by the+ difference, which reads as ghosting rather than as an obvious failure.+ Plane count, ``pixel_frame_indices``, and :attr:`clip_start_frame` are untouched -- a+ spatial split leaves every worker the full frame range.+ """+ return DecodeKeyframes(+ latents=self.latents[:, :, :, height, width],+ pixel_frame_indices=self.pixel_frame_indices,+ clip_start_frame=self.clip_start_frame,+ )++ @property+ def num_planes(self) -> int:+ return int(self.latents.shape[2])+++@dataclass(frozen=True)+class KeyframeStream:+ """The keyframe half of the dual stream at one decoder stage.+ Attributes:+ x: ``(B, P, H, W, C)`` channels-last activations. ``H``/``W`` always match the+ video stream at the same stage; ``P`` is invariant across the whole decode.+ times: ``(P,)`` float32 plane position in *this stage's* temporal units and+ *local to the current tile* -- the same origin the video stream's RoPE uses.+ Both streams must share one origin or the joint softmax sees wrong offsets.+ valid: ``(P,)`` bool. Invalid planes are masked out of every softmax and their+ activations are re-zeroed after each upsample.+ """++ x: torch.Tensor+ times: torch.Tensor+ valid: torch.Tensor++ def masked(self) -> KeyframeStream:+ """Re-zero invalid planes' activations (channels-last plane axis)."""+ return KeyframeStream(x=self.x * self.valid[None, :, None, None, None], times=self.times, valid=self.valid)++ def select_planes(self, keep: torch.Tensor) -> KeyframeStream:+ """Subset the plane axis, keeping ``x``/``times``/``valid`` in step.+ ``keep`` is a ``(P,)`` bool mask. Used by tiled decode, which gives each tile only the+ planes near it -- see :func:`planes_for_tile`.+ """+ if keep.shape != (self.num_planes,):+ raise ValueError(f"keep must be ({self.num_planes},) bool, got {tuple(keep.shape)}")+ return KeyframeStream(x=self.x[:, keep], times=self.times[keep], valid=self.valid[keep])++ def crop_spatial(self, height: slice, width: slice) -> KeyframeStream:+ """Crop H/W with the *same* slices the video stream's tile used.+ Cropping only one stream offsets every plane from the video by the difference, which+ reads as ghosting rather than as an obvious failure -- the same hazard as the spatial+ padding rule.+ """+ return KeyframeStream(x=self.x[:, :, height, width, :], times=self.times, valid=self.valid)++ @property+ def num_planes(self) -> int:+ return int(self.x.shape[1])+++def keyframe_stage_times(pixel_frame_indices: torch.Tensor, remaining_time_stride: int) -> torch.Tensor:+ """Chunk-center position of each keyframe in a stage's temporal units.+ A stage whose remaining temporal upsampling is ``r`` has cells covering ``r`` pixel+ frames each, except cell 0 which covers only pixel frame 0 (the causal first frame).+ So ``t_s(0) = 0`` and ``t_s(f) = (f + (r - 1) / 2) / r`` -- the center of the chunk+ holding ``f``. At stage 5 ``r == 1``, making the times the raw pixel indices.+ Args:+ pixel_frame_indices: ``(P,)`` global pixel frame index per plane.+ remaining_time_stride: product of the temporal strides *still to come*.+ """+ if remaining_time_stride < 1:+ raise ValueError(f"remaining_time_stride must be positive, got {remaining_time_stride}")+ frames = pixel_frame_indices.to(torch.float32)+ center_offset = (remaining_time_stride - 1) / 2+ times = (frames + center_offset) / remaining_time_stride+ return torch.where(frames == 0, torch.zeros_like(times), times)+++def keyframe_clip_times(+ pixel_frame_indices: torch.Tensor,+ remaining_time_stride: int,+ clip_start_frame: int,+ extra_origin: float = 0.0,+) -> torch.Tensor:+ """Stage times relative to a decode whose first pixel frame is ``clip_start_frame``.+ ``t_s(global) - t_s(clip_start)`` is the gap joint attention should see. Rebasing the+ indices onto the tile (``48 -> -8``) and then calling :func:`keyframe_stage_times` is not+ the same: ``t_s`` is not linear through a fake clip start, so stages with ``r > 1`` get+ the wrong ``|dt|``.+ Single-GPU tiled decode uses ``clip_start_frame=0`` and passes the in-volume tile origin+ as ``extra_origin``. A Dist slice whose first pixel is global 56 uses+ ``clip_start_frame=56`` and ``extra_origin=0``.+ """+ times = keyframe_stage_times(pixel_frame_indices, remaining_time_stride)+ origin = keyframe_stage_times(+ torch.as_tensor([clip_start_frame], dtype=torch.int64, device=pixel_frame_indices.device),+ remaining_time_stride,+ )+ return times - origin - extra_origin+++def planes_for_tile(+ pixel_frame_indices: torch.Tensor,+ frame_lo: int,+ frame_hi: int,+ *,+ clip_start_frame: int = 0,+) -> torch.Tensor:+ """``(P,)`` bool: which planes a tile spanning pixel frames ``[lo, hi]`` should carry.+ Every plane inside the span, **plus the nearest plane on each side outside it**. Those two+ boundary planes are the point: without them a video frame at a tile edge ranks only+ in-tile planes and attends to the wrong one, which is what made tiled keyframe decode+ non-invariant. They arrive with negative / past-the-end tile-local times, and the+ ``(|dt|, index)`` slot ranking already handles those, so nothing downstream changes.+ Selection is by *value*, not position: ``pixel_frame_indices`` is not required to be+ sorted.+ Args:+ pixel_frame_indices: ``(P,)`` global pixel frame index per plane.+ frame_lo: first pixel frame in the tile, relative to ``clip_start_frame``.+ frame_hi: last pixel frame in the tile (inclusive), relative to ``clip_start_frame``.+ clip_start_frame: first global pixel of this latent. A full-clip decode leaves it 0.+ Dist tiles keep global indices and pass the slice origin so a local ``[0, 72)``+ still selects global ``[56, 127]``.+ """+ frame_lo = frame_lo + clip_start_frame+ frame_hi = frame_hi + clip_start_frame+ indices = pixel_frame_indices.to(torch.int64)+ keep = (indices >= frame_lo) & (indices <= frame_hi)+ before = indices < frame_lo+ if bool(before.any()):+ # Latest plane strictly before the tile.+ keep[int(torch.where(before, indices, torch.full_like(indices, -1)).argmax())] = True+ after = indices > frame_hi+ if bool(after.any()):+ # Earliest plane strictly after the tile.+ sentinel = int(indices.max()) + 1+ keep[int(torch.where(after, indices, torch.full_like(indices, sentinel)).argmin())] = True+ return keep+++def remaining_time_strides(upsamples: Sequence[torch.nn.Module]) -> tuple[int, ...]:+ """Remaining temporal upsampling at each stage input, plus 1 for stage 5.+ For the production ladder (temporal strides ``1, 2, 2, 2``) this is+ ``(8, 8, 4, 2, 1)``: stage ``i``'s blocks see the product of strides ``i..end``.+ """+ strides = [int(up.stride[0]) for up in upsamples]+ remaining: list[int] = []+ for index in range(len(strides)):+ product = 1+ for stride in strides[index:]:+ product *= stride+ remaining.append(product)+ remaining.append(1)+ return tuple(remaining)+++def upsample_keyframe_planes(upsample: torch.nn.Module, x: torch.Tensor) -> torch.Tensor:+ """Spatially upsample keyframe planes, keeping the plane count invariant.+ Each plane is folded into the batch as its own ``T=1`` clip and pushed through the+ *same* upsample module as video, always with ``drop_leading_frame=True``: a temporal+ stride of 2 expands ``T=1`` to 2 and the leading-frame drop takes it back to 1,+ keeping phase 1. So temporal strides collapse and only ``H``/``W`` grow.+ Passing ``drop_leading_frame=False`` here (as tiled video does for non-origin tiles)+ would invent a second temporal plane per keyframe and is always wrong.+ Args:+ upsample: the video stream's ``LinearPixelShuffleUpsample`` for this stage.+ x: ``(B, P, H, W, C)`` keyframe activations.+ """+ planes = x.shape[1]+ flat = rearrange(x, "b p h w c -> (b p) 1 h w c")+ upsampled = upsample(flat, drop_leading_frame=True)+ if upsampled.shape[1] != 1:+ raise RuntimeError(f"isolated keyframe upsampling must preserve one temporal plane, got T={upsampled.shape[1]}")+ out = rearrange(upsampled[:, 0], "(b p) h w c -> b p h w c", p=planes)+ if out.shape[1] != planes:+ raise RuntimeError(f"keyframe plane count changed under upsample: {planes} -> {out.shape[1]}")+ return out+++def _nearest_slots(+ query_times: torch.Tensor,+ candidate_times: torch.Tensor,+ candidate_valid: torch.Tensor | None,+ num_slots: int,+) -> torch.Tensor:+ """``(Q, num_slots)`` candidate indices ranked by ``(|dt|, index)``, ``-1`` when empty.+ A stable argsort on ``|dt|`` breaks ties by ascending candidate index, which is+ exactly upstream's ``distances + arange * 1e-6`` tie-break.+ """+ distances = (query_times[:, None] - candidate_times[None, :]).abs().to(torch.float32)+ if candidate_valid is not None:+ distances = distances.masked_fill(~candidate_valid[None, :], float("inf"))+ order = torch.argsort(distances, dim=-1, stable=True)+ take = min(num_slots, candidate_times.shape[0])+ chosen = order[:, :take]+ # Drop slots that only exist because every remaining candidate was invalid.+ finite = torch.gather(distances, 1, chosen).isfinite()+ chosen = torch.where(finite, chosen, torch.full_like(chosen, -1))+ if take < num_slots:+ pad = torch.full((chosen.shape[0], num_slots - take), -1, dtype=chosen.dtype, device=chosen.device)+ chosen = torch.cat([chosen, pad], dim=1)+ return chosen+++def video_keyframe_slots(+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ video_length: int,+ num_slots: int = KEYFRAME_CONTEXT_SLOTS,+) -> torch.Tensor:+ """``(T, num_slots)`` keyframe plane index per video frame, ``-1`` for an empty slot.+ Ranked by ``(|t_s(plane) - t|, plane)``. Deliberately independent of the temporal+ kernel: the nearest planes are visible even when they lie outside ``K_t``.+ """+ query = torch.arange(video_length, dtype=torch.float32, device=keyframe_times.device)+ return _nearest_slots(query, keyframe_times.to(torch.float32), keyframe_valid, num_slots)+++def keyframe_video_slots(+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ video_length: int,+ num_slots: int = KEYFRAME_CONTEXT_SLOTS,+) -> torch.Tensor:+ """``(P, num_slots)`` video frame index per keyframe plane, ``-1`` for an empty slot.+ Ranked by ``(|t' - t_s(plane)|, t')``. Rows of invalid planes are all ``-1``.+ """+ candidates = torch.arange(video_length, dtype=torch.float32, device=keyframe_times.device)+ slots = _nearest_slots(keyframe_times.to(torch.float32), candidates, None, num_slots)+ return torch.where(keyframe_valid[:, None], slots, torch.full_like(slots, -1))diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/model_configurator.py b/packages/ltx-core/src/ltx_core/model/video_vae/model_configurator.pyindex 89b7fb8..8f41435 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/model_configurator.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/model_configurator.py@@ -300,6 +300,8 @@ _BARE_DIFFUSION_DECODER_PREFIX = "decoder."_K_NORM_SUFFIX = ".attn.k_norm.weight"_CONTEXT_PROJ_WEIGHT_SUFFIX = ".context_proj.weight"_CONTEXT_PROJ_BIAS_SUFFIX = ".context_proj.bias"+_TYPE_EMB_KEY = "type_emb"+_CONV_IN_WEIGHT_KEY = "conv_in.weight"_UPSAMPLE3_WEIGHT_KEY = "upsamples.3.proj.weight"_UPSAMPLE3_BIAS_KEY = "upsamples.3.proj.bias"_GATE_PARAM_SUFFIXES = (".gate_msa", ".gate_mlp", ".gate_ctx")@@ -441,6 +443,29 @@ def _build_diffusion_vae_decoder_sd_ops(DIFFUSION_VAE_DECODER_COMFY_KEYS_FILTER = _build_diffusion_vae_decoder_sd_ops({})+def _checkpoint_has_type_emb(checkpoint_path: str | Path) -> bool:+ """Whether the checkpoint carries the keyframe ``type_emb`` tag."""+ with safetensors.safe_open(str(checkpoint_path), framework="pt", device="cpu") as handle:+ return any(_strip_diffusion_decoder_prefix(key) == _TYPE_EMB_KEY for key in handle.keys()) # noqa: SIM118+++def _emit_zero_type_emb(param_key: str, value: torch.Tensor) -> list[KeyValueOperationResult]:+ """Pass ``conv_in.weight`` through and synthesize a zero ``type_emb`` beside it.+ ``type_emb`` is registered unconditionally on the decoder but only exists in+ keyframe-trained checkpoints. The loader does a non-strict ``assign=True`` load onto a+ meta model, so a missing parameter would stay on the meta device -- and+ ``_check_uninitialized`` then returns the whole decoder still on meta, breaking every+ pre-keyframe checkpoint. Synthesizing zeros here keeps those checkpoints loadable and+ is exactly the no-op the tag has when untrained (it is added to the keyframe latents,+ and zero means "no tag"). Attached to ``conv_in.weight`` because it always exists and+ its ``(out, in)`` shape carries the latent width.+ """+ return [+ KeyValueOperationResult(param_key, value),+ KeyValueOperationResult(_TYPE_EMB_KEY, torch.zeros(value.shape[1], dtype=value.dtype)),+ ]++def _emit_na_softmax_bound(param_key: str, value: torch.Tensor) -> list[KeyValueOperationResult]:"""Pass ``attn.k_norm.weight`` through and emit the DSL kernel's softmax bound beside it.The CuTe DSL neighborhood-attention kernel replaces the online row max with a fixed@@ -496,9 +521,9 @@ class _Stage4Hop:context_biases: dict[str, torch.Tensor] = {}with safetensors.safe_open(str(checkpoint_path), framework="pt", device="cpu") as handle:for key in handle.keys(): # noqa: SIM118- if not key.startswith(_RAW_DIFFUSION_DECODER_PREFIX):+ short = _strip_diffusion_decoder_prefix(key)+ if short is None:continue- short = key.removeprefix(_RAW_DIFFUSION_DECODER_PREFIX)if short == _UPSAMPLE3_WEIGHT_KEY:upsample_weight = handle.get_tensor(key)elif short == _UPSAMPLE3_BIAS_KEY:@@ -558,8 +583,12 @@ def video_decoder_sd_ops_for_checkpoint(if not diffusion_vae:return VAE_DECODER_COMFY_KEYS_FILTERgates = _read_diff_vae_gates(checkpoint_path)- if not na_dsl_kernel:- return _build_diffusion_vae_decoder_sd_ops(gates)- return _build_diffusion_vae_decoder_sd_ops(gates, stage4_hop=_Stage4Hop.read(checkpoint_path)).with_kv_operation(- operation=_emit_na_softmax_bound, key_suffix=_K_NORM_SUFFIX- )+ if na_dsl_kernel:+ ops = _build_diffusion_vae_decoder_sd_ops(gates, stage4_hop=_Stage4Hop.read(checkpoint_path)).with_kv_operation(+ operation=_emit_na_softmax_bound, key_suffix=_K_NORM_SUFFIX+ )+ else:+ ops = _build_diffusion_vae_decoder_sd_ops(gates)+ if not _checkpoint_has_type_emb(checkpoint_path):+ ops = ops.with_kv_operation(operation=_emit_zero_type_emb, key_suffix=_CONV_IN_WEIGHT_KEY)+ return opsdiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/apply.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/apply.pyindex b4a619f..b9d34a7 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/apply.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/apply.py@@ -37,6 +37,7 @@ from ltx_core.model.video_vae.transformer.dsl_kernels.block import DSLDiffusionNfrom ltx_core.model.video_vae.transformer.fallback_na import (EagerSdpaAttention,TritonNaAttention,+ joint_na_attention,triton_na_available,warn_no_natten,)@@ -56,24 +57,21 @@ def _block_cls_for(cfg: DiffVAEConfig) -> type[DiffusionNABlock]:def resolve_attention_for_host(cfg: DiffVAEConfig) -> DiffVAEConfig:- """Remap chunked NATTEN recipes to Triton/eager when natten is missing.- ``COMBINED`` (full-volume) compile requires natten — Dynamo + fallback NA is- not supported. Chunked modes remapped to fallback also disable ``torch.compile``- for now (fallback NA is an opaque custom_op, but the remap still keeps the- no-natten path on the eager chunked recipe).+ """Remap NATTEN recipes to Triton/eager when natten is missing.+ Both fallback backends are opaque ``custom_op``s, so Dynamo traces straight over them and+ ``COMBINED`` keeps its compilation. Chunked modes remapped to fallback drop ``torch.compile``+ instead: there it would only cover the attn+mlp region, which is exactly what+ ``CHUNKED_COMPILE``'s higher memory coefficient pays for, so a no-natten host is better served+ by the eager chunked recipe. Auto tiling reads this decision back through+ :func:`~ltx_core.model.video_vae.diffusion_tiling.stage5_mem_coef`."""if cfg.attention is not NAttentionKind.NATTEN:return cfgif natten_available():return cfg- if cfg.block is DiffVAEBlockKind.COMBINED:- raise RuntimeError(- "diffvae_optimization=combined_compile requires natten "- "(full-volume NA + torch.compile). Install with: "- "uv sync --package ltx-core --extra natten "- "(or use chunked_eager / chunked_compile, which fall back to Triton/eager)."- )kind = NAttentionKind.TRITON if triton_na_available() else NAttentionKind.EAGER_SDPA+ if cfg.block is DiffVAEBlockKind.COMBINED:+ return replace(cfg, attention=kind, natten_backend=None)return replace(cfg,attention=kind,@@ -102,6 +100,27 @@ def _set_attention_function(decoder: DiffusionVideoDecoder, attn_fn: object) ->module.natten_backend = None+def _install_joint_attention(decoder: DiffusionVideoDecoder, cfg: DiffVAEConfig) -> None:+ """Install the keyframe-aware backend on every NA module, for every mode.+ This is the whole "natten only when installed **and** no keyframes" gate: it lives in+ a slot of its own, so keyframe-less decode keeps whatever ``attention_function`` the+ mode chose (NATTEN when installed) while keyframe decode always routes here -- NATTEN+ cannot express a joint window. It also survives ``configure_natten_backend``-style+ wholesale overwrites of ``attention_function``.+ The CuTe DSL kernel *can* express it, and under ``BLACKWELL_DSL`` it is preferred, with+ ``joint_na_attention()`` behind it for the calls it cannot serve -- a CPU module, a volume+ under its halo panel, or a checkpoint loaded without the DSL SDOps.+ """+ joint = joint_na_attention()+ if cfg.attention is NAttentionKind.BLACKWELL_DSL:+ from ltx_core.model.video_vae.transformer.dsl_kernels import DSLJointAttention # noqa: PLC0415++ joint = DSLJointAttention(joint)+ for module in decoder.modules():+ if isinstance(module, NeighborhoodAttention3D):+ module.joint_attention_function = joint # type: ignore[assignment]++def _install_attention(decoder: DiffusionVideoDecoder, cfg: DiffVAEConfig) -> None:if cfg.attention is NAttentionKind.BLACKWELL_DSL:from ltx_core.model.video_vae.transformer.dsl_kernels.apply_dsl import ( # noqa: PLC0415@@ -142,6 +161,7 @@ def apply_diffvae_config(configure_w_chunks(block, cfg.w_chunks)_install_attention(decoder, cfg)+ _install_joint_attention(decoder, cfg)if cfg.compile_blocks:compile_diffusion_decoder(diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/attention.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/attention.pyindex 550782b..5a73311 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/attention.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/attention.py@@ -7,12 +7,13 @@ det stages use ``det_attn_rope`` from :meth:`NeighborhoodAttention3D.forward`.from __future__ import annotations-from typing import Protocol+import dataclasses+from typing import TYPE_CHECKING, Protocolimport torchfrom torch import nn-from ltx_core.model.video_vae.transformer.det_attn_rope import det_qkv_rope+from ltx_core.model.video_vae.transformer.det_attn_rope import det_qkv_rope, det_qkv_rope_at_timesfrom ltx_core.model.video_vae.transformer.qkv import QKVProjectionsfrom ltx_core.model.video_vae.transformer.rope_math import (DEFAULT_ABS_ROPE_NUM_TILES,@@ -20,6 +21,9 @@ from ltx_core.model.video_vae.transformer.rope_math import (rope_inv_freqs,)+if TYPE_CHECKING:+ from ltx_core.model.video_vae.keyframes import KeyframeStream+try:import natten@@ -50,6 +54,32 @@ class NAAttentionCallable(Protocol):) -> torch.Tensor: ...+class JointNAAttentionCallable(Protocol):+ """A windowed 3D NA backend that also carries a keyframe plane stack.+ Same conventions as :class:`NAAttentionCallable` -- Q/K/V already normed, scaled and+ absolutely RoPE'd -- with a second stream shaped ``(B, P, H, W, NH, HD)`` whose plane+ axis sits in video's temporal slot. Both streams' RoPE must share one origin, so+ ``keyframe_times`` are tile-local. Returns one output per stream.+ NATTEN and the CuTe DSL kernel cannot express a joint window, so this is a separate+ slot from ``attention_function`` rather than a widening of it: it keeps the shipping+ keyframe-less hot path untouched, and it is immune to the install-order hazard that+ ``configure_natten_backend`` creates by overwriting ``attention_function`` wholesale.+ """++ def __call__(+ self,+ attn: NeighborhoodAttention3D,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]: ...++class NattenAttention(NAAttentionCallable):"""``natten.na3d``, the default backend.``backend`` pins ``na3d``'s own kernel choice (e.g. ``"cutlass-fna"``); ``None``@@ -119,6 +149,9 @@ class NeighborhoodAttention3D(nn.Module):# Kept for the chunked opaque residual (string arg); callable is the swap surface.self.natten_backend: str | None = Noneself.attention_function: NAAttentionCallable = NattenAttention()+ # Separate slot, installed for every mode; never NATTEN/DSL. Only the keyframe+ # decode path reads it, so keyframe-less decode keeps NATTEN when it is installed.+ self.joint_attention_function: JointNAAttentionCallable | None = Noneself.register_buffer("rope_inv_t", rope_inv_freqs(rope_dim_split[0], rope_base), persistent=False)self.register_buffer("rope_inv_h", rope_inv_freqs(rope_dim_split[1], rope_base), persistent=False)@@ -160,6 +193,45 @@ class NeighborhoodAttention3D(nn.Module):out = out.reshape(batch, t, h, w, self.dim)return self.proj(out)+ def forward_with_keyframes(+ self,+ x: torch.Tensor,+ keyframes: KeyframeStream,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """Dual-stream det NA: one joint softmax over video and keyframe planes.+ Unlike :meth:`forward` there is no ``dims >= kernel_size`` floor: the joint window+ is clamp-and-mask, so an undersized axis simply masks its out-of-range offsets.+ """+ if self.joint_attention_function is None:+ raise RuntimeError(+ "keyframe decode needs joint_attention_function installed; build the decoder "+ "through apply_diffvae_config / apply_diffvae_mode"+ )+ batch, t, h, w, _ = x.shape+ planes = keyframes.x.shape[1]++ q, k, v = det_qkv_rope(self, x)+ keyframe_q, keyframe_k, keyframe_v = det_qkv_rope_at_times(self, keyframes.x, keyframes.times)+ q, k, v = q.contiguous(), k.contiguous(), v.contiguous()+ keyframe_q = keyframe_q.contiguous()+ keyframe_k = keyframe_k.contiguous()+ keyframe_v = keyframe_v.contiguous()++ out, keyframe_out = self.joint_attention_function(+ self,+ q,+ k,+ v,+ keyframe_q,+ keyframe_k,+ keyframe_v,+ keyframes.times,+ keyframes.valid,+ )+ out = self.proj(out.reshape(batch, t, h, w, self.dim))+ keyframe_out = self.proj(keyframe_out.reshape(batch, planes, h, w, self.dim))+ return out, dataclasses.replace(keyframes, x=keyframe_out)+def configure_w_chunks(module_root: nn.Module, w_chunks: int = 1) -> None:"""Set W-chunking on ``NeighborhoodAttention3D`` under ``module_root``.diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/blocks.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/blocks.pyindex 45f9d8e..152dd4d 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/blocks.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/blocks.py@@ -6,6 +6,9 @@ weights + shared AdaLN helpers only — no pathway forward.from __future__ import annotations+import dataclasses+from typing import TYPE_CHECKING+import torchfrom torch import nn@@ -13,6 +16,9 @@ from ltx_core.model.video_vae.transformer.attention import NeighborhoodAttentionfrom ltx_core.model.video_vae.transformer.layers import AdaLNZerofrom ltx_core.model.video_vae.transformer.swiglu import SwiGLU, plain_mlp+if TYPE_CHECKING:+ from ltx_core.model.video_vae.keyframes import KeyframeStream+__all__ = ["DiffusionNABlock","NABlock",@@ -43,6 +49,28 @@ class NABlock(nn.Module):x = plain_mlp(x, self.mlp, self.norm2, self.mlp.tile)return x+ def forward_with_keyframes(+ self,+ x: torch.Tensor,+ keyframes: KeyframeStream,+ ) -> tuple[torch.Tensor, KeyframeStream]:+ """Dual-stream block: video ``(B,T,H,W,C)`` and keyframe planes ``(B,P,H,W,C)``.+ Every weight is shared with :meth:`forward`; the streams meet only inside the+ joint attention softmax. Invalid planes are deliberately *not* re-zeroed here --+ the decoder re-zeroes after each upsample instead, matching upstream, so a masked+ plane's hidden state may drift within a stage. It is masked out of every softmax+ regardless, so this is cosmetic; reproducing it keeps us comparable.+ """+ attn_out, keyframe_attn = self.attn.forward_with_keyframes(+ self.norm1(x),+ dataclasses.replace(keyframes, x=self.norm1(keyframes.x)),+ )+ x = x + attn_out+ keyframe_x = keyframes.x + keyframe_attn.x+ x = plain_mlp(x, self.mlp, self.norm2, self.mlp.tile)+ keyframe_x = plain_mlp(keyframe_x, self.mlp, self.norm2, self.mlp.tile)+ return x, dataclasses.replace(keyframes, x=keyframe_x)+class DiffusionNABlock(nn.Module):"""Parameter shell for diffusion NA + SwiGLU with shared AdaLN-Zero.diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/attn.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/attn.pyindex febacea..79da5e0 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/attn.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/attn.py@@ -5,6 +5,13 @@ NA goes through ``attn.attention_function`` (same pluggable backend as combinedThe W-chunk loop stays behind opaque ``ltx_core::na_residual_w_chunked`` so Dynamodoes not unroll it; the callable is bound via a contextvar around the op call(custom_op schemas cannot take Python callables as args).+The keyframe (dual-stream) variant lives here too, behind its *own* op+``ltx_core::na_residual_w_chunked_joint`` rather than a widened+``mutates_args`` on the video-only op -- same reasoning as the separate+``joint_attention_function`` slot: the shipping hot path's schema stays byte-identical+and the keyframe arm remains trivially separable. Both streams are cut into the *same*+W slabs with the same ``halo`` and the same ``w_pos``, which is what keeps their W RoPE+phases comparable inside the joint softmax."""from __future__ import annotations@@ -19,6 +26,7 @@ import torch.nn.functional as Ffrom torch import nnfrom ltx_core.model.video_vae.transformer.attention import (+ JointNAAttentionCallable,NAAttentionCallable,NattenAttention,NeighborhoodAttention3D,@@ -67,6 +75,25 @@ def _resolve_chunked_attention() -> tuple[NAAttentionCallable, NeighborhoodAttenreturn fn, mod+def _resolve_chunked_joint_attention() -> tuple[JointNAAttentionCallable, NeighborhoodAttention3D]:+ """The joint backend for the keyframe arm, read off the bound NA module.+ Deliberately not a third contextvar: the joint callable lives in its own slot on the+ module, so binding the module is enough and there is one place it can come from.+ """+ mod = _CHUNKED_ATTN_MODULE.get()+ if mod is None:+ raise RuntimeError(+ "ltx_core::na_residual_w_chunked_joint requires NA module binding; "+ "call via chunked_with_keyframes(), not the custom_op directly"+ )+ if mod.joint_attention_function is None:+ raise RuntimeError(+ "keyframe decode needs joint_attention_function installed; build the decoder "+ "through apply_diffvae_config / apply_diffvae_mode"+ )+ return mod.joint_attention_function, mod++def _apply_in_slab_abs_rope(x: torch.Tensor,rope_split: tuple[int, int, int],@@ -74,17 +101,21 @@ def _apply_in_slab_abs_rope(w_pos: torch.Tensor,*,compute_dtype: torch.dtype,+ t_pos: torch.Tensor | None = None,) -> torch.Tensor:"""Single-extent abs-RoPE via raw rot (no RoPE tile loop, no nested region).Used inside the W-chunk residual body: the chunk is already one W slab.Nested-in-nested breaks FakeTensor mode matching under Inductor.``w_pos`` must be length ``x.shape[3]`` (global W coords for this slab).+ ``t_pos`` overrides the integer ``arange`` on the first axis; the keyframe stream+ passes its fractional plane times there so both streams' RoPE shares one origin."""d_t, d_h, _ = rope_splitinv_t, inv_h, inv_w = inv_freqst = x.shape[1]h = x.shape[2]- xt = rot_abs_axis_impl(x[..., :d_t], t_positions(t, x.device), inv_t, axis=1, compute_dtype=compute_dtype)+ positions_t = t_positions(t, x.device) if t_pos is None else t_pos+ xt = rot_abs_axis_impl(x[..., :d_t], positions_t, inv_t, axis=1, compute_dtype=compute_dtype)xh = rot_abs_axis_impl(x[..., d_t : d_t + d_h],h_positions(h, x.device),@@ -96,6 +127,43 @@ def _apply_in_slab_abs_rope(return torch.cat([xt, xh, xw], dim=-1)+def _slab_qkv( # noqa: PLR0913+ y: torch.Tensor,+ w_pos: torch.Tensor,+ q_w: torch.Tensor,+ q_b: torch.Tensor,+ k_w: torch.Tensor,+ k_b: torch.Tensor,+ v_w: torch.Tensor,+ v_b: torch.Tensor,+ q_norm_w: torch.Tensor,+ k_norm_w: torch.Tensor,+ rope_split: tuple[int, int, int],+ inv_freqs: tuple[torch.Tensor, torch.Tensor, torch.Tensor],+ num_heads: int,+ head_dim: int,+ attn_scale: float,+ rope_dtype: torch.dtype,+ *,+ t_pos: torch.Tensor | None = None,+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Q/K/V proj + norm/scale + in-slab abs-RoPE for one already-modulated W slab.+ Shared by the video-only and joint bodies so the two cannot drift apart in the+ numerics that feed the softmax.+ """+ batch, t, h, ext_w, _ = y.shape+ eps = 1e-6+ head_shape = (batch, t, h, ext_w, num_heads, head_dim)+ q = F.linear(y, q_w, q_b).view(head_shape)+ q = F.rms_norm(q, (head_dim,), q_norm_w, eps) * attn_scale+ q = _apply_in_slab_abs_rope(q, rope_split, inv_freqs, w_pos, compute_dtype=rope_dtype, t_pos=t_pos)+ k = F.linear(y, k_w, k_b).view(head_shape)+ k = F.rms_norm(k, (head_dim,), k_norm_w, eps)+ k = _apply_in_slab_abs_rope(k, rope_split, inv_freqs, w_pos, compute_dtype=rope_dtype, t_pos=t_pos)+ v = F.linear(y, v_w, v_b).view(head_shape)+ return q, k, v++def _attn_on_chunk_impl( # noqa: PLR0913attention_function: NAAttentionCallable,attn: NeighborhoodAttention3D | SimpleNamespace,@@ -136,22 +204,31 @@ def _attn_on_chunk_impl( # noqa: PLR0913raise ImportError("natten is required for W-chunked residual attention")batch, t, h, ext_w, _ = x_chunk.shape- eps = 1e-6rope_dtype = torch.bfloat16 if rope_compute_bf16 else torch.float32inv_freqs = (inv_t, inv_h, inv_w)rope_split = (d_t, d_h, d_w)- y = F.rms_norm(x_chunk, (dim,), norm_weight, eps)+ y = F.rms_norm(x_chunk, (dim,), norm_weight, 1e-6)y = y * (1.0 + scale) + shift- head_shape = (batch, t, h, ext_w, num_heads, head_dim)- q = F.linear(y, q_w, q_b).view(head_shape)- q = F.rms_norm(q, (head_dim,), q_norm_w, eps) * attn_scale- q = _apply_in_slab_abs_rope(q, rope_split, inv_freqs, w_pos, compute_dtype=rope_dtype)- k = F.linear(y, k_w, k_b).view(head_shape)- k = F.rms_norm(k, (head_dim,), k_norm_w, eps)- k = _apply_in_slab_abs_rope(k, rope_split, inv_freqs, w_pos, compute_dtype=rope_dtype)- v = F.linear(y, v_w, v_b).view(head_shape)+ q, k, v = _slab_qkv(+ y,+ w_pos,+ q_w,+ q_b,+ k_w,+ k_b,+ v_w,+ v_b,+ q_norm_w,+ k_norm_w,+ rope_split,+ inv_freqs,+ num_heads,+ head_dim,+ attn_scale,+ rope_dtype,+ )del yout = attention_function(attn, q.contiguous(), k.contiguous(), v.contiguous()) # type: ignore[arg-type]@@ -159,6 +236,85 @@ def _attn_on_chunk_impl( # noqa: PLR0913return F.linear(out.reshape(batch, t, h, ext_w, dim), proj_w, proj_b)+def _joint_attn_on_chunk_impl( # noqa: PLR0913+ joint_attention_function: JointNAAttentionCallable,+ attn: NeighborhoodAttention3D | SimpleNamespace,+ x_chunk: torch.Tensor,+ keyframe_chunk: torch.Tensor,+ w_pos: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ norm_weight: torch.Tensor,+ q_w: torch.Tensor,+ q_b: torch.Tensor,+ k_w: torch.Tensor,+ k_b: torch.Tensor,+ v_w: torch.Tensor,+ v_b: torch.Tensor,+ q_norm_w: torch.Tensor,+ k_norm_w: torch.Tensor,+ proj_w: torch.Tensor,+ proj_b: torch.Tensor,+ inv_t: torch.Tensor,+ inv_h: torch.Tensor,+ inv_w: torch.Tensor,+ d_t: int,+ d_h: int,+ d_w: int,+ kt: int,+ kh: int,+ kw: int,+ num_heads: int,+ head_dim: int,+ dim: int,+ attn_scale: float,+ rope_num_tiles: int,+ rope_compute_bf16: bool,+) -> tuple[torch.Tensor, torch.Tensor]:+ """One W-slab of both streams through a single joint softmax; shared weights.+ Both slabs get the same ``scale``/``shift`` and the same ``w_pos``; only the first RoPE+ axis differs, where the keyframe stream substitutes its fractional plane times.+ """+ del rope_num_tiles, kt, kh, kw # chunk is already one W slab; kernel_size lives on ``attn``+ batch, t, h, ext_w, _ = x_chunk.shape+ planes = keyframe_chunk.shape[1]+ rope_dtype = torch.bfloat16 if rope_compute_bf16 else torch.float32+ inv_freqs = (inv_t, inv_h, inv_w)+ rope_split = (d_t, d_h, d_w)+ weights = (q_w, q_b, k_w, k_b, v_w, v_b, q_norm_w, k_norm_w)+ meta = (rope_split, inv_freqs, num_heads, head_dim, attn_scale, rope_dtype)++ y = F.rms_norm(x_chunk, (dim,), norm_weight, 1e-6)+ y = y * (1.0 + scale) + shift+ keyframe_y = F.rms_norm(keyframe_chunk, (dim,), norm_weight, 1e-6)+ keyframe_y = keyframe_y * (1.0 + scale) + shift++ q, k, v = _slab_qkv(y, w_pos, *weights, *meta)+ del y+ times = keyframe_times.to(device=keyframe_chunk.device, dtype=torch.float32)+ keyframe_q, keyframe_k, keyframe_v = _slab_qkv(keyframe_y, w_pos, *weights, *meta, t_pos=times)+ del keyframe_y++ out, keyframe_out = joint_attention_function(+ attn, # type: ignore[arg-type]+ q.contiguous(),+ k.contiguous(),+ v.contiguous(),+ keyframe_q.contiguous(),+ keyframe_k.contiguous(),+ keyframe_v.contiguous(),+ times,+ keyframe_valid,+ )+ del q, k, v, keyframe_q, keyframe_k, keyframe_v+ return (+ F.linear(out.reshape(batch, t, h, ext_w, dim), proj_w, proj_b),+ F.linear(keyframe_out.reshape(batch, planes, h, ext_w, dim), proj_w, proj_b),+ )++@torch.compiler.disabledef _pack_residual_weights(attn: NeighborhoodAttention3D, norm: nn.RMSNorm, x: torch.Tensor) -> tuple:"""Pack NA + norm weights / RoPE meta for the opaque chunked residual op."""@@ -197,6 +353,58 @@ def _pack_residual_weights(attn: NeighborhoodAttention3D, norm: nn.RMSNorm, x: t)+def _cut_slab(+ x: torch.Tensor,+ core_start: int,+ core_end: int,+ halo: int,+ extent: int,+ left_halo: torch.Tensor | None,+ *,+ has_right_neighbor: bool,+) -> torch.Tensor:+ """One fixed-``extent`` W slab: core + neighbour halos + edge-replicated volume edges.+ ``left_halo`` is ``None`` exactly on the first slab (the true left W boundary); it is+ passed in rather than re-read from ``x`` because the caller mutates ``x`` in place as it+ goes, so the left halo has to be captured before the previous slab's ``add_``.+ Missing true-boundary halo slots are edge-replicated -- same spirit as trailing-frame+ replicate -- so attention never sees zero-padded W boundaries. This is a deliberate+ approximation of the untiled window at the two volume edges, and it is shared verbatim+ by the video-only and keyframe arms so both streams' slabs stay phase-comparable.+ """+ w = x.shape[3]+ c = x.shape[4]+ buf = x.new_zeros(*x.shape[:3], extent, c)+ core_len = core_end - core_start+ if left_halo is not None:+ lh = left_halo.shape[3]+ buf[:, :, :, halo - lh : halo, :] = left_halo+ buf[:, :, :, halo : halo + core_len, :] = x[:, :, :, core_start:core_end, :]+ right_filled = 0+ if has_right_neighbor:+ right_end = min(w, core_end + halo)+ right = x[:, :, :, core_end:right_end, :]+ right_filled = right.shape[3]+ buf[:, :, :, halo + core_len : halo + core_len + right_filled, :] = right++ # True W-boundary: replicate-pad missing halo slots (do not overwrite neighbors).+ if left_halo is None and halo > 0 and core_len > 0:+ edge_l = buf[:, :, :, halo : halo + 1, :]+ buf[:, :, :, :halo, :] = edge_l.expand(*x.shape[:3], halo, c)+ missing_right = extent - (halo + core_len + right_filled)+ if missing_right > 0 and core_len > 0:+ edge_r = buf[:, :, :, halo + core_len - 1 : halo + core_len, :]+ lo_r = halo + core_len + right_filled+ buf[:, :, :, lo_r:extent, :] = edge_r.expand(*x.shape[:3], missing_right, c)+ return buf+++def _slab_geometry(w: int, w_chunks: int, halo: int) -> tuple[int, int]:+ """``(chunk_w, extent)`` for a W-chunked pass."""+ chunk_w = (w + w_chunks - 1) // w_chunks+ return chunk_w, chunk_w + 2 * halo++def _run_w_chunked_residual(x: torch.Tensor,scale: torch.Tensor,@@ -211,40 +419,18 @@ def _run_w_chunked_residual(left/right halo slots (volume edges) are edge-replicated — same spirit astrailing-frame replicate — so NA never sees zero-padded W boundaries."""- _, _, _, w, c = x.shape- chunk_w = (w + w_chunks - 1) // w_chunks- extent = chunk_w + 2 * halo+ w = x.shape[3]+ chunk_w, extent = _slab_geometry(w, w_chunks, halo)left_halo: torch.Tensor | None = Nonefor i in range(w_chunks):core_start = i * chunk_wcore_end = min(w, (i + 1) * chunk_w)core_len = core_end - core_start+ has_right = i + 1 < w_chunks- buf = x.new_zeros(*x.shape[:3], extent, c)- if i > 0:- assert left_halo is not None- lh = left_halo.shape[3]- buf[:, :, :, halo - lh : halo, :] = left_halo- buf[:, :, :, halo : halo + core_len, :] = x[:, :, :, core_start:core_end, :]- right_filled = 0- if i + 1 < w_chunks:- right_end = min(w, core_end + halo)- right = x[:, :, :, core_end:right_end, :]- right_filled = right.shape[3]- buf[:, :, :, halo + core_len : halo + core_len + right_filled, :] = right-- # True W-boundary: replicate-pad missing halo slots (do not overwrite neighbors).- if i == 0 and halo > 0 and core_len > 0:- edge_l = buf[:, :, :, halo : halo + 1, :]- buf[:, :, :, :halo, :] = edge_l.expand(*x.shape[:3], halo, c)- missing_right = extent - (halo + core_len + right_filled)- if missing_right > 0 and core_len > 0:- edge_r = buf[:, :, :, halo + core_len - 1 : halo + core_len, :]- lo_r = halo + core_len + right_filled- buf[:, :, :, lo_r:extent, :] = edge_r.expand(*x.shape[:3], missing_right, c)-- if i + 1 < w_chunks:+ buf = _cut_slab(x, core_start, core_end, halo, extent, left_halo, has_right_neighbor=has_right)+ if has_right:take = min(halo, core_len)left_halo = x[:, :, :, core_end - take : core_end, :].clone()@@ -255,6 +441,72 @@ def _run_w_chunked_residual(return x+def _run_w_chunked_joint_residual(+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ packed: tuple,+ w_chunks: int,+ halo: int,+ attn_fn: Callable[..., tuple[torch.Tensor, torch.Tensor]],+) -> tuple[torch.Tensor, torch.Tensor]:+ """In-place dual-stream ``x += attn(...)`` / ``kf_x += attn(...)`` over shared W slabs.+ The two streams are cut with one geometry and one ``w_pos``, so a video core query and+ the keyframe keys it needs land at the same buffer offsets. That is why the keyframe+ stream must already share the video stream's ``H``/``W`` -- it does at stage 5, where+ keyframe upsampling is spatial-only, and it is checked rather than assumed.+ """+ if x.shape[2:4] != keyframe_x.shape[2:4]:+ raise ValueError(+ f"joint W-chunked residual needs matching (H, W); video {tuple(x.shape[2:4])} vs "+ f"keyframes {tuple(keyframe_x.shape[2:4])}"+ )+ w = x.shape[3]+ chunk_w, extent = _slab_geometry(w, w_chunks, halo)+ left_halo: torch.Tensor | None = None+ keyframe_left_halo: torch.Tensor | None = None++ for i in range(w_chunks):+ core_start = i * chunk_w+ core_end = min(w, (i + 1) * chunk_w)+ core_len = core_end - core_start+ has_right = i + 1 < w_chunks++ buf = _cut_slab(x, core_start, core_end, halo, extent, left_halo, has_right_neighbor=has_right)+ keyframe_buf = _cut_slab(+ keyframe_x,+ core_start,+ core_end,+ halo,+ extent,+ keyframe_left_halo,+ has_right_neighbor=has_right,+ )+ if has_right:+ take = min(halo, core_len)+ left_halo = x[:, :, :, core_end - take : core_end, :].clone()+ keyframe_left_halo = keyframe_x[:, :, :, core_end - take : core_end, :].clone()++ w_pos = torch.arange(extent, device=x.device, dtype=torch.float32) + (core_start - halo)+ out, keyframe_out = attn_fn(+ buf,+ keyframe_buf,+ w_pos,+ keyframe_times,+ keyframe_valid,+ scale,+ shift,+ *packed,+ )+ x[:, :, :, core_start:core_end, :].add_(out[:, :, :, halo : halo + core_len, :])+ keyframe_x[:, :, :, core_start:core_end, :].add_(keyframe_out[:, :, :, halo : halo + core_len, :])++ return x, keyframe_x++@torch.library.custom_op("ltx_core::na_residual_w_chunked", mutates_args=("x",))def _na_residual_w_chunked_op( # noqa: PLR0913x: torch.Tensor,@@ -401,6 +653,219 @@ def _na_residual_w_chunked_fake( # noqa: PLR0913)[email protected]_op("ltx_core::na_residual_w_chunked_joint", mutates_args=("x", "keyframe_x"))+def _na_residual_w_chunked_joint_op( # noqa: PLR0913+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ norm_weight: torch.Tensor,+ q_w: torch.Tensor,+ q_b: torch.Tensor,+ k_w: torch.Tensor,+ k_b: torch.Tensor,+ v_w: torch.Tensor,+ v_b: torch.Tensor,+ q_norm_w: torch.Tensor,+ k_norm_w: torch.Tensor,+ proj_w: torch.Tensor,+ proj_b: torch.Tensor,+ inv_t: torch.Tensor,+ inv_h: torch.Tensor,+ inv_w: torch.Tensor,+ d_t: int,+ d_h: int,+ d_w: int,+ kt: int,+ kh: int,+ kw: int,+ num_heads: int,+ head_dim: int,+ dim: int,+ attn_scale: float,+ rope_num_tiles: int,+ rope_compute_bf16: bool,+ w_chunks: int,+) -> None:+ """Opaque in-place dual-stream W-chunked residual (own op, video-only schema untouched).+ Reads the joint backend / NA module from the contextvars set by+ ``chunked_with_keyframes``. Slot tables are built inside the joint backend, so their+ T-dependent extents never reach Dynamo.+ """+ joint_attention_function, attn = _resolve_chunked_joint_attention()+ halo = kw // 2+ packed = (+ norm_weight,+ q_w,+ q_b,+ k_w,+ k_b,+ v_w,+ v_b,+ q_norm_w,+ k_norm_w,+ proj_w,+ proj_b,+ inv_t,+ inv_h,+ inv_w,+ d_t,+ d_h,+ d_w,+ kt,+ kh,+ kw,+ num_heads,+ head_dim,+ dim,+ attn_scale,+ rope_num_tiles,+ rope_compute_bf16,+ )++ def _slab(+ x_chunk: torch.Tensor,+ keyframe_chunk: torch.Tensor,+ w_pos: torch.Tensor,+ times: torch.Tensor,+ valid: torch.Tensor,+ scale_: torch.Tensor,+ shift_: torch.Tensor,+ *rest: object,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ return _joint_attn_on_chunk_impl(+ joint_attention_function,+ attn,+ x_chunk,+ keyframe_chunk,+ w_pos,+ times,+ valid,+ scale_,+ shift_,+ *rest, # type: ignore[arg-type]+ )++ _run_w_chunked_joint_residual(+ x,+ keyframe_x,+ scale,+ shift,+ keyframe_times,+ keyframe_valid,+ packed,+ w_chunks,+ halo,+ _slab,+ )+++@_na_residual_w_chunked_joint_op.register_fake+def _na_residual_w_chunked_joint_fake( # noqa: PLR0913+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ norm_weight: torch.Tensor,+ q_w: torch.Tensor,+ q_b: torch.Tensor,+ k_w: torch.Tensor,+ k_b: torch.Tensor,+ v_w: torch.Tensor,+ v_b: torch.Tensor,+ q_norm_w: torch.Tensor,+ k_norm_w: torch.Tensor,+ proj_w: torch.Tensor,+ proj_b: torch.Tensor,+ inv_t: torch.Tensor,+ inv_h: torch.Tensor,+ inv_w: torch.Tensor,+ d_t: int,+ d_h: int,+ d_w: int,+ kt: int,+ kh: int,+ kw: int,+ num_heads: int,+ head_dim: int,+ dim: int,+ attn_scale: float,+ rope_num_tiles: int,+ rope_compute_bf16: bool,+ w_chunks: int,+) -> None:+ del (+ x,+ keyframe_x,+ scale,+ shift,+ keyframe_times,+ keyframe_valid,+ norm_weight,+ q_w,+ q_b,+ k_w,+ k_b,+ v_w,+ v_b,+ q_norm_w,+ k_norm_w,+ proj_w,+ proj_b,+ inv_t,+ inv_h,+ inv_w,+ d_t,+ d_h,+ d_w,+ kt,+ kh,+ kw,+ num_heads,+ head_dim,+ dim,+ attn_scale,+ rope_num_tiles,+ rope_compute_bf16,+ w_chunks,+ )+++def chunked_with_keyframes(+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ attn: NeighborhoodAttention3D,+ norm: nn.RMSNorm,+ scale: torch.Tensor,+ shift: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor]:+ """In-place dual-stream W-chunked residual through one joint softmax per slab.+ Keyframe counterpart of :func:`chunked`, using ``attn.joint_attention_function``+ (never natten) instead of ``attn.attention_function``.+ """+ if attn.w_chunks < 1:+ raise ValueError(f"w_chunks must be >= 1, got {attn.w_chunks}")+ packed = _pack_residual_weights(attn, norm, x)+ with _bound_chunked_attention(attn.attention_function, attn):+ _na_residual_w_chunked_joint_op(+ x,+ keyframe_x,+ scale,+ shift,+ keyframe_times,+ keyframe_valid,+ *packed,+ attn.w_chunks,+ )+ return x, keyframe_x++def chunked(x: torch.Tensor,attn: NeighborhoodAttention3D,diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/block.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/block.pyindex db567b2..e8e49b7 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/block.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/block.py@@ -6,7 +6,11 @@ import torchfrom ltx_core.model.video_vae.transformer.blocks import DiffusionNABlockfrom ltx_core.model.video_vae.transformer.chunked.attn import chunked as residual_attn+from ltx_core.model.video_vae.transformer.chunked.attn import (+ chunked_with_keyframes as residual_attn_with_keyframes,+)from ltx_core.model.video_vae.transformer.chunked.context import deferred as inject_context+from ltx_core.model.video_vae.transformer.chunked.context import deferred_keyframes as inject_keyframe_contextfrom ltx_core.model.video_vae.transformer.chunked.mlp import residual_modulating_mlpfrom ltx_core.model.video_vae.transformer.layers import LinearPixelShuffleUpsample@@ -35,6 +39,89 @@ class ChunkedDiffusionNABlock(DiffusionNABlock):x = residual_modulating_mlp(x, self.mlp, self.norm2, scale_mlp, shift_mlp, self.mlp.tile)return x+ def forward_attn_mlp_with_keyframes(+ self,+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ scale_msa: torch.Tensor,+ shift_msa: torch.Tensor,+ scale_mlp: torch.Tensor,+ shift_mlp: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Dual-stream chunked NA residual + modulating SwiGLU, both in place.+ Invalid keyframe planes are re-zeroed on the way out, matching+ :meth:`~ltx_core.model.video_vae.transformer.combined.block.CombinedDiffusionNABlock.forward_combined_with_keyframes`.+ ``mul_`` rather than ``*`` keeps the buffer identity the in-place chunked pathway+ depends on, so the next block's deferred inject writes into the same tensor.+ """+ x, keyframe_x = residual_attn_with_keyframes(+ x,+ keyframe_x,+ self.attn,+ self.norm1,+ scale_msa,+ shift_msa,+ keyframe_times,+ keyframe_valid,+ )+ x = residual_modulating_mlp(x, self.mlp, self.norm2, scale_mlp, shift_mlp, self.mlp.tile)+ keyframe_x = residual_modulating_mlp(keyframe_x, self.mlp, self.norm2, scale_mlp, shift_mlp, self.mlp.tile)+ keyframe_x.mul_(keyframe_valid[None, :, None, None, None])+ return x, keyframe_x++ def forward_x_ctx_with_keyframes(+ self,+ x: torch.Tensor,+ stage4_feat: torch.Tensor,+ keyframe_x: torch.Tensor,+ keyframe_stage4_feat: torch.Tensor,+ modulation: tuple[torch.Tensor, ...],+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ *,+ drop_leading_frame: bool = True,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Deferred-context dual-stream block: per-stream inject, then joint attn + MLP.+ The keyframe inject always collapses its temporal stride (each plane is a ``T=1``+ clip), so ``drop_leading_frame`` applies to the video stream only -- it is a tiling+ property and must not leak into the keyframe arm.+ """+ if self.stage4_upsample is None:+ raise RuntimeError("stage4_upsample not configured; apply DiffVAEConfig with block=CHUNKED")++ scale_msa, shift_msa, scale_mlp, shift_mlp = self._modulation(modulation)+ upsample = self.stage4_upsample+ stride: tuple[int, int, int] = tuple(upsample.stride) # type: ignore[assignment]+ x = inject_context(+ x,+ stage4_feat,+ upsample.proj,+ self.context_proj,+ stride,+ w_chunks=self.attn.w_chunks,+ drop_leading_frame=drop_leading_frame,+ )+ keyframe_x = inject_keyframe_context(+ keyframe_x,+ keyframe_stage4_feat,+ upsample.proj,+ self.context_proj,+ stride,+ w_chunks=self.attn.w_chunks,+ )+ return self.forward_attn_mlp_with_keyframes(+ x,+ keyframe_x,+ scale_msa,+ shift_msa,+ scale_mlp,+ shift_mlp,+ keyframe_times,+ keyframe_valid,+ )+def forward_x_ctx(self,x: torch.Tensor,diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/context.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/context.pyindex 67130cf..5907c56 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/context.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/context.py@@ -86,3 +86,43 @@ def deferred(x[:, :, :, lo:hi, :].add_(ctx[:, :, :, : hi - lo, :])lo = hireturn x+++def deferred_keyframes(+ x: torch.Tensor,+ stage4_feat: torch.Tensor,+ upsample_proj: nn.Linear,+ context_proj: nn.Linear,+ stride: tuple[int, int, int],+ *,+ w_chunks: int,+) -> torch.Tensor:+ """Keyframe counterpart of :func:`deferred`. ``x``/``stage4_feat`` are ``(B, P, H, W, C)``.+ Each plane is its own ``T=1`` clip, so folding the plane axis into the batch turns this+ into exactly the video case and the whole W-chunk / halo policy is inherited rather than+ re-derived -- which is what keeps the two streams' W phases comparable downstream.+ ``drop_leading_frame`` is pinned ``True``: a temporal stride of 2 expands ``T=1`` to 2 and+ the drop takes it back to 1, keeping phase 1. Passing ``False`` (as tiled video does for+ non-origin tiles) would invent a second temporal plane per keyframe.+ The reshape is a view of a contiguous tensor, so :func:`deferred`'s in-place ``add_``+ writes through to ``x``. Returns ``x`` (mutated).+ """+ if x.shape[:2] != stage4_feat.shape[:2]:+ raise ValueError(+ f"keyframe x and stage-4 feat must share (B, P), got {tuple(x.shape[:2])} vs {tuple(stage4_feat.shape[:2])}"+ )+ if not x.is_contiguous():+ # A non-contiguous x makes the fold a copy instead of a view, and the inject would be+ # silently dropped rather than failing. Refuse instead of quietly decoding without it.+ raise ValueError("keyframe x must be contiguous channels-last so the plane fold stays a view")+ folded = x.shape[0] * x.shape[1]+ deferred(+ x.reshape(folded, 1, *x.shape[2:]),+ stage4_feat.reshape(folded, 1, *stage4_feat.shape[2:]),+ upsample_proj,+ context_proj,+ stride,+ w_chunks=w_chunks,+ drop_leading_frame=True,+ )+ return xdiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/mlp.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/mlp.pyindex adf98de..7131697 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/mlp.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/chunked/mlp.py@@ -11,6 +11,7 @@ from ltx_core.model.video_vae.transformer.swiglu import (_fused_gate_up_swiglu_triton,_fused_up_mul_torch,_fused_up_mul_triton,+ _resolve_use_triton,_tile_from_op_args,dual_gate_up_triton_eligible,token_intervals,@@ -67,12 +68,15 @@ def _chunked_residual_modulated_impl(if n_tok == 0:return+ # Triton needs every pointer on the launch device; all-CPU falls back to torch.mm.+ use_triton = _resolve_use_triton(bool(use_triton), x_flat, w_gate, w_up, w_down)+s, sh = _channel_affine_bc(scale, shift, dim)max_chunk = max((iv.end - iv.start for iv in intervals), default=0)workspace = torch.empty((max_chunk, hidden), device=x.device, dtype=x.dtype)y_buf = torch.empty((max_chunk, dim), device=x.device, dtype=x.dtype)out_buf = torch.empty((max_chunk, dim), device=x.device, dtype=x.dtype)- use_dual = bool(use_triton) and dual_gate_up_triton_eligible(x, w_gate, w_up)+ use_dual = use_triton and dual_gate_up_triton_eligible(x, w_gate, w_up)w_gate_c = w_gate.contiguous() if use_dual else w_gatew_up_c = w_up.contiguous() if use_triton else w_updiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/attn.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/attn.pyindex 49bb97c..efcb05b 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/attn.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/attn.py@@ -26,13 +26,18 @@ def _apply_nested_abs_rope_slab(*,w_pos: torch.Tensor,compute_dtype: torch.dtype,+ t_pos: torch.Tensor | None = None,) -> torch.Tensor:- """Rotate one W-extent with nested per-axis abs-RoPE."""+ """Rotate one W-extent with nested per-axis abs-RoPE.+ ``t_pos`` overrides the integer ``arange`` on the first axis; the keyframe stream passes+ its fractional plane times there so both streams' RoPE shares one origin.+ """d_t, d_h, _ = rope_splitinv_t, inv_h, inv_w = inv_freqst = x.shape[1]h = x.shape[2]- xt = _rot_abs_axis(x[..., :d_t], t_positions(t, x.device), inv_t, axis=1, compute_dtype=compute_dtype)+ positions_t = t_positions(t, x.device) if t_pos is None else t_pos+ xt = _rot_abs_axis(x[..., :d_t], positions_t, inv_t, axis=1, compute_dtype=compute_dtype)xh = _rot_abs_axis(x[..., d_t : d_t + d_h],h_positions(h, x.device),@@ -51,8 +56,13 @@ def _apply_nested_full_volume_rope(*,num_tiles: int,compute_dtype: torch.dtype,+ t_pos: torch.Tensor | None = None,) -> torch.Tensor:- """Fixed-``num_tiles`` W split + nested per-slab rotation (Dynamo-safe)."""+ """Fixed-``num_tiles`` W split + nested per-slab rotation (Dynamo-safe).+ Both streams share the same W extent at stage 5, so the same ``num_tiles`` gives+ identical slab boundaries and ``w_pos`` -- required for their W phases to be comparable+ inside the joint softmax.+ """slabs = torch.chunk(x, num_tiles, dim=3)w_off = 0parts: list[torch.Tensor] = []@@ -66,14 +76,22 @@ def _apply_nested_full_volume_rope(inv_freqs,w_pos=w_pos,compute_dtype=compute_dtype,+ t_pos=t_pos,))w_off = w_off + w_slabreturn torch.cat(parts, dim=3)-def _qkv_nested_rope(attn: NeighborhoodAttention3D, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- """Q/K/V proj + norm/scale + nested full-volume abs-RoPE."""+def _qkv_nested_rope(+ attn: NeighborhoodAttention3D,+ x: torch.Tensor,+ t_pos: torch.Tensor | None = None,+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Q/K/V proj + norm/scale + nested abs-RoPE.+ ``t_pos`` overrides the integer first-axis positions; the keyframe stream passes+ its (possibly fractional) plane times there.+ """q, k, v = attn.project_qkv(x)q = attn.q_norm(q) * attn.scalek = attn.k_norm(k)@@ -82,12 +100,14 @@ def _qkv_nested_rope(attn: NeighborhoodAttention3D, x: torch.Tensor) -> tuple[toattn.rope_inv_h.to(device=x.device),attn.rope_inv_w.to(device=x.device),)+ positions = None if t_pos is None else t_pos.to(device=x.device, dtype=torch.float32)q = _apply_nested_full_volume_rope(q,attn.rope_dim_split,inv_freqs,num_tiles=attn.rope_num_tiles,compute_dtype=attn.rope_compute_dtype,+ t_pos=positions,)k = _apply_nested_full_volume_rope(k,@@ -95,10 +115,64 @@ def _qkv_nested_rope(attn: NeighborhoodAttention3D, x: torch.Tensor) -> tuple[toinv_freqs,num_tiles=attn.rope_num_tiles,compute_dtype=attn.rope_compute_dtype,+ t_pos=positions,)return q, k, v+def full_with_keyframes(+ x: torch.Tensor,+ keyframe_x: torch.Tensor,+ attn: NeighborhoodAttention3D,+ norm: nn.RMSNorm,+ scale: torch.Tensor,+ shift: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Dual-stream AdaLN residual attention: one joint softmax, shared weights.+ Plain tensors rather than a ``KeyframeStream`` here: this is the stage-5 hot path, and+ rebuilding a dataclass per block inside a compiled region buys nothing.+ Both streams take the *same* ``scale``/``shift``. Upstream computes a separate keyframe+ modulation, but the two are identical unless per-frame timestep conditioning supplies a+ conditioning mask, which we deliberately do not implement yet.+ No ``dims >= kernel_size`` floor, unlike :func:`full`: the joint window is+ clamp-and-mask, so undersized axes simply mask their out-of-range offsets.+ """+ if attn.joint_attention_function is None:+ raise RuntimeError(+ "keyframe decode needs joint_attention_function installed; build the decoder "+ "through apply_diffvae_config / apply_diffvae_mode"+ )+ batch, t, h, w, _ = x.shape+ planes = keyframe_x.shape[1]++ y = norm(x) * (1.0 + scale) + shift+ keyframe_y = norm(keyframe_x) * (1.0 + scale) + shift++ q, k, v = _qkv_nested_rope(attn, y)+ keyframe_q, keyframe_k, keyframe_v = _qkv_nested_rope(attn, keyframe_y, keyframe_times)+ q, k, v = q.contiguous(), k.contiguous(), v.contiguous()+ keyframe_q = keyframe_q.contiguous()+ keyframe_k = keyframe_k.contiguous()+ keyframe_v = keyframe_v.contiguous()++ out, keyframe_out = attn.joint_attention_function(+ attn,+ q,+ k,+ v,+ keyframe_q,+ keyframe_k,+ keyframe_v,+ keyframe_times,+ keyframe_valid,+ )+ x = x + attn.proj(out.reshape(batch, t, h, w, attn.dim))+ keyframe_x = keyframe_x + attn.proj(keyframe_out.reshape(batch, planes, h, w, attn.dim))+ return x, keyframe_x++def full(x: torch.Tensor,attn: NeighborhoodAttention3D,diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/block.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/block.pyindex b7395b5..89d237f 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/block.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/combined/block.py@@ -6,6 +6,7 @@ import torchfrom ltx_core.model.video_vae.transformer.blocks import DiffusionNABlockfrom ltx_core.model.video_vae.transformer.combined.attn import full as residual_attn+from ltx_core.model.video_vae.transformer.combined.attn import full_with_keyframes as residual_attn_with_keyframesfrom ltx_core.model.video_vae.transformer.combined.context import combined as inject_contextfrom ltx_core.model.video_vae.transformer.combined.mlp import residual_mlp@@ -13,6 +14,38 @@ from ltx_core.model.video_vae.transformer.combined.mlp import residual_mlpclass CombinedDiffusionNABlock(DiffusionNABlock):"""Combined-context diffusion block: ``forward`` / ``forward_combined``."""+ def forward_combined_with_keyframes(+ self,+ context_and_x: torch.Tensor,+ keyframe_context_and_x: torch.Tensor,+ modulation: tuple[torch.Tensor, ...],+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Dual-stream block; returns the two updated x halves (not the concat buffers).+ Each stream gets its own ``context_proj(context)`` injection from its own+ ``[context | x]`` buffer, then both meet in one joint attention softmax, then each+ runs the shared MLP. Invalid keyframe planes are re-zeroed on the way out -- unlike+ the deterministic ``NABlock``, which leaves that to the decoder's post-upsample+ masking. Both asymmetries are upstream's.+ """+ scale_msa, shift_msa, scale_mlp, shift_mlp = self._modulation(modulation)+ x = inject_context(context_and_x, self.context_proj.weight, self.context_proj.bias)+ keyframe_x = inject_context(keyframe_context_and_x, self.context_proj.weight, self.context_proj.bias)+ x, keyframe_x = residual_attn_with_keyframes(+ x,+ keyframe_x,+ self.attn,+ self.norm1,+ scale_msa,+ shift_msa,+ keyframe_times,+ keyframe_valid,+ )+ x = residual_mlp(x, self.mlp, self.norm2, scale_mlp, shift_mlp, self.mlp.tile)+ keyframe_x = residual_mlp(keyframe_x, self.mlp, self.norm2, scale_mlp, shift_mlp, self.mlp.tile)+ return x, keyframe_x * keyframe_valid[None, :, None, None, None]+def forward_combined(self,context_and_x: torch.Tensor,diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/config.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/config.pyindex 2489fc3..79a3db3 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/config.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/config.py@@ -58,8 +58,12 @@ class DiffVAEMode(Enum):- **BLACKWELL_DSL:** datacenter Blackwell CuTe DSL NA + fused stage-5(deferred stage-4 inputs; upsample+context_proj inside the fused kernel).CHUNKED_* always use deferred stage-4 + w_chunks=4. COMBINED_COMPILE is- combined context + w_chunks=1 (best runtime, highest memory) and **requires- natten**. Chunked modes fall back to Triton/eager when natten is missing.+ combined context + w_chunks=1 (best runtime, highest memory). Every mode falls+ back to Triton/eager when natten is missing; only the chunked ones also drop+ compilation there (see ``apply.resolve_attention_for_host``).+ A keyframe decode is never compiled -- the compiled entry points are the+ keyframe-free ones -- so its memory budget follows the block shape rather than+ the mode's name. ``diffusion_tiling`` owns that table."""CHUNKED_EAGER = "chunked_eager"diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/det_attn_rope.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/det_attn_rope.pyindex 5888182..22b772b 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/det_attn_rope.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/det_attn_rope.py@@ -32,13 +32,18 @@ def _apply_opaque_rope_slab(*,w_pos: torch.Tensor,compute_dtype: torch.dtype,+ t_pos: torch.Tensor | None = None,) -> torch.Tensor:- """Rotate one W-extent with raw abs-RoPE (runs inside the opaque op)."""+ """Rotate one W-extent with raw abs-RoPE (runs inside the opaque op).+ ``t_pos`` overrides the default integer ``arange`` on the first axis; the keyframe+ stream passes its (possibly fractional) plane times there.+ """d_t, d_h, _ = rope_splitinv_t, inv_h, inv_w = inv_freqst = x.shape[1]h = x.shape[2]- xt = rot_abs_axis_impl(x[..., :d_t], t_positions(t, x.device), inv_t, axis=1, compute_dtype=compute_dtype)+ positions_t = t_positions(t, x.device) if t_pos is None else t_pos+ xt = rot_abs_axis_impl(x[..., :d_t], positions_t, inv_t, axis=1, compute_dtype=compute_dtype)xh = rot_abs_axis_impl(x[..., d_t : d_t + d_h],h_positions(h, x.device),@@ -57,8 +62,13 @@ def _apply_opaque_tiled_rope(*,num_tiles: int,compute_dtype: torch.dtype,+ t_pos: torch.Tensor | None = None,) -> torch.Tensor:- """Fixed-``num_tiles`` W split + per-slab rotation (body of the opaque op)."""+ """Fixed-``num_tiles`` W split + per-slab rotation (body of the opaque op).+ The keyframe stream shares the video stream's W extent at every stage, so passing the+ same ``num_tiles`` yields identical slab boundaries and identical ``w_pos`` -- which+ is what keeps the two streams' W phases comparable inside the joint softmax.+ """slabs = torch.chunk(x, num_tiles, dim=3)w_off = 0parts: list[torch.Tensor] = []@@ -72,6 +82,7 @@ def _apply_opaque_tiled_rope(inv_freqs,w_pos=w_pos,compute_dtype=compute_dtype,+ t_pos=t_pos,))w_off = w_off + w_slab@@ -144,13 +155,50 @@ def _apply_opaque_abs_rope()-def det_qkv_rope(attn: object, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- """Q/K/V proj + norm/scale + opaque full-volume abs-RoPE."""- q, k, v = attn.project_qkv(x) # type: ignore[attr-defined]- q = attn.q_norm(q) # type: ignore[attr-defined]- k = attn.k_norm(k) # type: ignore[attr-defined]- q = q * attn.scale # type: ignore[attr-defined][email protected]_op("ltx_core::abs_rope_at_t", mutates_args=())+def _abs_rope_at_t_op(+ x: torch.Tensor,+ t_pos: torch.Tensor,+ inv_t: torch.Tensor,+ inv_h: torch.Tensor,+ inv_w: torch.Tensor,+ d_t: int,+ d_h: int,+ d_w: int,+ num_tiles: int,+ compute_dtype_is_bf16: bool,+) -> torch.Tensor:+ """Opaque abs-RoPE with caller-supplied (possibly fractional) first-axis positions."""+ compute_dtype = torch.bfloat16 if compute_dtype_is_bf16 else torch.float32+ return _apply_opaque_tiled_rope(+ x,+ (d_t, d_h, d_w),+ (inv_t, inv_h, inv_w),+ num_tiles=num_tiles,+ compute_dtype=compute_dtype,+ t_pos=t_pos,+ )+++@_abs_rope_at_t_op.register_fake+def _abs_rope_at_t_fake(+ x: torch.Tensor,+ t_pos: torch.Tensor,+ inv_t: torch.Tensor,+ inv_h: torch.Tensor,+ inv_w: torch.Tensor,+ d_t: int,+ d_h: int,+ d_w: int,+ num_tiles: int,+ compute_dtype_is_bf16: bool,+) -> torch.Tensor:+ del t_pos, inv_t, inv_h, inv_w, d_t, d_h, d_w, num_tiles, compute_dtype_is_bf16+ return torch.empty(x.shape, device=x.device, dtype=x.dtype)++def _rope_config(attn: object, x: torch.Tensor) -> tuple[tuple[torch.Tensor, ...], int, torch.dtype]:+ """``(inv_freqs, num_tiles, compute_dtype)`` read off an attention module."""inv_freqs = (attn.rope_inv_t.to(device=x.device), # type: ignore[attr-defined]attn.rope_inv_h.to(device=x.device), # type: ignore[attr-defined]@@ -158,6 +206,57 @@ def det_qkv_rope(attn: object, x: torch.Tensor) -> tuple[torch.Tensor, torch.Ten)num_tiles = getattr(attn, "rope_num_tiles", DEFAULT_ABS_ROPE_NUM_TILES)compute_dtype = getattr(attn, "rope_compute_dtype", torch.float32)+ return inv_freqs, num_tiles, compute_dtype+++def _det_project_qkv(attn: object, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Shared Q/K/V proj + norm + scale for :func:`det_qkv_rope` and ``_at_times``."""+ q, k, v = attn.project_qkv(x) # type: ignore[attr-defined]+ q = attn.q_norm(q) # type: ignore[attr-defined]+ k = attn.k_norm(k) # type: ignore[attr-defined]+ q = q * attn.scale # type: ignore[attr-defined]+ return q, k, v+++def det_qkv_rope_at_times(+ attn: object,+ x: torch.Tensor,+ t_pos: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Q/K/V proj + norm/scale + abs-RoPE with explicit first-axis positions.+ The keyframe-stream counterpart of :func:`det_qkv_rope`. ``t_pos`` is ``(P,)`` float+ stage times *in the same origin* the video stream's RoPE uses, so the joint softmax+ sees true relative offsets: absolute-vs-local RoPE only cancels as a global phase+ when every token in the softmax shares one origin, which no longer holds once+ keyframe tokens join a video window.+ """+ if t_pos.ndim != 1 or t_pos.shape[0] != x.shape[1]:+ raise ValueError(f"t_pos must be ({x.shape[1]},) to match the plane axis, got {tuple(t_pos.shape)}")+ q, k, v = _det_project_qkv(attn, x)++ inv_freqs, num_tiles, compute_dtype = _rope_config(attn, x)+ d_t, d_h, d_w = attn.rope_dim_split # type: ignore[attr-defined]+ positions = t_pos.to(device=x.device, dtype=torch.float32)+ rotated = [+ _abs_rope_at_t_op(+ tensor,+ positions,+ *inv_freqs,+ d_t,+ d_h,+ d_w,+ num_tiles,+ compute_dtype == torch.bfloat16,+ )+ for tensor in (q, k)+ ]+ return rotated[0], rotated[1], v+++def det_qkv_rope(attn: object, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Q/K/V proj + norm/scale + opaque full-volume abs-RoPE."""+ q, k, v = _det_project_qkv(attn, x)+ inv_freqs, num_tiles, compute_dtype = _rope_config(attn, x)q = _apply_opaque_abs_rope(q,attn.rope_dim_split, # type: ignore[attr-defined]diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/__init__.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/__init__.pyindex 6b3d4a6..39a46d7 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/__init__.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/__init__.py@@ -20,6 +20,11 @@ from ltx_core.model.video_vae.transformer.dsl_kernels.chain import (alloc_block_volume,linear_into_block_volume,)+from ltx_core.model.video_vae.transformer.dsl_kernels.joint_attn import (+ DSLJointAttention,+ dsl_joint_supported,+ na_attention_joint_dsl,+)__all__ = ["FUSED_CTX_BIAS_BUFFER",@@ -29,11 +34,14 @@ __all__ = ["DSLChannelLinear","DSLDiffusionBlockChain","DSLDiffusionNABlock",+ "DSLJointAttention","alloc_block_volume",+ "dsl_joint_supported","enable_blackwell_dsl","fused_na_block_supported","linear_into_block_volume","na_attention_dsl",+ "na_attention_joint_dsl","na_dsl_available","require_softmax_bound",]diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/block.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/block.pyindex 567a9e4..223805a 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/block.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/block.py@@ -86,6 +86,63 @@ class DSLDiffusionNABlock(DiffusionNABlock):) -> torch.Tensor:return self.forward_x_ctx(x, stage4_feat, modulation, drop_leading_frame=drop_leading_frame, out=out)+ @torch.compiler.disable+ def forward_x_ctx_with_keyframes(+ self,+ x: torch.Tensor,+ stage4_feat: torch.Tensor,+ keyframe_x: torch.Tensor,+ keyframe_stage4_feat: torch.Tensor,+ modulation: tuple[torch.Tensor, ...],+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ *,+ drop_leading_frame: bool = True,+ out: torch.Tensor | None = None,+ out_keyframes: torch.Tensor | None = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Both streams in one fused launch, joint softmax included.+ Signature-compatible with ``chunked.block``'s method of the same name, so the+ decoder's deferred keyframe loop drives either without knowing which it has.+ ``drop_leading_frame`` is the video stream's alone: each plane is a ``T=1`` clip whose+ temporal stride collapses, so the kernel always takes the subpixel a one-frame input+ shuffles out to. That is a tiling property and must not leak into the anchor arm.+ ``keyframe_valid`` is applied by dropping the invalid planes before the launch and+ restoring their rows as zeros -- the kernel has no notion of validity, and dropping is+ order-preserving, so the surviving planes rank identically under the ``(|dt|, index)``+ tie-break. Zero rows are the contract: an invalid plane's every key is masked.+ """+ keep = keyframe_valid.nonzero().flatten()+ if int(keep.numel()) == int(keyframe_x.shape[1]):+ return self._fused_forward_x_ctx(+ x,+ stage4_feat,+ modulation,+ drop_leading_frame=drop_leading_frame,+ out=out,+ keyframes=(keyframe_x, keyframe_stage4_feat, keyframe_times),+ out_keyframes=out_keyframes,+ )+ # Dropping planes shortens the anchor stream, so a buffer sized for the full plane+ # count no longer fits it -- and the result is scattered into a fresh tensor anyway.+ # The anchor stream forgoes recycling for this launch; the video stream does not.+ video_out, live = self._fused_forward_x_ctx(+ x,+ stage4_feat,+ modulation,+ drop_leading_frame=drop_leading_frame,+ out=out,+ keyframes=(+ keyframe_x.index_select(1, keep),+ keyframe_stage4_feat.index_select(1, keep),+ keyframe_times.index_select(0, keep),+ ),+ )+ restored = keyframe_x.new_zeros(keyframe_x.shape)+ if int(keep.numel()):+ restored.index_copy_(1, keep, live.to(dtype=restored.dtype))+ return video_out, restored+@torch.compiler.disabledef _fused_forward_x_ctx(self,@@ -95,8 +152,16 @@ class DSLDiffusionNABlock(DiffusionNABlock):*,drop_leading_frame: bool,out: torch.Tensor | None,- ) -> torch.Tensor:- """Marshal weights into :func:`ltx_kernels.vae.run_block_fna_dsl`."""+ keyframes: "tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None" = None,+ out_keyframes: torch.Tensor | None = None,+ ) -> "torch.Tensor | tuple[torch.Tensor, torch.Tensor]":+ """Marshal weights into :func:`ltx_kernels.vae.run_block_fna_dsl`.+ ``keyframes`` is ``(x, stage4_feat, times)`` for the anchor stream, and passing it+ makes the launch dual-stream and the return a pair. ``out_keyframes`` is that+ stream's recycled output buffer, the anchor-side counterpart of ``out``. Its stage-4 feature is the+ *pre*-upsample one, like the video's: the kernel runs the deferred hop over each+ plane in isolation, taking the temporal subpixel a one-frame input shuffles out to.+ """from ltx_kernels.vae import run_block_fna_dsl # noqa: PLC0415upsample = self.stage4_upsample@@ -113,7 +178,7 @@ class DSLDiffusionNABlock(DiffusionNABlock):modulation[i] + self.scale_shift_table[i].view(1, 1, 1, 1, -1) for i in range(AdaLNZero.NUM_CHUNKS)]attn = self.attn- return run_block_fna_dsl(+ result = run_block_fna_dsl(x,stage4_feat,w_ctx=w_fused,@@ -145,7 +210,21 @@ class DSLDiffusionNABlock(DiffusionNABlock):inv_w=attn.rope_inv_w.to(device=x.device),num_heads=attn.num_heads,attn_scale=attn.scale,+ **(+ {}+ if keyframes is None+ else {+ "x_keyframes": keyframes[0],+ "stage4_keyframes": keyframes[1],+ "keyframe_times": keyframes[2],+ "out_keyframes": out_keyframes,+ }+ ),rope_dim_split=tuple(attn.rope_dim_split),kernel_size=tuple(attn.kernel_size),out=out,- ).to(dtype=x.dtype)+ )+ if keyframes is None:+ return result.to(dtype=x.dtype)+ video_out, keyframe_out = result+ return video_out.to(dtype=x.dtype), keyframe_out.to(dtype=keyframes[0].dtype)diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/chain.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/chain.pyindex 1919b5e..c3bcd19 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/chain.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/chain.py@@ -53,8 +53,14 @@ class DSLChannelLinear(ChannelLinear):class DSLDiffusionBlockChain(nn.ModuleList):- """Stage-5 blocks as one callable chain, alternating two output buffers.- Signature matches deferred decode: ``(x, stage4_feat, modulation)``.+ """Stage-5 blocks as one callable chain, alternating two output buffers per stream.+ Signature matches deferred decode: ``(x, stage4_feat, modulation)``, with+ :meth:`forward_x_ctx_with_keyframes` as the joint entry.+ A block cannot write into its own input -- it reads neighborhoods of it -- so the+ chain keeps the buffer it *stopped* reading and hands that back as the next block's+ output. Two volumes per stream for the whole stage, rather than one per block. The+ first block still allocates, because the entry volume is the caller's and the chain+ has nothing spare yet; from the second on it alternates."""def forward(@@ -77,3 +83,41 @@ class DSLDiffusionBlockChain(nn.ModuleList):spare = _recyclable_rows(x)x = yreturn x++ def forward_x_ctx_with_keyframes(+ self,+ x: torch.Tensor,+ stage4_feat: torch.Tensor,+ keyframe_x: torch.Tensor,+ keyframe_stage4_feat: torch.Tensor,+ modulation: tuple[torch.Tensor, ...],+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ *,+ drop_leading_frame: bool = True,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """The joint chain, recycling both streams' buffers.+ The anchor stream alternates on its own pair: its volume is ``n_kf`` planes against+ the video's ``T`` frames, so the two buffer sizes differ and one pool cannot serve+ both. Same rule per stream -- last block's input becomes this block's output. A+ block that drops invalid planes returns a tight anchor tensor, which simply offers+ nothing to recycle on the next hop.+ """+ spare: torch.Tensor | None = None+ keyframe_spare: torch.Tensor | None = None+ for block in self:+ y, keyframe_y = block.forward_x_ctx_with_keyframes(+ x,+ stage4_feat,+ keyframe_x,+ keyframe_stage4_feat,+ modulation,+ keyframe_times,+ keyframe_valid,+ drop_leading_frame=drop_leading_frame,+ out=spare,+ out_keyframes=keyframe_spare,+ )+ spare, keyframe_spare = _recyclable_rows(x), _recyclable_rows(keyframe_x)+ x, keyframe_x = y, keyframe_y+ return x, keyframe_xdiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/joint_attn.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/joint_attn.pynew file mode 100644index 0000000..69d090d--- /dev/null+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/dsl_kernels/joint_attn.py@@ -0,0 +1,166 @@+"""The CuTe DSL kernel as a joint (video + keyframe) NA backend.+A third option at ``NeighborhoodAttention3D.joint_attention_function``, next to the Triton+and eager ones. The DSL kernel *can* express the joint window: it folds each visible+keyframe plane's ``Kh x Kw`` panel into the same fixed-offset accumulator as the local+window, so continuing the accumulation is already one softmax over both key sets -- no+rescale and no state merge, because the softmax offset is a bound rather than an online+max (see :mod:`ltx_kernels.vae.softmax_bound`).+It is not always selectable, so this is a *preference* rather than an install: the kernel+needs a datacenter Blackwell GPU, CUDA tensors, a filled softmax bound (only the+``BLACKWELL_DSL`` mode registers one) and a volume at least as large as its halo panel.+Whenever any of that fails the call goes to the backend this wraps.+Two things the seam offers that the kernel has no notion of, both handled here rather than+in the kernel:+``keyframe_valid``+ Invalid planes are dropped before the launch and their output rows restored as zeros+ afterwards. Dropping is order-preserving, so the surviving planes rank identically+ under the ``(|dt|, index)`` tie-break -- the compaction cannot change which plane a+ query selects, only what it is numbered.+``float64 / CPU tensors``+ Handed straight to the wrapped backend; the kernel is bf16 on device.+"""++from __future__ import annotations++import torch++from ltx_core.model.video_vae.transformer.attention import (+ JointNAAttentionCallable,+ NeighborhoodAttention3D,+)+from ltx_core.model.video_vae.transformer.dsl_kernels.attn import (+ NA_SOFTMAX_BOUND_BUFFER,+ na_dsl_available,+ require_softmax_bound,+)++[email protected]_op("ltx_core::na_attention_joint_dsl", mutates_args=())+def na_attention_joint_dsl( # noqa: PLR0913 -- a custom_op schema takes only flat tensors/ints+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ softmax_bound: torch.Tensor,+ kernel_size: list[int],+ num_slots: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Opaque joint DSL NA. Slot tables are built inside for the same reason as the others.+ Their extent depends on ``T``, which the decoder marks dynamic at five sites, so a table+ built outside would put a guard on those symbols -- an error there rather than a+ recompile.+ """+ from ltx_kernels.vae import run_na_attention_bound # noqa: PLC0415+ from ltx_kernels.vae.keyframe_slots import nearest_keyframe_slots # noqa: PLC0415++ planes = int(keyframe_q.shape[1])+ keep = keyframe_valid.nonzero().flatten()+ live_times = keyframe_times.index_select(0, keep)+ video_out, keyframe_out = run_na_attention_bound(+ q,+ k,+ v,+ kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),+ k_bound=softmax_bound,+ k_keyframes=keyframe_k.index_select(1, keep),+ v_keyframes=keyframe_v.index_select(1, keep),+ keyframe_slots=nearest_keyframe_slots(live_times, int(q.shape[1]), slots=num_slots),+ q_keyframes=keyframe_q.index_select(1, keep),+ keyframe_times=live_times,+ )+ video_out = video_out.reshape(q.shape)+ if int(keep.numel()) == planes:+ return video_out, keyframe_out.reshape(keyframe_q.shape)+ # Restore the dropped rows as zeros: an invalid plane's every key is masked, and the+ # contract is that such a row comes out exactly zero rather than NaN.+ restored = keyframe_q.new_zeros(keyframe_q.shape)+ if int(keep.numel()):+ restored.index_copy_(1, keep, keyframe_out.reshape(1, int(keep.numel()), *keyframe_q.shape[2:]))+ return video_out, restored+++@na_attention_joint_dsl.register_fake+def _na_attention_joint_dsl_fake( # noqa: PLR0913 -- mirrors the op's schema+ q: torch.Tensor,+ k: torch.Tensor, # noqa: ARG001+ v: torch.Tensor, # noqa: ARG001+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor, # noqa: ARG001+ keyframe_v: torch.Tensor, # noqa: ARG001+ keyframe_times: torch.Tensor, # noqa: ARG001+ keyframe_valid: torch.Tensor, # noqa: ARG001+ softmax_bound: torch.Tensor, # noqa: ARG001+ kernel_size: list[int], # noqa: ARG001+ num_slots: int, # noqa: ARG001+) -> tuple[torch.Tensor, torch.Tensor]:+ return torch.empty_like(q), torch.empty_like(keyframe_q)+++def dsl_joint_supported(attn: NeighborhoodAttention3D, q: torch.Tensor) -> bool:+ """Whether the DSL joint kernel can serve *this* call.+ Per call rather than at install time: ``joint_attention_function`` is installed on every+ NA module for every mode, and both the softmax bound and the volume are properties of the+ module and the tensors, not of the host.+ """+ if not q.is_cuda or q.dtype not in (torch.bfloat16, torch.float16, torch.float32):+ return False+ if getattr(attn, NA_SOFTMAX_BOUND_BUFFER, None) is None:+ return False+ from ltx_kernels.vae import na_supported # noqa: PLC0415++ _, time, height, width, num_heads, head_dim = q.shape+ return na_supported(+ num_heads=num_heads,+ head_dim=head_dim,+ kernel_size=tuple(attn.kernel_size),+ T=time,+ H=height,+ W=width,+ )+++class DSLJointAttention(JointNAAttentionCallable):+ """Joint NA on the CuTe DSL kernel, falling back to ``fallback`` when it cannot serve.+ The fallback is not a nicety: this is installed for every mode, so a CPU decoder, a+ volume smaller than the kernel's halo panel, or a checkpoint loaded without the DSL+ SDOps all land here and must still decode.+ """++ def __init__(self, fallback: JointNAAttentionCallable) -> None:+ self._fallback = fallback+ self._available = na_dsl_available()++ def __call__(+ self,+ attn: NeighborhoodAttention3D,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ from ltx_core.model.video_vae.keyframes import KEYFRAME_CONTEXT_SLOTS # noqa: PLC0415++ if not self._available or not dsl_joint_supported(attn, q):+ return self._fallback(attn, q, k, v, keyframe_q, keyframe_k, keyframe_v, keyframe_times, keyframe_valid)+ dtype = keyframe_v.dtype+ return na_attention_joint_dsl(+ q.to(dtype=dtype),+ k.to(dtype=dtype),+ v.to(dtype=dtype),+ keyframe_q.to(dtype=dtype),+ keyframe_k.to(dtype=dtype),+ keyframe_v,+ keyframe_times,+ keyframe_valid,+ require_softmax_bound(attn),+ list(attn.kernel_size),+ KEYFRAME_CONTEXT_SLOTS,+ )diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/__init__.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/__init__.pyindex 474ef62..68f8225 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/__init__.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/__init__.py@@ -1,6 +1,9 @@"""DiffVAE NA fallbacks when natten is unavailable: Triton then eager SDPA.Vendored from comfy-kitchen (Apache-2.0). Selection order for NATTEN-kind recipes::- natten → (loud warning) Triton → eager tiled SDPA+ natten -> (loud warning) Triton -> eager tiled SDPA+Keyframe decode has its own pair, since NATTEN cannot express a joint window::+ (CuTe DSL, when installed) -> Triton joint -> pure-torch joint+and no warning: that is the only ladder there is, not a degraded one."""from __future__ import annotations@@ -11,6 +14,9 @@ from typing import TYPE_CHECKINGimport torchfrom ltx_core.model.video_vae.transformer.fallback_na.eager import na3d as eager_na3d+from ltx_core.model.video_vae.transformer.fallback_na.joint_eager import (+ sdpa_materializes_scores as joint_sdpa_materializes_scores,+)if TYPE_CHECKING:from ltx_core.model.video_vae.transformer.attention import NAAttentionCallable, NeighborhoodAttention3D@@ -91,6 +97,212 @@ def _na_attention_triton_fake(return torch.empty_like(q)[email protected]_op("ltx_core::na_attention_joint_eager", mutates_args=())+def na_attention_joint_eager(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: list[int],+ num_slots: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Opaque joint NA. Slot tables are built inside, so their T-dependent extent never+ reaches Dynamo and cannot fight the decoder's ``mark_dynamic`` on T/H/W."""+ from ltx_core.model.video_vae.transformer.fallback_na.joint_eager import ( # noqa: PLC0415+ joint_na3d,+ )++ kernel = (kernel_size[0], kernel_size[1], kernel_size[2])+ return joint_na3d(+ q,+ k,+ v,+ keyframe_q,+ keyframe_k,+ keyframe_v,+ keyframe_times,+ keyframe_valid,+ kernel_size=kernel,+ num_slots=num_slots,+ )+++@na_attention_joint_eager.register_fake+def _na_attention_joint_eager_fake(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: list[int],+ num_slots: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ del k, v, keyframe_k, keyframe_v, keyframe_times, keyframe_valid, kernel_size, num_slots+ return torch.empty_like(q), torch.empty_like(keyframe_q)++[email protected]_op("ltx_core::na_attention_joint_triton", mutates_args=())+def na_attention_joint_triton(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: list[int],+ num_slots: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Opaque joint Triton NA. Slot tables are built inside for the same reason as the+ eager op: their T-dependent extent must not reach Dynamo."""+ from ltx_core.model.video_vae.transformer.fallback_na.joint_triton import ( # noqa: PLC0415+ joint_na3d as triton_joint_na3d,+ )++ return triton_joint_na3d(+ q,+ k,+ v,+ keyframe_q,+ keyframe_k,+ keyframe_v,+ keyframe_times,+ keyframe_valid,+ kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),+ num_slots=num_slots,+ )+++@na_attention_joint_triton.register_fake+def _na_attention_joint_triton_fake(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: list[int],+ num_slots: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ del k, v, keyframe_k, keyframe_v, keyframe_times, keyframe_valid, kernel_size, num_slots+ return torch.empty_like(q), torch.empty_like(keyframe_q)+++def _joint_dtypes(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+) -> tuple[torch.Tensor, ...]:+ """Cast Q/K to V's dtype per stream (RoPE may have promoted them)."""+ if q.dtype != v.dtype or k.dtype != v.dtype:+ q, k = q.to(dtype=v.dtype), k.to(dtype=v.dtype)+ if keyframe_q.dtype != keyframe_v.dtype or keyframe_k.dtype != keyframe_v.dtype:+ keyframe_q = keyframe_q.to(dtype=keyframe_v.dtype)+ keyframe_k = keyframe_k.to(dtype=keyframe_v.dtype)+ return q, k, v, keyframe_q, keyframe_k, keyframe_v+++class TritonJointAttention:+ """Triton joint video+keyframe NA (hosts with CUDA + a working Triton install)."""++ def __call__(+ self,+ attn: NeighborhoodAttention3D,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ from ltx_core.model.video_vae.keyframes import KEYFRAME_CONTEXT_SLOTS # noqa: PLC0415++ if not triton_na_available():+ raise ImportError(+ "Triton joint neighborhood attention requires CUDA and the triton package "+ "(on Windows: https://github.com/triton-lang/triton-windows)."+ )+ return na_attention_joint_triton(+ *_joint_dtypes(q, k, v, keyframe_q, keyframe_k, keyframe_v),+ keyframe_times,+ keyframe_valid,+ list(attn.kernel_size),+ KEYFRAME_CONTEXT_SLOTS,+ )+++class EagerJointAttention:+ """Pure-torch joint video+keyframe NA over query bricks (always available).+ The backend for hosts with neither Triton nor the CuTe DSL kernel -- CPU, macOS/MPS, Windows+ without a built extra. Within a few percent of the Triton kernel end to end.+ """++ def __call__(+ self,+ attn: NeighborhoodAttention3D,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ from ltx_core.model.video_vae.keyframes import KEYFRAME_CONTEXT_SLOTS # noqa: PLC0415++ return na_attention_joint_eager(+ *_joint_dtypes(q, k, v, keyframe_q, keyframe_k, keyframe_v),+ keyframe_times,+ keyframe_valid,+ list(attn.kernel_size),+ KEYFRAME_CONTEXT_SLOTS,+ )+++class AutoJointAttention:+ """Joint NA that picks its kernel from the *tensors*, not from the host.+ Chooses per call rather than at install time because ``joint_attention_function`` is+ installed for every mode on every NA module, and a CPU decoder on a CUDA host is an+ ordinary case (unit tests, CPU dev). Deciding by ``triton_na_available()`` alone would+ hand CPU tensors to a Triton kernel.+ """++ def __init__(self) -> None:+ self._triton = TritonJointAttention() if triton_na_available() else None+ self._eager = EagerJointAttention()++ def __call__(+ self,+ attn: NeighborhoodAttention3D,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ backend = self._triton if self._triton is not None and q.is_cuda else self._eager+ return backend(attn, q, k, v, keyframe_q, keyframe_k, keyframe_v, keyframe_times, keyframe_valid)++class EagerSdpaAttention:"""Limited-workspace tiled SDPA NA (always available)."""@@ -143,11 +355,29 @@ def fallback_na_attention() -> NAAttentionCallable:return EagerSdpaAttention()+def joint_na_attention() -> object:+ """The joint (keyframe-aware) NA backend: Triton on CUDA tensors, eager otherwise.+ Never NATTEN, which cannot express the joint window. The CuTe DSL kernel can, and under+ ``BLACKWELL_DSL`` ``apply`` wraps this in ``DSLJointAttention``, which prefers the kernel+ and falls back here for the calls it cannot serve. So this+ is independent of ``natten_available()`` and emits no warning: unlike the video-only+ fallbacks this is not a degraded path, it is the only one there is.+ """+ return AutoJointAttention()++__all__ = [+ "AutoJointAttention",+ "EagerJointAttention","EagerSdpaAttention",+ "TritonJointAttention","TritonNaAttention","fallback_na_attention",+ "joint_na_attention",+ "joint_sdpa_materializes_scores","na_attention_eager",+ "na_attention_joint_eager",+ "na_attention_joint_triton","na_attention_triton","triton_na_available","warn_no_natten",diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_eager.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_eager.pynew file mode 100644index 0000000..9522e7b--- /dev/null+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_eager.py@@ -0,0 +1,642 @@+"""Pure-torch joint (video + keyframe) 3D neighborhood attention.+Computes, for one softmax per query:+* **video query** at ``(t, h, w)``: its local ``Kt x Kh x Kw`` video window, clamped to the+ volume and masked where it hangs over the edge, **plus** the whole ``Kh x Kw`` window at the+ same ``(h, w)`` on each of the ``num_slots`` nearest keyframe planes. Keyframe visibility does+ not depend on ``Kt`` -- a plane far outside the temporal radius is still visible.+* **keyframe query** on plane ``i``: the ``Kh x Kw`` window on its own plane (there is no+ plane-to-plane attention), plus the same window on each of the nearest video frames.+Which planes and frames are "nearest" comes from :func:`video_keyframe_slots` /+:func:`keyframe_video_slots`, so every backend agrees on visibility.+No Triton, no natten, no ``torch.compile``: this is the backend that always exists -- CPU,+macOS/MPS, Windows without a built extra.+Structure+---------+Everything is arranged so the arithmetic happens inside ``F.scaled_dot_product_attention``:+**Query bricks.** Queries are grouped into ``(bt, bh, bw)`` bricks and many bricks ride one SDPA+call as its batch dimension, so a frame costs a handful of launches rather than thousands. All+queries in a brick share one gathered key slab, of extent ``(bt + Kt - 1, bh + Kh - 1, bw + Kw - 1)``.+**Brick shape.** Wasted work is ``Nk / keys_actually_visible`` and *grows* with the brick, so the+spatial face stays small and square (square minimizes the slab at a fixed query count). Depth is+the exception: the gather is the larger cost and it scales with ``Nk / Nq``, which *falls* with+depth, so :data:`DEFAULT_BRICK_DEPTH` frames deep beats one frame deep despite doing more+arithmetic. Both defaults sit on measured plateaus at the production stage-5 shape.+**One shared, 2D-broadcast mask.** The visible-key pattern is a property of the brick geometry,+identical for every brick, so it is built once and passed as ``(1, 1, Nq, Nk)``. That shape is+load-bearing: torch keeps the memory-efficient backend and expands neither the mask nor the+scores, whereas a pre-expanded ``(G, NH, Nq, Nk)`` bias halves throughput and costs gigabytes.+**Per-key validity rides in the keys.** Out-of-volume positions, empty slots (``-1``) and invalid+planes are data-dependent, so folding them into the mask would make it per-brick. Instead ``K``+carries one extra channel holding ``0`` for a live key and :data:`_DEAD` for a dead one, against a+constant ``1`` channel on ``Q``. Q arrives pre-scaled, so with ``scale=1.0`` that adds exactly the+bias to the score. The channel count is then rounded up to :data:`_HEAD_DIM_ALIGN`.+**Head-major staging.** Key slabs are gathered from a ``(B, NH, A, Hp, Wp, C)`` copy rather than+from the caller's channels-last layout, so the gather's innermost contiguous run is ``ew * C``+instead of ``C``.+**Runs of constant slot row.** A brick spanning several frames shares one keyframe key slab, so it+must not straddle a change of visible planes. ``T`` is cut into maximal runs of identical slot rows+and bricks are tiled inside a run -- which also means one plane gather per run, entering the slab+view with a **zero** group stride.+Both loops are budgeted by :data:`DEFAULT_WORKSPACE_BYTES`: frames per staging pass, then+``(bricks, brick rows)`` per SDPA call. Peak transient memory is therefore bounded by that budget+and not by the volume, which is what lets this sit next to a decoder that has its own memory plan.+The gather is the floor: SDPA needs materialized ``(G, NH, Nk, HD)`` keys, so every key is copied+``Nk / Nq`` times. Only a fused neighborhood kernel avoids that.+"""++from __future__ import annotations++import math++import torch+import torch.nn.functional as F++from ltx_core.model.video_vae.keyframes import (+ KEYFRAME_CONTEXT_SLOTS,+ keyframe_video_slots,+ video_keyframe_slots,+)++#: Score bias for a dead key, carried in ``K``'s extra channel. Large enough that+#: ``exp(bias - m)`` underflows to zero, small enough to stay finite in bf16.+_DEAD = -1.0e4++#: Q/K head dim must stay a multiple of this or torch rejects the memory-efficient backend and+#: silently falls back to ``MATH``, which materializes the scores and costs ~20x. The bias+#: channel therefore rounds ``HD`` up rather than merely adding one.+_HEAD_DIM_ALIGN = 8++#: Spatial queries per brick. Smaller wastes less work but gathers more and gives SDPA less to+#: chew on; measured flat between roughly 36 and 144.+DEFAULT_BRICK_QUERIES = 64++#: Brick depth along T. Trades arithmetic for gather traffic, and the gather is the larger cost:+#: measured 1.5x at the production stage-5 shape, flat from 4 to 8.+DEFAULT_BRICK_DEPTH = 4++#: Default transient budget, bounding both the staged window and the key/value block. Trades peak+#: memory for launch count and staging redundancy: at the production stage-5 shape 1 GiB buys ~13%+#: over 256 MiB, which is not worth 4x the transient on a consumer card.+DEFAULT_WORKSPACE_BYTES = 256 * 1024**2+++#: Peak-to-staging multipliers by the SDPA kernel that ends up running, measured at the production+#: stage-5 shape (T=25, 272x130, kernel 11^3, brick 4x8x8):+#:+#: ===================== ====== ==========+#: kernel factor peak+#: ===================== ====== ==========+#: cuDNN / cutlass 4.75 2.99 GiB+#: math (scores in HBM) 22.1 3.75 GiB+#: ===================== ====== ==========+#:+#: Written down rather than probed: the only thing that varies is whether the selected kernel+#: materializes its score block, and that follows from the host, not from the clip.+_STAGING_FACTOR_FUSED = 4.75+_STAGING_FACTOR_MATERIALIZED = 22.1+++def sdpa_materializes_scores(device: torch.device) -> bool:+ """Whether torch's SDPA will materialize this backend's score block on ``device``.+ CUDA takes the memory-efficient (or cuDNN) kernel for this backend's broadcast mask and+ aligned head dim. Everywhere else the math path runs and the ``(G, NH, Nq, Nk)`` scores land+ in memory -- notably MPS. Auto tiling reads this to size its reserve.+ """+ return device.type != "cuda"+++def staging_factor(device: torch.device) -> float:+ """The peak-to-staging multiplier for this host, from the table above."""+ return _STAGING_FACTOR_MATERIALIZED if sdpa_materializes_scores(device) else _STAGING_FACTOR_FUSED+++def _key_channels(head_dim: int) -> int:+ """Key/query channel count: ``head_dim``, the bias channel, and alignment padding."""+ return -(-(head_dim + 1) // _HEAD_DIM_ALIGN) * _HEAD_DIM_ALIGN+++def _window(kernel: int) -> tuple[int, int]:+ """``(lo, hi)`` halo for one axis: the offsets ``range(-k // 2, k - k // 2)`` reach."""+ lo = kernel // 2+ return lo, kernel - lo - 1+++def pick_brick(+ time: int,+ height: int,+ width: int,+ target: int = DEFAULT_BRICK_QUERIES,+ depth: int = DEFAULT_BRICK_DEPTH,+) -> tuple[int, int, int]:+ """``(bt, bh, bw)``: ``depth`` frames deep with the squarest ~``target``-query face.+ Square minimizes the key slab ``(bh + Kh - 1) * (bw + Kw - 1)`` at a fixed query count, which+ is exactly the wasted-work term.+ """+ side = max(1, round(math.sqrt(target)))+ return min(depth, time), min(side, height), min(side, width)+++class _Geometry:+ """Brick decomposition of a volume, plus the padding and slab extents it implies."""++ def __init__(+ self,+ height: int,+ width: int,+ kernel: tuple[int, int, int],+ brick: tuple[int, int, int],+ ) -> None:+ kernel_t, kernel_h, kernel_w = kernel+ lo_h, hi_h = _window(kernel_h)+ lo_w, hi_w = _window(kernel_w)+ self.height, self.width = height, width+ self.brick = brick+ self.kernel = kernel+ self.grid = (-(-height // brick[1]), -(-width // brick[2]))+ # Slab extents: T grows with the brick depth, H/W with the spatial face.+ self.span_t = brick[0] + kernel_t - 1+ self.span = (brick[1] + kernel_h - 1, brick[2] + kernel_w - 1)+ # Halo, plus enough to cover the last (partial) brick's slab.+ self.pad_h = (lo_h, hi_h + self.grid[0] * brick[1] - height)+ self.pad_w = (lo_w, hi_w + self.grid[1] * brick[2] - width)+ self.pad_t = _window(kernel_t)+ self.queries = brick[0] * brick[1] * brick[2]+ self.footprint = self.span[0] * self.span[1]+ self.padded_height = height + sum(self.pad_h)+ self.padded_width = width + sum(self.pad_w)++ def row_extent(self, rows: int) -> int:+ """Padded ``H`` extent a group of ``rows`` brick rows needs from the staged volume."""+ return (rows - 1) * self.brick[1] + self.span[0]+++class _Schedule:+ """How the nested loops are cut so transient memory stays inside the budget.+ ``group_axis`` counts *bricks* along the volume's leading axis (frames for the video pass,+ planes for the keyframe pass); ``stage_axis`` counts them per staging pass.+ """++ def __init__(+ self,+ geometry: _Geometry,+ blocks: int,+ heads: int,+ head_dim: int,+ axis_bricks: int,+ element_size: int,+ workspace_bytes: int,+ factor: float,+ ) -> None:+ channels = _key_channels(head_dim)+ # One (brick along the axis, brick row) pair's worth of gathered keys and values, plus its+ # score block on backends that materialize one.+ keys = blocks * geometry.footprint+ pair_bytes = geometry.grid[1] * heads * keys * (channels + head_dim) * element_size+ # ``factor`` folds in whatever the selected SDPA kernel allocates on top of the staging,+ # chiefly a materialized score block. See :data:`_STAGING_FACTOR_FUSED`.+ pairs = max(1, int(workspace_bytes / max(pair_bytes * factor, 1.0)))+ if pairs >= geometry.grid[0]:+ self.group_axis = min(axis_bricks, max(1, pairs // geometry.grid[0]))+ self.group_rows = geometry.grid[0]+ else:+ self.group_axis = 1+ self.group_rows = pairs+ staged = geometry.padded_height * geometry.padded_width * heads * (channels + head_dim) * element_size+ per_axis_brick = staged * geometry.brick[0]+ self.stage_axis = min(axis_bricks, max(self.group_axis, workspace_bytes // max(per_axis_brick, 1)))+++def _banded(queries: int, span: int, kernel: int, device: torch.device) -> torch.Tensor:+ """``(queries, span)`` bool: key ``i`` is visible to query ``j`` iff ``j <= i < j + kernel``."""+ key = torch.arange(span, device=device)[None, :]+ query = torch.arange(queries, device=device)[:, None]+ return (key >= query) & (key < query + kernel)+++def _joint_mask(geometry: _Geometry, num_slots: int, device: torch.device) -> torch.Tensor:+ """``(1, 1, Nq, Nk)`` visibility, shared by every brick.+ Query order is ``(jt, jh, jw)``; key order is the video slab ``(it, p, r)`` followed by the+ keyframe slab ``(slot, p, r)``. Keyframe keys carry no temporal condition -- a plane is visible+ to every frame in the brick, which is what makes the run grouping legal.+ """+ brick_t, brick_h, brick_w = geometry.brick+ kernel_t, kernel_h, kernel_w = geometry.kernel+ spatial = (+ _banded(brick_h, geometry.span[0], kernel_h, device)[:, None, :, None]+ & _banded(brick_w, geometry.span[1], kernel_w, device)[None, :, None, :]+ ).reshape(brick_h * brick_w, geometry.footprint)+ temporal = _banded(brick_t, geometry.span_t, kernel_t, device)+ video = (temporal[:, None, :, None] & spatial[None, :, None, :]).reshape(+ geometry.queries, geometry.span_t * geometry.footprint+ )+ planes = (+ spatial[None, :, None, :]+ .expand(brick_t, brick_h * brick_w, num_slots, geometry.footprint)+ .reshape(geometry.queries, num_slots * geometry.footprint)+ )+ return torch.cat([video, planes], dim=1)[None, None].contiguous()+++def _stage(+ x: torch.Tensor,+ geometry: _Geometry,+ pad_t: tuple[int, int],+ *,+ with_bias_channel: bool,+) -> torch.Tensor:+ """``(B, A, H, W, NH, HD)`` -> padded head-major ``(B, NH, A + pad, Hp, Wp, C)``.+ Head-major so a brick slab's innermost ``(ew, C)`` block is contiguous in both source and+ destination; channels-last staging makes the same gather markedly slower.+ """+ batch, axis, height, width, heads, head_dim = x.shape+ channels = _key_channels(head_dim) if with_bias_channel else head_dim+ out = x.new_zeros((batch, heads, axis + sum(pad_t), geometry.padded_height, geometry.padded_width, channels))+ if with_bias_channel:+ out[..., head_dim] = _DEAD+ live = out[+ :,+ :,+ pad_t[0] : pad_t[0] + axis,+ geometry.pad_h[0] : geometry.pad_h[0] + height,+ geometry.pad_w[0] : geometry.pad_w[0] + width,+ ]+ live[..., :head_dim] = x.permute(0, 4, 1, 2, 3, 5)+ if with_bias_channel:+ live[..., head_dim] = 0.0+ return out+++def _slabs(+ staged: torch.Tensor,+ geometry: _Geometry,+ bricks: int,+ rows: int,+ blocks: int,+ *,+ group_stride: int,+) -> torch.Tensor:+ """Overlapping brick slabs as a *view*: ``(B, bricks, rows, Gw, NH, blocks, eh, ew, C)``.+ ``staged`` is head-major ``(B, NH, A, Hp, Wp, C)``, already sliced to this group's first brick+ and brick row, so the view inherits its storage offset. ``group_stride`` is how far consecutive+ bricks advance along ``A``: the brick depth for the sliding video window, and **zero** for the+ keyframe planes, which every brick in a run shares.+ """+ batch, heads = staged.shape[0], staged.shape[1]+ stride_b, stride_nh, stride_a, stride_h, stride_w, _ = staged.stride()+ return staged.as_strided(+ (batch, bricks, rows, geometry.grid[1], heads, blocks, *geometry.span, staged.shape[-1]),+ (+ stride_b,+ group_stride * stride_a,+ geometry.brick[1] * stride_h,+ geometry.brick[2] * stride_w,+ stride_nh,+ stride_a,+ stride_h,+ stride_w,+ 1,+ ),+ )+++def _query_bricks(x: torch.Tensor, geometry: _Geometry, bricks: int, rows: int) -> torch.Tensor:+ """``(B, A, h, W, NH, HD)`` -> ``(B * bricks * rows * Gw, NH, Nq, C)``, unit channel set.+ ``x`` is this group's slice, so ``A`` may be short of ``bricks * bt`` and ``h`` short of+ ``rows * bh`` at a volume edge; the shortfall is zero-padded here and cropped by+ :func:`_unbrick`.+ """+ batch, axis, height, width, heads, head_dim = x.shape+ brick_t, brick_h, brick_w = geometry.brick+ pad_t, pad_h, pad_w = bricks * brick_t - axis, rows * brick_h - height, geometry.grid[1] * brick_w - width+ if pad_t or pad_h or pad_w:+ x = F.pad(x, (0, 0, 0, 0, 0, pad_w, 0, pad_h, 0, pad_t))+ bricked = (+ x.reshape(batch, bricks, brick_t, rows, brick_h, geometry.grid[1], brick_w, heads, head_dim)+ .permute(0, 1, 3, 5, 7, 2, 4, 6, 8)+ .reshape(batch * bricks * rows * geometry.grid[1], heads, geometry.queries, head_dim)+ )+ out = bricked.new_zeros((*bricked.shape[:-1], _key_channels(head_dim)))+ out[..., :head_dim] = bricked+ out[..., head_dim] = 1.0+ return out+++def _unbrick(+ attended: torch.Tensor,+ geometry: _Geometry,+ batch: int,+ bricks: int,+ rows: int,+ extent: tuple[int, int],+) -> torch.Tensor:+ """Inverse of :func:`_query_bricks`, cropping to ``extent`` frames/rows and the real width."""+ brick_t, brick_h, brick_w = geometry.brick+ heads, head_dim = attended.shape[1], attended.shape[3]+ plane = (+ attended.reshape(batch, bricks, rows, geometry.grid[1], heads, brick_t, brick_h, brick_w, head_dim)+ .permute(0, 1, 5, 2, 6, 3, 7, 4, 8)+ .reshape(batch, bricks * brick_t, rows * brick_h, geometry.grid[1] * brick_w, heads, head_dim)+ )+ return plane[:, : extent[0], : extent[1], : geometry.width]+++def _with_null(slots: torch.Tensor, null_index: int) -> torch.Tensor:+ """Map empty slots (``-1``) onto the appended null row, which biases itself out."""+ return torch.where(slots < 0, torch.full_like(slots, null_index), slots)+++def _append_null(keys: torch.Tensor, values: torch.Tensor, head_dim: int) -> tuple[torch.Tensor, torch.Tensor]:+ """Append one all-dead key plane (and a zero value plane) along the staged plane axis."""+ shape = (keys.shape[0], keys.shape[1], 1, *keys.shape[3:])+ null_key = keys.new_zeros(shape)+ null_key[..., head_dim] = _DEAD+ null_value = values.new_zeros((*shape[:-1], values.shape[-1]))+ return torch.cat([keys, null_key], dim=2), torch.cat([values, null_value], dim=2)+++def _slot_runs(slots: torch.Tensor) -> list[tuple[int, int]]:+ """Maximal ``[start, stop)`` runs of leading-axis positions whose slot row is identical.+ A brick spanning several frames shares one keyframe key slab, so it may not straddle a change+ of slot row. At production keyframe spacing these runs are ~16 frames long, so the constraint+ costs little; carrying every frame's slots in the slab instead would more than give back what+ brick depth wins.+ """+ rows = slots.tolist()+ runs: list[tuple[int, int]] = []+ start = 0+ for index in range(1, len(rows)):+ if rows[index] != rows[start]:+ runs.append((start, index))+ start = index+ runs.append((start, len(rows)))+ return runs+++def _attend_group(+ query_slice: torch.Tensor,+ key_views: tuple[torch.Tensor, ...],+ value_views: tuple[torch.Tensor, ...],+ geometry: _Geometry,+ shape: tuple[int, int],+ mask: torch.Tensor,+) -> torch.Tensor:+ """Gather one ``(bricks x brick rows)`` block's keys, attend, and un-brick the result.+ ``key_views`` / ``value_views`` are the strided slab views to concatenate along the key axis,+ in order. ``shape`` is ``(bricks, rows)``.+ """+ bricks, rows = shape+ batch = query_slice.shape[0]+ heads, head_dim = query_slice.shape[4], query_slice.shape[5]+ blocks = sum(view.shape[5] for view in key_views)+ channels = _key_channels(head_dim)+ keys = query_slice.new_empty((batch, bricks, rows, geometry.grid[1], heads, blocks, *geometry.span, channels))+ values = query_slice.new_empty((batch, bricks, rows, geometry.grid[1], heads, blocks, *geometry.span, head_dim))+ start = 0+ for key_view, value_view in zip(key_views, value_views, strict=True):+ stop = start + key_view.shape[5]+ keys[:, :, :, :, :, start:stop].copy_(key_view)+ values[:, :, :, :, :, start:stop].copy_(value_view)+ start = stop+ count = batch * bricks * rows * geometry.grid[1]+ attended = F.scaled_dot_product_attention(+ _query_bricks(query_slice, geometry, bricks, rows),+ keys.view(count, heads, blocks * geometry.footprint, channels),+ values.view(count, heads, blocks * geometry.footprint, head_dim),+ attn_mask=mask,+ scale=1.0,+ )+ return _unbrick(attended, geometry, batch, bricks, rows, (query_slice.shape[1], query_slice.shape[2]))+++def _row_groups(geometry: _Geometry, schedule: _Schedule) -> list[tuple[int, int, slice, slice]]:+ """``(row, rows, staged H slice, output H slice)`` per brick-row group."""+ brick_h = geometry.brick[1]+ groups = []+ for row in range(0, geometry.grid[0], schedule.group_rows):+ rows = min(schedule.group_rows, geometry.grid[0] - row)+ groups.append(+ (+ row,+ rows,+ slice(row * brick_h, row * brick_h + geometry.row_extent(rows)),+ slice(row * brick_h, min((row + rows) * brick_h, geometry.height)),+ )+ )+ return groups+++def _video_query_pass(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ slots: torch.Tensor,+ geometry: _Geometry,+ workspace_bytes: int,+ factor: float,+) -> torch.Tensor:+ """Video queries: the local ``Kt x Kh x Kw`` window plus the nearest keyframe planes."""+ time, heads, head_dim = q.shape[1], q.shape[4], q.shape[5]+ brick_t = geometry.brick[0]+ lo_t, hi_t = geometry.pad_t+ num_slots = slots.shape[1]+ blocks = geometry.span_t + num_slots++ plane_keys, plane_values = _append_null(+ _stage(keyframe_k, geometry, (0, 0), with_bias_channel=True),+ _stage(keyframe_v, geometry, (0, 0), with_bias_channel=False),+ head_dim,+ )+ slot_table = _with_null(slots, keyframe_k.shape[1])+ mask = _joint_mask(geometry, num_slots, q.device)+ schedule = _Schedule(+ geometry,+ blocks,+ heads,+ head_dim,+ -(-time // brick_t),+ q.element_size(),+ workspace_bytes,+ factor,+ )+ rows_groups = _row_groups(geometry, schedule)++ out = torch.empty_like(q)+ for run_start, run_stop in _slot_runs(slot_table):+ # One plane gather per run: every brick inside it sees the same slots.+ planes = plane_keys.index_select(2, slot_table[run_start])+ plane_vals = plane_values.index_select(2, slot_table[run_start])+ run_bricks = -(-(run_stop - run_start) // brick_t)+ for staged_brick in range(0, run_bricks, schedule.stage_axis):+ staged_bricks = min(schedule.stage_axis, run_bricks - staged_brick)+ first = run_start + staged_brick * brick_t+ last = first + staged_bricks * brick_t # exclusive; may reach past the run or T+ source = slice(max(0, first - lo_t), min(time, last + hi_t))+ pad_t = (max(0, lo_t - first), max(0, last + hi_t - time))+ window_keys = _stage(k[:, source], geometry, pad_t, with_bias_channel=True)+ window_values = _stage(v[:, source], geometry, pad_t, with_bias_channel=False)++ for brick in range(staged_brick, staged_brick + staged_bricks, schedule.group_axis):+ count = min(schedule.group_axis, staged_brick + staged_bricks - brick)+ start = run_start + brick * brick_t+ stop = min(start + count * brick_t, run_stop)+ offset = (brick - staged_brick) * brick_t+ for _, rows, key_rows, out_rows in rows_groups:+ tile = _attend_group(+ q[:, start:stop, out_rows],+ (+ _slabs(+ window_keys[:, :, offset:, key_rows],+ geometry,+ count,+ rows,+ geometry.span_t,+ group_stride=brick_t,+ ),+ _slabs(planes[:, :, :, key_rows], geometry, count, rows, num_slots, group_stride=0),+ ),+ (+ _slabs(+ window_values[:, :, offset:, key_rows],+ geometry,+ count,+ rows,+ geometry.span_t,+ group_stride=brick_t,+ ),+ _slabs(plane_vals[:, :, :, key_rows], geometry, count, rows, num_slots, group_stride=0),+ ),+ geometry,+ (count, rows),+ mask,+ )+ out[:, start:stop, out_rows] = tile+ return out+++def _keyframe_query_pass(+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ slots: torch.Tensor,+ keyframe_valid: torch.Tensor,+ geometry: _Geometry,+ workspace_bytes: int,+ factor: float,+) -> torch.Tensor:+ """Keyframe queries: own plane only (``d_t == 0``) plus the nearest video frames.+ Runs one plane per brick: planes have no temporal window, so depth would buy nothing, and each+ plane's video slots differ anyway.+ """+ planes_total, heads, head_dim = keyframe_q.shape[1], keyframe_q.shape[4], keyframe_q.shape[5]+ num_slots = slots.shape[1]+ blocks = 1 + num_slots+ time = k.shape[1]+ flat = _Geometry(geometry.height, geometry.width, (1, *geometry.kernel[1:]), (1, *geometry.brick[1:]))++ # Only the frames some plane actually points at get staged -- at most ``P * num_slots`` of them,+ # against the whole volume if this staged ``k`` wholesale. ``unique`` doubles as the remap: slot+ # rows are rewritten to index the compacted stack.+ wanted, inverse = torch.unique(_with_null(slots, time).reshape(-1), return_inverse=True)+ frame_keys = _stage(k.index_select(1, wanted.clamp(max=time - 1)), flat, (0, 0), with_bias_channel=True)+ frame_values = _stage(v.index_select(1, wanted.clamp(max=time - 1)), flat, (0, 0), with_bias_channel=False)+ # An empty slot clamped onto a real frame above; kill it here instead of appending a null row.+ frame_keys[:, :, wanted == time, ..., head_dim] = _DEAD+ own_keys = _stage(keyframe_k, flat, (0, 0), with_bias_channel=True)+ own_values = _stage(keyframe_v, flat, (0, 0), with_bias_channel=False)+ own_keys[:, :, ~keyframe_valid, ..., head_dim] = _DEAD+ slot_table = inverse.reshape(planes_total, num_slots)+ mask = _joint_mask(flat, num_slots, keyframe_q.device)+ schedule = _Schedule(+ flat,+ blocks,+ heads,+ head_dim,+ planes_total,+ keyframe_q.element_size(),+ workspace_bytes,+ factor,+ )+ rows_groups = _row_groups(flat, schedule)++ out = torch.empty_like(keyframe_q)+ for start in range(0, planes_total, schedule.group_axis):+ stop = min(start + schedule.group_axis, planes_total)+ count = stop - start+ picked = slot_table[start:stop].reshape(-1)+ frames = frame_keys.index_select(2, picked)+ frame_vals = frame_values.index_select(2, picked)+ for _, rows, key_rows, out_rows in rows_groups:+ tile = _attend_group(+ keyframe_q[:, start:stop, out_rows],+ (+ _slabs(own_keys[:, :, start:, key_rows], flat, count, rows, 1, group_stride=1),+ _slabs(frames[:, :, :, key_rows], flat, count, rows, num_slots, group_stride=num_slots),+ ),+ (+ _slabs(own_values[:, :, start:, key_rows], flat, count, rows, 1, group_stride=1),+ _slabs(frame_vals[:, :, :, key_rows], flat, count, rows, num_slots, group_stride=num_slots),+ ),+ flat,+ (count, rows),+ mask,+ )+ out[:, start:stop, out_rows] = tile+ # An invalid plane sees nothing; zero it rather than shipping the uniform mean.+ return out * keyframe_valid[None, :, None, None, None, None]+++def joint_na3d( # noqa: PLR0913+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: tuple[int, int, int],+ num_slots: int = KEYFRAME_CONTEXT_SLOTS,+ brick: tuple[int, int, int] | None = None,+ workspace_bytes: int = DEFAULT_WORKSPACE_BYTES,+ factor: float | None = None,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Joint neighborhood attention over a video volume and a keyframe plane stack.+ Args:+ q, k, v: ``(B, T, H, W, NH, HD)`` video stream. ``q`` must arrive pre-scaled by+ ``head_dim ** -0.5``, as the shared attention module does.+ keyframe_q, keyframe_k, keyframe_v: ``(B, P, H, W, NH, HD)`` keyframe stream.+ keyframe_times: ``(P,)`` float32 plane times, same origin as the video RoPE.+ keyframe_valid: ``(P,)`` bool.+ kernel_size: ``(Kt, Kh, Kw)``.+ num_slots: cross-stream slots per query.+ brick: query brick ``(bt, bh, bw)``; defaults to :func:`pick_brick`.+ workspace_bytes: transient budget bounding the staged window and key/value block.+ factor: peak-to-staging multiplier; :func:`staging_factor` supplies it when omitted.+ Returns:+ ``(video_out, keyframe_out)``, each shaped like its stream's ``q``.+ """+ time, height, width = q.shape[1], q.shape[2], q.shape[3]+ video_slots = video_keyframe_slots(keyframe_times, keyframe_valid, time, num_slots)+ keyframe_slots = keyframe_video_slots(keyframe_times, keyframe_valid, time, num_slots)+ geometry = _Geometry(height, width, kernel_size, brick if brick is not None else pick_brick(time, height, width))+ if factor is None:+ factor = staging_factor(q.device)+ return (+ _video_query_pass(q, k, v, keyframe_k, keyframe_v, video_slots, geometry, workspace_bytes, factor),+ _keyframe_query_pass(+ keyframe_q,+ keyframe_k,+ keyframe_v,+ k,+ v,+ keyframe_slots,+ keyframe_valid,+ geometry,+ workspace_bytes,+ factor,+ ),+ )diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_triton.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_triton.pynew file mode 100644index 0000000..726737a--- /dev/null+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/joint_triton.py@@ -0,0 +1,491 @@+# ruff: noqa: ANN001, ANN202, PLR0913+"""Triton joint (video + keyframe) 3D neighborhood attention.+Same semantics as :mod:`joint_eager` -- see its module docstring for the window rule and+the two query kinds -- but flash-style: one program owns ``BLOCK_Q`` queries along W at a+fixed (frame-or-plane, h), keeps ``m/l/acc`` in registers, and never materializes scores.+Two kernels, because the two query kinds have different key topologies and different grids:+* ``_joint_video_kernel`` -- grid ``(cdiv(W, BQ), H, T * B * NH)``+* ``_joint_keyframe_kernel`` -- grid ``(cdiv(W, BQ), H, P * B * NH)``+The axis split matters at production sizes. Folding ``T * H`` into one grid axis passes+CUDA's 65535 cap on ``gridDim.y``/``z`` for a real tile (392 frames x 272 rows = 106624), so+the frame index shares axis 2 with batch and head while H owns axis 1 and the W block stays on+axis 0 -- keeping neighbouring programs on neighbouring addresses. Pointer arithmetic is+**int64**: every individual stride fits in int32, so Triton specializes them there, but+``t_q * s_t`` reaches ~6.5e9 on that same tile and would wrap.+Three things here differ from the vendored video-only ``triton_na`` kernel, and each is+load-bearing:+1. **Clamp-and-mask, not NATTEN's inward shift.** The T and H loops run a *fixed*+ ``kt``/``kh`` iterations (so nothing depends on runtime control flow, matching how+ upstream's Pallas kernel is written); out-of-range taps are clamped for the load and+ masked out of the softmax. There is no ``min(kernel, axis)`` shrink and no shift, so a+ boundary query sees fewer keys and the softmax renormalizes.+2. **The slot loop shares the same ``m_i``/``l_i``/``acc``.** Cross-stream keys are folded+ into the *same* online softmax as the local window -- one softmax per query over both+ sets, which is the whole point of "joint".+3. **The softmax weights are masked, not just the scores.** ``p = where(vis, exp(s - m), 0)``+ rather than relying on ``exp(-inf - -inf)``. A fully masked row is reachable here (an+ invalid keyframe plane attends to nothing at all), and with only the scores masked it+ would evaluate ``exp(0) = 1`` for every key and return the plain mean of V. The+ video-only kernel gets away without this because its rows are never wholly empty.+Keyframe count is a **runtime** argument, never ``constexpr``: plane counts vary per decode+and specializing on them would recompile per clip. Only ``num_slots`` (2) is ``constexpr``.+"""++from __future__ import annotations++import torch+import triton+import triton.language as tl++from ltx_core.model.video_vae.keyframes import (+ KEYFRAME_CONTEXT_SLOTS,+ keyframe_video_slots,+ video_keyframe_slots,+)++# Triton requires module-level JIT globals to be constexpr instances (not annotations).+_NEG_INF = tl.constexpr(-3.0e38)+_LSE_FLOOR = tl.constexpr(1e-30)+++def _fold_w_run(+ m_i,+ l_i,+ acc,+ q_blk,+ k_ptr,+ v_ptr,+ plane_base,+ row_ok,+ w_lo,+ w_hi,+ w_start,+ w_end,+ s_w,+ d_off,+ d_mask,+ block_k: tl.constexpr,+ is_fp32: tl.constexpr,+):+ """Fold one ``(frame|plane, h)`` row's W run into the running softmax state.+ ``row_ok`` is a scalar predicate for the whole row (the T/H tap or the slot being in+ range); ``w_start``/``w_end`` are per-query clamped window bounds. Shared by both+ kernels and by the local and slot loops, so every key set is folded by identical code.+ """+ for wk0 in range(w_lo, w_hi, block_k):+ wk = wk0 + tl.arange(0, block_k)+ kmask = wk < w_hi+ kv_ptrs = plane_base + wk[:, None] * s_w + d_off[None, :]+ # ``row_ok`` gates the *load*, not just the softmax: an out-of-range tap or an empty+ # slot has its index clamped to 0, and with no keyframe planes at all there is no+ # element 0 to read. Masking only ``vis`` would dereference it anyway.+ kv_mask = kmask[:, None] & d_mask[None, :] & row_ok+ k_blk = tl.load(k_ptr + kv_ptrs, mask=kv_mask, other=0.0)+ k_t = tl.trans(k_blk)+ s = tl.dot(q_blk, k_t, input_precision="ieee") if is_fp32 else tl.dot(q_blk, k_t)+ vis = (wk[None, :] >= w_start[:, None]) & (wk[None, :] < w_end[:, None]) & kmask[None, :] & row_ok+ s = tl.where(vis, s, _NEG_INF)+ m_new = tl.maximum(m_i, tl.max(s, 1))+ alpha = tl.exp(m_i - m_new)+ # Mask p, not only s: a wholly masked row must contribute 0, not exp(0) == 1.+ p = tl.where(vis, tl.exp(s - m_new[:, None]), 0.0)+ l_i = l_i * alpha + tl.sum(p, 1)+ v_blk = tl.load(v_ptr + kv_ptrs, mask=kv_mask, other=0.0)+ if is_fp32:+ acc = acc * alpha[:, None] + tl.dot(p, v_blk, input_precision="ieee")+ else:+ acc = acc * alpha[:, None] + tl.dot(p.to(v_blk.dtype), v_blk)+ m_i = m_new+ return m_i, l_i, acc+++def _joint_video_kernel(+ q_ptr,+ k_ptr,+ v_ptr,+ kf_k_ptr,+ kf_v_ptr,+ slot_ptr,+ out_ptr,+ t_size,+ h_size,+ w_size,+ num_heads,+ bn_count,+ s_b,+ s_t,+ s_h,+ s_w,+ s_n,+ kf_s_b,+ kf_s_p,+ kt: tl.constexpr,+ kh: tl.constexpr,+ kw: tl.constexpr,+ num_slots: tl.constexpr,+ hd: tl.constexpr,+ hd_pad: tl.constexpr,+ block_q: tl.constexpr,+ block_k: tl.constexpr,+ is_fp32: tl.constexpr,+):+ """Video queries: local ``Kt x Kh x Kw`` window plus ``num_slots`` keyframe planes."""+ pid_w = tl.program_id(0)+ h_q = tl.program_id(1)+ pid_tbn = tl.program_id(2)++ # (frame, batch, head) share axis 2 and H owns axis 1, rather than folding T*H into axis 1:+ # gridDim.y/z are capped at 65535 and T*H passes that at production tile sizes (392*272).+ # Axis 0 stays the W block so neighbouring programs keep touching neighbouring addresses.+ t_q = pid_tbn // bn_count+ pid_bn = pid_tbn % bn_count+ batch_i = pid_bn // num_heads+ head_i = pid_bn % num_heads+ # int64 throughout: s_t alone fits in int32, but t_q * s_t reaches ~6.5e9 on a 392-frame+ # tile at 1088x1920, and Triton would otherwise do that product in int32 and wrap.+ base = batch_i.to(tl.int64) * s_b + head_i.to(tl.int64) * s_n+ kf_base = batch_i.to(tl.int64) * kf_s_b + head_i.to(tl.int64) * s_n++ w_off = pid_w * block_q + tl.arange(0, block_q)+ w_valid = w_off < w_size+ d_off = tl.arange(0, hd_pad)+ d_mask = d_off < hd++ q_ptrs = q_ptr + base + t_q.to(tl.int64) * s_t + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]+ q_blk = tl.load(q_ptrs, mask=w_valid[:, None] & d_mask[None, :], other=0.0)++ # Per-query clamped W window, and the union of them for this block of queries.+ w_q = tl.where(w_valid, w_off, 0)+ w_start = tl.maximum(w_q - kw // 2, 0)+ w_end = tl.minimum(w_q - kw // 2 + kw, w_size)+ blk_last = tl.minimum(pid_w * block_q + block_q - 1, w_size - 1)+ w_lo = tl.maximum(pid_w * block_q - kw // 2, 0)+ w_hi = tl.minimum(blk_last - kw // 2 + kw, w_size)++ m_i = tl.full((block_q,), _NEG_INF, dtype=tl.float32)+ l_i = tl.zeros((block_q,), dtype=tl.float32)+ acc = tl.zeros((block_q, hd_pad), dtype=tl.float32)++ # Local video window: fixed kt*kh taps, clamped for the load and masked in the softmax.+ for d_t in range(kt):+ tk = t_q - kt // 2 + d_t+ t_ok = (tk >= 0) & (tk < t_size)+ tk_c = tl.maximum(tl.minimum(tk, t_size - 1), 0)+ for d_h in range(kh):+ hk = h_q - kh // 2 + d_h+ row_ok = t_ok & (hk >= 0) & (hk < h_size)+ hk_c = tl.maximum(tl.minimum(hk, h_size - 1), 0)+ m_i, l_i, acc = _fold_w_run(+ m_i,+ l_i,+ acc,+ q_blk,+ k_ptr,+ v_ptr,+ base + tk_c.to(tl.int64) * s_t + hk_c.to(tl.int64) * s_h,+ row_ok,+ w_lo,+ w_hi,+ w_start,+ w_end,+ s_w,+ d_off,+ d_mask,+ block_k=block_k,+ is_fp32=is_fp32,+ )++ # Nearest keyframe planes, into the same softmax state. No temporal offset: the plane+ # itself is the tap, and its visibility does not depend on kt.+ for slot in range(num_slots):+ plane = tl.load(slot_ptr + t_q * num_slots + slot)+ plane_ok = plane >= 0+ plane_c = tl.maximum(plane, 0)+ for d_h in range(kh):+ hk = h_q - kh // 2 + d_h+ row_ok = plane_ok & (hk >= 0) & (hk < h_size)+ hk_c = tl.maximum(tl.minimum(hk, h_size - 1), 0)+ m_i, l_i, acc = _fold_w_run(+ m_i,+ l_i,+ acc,+ q_blk,+ kf_k_ptr,+ kf_v_ptr,+ kf_base + plane_c.to(tl.int64) * kf_s_p + hk_c.to(tl.int64) * s_h,+ row_ok,+ w_lo,+ w_hi,+ w_start,+ w_end,+ s_w,+ d_off,+ d_mask,+ block_k=block_k,+ is_fp32=is_fp32,+ )++ out = acc / tl.maximum(l_i, _LSE_FLOOR)[:, None]+ out_ptrs = out_ptr + base + t_q.to(tl.int64) * s_t + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]+ tl.store(out_ptrs, out.to(out_ptr.dtype.element_ty), mask=w_valid[:, None] & d_mask[None, :])+++def _joint_keyframe_kernel(+ kf_q_ptr,+ kf_k_ptr,+ kf_v_ptr,+ k_ptr,+ v_ptr,+ slot_ptr,+ valid_ptr,+ out_ptr,+ h_size,+ w_size,+ num_heads,+ bn_count,+ s_b,+ s_t,+ s_h,+ s_w,+ s_n,+ kf_s_b,+ kf_s_p,+ kh: tl.constexpr,+ kw: tl.constexpr,+ num_slots: tl.constexpr,+ hd: tl.constexpr,+ hd_pad: tl.constexpr,+ block_q: tl.constexpr,+ block_k: tl.constexpr,+ is_fp32: tl.constexpr,+):+ """Keyframe queries: own plane only (no plane-to-plane) plus ``num_slots`` video frames.+ An invalid plane has no visible key at all -- its own-plane predicate is false and+ ``keyframe_video_slots`` gives it ``-1`` slots -- so ``l_i`` stays 0 and the store is+ exactly zero. That is the same observable result as upstream's overwrite-scores-with-0+ NaN guard.+ """+ pid_w = tl.program_id(0)+ h_q = tl.program_id(1)+ pid_pbn = tl.program_id(2)++ # Same axis split and the same int64 discipline as the video kernel.+ p_q = pid_pbn // bn_count+ pid_bn = pid_pbn % bn_count+ batch_i = pid_bn // num_heads+ head_i = pid_bn % num_heads+ base = batch_i.to(tl.int64) * s_b + head_i.to(tl.int64) * s_n+ kf_base = batch_i.to(tl.int64) * kf_s_b + head_i.to(tl.int64) * s_n++ w_off = pid_w * block_q + tl.arange(0, block_q)+ w_valid = w_off < w_size+ d_off = tl.arange(0, hd_pad)+ d_mask = d_off < hd++ q_ptrs = (+ kf_q_ptr + kf_base + p_q.to(tl.int64) * kf_s_p + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]+ )+ q_blk = tl.load(q_ptrs, mask=w_valid[:, None] & d_mask[None, :], other=0.0)++ w_q = tl.where(w_valid, w_off, 0)+ w_start = tl.maximum(w_q - kw // 2, 0)+ w_end = tl.minimum(w_q - kw // 2 + kw, w_size)+ blk_last = tl.minimum(pid_w * block_q + block_q - 1, w_size - 1)+ w_lo = tl.maximum(pid_w * block_q - kw // 2, 0)+ w_hi = tl.minimum(blk_last - kw // 2 + kw, w_size)++ m_i = tl.full((block_q,), _NEG_INF, dtype=tl.float32)+ l_i = tl.zeros((block_q,), dtype=tl.float32)+ acc = tl.zeros((block_q, hd_pad), dtype=tl.float32)++ own_ok = tl.load(valid_ptr + p_q) != 0+ for d_h in range(kh):+ hk = h_q - kh // 2 + d_h+ row_ok = own_ok & (hk >= 0) & (hk < h_size)+ hk_c = tl.maximum(tl.minimum(hk, h_size - 1), 0)+ m_i, l_i, acc = _fold_w_run(+ m_i,+ l_i,+ acc,+ q_blk,+ kf_k_ptr,+ kf_v_ptr,+ kf_base + p_q.to(tl.int64) * kf_s_p + hk_c.to(tl.int64) * s_h,+ row_ok,+ w_lo,+ w_hi,+ w_start,+ w_end,+ s_w,+ d_off,+ d_mask,+ block_k=block_k,+ is_fp32=is_fp32,+ )++ for slot in range(num_slots):+ frame = tl.load(slot_ptr + p_q * num_slots + slot)+ frame_ok = frame >= 0+ frame_c = tl.maximum(frame, 0)+ for d_h in range(kh):+ hk = h_q - kh // 2 + d_h+ row_ok = frame_ok & (hk >= 0) & (hk < h_size)+ hk_c = tl.maximum(tl.minimum(hk, h_size - 1), 0)+ m_i, l_i, acc = _fold_w_run(+ m_i,+ l_i,+ acc,+ q_blk,+ k_ptr,+ v_ptr,+ base + frame_c.to(tl.int64) * s_t + hk_c.to(tl.int64) * s_h,+ row_ok,+ w_lo,+ w_hi,+ w_start,+ w_end,+ s_w,+ d_off,+ d_mask,+ block_k=block_k,+ is_fp32=is_fp32,+ )++ out = acc / tl.maximum(l_i, _LSE_FLOOR)[:, None]+ out_ptrs = (+ out_ptr + kf_base + p_q.to(tl.int64) * kf_s_p + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]+ )+ tl.store(out_ptrs, out.to(out_ptr.dtype.element_ty), mask=w_valid[:, None] & d_mask[None, :])+++def _check_shared_layout(video: torch.Tensor, keyframes: torch.Tensor) -> None:+ """Both streams must be contiguous and agree on H/W/NH/HD.+ The kernels pass one set of ``s_h``/``s_w``/``s_n`` strides for both streams, which is+ only sound because of this -- so it is checked rather than assumed.+ """+ if video.shape[2:] != keyframes.shape[2:]:+ raise ValueError(+ f"video and keyframe streams must agree on H/W/NH/HD, got {tuple(video.shape)} vs {tuple(keyframes.shape)}"+ )+ if not video.is_contiguous() or not keyframes.is_contiguous():+ raise ValueError("joint Triton NA needs both streams contiguous")+ if video.stride()[2:5] != keyframes.stride()[2:5]:+ raise ValueError(+ f"H/W/NH strides must match across streams, got {video.stride()[2:5]} vs {keyframes.stride()[2:5]}"+ )+++def joint_na3d(+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ keyframe_q: torch.Tensor,+ keyframe_k: torch.Tensor,+ keyframe_v: torch.Tensor,+ keyframe_times: torch.Tensor,+ keyframe_valid: torch.Tensor,+ kernel_size: tuple[int, int, int],+ num_slots: int = KEYFRAME_CONTEXT_SLOTS,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Joint neighborhood attention over a video volume and a keyframe plane stack.+ Signature-compatible with :func:`joint_eager.joint_na3d` so the two are drop-in+ swappable and can be diffed directly.+ Args:+ q, k, v: ``(B, T, H, W, NH, HD)`` video stream, already normed/scaled/RoPE'd.+ keyframe_q, keyframe_k, keyframe_v: ``(B, P, H, W, NH, HD)`` keyframe stream.+ keyframe_times: ``(P,)`` float32 plane times, same origin as the video RoPE.+ keyframe_valid: ``(P,)`` bool.+ kernel_size: ``(Kt, Kh, Kw)``.+ num_slots: cross-stream slots per query.+ Returns:+ ``(video_out, keyframe_out)``, each shaped like its stream's ``q``.+ """+ q, k, v = q.contiguous(), k.contiguous(), v.contiguous()+ keyframe_q = keyframe_q.contiguous()+ keyframe_k = keyframe_k.contiguous()+ keyframe_v = keyframe_v.contiguous()+ _check_shared_layout(q, keyframe_q)++ batch, time, height, width, heads, head_dim = q.shape+ planes = keyframe_q.shape[1]+ if keyframe_times.shape != (planes,) or keyframe_valid.shape != (planes,):+ raise ValueError(+ f"keyframe_times/keyframe_valid must be ({planes},), got "+ f"{tuple(keyframe_times.shape)} / {tuple(keyframe_valid.shape)}"+ )+ kernel_t, kernel_h, kernel_w = kernel_size++ # Slot tables are built here rather than passed in: every backend must agree on+ # selection, so they come from the one shared implementation.+ video_slots = video_keyframe_slots(keyframe_times, keyframe_valid, time, num_slots)+ keyframe_slots = keyframe_video_slots(keyframe_times, keyframe_valid, time, num_slots)+ video_slots = video_slots.to(device=q.device, dtype=torch.int32).contiguous()+ keyframe_slots = keyframe_slots.to(device=q.device, dtype=torch.int32).contiguous()+ valid_i32 = keyframe_valid.to(device=q.device, dtype=torch.int32).contiguous()++ video_out = torch.empty_like(q)+ keyframe_out = torch.empty_like(keyframe_q)++ hd_pad = max(16, triton.next_power_of_2(head_dim))+ block_q = 16+ block_k = max(16, min(32, triton.next_power_of_2(min(width, block_q + kernel_w))))+ is_fp32 = q.dtype == torch.float32+ strides = (q.stride(0), q.stride(1), q.stride(2), q.stride(3), q.stride(4))+ kf_strides = (keyframe_q.stride(0), keyframe_q.stride(1))++ bn_count = batch * heads+ _joint_video_kernel[(triton.cdiv(width, block_q), height, time * bn_count)](+ q,+ k,+ v,+ keyframe_k,+ keyframe_v,+ video_slots,+ video_out,+ time,+ height,+ width,+ heads,+ bn_count,+ *strides,+ *kf_strides,+ kt=kernel_t,+ kh=kernel_h,+ kw=kernel_w,+ num_slots=num_slots,+ hd=head_dim,+ hd_pad=hd_pad,+ block_q=block_q,+ block_k=block_k,+ is_fp32=is_fp32,+ num_warps=4,+ )+ _joint_keyframe_kernel[(triton.cdiv(width, block_q), height, planes * bn_count)](+ keyframe_q,+ keyframe_k,+ keyframe_v,+ k,+ v,+ keyframe_slots,+ valid_i32,+ keyframe_out,+ height,+ width,+ heads,+ bn_count,+ *strides,+ *kf_strides,+ kh=kernel_h,+ kw=kernel_w,+ num_slots=num_slots,+ hd=head_dim,+ hd_pad=hd_pad,+ block_q=block_q,+ block_k=block_k,+ is_fp32=is_fp32,+ num_warps=4,+ )+ return video_out, keyframe_outdiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/triton_na.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/triton_na.pyindex e0e863f..0e95d91 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/triton_na.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/fallback_na/triton_na.py@@ -27,6 +27,7 @@ def _na3d_kernel(h_size,w_size,num_heads,+ bn_count,s_b,s_t,s_h,@@ -46,19 +47,26 @@ def _na3d_kernel(is_fp32: tl.constexpr,):pid_w = tl.program_id(0)- pid_th = tl.program_id(1)- pid_bn = tl.program_id(2)-- t_q = pid_th // h_size- h_q = pid_th % h_size- base = (pid_bn // num_heads) * s_b + (pid_bn % num_heads) * s_n+ h_q = tl.program_id(1)+ pid_tbn = tl.program_id(2)++ # (frame, batch, head) share axis 2 and H owns axis 1, rather than folding T*H into axis 1:+ # gridDim.y/z are capped at 65535 and T*H passes that at production tile sizes (392*272 =+ # 106624), which fails the launch outright with "Triton Error [CUDA]: invalid argument".+ # Same layout as joint_triton, for the same reason.+ t_q = pid_tbn // bn_count+ pid_bn = pid_tbn % bn_count+ # int64 throughout: every individual stride fits in int32, so Triton specializes them there,+ # but t_q * s_t reaches ~1.3e10 on a 392-frame tile and would wrap -- an illegal memory access+ # rather than a wrong answer.+ base = (pid_bn // num_heads).to(tl.int64) * s_b + (pid_bn % num_heads).to(tl.int64) * s_nw_off = pid_w * block_q + tl.arange(0, block_q)w_valid = w_off < w_sized_off = tl.arange(0, hd_pad)d_mask = d_off < hd- q_ptrs = q_ptr + base + t_q * s_t + h_q * s_h + w_off[:, None] * s_w + d_off[None, :]+ q_ptrs = q_ptr + base + t_q.to(tl.int64) * s_t + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]q_blk = tl.load(q_ptrs, mask=w_valid[:, None] & d_mask[None, :], other=0.0)if causal_t:@@ -96,7 +104,7 @@ def _na3d_kernel(for tk in range(t_lo, t_hi):for hk in range(h_lo, h_hi):- plane = base + tk * s_t + hk * s_h+ plane = base + tk.to(tl.int64) * s_t + hk.to(tl.int64) * s_hfor wk0 in range(w_lo, w_hi, block_k):wk = wk0 + tl.arange(0, block_k)kmask = wk < w_hi@@ -121,7 +129,7 @@ def _na3d_kernel(m_i = m_newout = acc / tl.maximum(l_i, 1e-30)[:, None]- out_ptrs = out_ptr + base + t_q * s_t + h_q * s_h + w_off[:, None] * s_w + d_off[None, :]+ out_ptrs = out_ptr + base + t_q.to(tl.int64) * s_t + h_q.to(tl.int64) * s_h + w_off[:, None] * s_w + d_off[None, :]tl.store(out_ptrs, out.to(out_ptr.dtype.element_ty), mask=w_valid[:, None] & d_mask[None, :])@@ -149,7 +157,7 @@ def na3d(block_q = 16block_k = max(16, min(32, triton.next_power_of_2(min(w, block_q + kw))))- grid = (triton.cdiv(w, block_q), t * h, batch * nh)+ grid = (triton.cdiv(w, block_q), h, t * batch * nh)_na3d_kernel[grid](q,k,@@ -159,6 +167,7 @@ def na3d(h,w,nh,+ batch * nh,q.stride(0),q.stride(1),q.stride(2),diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/swiglu.py b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/swiglu.pyindex c2ee73e..21b92a2 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/transformer/swiglu.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/transformer/swiglu.py@@ -67,6 +67,28 @@ def triton_swiglu_available() -> bool:return _TRITON_AVAILABLE and torch.cuda.is_available()+def _cuda_tensors_for_triton(*tensors: torch.Tensor) -> bool:+ """True when every tensor is CUDA and all share one device (Triton launch context)."""+ if not tensors or not tensors[0].is_cuda:+ return False+ device = tensors[0].device+ return all(t.is_cuda and t.device == device for t in tensors)+++def _resolve_use_triton(use_triton: bool, *tensors: torch.Tensor) -> bool:+ """Enable Triton only when every tensor is on the same CUDA device; reject mixed devices."""+ if not use_triton:+ return False+ if _cuda_tensors_for_triton(*tensors):+ return True+ devices = {t.device for t in tensors}+ if len(devices) > 1:+ raise ValueError(+ f"SwiGLU requires all tensors on one device for Triton or torch.mm; got {sorted(str(d) for d in devices)}"+ )+ return False++def token_intervals(n_tok: int, tile: SwiGLUTileSpec) -> list[DimensionInterval]:"""Split ``n_tok`` tokens per ``tile`` (count or size). Overlap is always 0."""if n_tok < 0:@@ -216,10 +238,10 @@ def dual_gate_up_triton_eligible(w_up: torch.Tensor,) -> bool:"""True when the fused gate+up SwiGLU Triton kernel can run.- Requires BF16 activations/weights, ``hidden == 4 * dim``, and ``dim`` in- ``[256, 2048]`` (DiffVAE MLP shapes).+ Requires BF16 activations/weights on the same CUDA device, ``hidden == 4 * dim``,+ and ``dim`` in ``[256, 2048]`` (DiffVAE MLP shapes)."""- if not triton_swiglu_available() or not x.is_cuda:+ if not triton_swiglu_available() or not _cuda_tensors_for_triton(x, w_gate, w_up):return Falseif x.dtype != torch.bfloat16 or w_gate.dtype != torch.bfloat16 or w_up.dtype != torch.bfloat16:return False@@ -241,57 +263,69 @@ def _fused_gate_up_swiglu_triton("""``out = silu(x @ W_gateᵀ) * (x @ W_upᵀ)`` with one x-tile load (BF16)."""if not _TRITON_AVAILABLE:raise RuntimeError("Triton is not available")+ if not _cuda_tensors_for_triton(x, w_gate, w_up, out):+ raise ValueError(+ "fused gate+up SwiGLU Triton requires CUDA tensors on one device; "+ f"got x={x.device}, w_gate={w_gate.device}, w_up={w_up.device}, out={out.device}"+ )m, k = x.shapen = w_gate.shape[0]block_m, block_n, block_k = 64, 64, 32grid = (triton.cdiv(m, block_m), triton.cdiv(n, block_n))- _fused_gate_up_swiglu_kernel[grid](- x,- w_gate,- w_up,- out,- m,- k,- n,- x.stride(0),- x.stride(1),- w_gate.stride(0),- w_gate.stride(1),- w_up.stride(0),- w_up.stride(1),- out.stride(0),- out.stride(1),- BLOCK_M=block_m,- BLOCK_N=block_n,- BLOCK_K=block_k,- )+ with torch.cuda.device(x.device):+ _fused_gate_up_swiglu_kernel[grid](+ x,+ w_gate,+ w_up,+ out,+ m,+ k,+ n,+ x.stride(0),+ x.stride(1),+ w_gate.stride(0),+ w_gate.stride(1),+ w_up.stride(0),+ w_up.stride(1),+ out.stride(0),+ out.stride(1),+ BLOCK_M=block_m,+ BLOCK_N=block_n,+ BLOCK_K=block_k,+ )def _fused_up_mul_triton(x: torch.Tensor, w_up: torch.Tensor, silu_gate: torch.Tensor) -> None:"""Inplace: ``silu_gate *= (x @ w_up.T)``."""if not _TRITON_AVAILABLE:raise RuntimeError("Triton is not available")+ if not _cuda_tensors_for_triton(x, w_up, silu_gate):+ raise ValueError(+ "fused up-mul SwiGLU Triton requires CUDA tensors on one device; "+ f"got x={x.device}, w_up={w_up.device}, silu_gate={silu_gate.device}"+ )m, k = x.shapen = w_up.shape[0]block_m, block_n, block_k = 64, 64, 32grid = (triton.cdiv(m, block_m), triton.cdiv(n, block_n))- _fused_up_mul_kernel[grid](- x,- w_up,- silu_gate,- m,- k,- n,- x.stride(0),- x.stride(1),- w_up.stride(0),- w_up.stride(1),- silu_gate.stride(0),- silu_gate.stride(1),- BLOCK_M=block_m,- BLOCK_N=block_n,- BLOCK_K=block_k,- )+ with torch.cuda.device(x.device):+ _fused_up_mul_kernel[grid](+ x,+ w_up,+ silu_gate,+ m,+ k,+ n,+ x.stride(0),+ x.stride(1),+ w_up.stride(0),+ w_up.stride(1),+ silu_gate.stride(0),+ silu_gate.stride(1),+ BLOCK_M=block_m,+ BLOCK_N=block_n,+ BLOCK_K=block_k,+ )def _fused_up_mul_torch(x: torch.Tensor, w_up: torch.Tensor, silu_gate: torch.Tensor) -> None:@@ -351,10 +385,13 @@ def _swiglu_chunked_impl(if n_tok == 0:return x+ # Triton needs every pointer on the launch device; all-CPU falls back to torch.mm.+ use_triton = _resolve_use_triton(bool(use_triton), x_flat, w_gate, w_up, w_down)+out_flat = torch.empty((n_tok, dim), device=x.device, dtype=x.dtype)max_chunk = max((iv.end - iv.start for iv in intervals), default=0)workspace = torch.empty((max_chunk, hidden), device=x.device, dtype=x.dtype)- use_dual = bool(use_triton) and dual_gate_up_triton_eligible(x_flat, w_gate, w_up)+ use_dual = use_triton and dual_gate_up_triton_eligible(x_flat, w_gate, w_up)w_gate_c = w_gate.contiguous() if use_dual else w_gatew_up_c = w_up.contiguous() if use_triton else w_updiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py b/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.pyindex e743ba7..8359d87 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py@@ -1,5 +1,6 @@import itertoolsimport logging+from collections.abc import Sequencefrom typing import Any, Callable, Iterator, List, Protocol, Tupleimport torch@@ -11,6 +12,7 @@ from ltx_core.model.transformer.attention import AttentionCallable, AttentionFunfrom ltx_core.model.video_vae.attention import AttnBlock3Dfrom ltx_core.model.video_vae.convolution import make_conv_ndfrom ltx_core.model.video_vae.enums import LogVarianceType, NormLayerType, PaddingModeType+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.ops import PerChannelStatistics, patchifyfrom ltx_core.model.video_vae.resnet import ResnetBlock3D, UNetMidBlock3Dfrom ltx_core.model.video_vae.sampling import SpaceToDepthDownsample@@ -479,6 +481,40 @@ def prepare_tiles_for_encoding(return tiles+def _clip_generators(+ count: int,+ generator: torch.Generator | Sequence[torch.Generator | None] | None,+) -> Sequence[torch.Generator | None]:+ if generator is None:+ return (None,) * count+ if isinstance(generator, torch.Generator):+ return (generator,) * count+ if len(generator) != count:+ raise ValueError(f"decode_single_frames got {count} latents and {len(generator)} generators")+ return generator+++def iter_decoded_single_frames(+ decoder: "VideoDecoder",+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,+) -> Iterator[torch.Tensor]:+ """Decode each latent through ``decode_video`` as its own clip.+ Dist must pass the inner SGPU decoder, not itself: ``decode_video`` on Dist splits the+ volume and workers return an empty iterator.+ """+ gens = _clip_generators(len(latents), generator)+ for index, (latent, gen) in enumerate(zip(latents, gens, strict=True)):+ if latent.ndim != 5 or latent.shape[2] != 1:+ raise ValueError(+ f"decode_single_frames expects (B, C, 1, H, W) latents, got {tuple(latent.shape)} at index {index}"+ )+ chunks = list(decoder.decode_video(latent, tiling_config=None, generator=gen))+ if not chunks:+ raise RuntimeError(f"Decoder returned no pixels for single-frame latent {index}")+ yield torch.cat(chunks, dim=0)++class VideoDecoder(Protocol):"""Structural interface for video VAE decoders.Implementations decode a latent tensor into pixel-space video chunks@@ -493,8 +529,25 @@ class VideoDecoder(Protocol):latent: torch.Tensor,tiling_config: TileSizeConfig | TileCountConfig | None = None,generator: torch.Generator | None = None,+ *,+ keyframes: "DecodeKeyframes | None" = None,+ ) -> Iterator[torch.Tensor]:+ """Decode a video latent tensor, yielding float chunks ``[f, h, w, c]`` in ``[0, 1]``.+ ``keyframes`` anchors the decode on already-encoded single-frame planes. It is a hint,+ not a contract: a decoder that cannot use it says so once and decodes plainly, so a+ caller never has to ask which decoder it got before handing keyframes over.+ """+ ...++ def decode_single_frames(+ self,+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,) -> Iterator[torch.Tensor]:- """Decode a video latent tensor, yielding float chunks ``[f, h, w, c]`` in ``[0, 1]``."""+ """Decode each latent as its own one-frame clip, yielding one RGB tensor per latent.+ A causal VAE cannot decode stacked independent planes without bleeding neighbours.+ Dist implementations decode locally on every rank; they do not split or gather.+ """...diff --git a/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py b/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.pyindex 7eb9144..55b0574 100644--- a/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py+++ b/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py@@ -14,7 +14,7 @@ management — they are independent concerns.from __future__ import annotationsimport logging-from collections.abc import Callable, Iterator+from collections.abc import Callable, Iterator, Sequencefrom dataclasses import dataclassimport torch@@ -23,8 +23,10 @@ from einops import rearrangefrom torch.multiprocessing import Queuefrom ltx_core.model.disposable import Disposable+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.video_vae import (VideoDecoder,+ iter_decoded_single_frames,map_spatial_slice,map_temporal_slice,to_mapping_operation,@@ -38,7 +40,7 @@ from ltx_core.tiling import (masks_are_complementary,scale_by_masks_1d,)-from ltx_core.types import SpatioTemporalScaleFactors, VideoLatentShape+from ltx_core.types import SpatioTemporalScaleFactors, VideoLatentShape, VideoPixelShapelogger = logging.getLogger(__name__)@@ -48,6 +50,68 @@ def _sgpu_has_temporal_tiling(tiling_config: TilingConfig | None, num_frames: inreturn tiling_config is not None and tiling_config.video_chunks_number(num_frames) > 1+def create_distributed_tiles(+ vae_tiling: TileCountConfig,+ latent_shape: VideoLatentShape,+ scale: SpatioTemporalScaleFactors,+) -> list[Tile]:+ """Latent tiles Dist decode uses: ``vae_tiling`` splitters + latent→pixel mappers."""+ t_split, h_split, w_split = vae_tiling.to_splitters(scale, causal_temporal=True)+ return create_tiles(+ torch.Size([latent_shape.frames, latent_shape.height, latent_shape.width]),+ splitters=[t_split, h_split, w_split],+ mappers=[+ to_mapping_operation(map_temporal_slice, scale.time),+ to_mapping_operation(map_spatial_slice, scale.height),+ to_mapping_operation(map_spatial_slice, scale.width),+ ],+ )+++def dist_rank_tiles(+ vae_tiling: TileCountConfig,+ latent_shape: VideoLatentShape,+ scale: SpatioTemporalScaleFactors,+ rank: int,+ world_size: int,+) -> list[Tile]:+ """Round-robin Dist tiles for ``rank`` (same assignment as :meth:`DistributedVideoDecoder._decode_tiles`)."""+ if world_size < 1:+ raise ValueError(f"world_size must be >= 1, got {world_size}")+ if not 0 <= rank < world_size:+ raise ValueError(f"rank must be in [0, {world_size}), got {rank}")+ all_tiles = create_distributed_tiles(vae_tiling, latent_shape, scale)+ return [t for i, t in enumerate(all_tiles) if i % world_size == rank]+++def dist_rank_tile_pixel_shape(+ vae_tiling: TileCountConfig,+ latent_shape: VideoLatentShape,+ scale: SpatioTemporalScaleFactors,+ rank: int,+ world_size: int,+ *,+ fps: float,+ batch: int = 1,+) -> VideoPixelShape:+ """Pixel extent of this rank's Dist decode volume (largest tile if the rank owns several).+ Matches ``decode_video`` of each ``latent[:, :, in_coords]`` slice: spatial axes scale+ by ``scale.height`` / ``scale.width``; temporal is ``(F_lat - 1) * scale.time + 1``.+ """+ my_tiles = dist_rank_tiles(vae_tiling, latent_shape, scale, rank, world_size)+ if not my_tiles:+ raise ValueError(f"rank {rank}/{world_size} has no Dist tiles")++ def pixel_thw(tile: Tile) -> tuple[int, int, int]:+ f_lat = tile.in_coords[0].stop - tile.in_coords[0].start+ h_lat = tile.in_coords[1].stop - tile.in_coords[1].start+ w_lat = tile.in_coords[2].stop - tile.in_coords[2].start+ return (f_lat - 1) * scale.time + 1, h_lat * scale.height, w_lat * scale.width++ frames, height, width = max(map(pixel_thw, my_tiles), key=lambda thw: thw[0] * thw[1] * thw[2])+ return VideoPixelShape(batch=batch, frames=frames, height=height, width=width, fps=fps)++# ------------------------------------------------------------------# Data structures# ------------------------------------------------------------------@@ -165,6 +229,10 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):driver_rank:Group-local rank of the driver process (the rank that collectsand assembles tiles).+ num_temporal_batches:+ Number of temporal batches the driver assembles the canvas in+ (:func:`gather_frames`); each is a ``frames/n x H x W x 3`` buffer, so a+ higher count lowers peak driver VRAM. Defaults to one batch per rank."""def __init__(@@ -174,6 +242,7 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):vae_group: dist.ProcessGroup,vae_tiling: TileCountConfig,driver_rank: int = 0,+ num_temporal_batches: int | None = None,) -> None:super().__init__()self.decoder = decoder@@ -183,6 +252,9 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):self.world_size = dist.get_world_size(vae_group)self.vae_tiling = vae_tilingself.driver_rank = driver_rank+ if num_temporal_batches is not None and num_temporal_batches < 1:+ raise ValueError(f"num_temporal_batches must be >= 1, got {num_temporal_batches}")+ self.num_temporal_batches = self.world_size if num_temporal_batches is None else num_temporal_batches@propertydef video_downscale_factors(self) -> SpatioTemporalScaleFactors:@@ -207,6 +279,8 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):tiling_config: TilingConfig | None = None,generator: torch.Generator | None = None,device_fn: Callable[[int], str | torch.device] | None = None,+ *,+ keyframes: DecodeKeyframes | None = None,) -> Iterator[torch.Tensor]:"""Distributed decode — all ranks decode, driver assembles.Not a generator so that worker side-effects (decode + queue.put)@@ -221,7 +295,7 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):full_shape = latent_shape.upscale(scale)# Phase 1: each rank decodes its assigned tiles.- my_tiles = self._decode_tiles(latent, latent_shape, scale, generator, tiling_config)+ my_tiles = self._decode_tiles(latent, latent_shape, scale, generator, tiling_config, keyframes)# Phase 2: workers send tiles to driver.if self.rank != self.driver_rank:@@ -249,13 +323,25 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):full_shape.frames,full_shape.height,full_shape.width,- self.world_size,+ self.num_temporal_batches,self.world_size,weights,device_fn=device_fn,)return batches+ def decode_single_frames(+ self,+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,+ ) -> Iterator[torch.Tensor]:+ """Local SGPU decode of each T=1 clip on every rank. Does not Dist-split or gather.+ ``decode_video`` on Dist is the wrong tool here: workers send their tile and yield+ nothing. Carry-keyframe planes are independent one-frame clips, so every rank+ decodes them on the inner decoder and keeps the pixels.+ """+ yield from iter_decoded_single_frames(self.decoder, latents, generator)+# ------------------------------------------------------------------# Private helpers# ------------------------------------------------------------------@@ -267,19 +353,18 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):scale: SpatioTemporalScaleFactors,generator: torch.Generator | None,tiling_config: TilingConfig | None = None,+ keyframes: DecodeKeyframes | None = None,) -> list[DecodedTile]:- """Decode this rank's assigned latent tiles and convert to :class:`DecodedTile` list."""- t_split, h_split, w_split = self.vae_tiling.to_splitters(scale, causal_temporal=True)- all_tiles = create_tiles(- torch.Size([latent_shape.frames, latent_shape.height, latent_shape.width]),- splitters=[t_split, h_split, w_split],- mappers=[- to_mapping_operation(map_temporal_slice, scale.time),- to_mapping_operation(map_spatial_slice, scale.height),- to_mapping_operation(map_spatial_slice, scale.width),- ],- )- my_tiles = [t for i, t in enumerate(all_tiles) if i % self.world_size == self.rank]+ """Decode this rank's assigned latent tiles and convert to :class:`DecodedTile` list.+ Each tile gets its keyframe planes narrowed to its own window:+ * spatially, with the same slices as its video latent -- planes are full-frame, so+ handing them over uncropped offsets every one of them by the tile origin;+ * temporally, via :meth:`DecodeKeyframes.for_frame_span`, which keeps the planes inside+ the tile **and the nearest one on each side of it**, leaves ``pixel_frame_indices``+ **global**, and sets ``clip_start_frame`` to the tile's first pixel. DiffVAE then+ uses ``t_s(48) - t_s(56)`` for the 8-frame gap instead of rewriting 48 to -8.+ """+ my_tiles = dist_rank_tiles(self.vae_tiling, latent_shape, scale, self.rank, self.world_size)if self.vae_tiling.frames.num_tiles > 1 and tiling_config is not None:for tile in my_tiles:latent_f = tile.in_coords[0].stop - tile.in_coords[0].start@@ -296,7 +381,17 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):# One MGPU tile only — cat stitches SGPU temporal yields of this tile,# not the full video (full assembly is gather_frames on the driver).latent_slice = latent[:, :, tile.in_coords[0], tile.in_coords[1], tile.in_coords[2]]- chunks = list(self.decoder.decode_video(latent_slice, tiling_config, generator=generator))+ tile_keyframes = (+ None+ if keyframes is None+ else keyframes.for_frame_span(tile.out_coords[0].start, tile.out_coords[0].stop - 1).crop_spatial(+ tile.in_coords[1], tile.in_coords[2]+ )+ )+ # Only pass the keyword when there is something to pass: the wrapped decoder may be+ # any VideoDecoder, including one written against the pre-keyframes signature.+ extra = {} if tile_keyframes is None else {"keyframes": tile_keyframes}+ chunks = list(self.decoder.decode_video(latent_slice, tiling_config, generator=generator, **extra))pixels = torch.cat(chunks, dim=0) # [F, H, W, C] in [0, 1]decoded.append(_to_decoded_tile(pixels, tile))return decodeddiff --git a/packages/ltx-core/src/ltx_core/quantization/fp8_cast.py b/packages/ltx-core/src/ltx_core/quantization/fp8_cast.pyindex 9082e9d..dfa8789 100644--- a/packages/ltx-core/src/ltx_core/quantization/fp8_cast.py+++ b/packages/ltx-core/src/ltx_core/quantization/fp8_cast.py@@ -59,6 +59,28 @@ def _naive_weight_or_bias_downcast(key: str, value: torch.Tensor) -> list[KeyValreturn [KeyValueOperationResult(key, value.to(dtype=torch.float8_e4m3fn))]+# Triton's fp8e4nv (torch.float8_e4m3fn) is only a legal kernel dtype on+# sm_89+ (Ada). Below that, tl.load of an e4m3fn tensor fails at compile with+# "type fp8e4nv not supported in this architecture". PyTorch eager conversion+# still works -- that is the software path used when Triton is missing.+_TRITON_FP8E4NV_MIN_CAPABILITY = (8, 9)+++def _triton_supports_fp8e4nv(device: torch.device) -> bool:+ """Return whether Triton's fused fp8 kernel can compile for *device*.+ ``device`` is the tensor's device, not the process's current CUDA device,+ so mixed-GPU hosts pick the capability that will actually run the kernel.+ """+ if device.type != "cuda" or not torch.cuda.is_available():+ return False+ return torch.cuda.get_device_capability(device) >= _TRITON_FP8E4NV_MIN_CAPABILITY+++def _use_triton_fp8_kernel(device: torch.device) -> bool:+ """True when ``fused_add_round_launch`` can compile on *device*."""+ return TRITON_AVAILABLE and _triton_supports_fp8e4nv(device)++def _upcast_and_round(weight: torch.Tensor, dtype: torch.dtype, with_stochastic_rounding: bool = False, seed: int = 0) -> torch.Tensor:@@ -66,10 +88,10 @@ def _upcast_and_round(Upcast the weight to the given dtype and optionally apply stochastic rounding.Input weight needs to have float8_e4m3fn or float8_e5m2 dtype.Stochastic rounding is implemented via a Triton kernel. When Triton is not- available (e.g., on Windows), this falls back to deterministic (nearest)- rounding via ``weight.to(dtype)``.+ available (e.g., on Windows) or cannot compile ``fp8e4nv`` (pre-Ada GPUs),+ this falls back to deterministic (nearest) rounding via ``weight.to(dtype)``."""- if not with_stochastic_rounding or not TRITON_AVAILABLE or weight.device.type != "cuda":+ if not with_stochastic_rounding or not _use_triton_fp8_kernel(weight.device):return weight.to(dtype)return fused_add_round_launch(torch.zeros_like(weight, dtype=dtype), weight, seed)@@ -206,13 +228,14 @@ def fuse_cast_fp8_weight(weight_fp8: torch.Tensor,) -> torch.Tensor:"""Return ``(delta_bf16 + dequantize(weight_fp8)).to(weight_fp8.dtype)``.- CUDA with Triton uses stochastic rounding via the fused kernel; otherwise- falls back to a deterministic bf16 add. ``delta_bf16`` is the bf16+ CUDA with Triton on sm_89+ uses stochastic rounding via the fused kernel;+ otherwise falls back to a deterministic bf16 add (no Triton, or a GPU+ whose Triton cannot compile ``fp8e4nv``). ``delta_bf16`` is the bf16accumulator and is mutated in place."""if delta_bf16.dtype != torch.bfloat16:raise ValueError(f"delta_bf16 must be bfloat16, got {delta_bf16.dtype}")- if str(weight_fp8.device).startswith("cuda") and TRITON_AVAILABLE:+ if _use_triton_fp8_kernel(weight_fp8.device):fused_add_round_launch(delta_bf16, weight_fp8, seed=0)else:delta_bf16.add_(weight_fp8.to(dtype=torch.bfloat16))@@ -226,7 +249,8 @@ def _fp8_cast_fuse(model_sd: StateDict,) -> dict[str, torch.Tensor]:"""Cast the dequantized FP8 weight + BF16 deltas back to ``weight.dtype``- (FP8) via the fused-add-round kernel on CUDA.+ (FP8) via the fused-add-round kernel on CUDA when Triton can compile+ ``fp8e4nv``, otherwise via a deterministic software add.Only a subset of linears are FP8-downcast (see ``TRANSFORMER_LINEAR_DOWNCAST_MAP``);LoRAs may also target layers left in BF16 (e.g. audio ``add_q/k/v_proj``, cross-modalprojections). For those, fall back to a plain BF16 fuse.diff --git a/packages/ltx-core/src/ltx_core/tiling.py b/packages/ltx-core/src/ltx_core/tiling.pyindex 7fd6b14..f3995de 100644--- a/packages/ltx-core/src/ltx_core/tiling.py+++ b/packages/ltx-core/src/ltx_core/tiling.py@@ -7,7 +7,7 @@ from typing import Callable, NamedTuple, Sequenceimport torch-from ltx_core.types import SpatioTemporalScaleFactors, VideoPixelShape+from ltx_core.types import VIDEO_SCALE_FACTORS, SpatioTemporalScaleFactors, VideoPixelShapedef compute_trapezoidal_mask_1d(@@ -301,6 +301,61 @@ def split_by_count_temporal_causal(return split+def split_at_seams(boundaries: Sequence[int], num_tiles: int, overlap: int = 0) -> SplitOperation:+ """Split a dimension on boundary cells whose content is already known, dropping the overlap.+ ``boundaries`` are the ``K + 1`` segment edges in grid cells, starting at 0 and ending at the+ last cell of the dimension. The ``K`` segments are dealt largest-first so leftover segments go to the leading tiles;+ ``num_tiles`` larger than ``K`` is clamped. Each tile but the first starts ``overlap`` cells+ before the boundary it resumes after. That run-up is context only: it lands in the interval's+ ``left_ramp``, which :func:`identity_mapping_operation` with ``rectangular=True`` masks to zero,+ so the earlier tile keeps the boundary cell and this one contributes strictly after it.+ The point of cutting here is that nothing needs blending. A ramp is what a pair of tiles needs+ when neither of them knows the truth at the seam; on a boundary cell both reproduce the same+ known frame, so averaging them only smears it.+ Args:+ boundaries: Segment edges in grid cells, strictly increasing, starting at 0.+ num_tiles: Number of tiles. Must be >= 1. Extra tiles beyond the segment count are dropped.+ overlap: Context cells each non-first tile denoises before the cell it resumes at, in grid+ units. Clamped at the start of the dimension.+ Returns:+ A split operation that divides a dimension on ``boundaries``.+ """+ boundaries = tuple(boundaries)+ if num_tiles < 1:+ raise ValueError(f"num_tiles must be >= 1, got {num_tiles}")+ if overlap < 0:+ raise ValueError(f"overlap must be >= 0, got {overlap}")+ if len(boundaries) < 2 or boundaries[0] != 0:+ raise ValueError(f"boundaries must start at 0 and hold at least one segment, got {list(boundaries)}")+ if any(b <= a for a, b in itertools.pairwise(boundaries)):+ raise ValueError(f"boundaries must be strictly increasing, got {list(boundaries)}")+ n_segments = len(boundaries) - 1+ n_tiles = min(num_tiles, n_segments)+ base, leftover = divmod(n_segments, n_tiles)+ counts = [base + (1 if index < leftover else 0) for index in range(n_tiles)]++ def split(dim_size: int) -> DimensionIntervals:+ if boundaries[-1] != dim_size - 1:+ raise ValueError(f"boundaries must end at the last cell ({dim_size - 1}), got {boundaries[-1]}")+ intervals: list[DimensionInterval] = []+ cursor = 0+ for tile_index, count in enumerate(counts):+ resume = boundaries[cursor] + 1+ start = 0 if tile_index == 0 else max(0, resume - overlap)+ cursor += count+ intervals.append(+ DimensionInterval(+ start=start,+ end=boundaries[cursor] + 1,+ left_ramp=0 if tile_index == 0 else resume - start,+ right_ramp=0,+ )+ )+ return DimensionIntervals(intervals=intervals)++ return split++def split_by_count(num_tiles: int, overlap: int = 0, min_tile_size: int | None = None) -> SplitOperation:"""Split a dimension into a given number of tiles with overlap.Computes the tile size as@@ -366,16 +421,24 @@ def split_by_count(num_tiles: int, overlap: int = 0, min_tile_size: int | None =# ----------------------------------------------------------------------------def identity_mapping_operation(intervals: DimensionIntervals) -> tuple[list[slice], list[torch.Tensor]]:- """Map each DimensionInterval to an output region at the same position, with trapezoidal blend masks.- For every interval the output start/end matches the input start/end and a- 1-D blending mask is built from the interval's left_ramp and right_ramp.+def identity_mapping_operation(+ intervals: DimensionIntervals,+ *,+ rectangular: bool = False,+) -> tuple[list[slice], list[torch.Tensor]]:+ """Map each DimensionInterval to an output region at the same position.+ For every interval the output start/end matches the input start/end and a 1-D mask is built+ from the interval's left_ramp and right_ramp. The default mask is trapezoidal (blend on the+ ramps). ``rectangular=True`` drops the ramps outright: the overlap is context the tile denoised+ but does not contribute. Pair that with a split whose ramps are one-sided, such as+ :func:`split_at_seams` -- ramps on both sides of an interval would leave a hole between tiles."""+ mask_1d = compute_rectangular_mask_1d if rectangular else compute_trapezoidal_mask_1dout_slices: list[slice] = []masks: list[torch.Tensor] = []for iv in intervals.intervals:out_slices.append(slice(iv.start, iv.end))- masks.append(compute_trapezoidal_mask_1d(iv.end - iv.start, iv.left_ramp, iv.right_ramp))+ masks.append(mask_1d(iv.end - iv.start, iv.left_ramp, iv.right_ramp))return out_slices, masks@@ -833,12 +896,24 @@ class TileSizeConfig:enable_size_axis(scale_factors.width, min_w, self.width, "width", temporal=False),)- def video_chunks_number(self, num_frames: int) -> int:- """Number of temporal decode chunks for ``num_frames`` under this layout."""+ def video_chunks_number(self, num_frames: int, *, time_scale: int = VIDEO_SCALE_FACTORS.time) -> int:+ """Number of temporal decode chunks for ``num_frames`` under this layout.+ Mirrors what decode actually does: :meth:`to_splitters` converts this axis to the+ latent grid and hands it to :func:`split_by_size`, so the count must be taken there+ too. Doing the arithmetic in pixel units instead over-reports by one whenever the+ trailing tile is absorbed -- including the common case of a tile larger than the+ clip, which is a single tile but used to report two.+ """if not self.frames.is_tiled():return 1- frame_stride = self.frames.tile_size - self.frames.overlap- return (num_frames - 1 + frame_stride - 1) // frame_stride+ # Same derivation as ``to_splitters.enable_size_axis``.+ overlap = self.frames.overlap // time_scale+ size = max(2, overlap + 1, self.frames.tile_size // time_scale)+ latent_frames = (num_frames - 1) // time_scale + 1+ if latent_frames <= size:+ return 1+ # Same tile count as ``split_by_size``.+ return (latent_frames + size - 2 * overlap - 1) // (size - overlap)# Either size-based (single-GPU VAE) or count-based (MGPU / explicit counts).diff --git a/packages/ltx-kernels/csrc/nvfp4/quantize.cu b/packages/ltx-kernels/csrc/nvfp4/quantize.cuindex 79ab370..5fd2ba4 100644--- a/packages/ltx-kernels/csrc/nvfp4/quantize.cu+++ b/packages/ltx-kernels/csrc/nvfp4/quantize.cu@@ -167,8 +167,13 @@ __global__ void quantize_kernel(const T *__restrict__ x, const float *__restrict// rows/cols for free (no torch::zeros needed).constexpr int kTileRows = 128;constexpr int kTileCols = 4; // scale columns == 64 elements-constexpr int kTileThreads = 256;-constexpr int kColsPerThread = 2;+// One scale column (16 elements) per thread, so a CTA covering one 128x4 tile has 512+// threads. Two columns per thread splits each thread's payload into two 8-byte stores+// that land in alternating halves of a 32-byte sector, so every store instruction writes+// partial sectors. Packed bytes are identical either way; GB200 CI goldens are the+// layout contract if they ever drift.+constexpr int kColsPerThread = 1;+constexpr int kTileThreads = kTileRows * kTileCols / kColsPerThread;template <typename T, bool kHiFirst>__global__ void quantize_tiled_kernel(const T *__restrict__ x, const float *__restrict__ per_tensor_scale,@@ -187,7 +192,7 @@ __global__ void quantize_tiled_kernel(const T *__restrict__ x, const float *__re// In-tile scale offsets for this thread's kColsPerThread adjacent columns.const int tile_off = (local_row & 31) * 16 + (local_row >> 5) * 4 + local_col;- uint8_t sf_bytes[kColsPerThread] = {0, 0};+ uint8_t sf_bytes[kColsPerThread] = {};if (row < rows) {#pragma unrollfor (int c = 0; c < kColsPerThread; ++c) {diff --git a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cuindex f2a4f98..c2c2bf9 100644--- a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu+++ b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu@@ -12,7 +12,8 @@ using bf16 = __nv_bfloat16;using fp8 = __nv_fp8_e4m3;__device__ __forceinline__ void _load_x(bf16* x, float x_vals[8], int h){bf16 x_tmp[8];- *reinterpret_cast<int4*>(x_tmp) = reinterpret_cast<int4*>(x + blockIdx.x * h)[threadIdx.x];+ const size_t row = static_cast<size_t>(blockIdx.x) * static_cast<size_t>(h);+ *reinterpret_cast<int4*>(x_tmp) = reinterpret_cast<int4*>(x + row)[threadIdx.x];#pragma unrollfor(int i = 0; i < 8; i++){x_vals[i] = float(x_tmp[i]);@@ -44,7 +45,7 @@ __device__ __forceinline__ void _load_freqs(template<typename out_t>__global__ void _rms_norm_split_rope_kernel(bf16* x, bf16* sin_freqs, bf16* cos_freqs, void* out, bf16* weights, int b, int s, int n, int h,long cos_sb, long cos_sn, long cos_ss, long sin_sb, long sin_sn, long sin_ss){- int token_idx = blockIdx.x;+ size_t token_idx = blockIdx.x;int tid = threadIdx.x;int lane_id = tid % 32;// freqs have shape [b, s, h/2]diff --git a/packages/ltx-kernels/pyproject.toml b/packages/ltx-kernels/pyproject.tomlindex 6d71784..01146bc 100644--- a/packages/ltx-kernels/pyproject.toml+++ b/packages/ltx-kernels/pyproject.toml@@ -8,7 +8,7 @@ build-backend = "setuptools.build_meta"[project]name = "ltx-kernels"-version = "1.2.0"+version = "1.3.0"dependencies = ["torch","nvidia-cutlass-dsl>=4.6.0.dev0,<5; sys_platform == 'linux'",diff --git a/packages/ltx-kernels/setup.py b/packages/ltx-kernels/setup.pyindex 63cd86d..8d548d9 100644--- a/packages/ltx-kernels/setup.py+++ b/packages/ltx-kernels/setup.py@@ -181,8 +181,14 @@ def _blockwise_gencode() -> tuple[list[str], bool]:# Arch codes the NVFP4 kernels support. The E2M1 pack/convert intrinsics and the cuBLASLt-# block-scaled FP4 kernels are Blackwell-only (sm_100a datacenter, sm_120a consumer).-_NVFP4_ARCHES = ["100a", "120a"]+# block-scaled FP4 kernels are Blackwell-only (sm_100a datacenter, sm_110a Jetson Thor,+# sm_120a consumer).+# All three are the arch-specific ("a") targets on purpose. cvt.rn.satfinite.e2m1x2.f32+# -- the hardware BF16/FP32 -> E2M1 pair conversion behind __nv_cvt_float2_to_fp4x2 -- is+# only emitted for those; on a plain family target (sm_110) the CUDA headers fall back to+# a software emulation and the quantize kernel balloons from 360 to 1312 SASS instructions,+# which drops it from memory-bound (~250 GB/s) to ALU-bound (~62 GB/s) on Thor.+_NVFP4_ARCHES = ["100a", "110a", "120a"]def _nvfp4_gencode() -> list[str]:@@ -196,6 +202,8 @@ def _nvfp4_gencode() -> list[str]:for tok in env:if tok.startswith("10.0"):sel.append("100a")+ elif tok.startswith("11.0"):+ sel.append("110a")elif tok.startswith("12.0"):sel.append("120a")return [a for a in dict.fromkeys(sel) if a in base]diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.pyindex 4612dba..365869c 100644--- a/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py@@ -8,7 +8,20 @@ from torch.library import triton_op, wrap_tritondef get_tma_aligned_size(n, element_size):num_elems_tma = 16 // element_size- return ((n + num_elems_tma - 1) // num_elems_tma) * num_elems_tma+ return ((n + num_elems_tma - 1) // num_elems_tma) * num_elems_tma++def empty_tma_aligned_scales(num_rows: int, num_blocks: int, device: torch.device) -> tuple[torch.Tensor, int]:+ """Allocate MN-major fp32 scales with TMA-padded row storage.+ TMA descriptors treat the padded M (16-byte aligned) as the tensor dimension, so+ the allocation must include those extra rows. ``empty_strided((num_rows, n),+ (1, aligned_m))`` only pads the stride and under-allocates when ``num_rows`` is+ not already aligned -- the GEMM then reads past the buffer.+ """+ tma_aligned_mn = get_tma_aligned_size(num_rows, 4)+ # (num_blocks, aligned_m).t()[:num_rows] keeps the full padded storage under a+ # (num_rows, num_blocks) view with stride (1, aligned_m).+ scales = torch.empty((num_blocks, tma_aligned_mn), dtype=torch.float, device=device).t()[:num_rows]+ return scales, tma_aligned_mn@jitdef _quantize(x, scale_max: tl.constexpr, NUM_BLOCKS: tl.constexpr, BLOCK_SIZE: tl.constexpr):@@ -68,7 +81,7 @@ def _block_quant_norm_kernel(TMA_ALIGNED_MN: tl.constexpr,SCALE_MAX: tl.constexpr,):- token_idx = tl.program_id(0)+ token_idx = tl.program_id(0).to(tl.int64)batch_id = token_idx // seqlenx_ptr = X + token_idx*H + tl.arange(0, H)@@ -104,7 +117,6 @@ def _block_quant_kernel(X,Out_scales,X_out,- seqlen: int,H: tl.constexpr,NUM_BLOCKS: tl.constexpr,BLOCK_SIZE: tl.constexpr,@@ -112,8 +124,8 @@ def _block_quant_kernel(USE_GELU: tl.constexpr,SCALE_MAX: tl.constexpr,):- batch_id, seq_id = tl.program_id(0), tl.program_id(1)- token_idx = batch_id*seqlen + seq_id+ # 1D grid over tokens: a (batch, seq) grid overflows CUDA gridDim.y at seq > 65535.+ token_idx = tl.program_id(0).to(tl.int64)x_ptr = X + token_idx*H + BLOCK_SIZE*tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]x = tl.load(x_ptr).to(tl.float32)if USE_GELU:@@ -132,15 +144,13 @@ def _quant_blockwise_tma_aligned_func(x: torch.Tensor, use_gelu: bool) -> Tuple[block_size = 128num_blocks = h // block_sizeout = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- tma_aligned_mn = get_tma_aligned_size(num_rows, 4)- scales = torch.empty_strided((num_rows, num_blocks), (1, tma_aligned_mn), dtype=torch.float, device=x.device)+ scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)scale_max: float = 448.0- wrap_triton(_block_quant_kernel)[(b, s)](+ wrap_triton(_block_quant_kernel)[(num_rows,)](x,scales,out,H=h,- seqlen=s,BLOCK_SIZE=128,NUM_BLOCKS=num_blocks,TMA_ALIGNED_MN=tma_aligned_mn,@@ -164,8 +174,7 @@ def run_quant_blockwise_norm_tma_aligned(x: torch.Tensor, w: Optional[torch.Tensblock_size = 128num_blocks = h // block_sizeout = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- tma_aligned_mn = get_tma_aligned_size(num_rows, 4)- scales = torch.empty_strided((num_rows, num_blocks), (1, tma_aligned_mn), dtype=torch.float, device=x.device)+ scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)norm_scale_batch_stride = norm_scale.stride(0)norm_shift_batch_stride = norm_shift.stride(0)@@ -209,7 +218,7 @@ def _quant_rms_sum_mult_kernel(QUANTIZE: tl.constexpr,SCALE_MAX: tl.constexpr,):- token_idx = tl.program_id(0)+ token_idx = tl.program_id(0).to(tl.int64)batch_id = token_idx // seqlenx_ptr = X + token_idx*H + tl.arange(0, H)@@ -250,8 +259,7 @@ def run_quant_blockwise_rms_fma(x: torch.Tensor, y: torch.Tensor, z: torch.Tensoblock_size = 128num_blocks = h // block_sizeout = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- tma_aligned_mn = get_tma_aligned_size(num_rows, 4)- scales = torch.empty_strided((num_rows, num_blocks), (1, tma_aligned_mn), dtype=torch.float, device=x.device)+ scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)z_batch_stride = z.stride(0)wrap_triton(_quant_rms_sum_mult_kernel)[(num_rows, 1, 1)](@@ -321,7 +329,7 @@ def _gated_attention_kernel(QUANTIZE: tl.constexpr,SCALE_MAX: tl.constexpr,):- token_idx = tl.program_id(0)+ token_idx = tl.program_id(0).to(tl.int64)# Load gate logits for all heads: shape [NUM_HEADS]gate_logits = tl.load(Gate_Logits + token_idx * NUM_HEADS + tl.arange(0, NUM_HEADS)).to(tl.float32)@@ -359,8 +367,7 @@ def run_gated_attention(x: torch.Tensor, gate_logits: torch.Tensor, quantize: boif quantize:out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- tma_aligned_mn = get_tma_aligned_size(num_rows, 4)- scales = torch.empty_strided((num_rows, num_blocks), (1, tma_aligned_mn), dtype=torch.float, device=x.device)+ scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)else:out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)tma_aligned_mn = 0@@ -395,7 +402,7 @@ def _blockwise_dequantize_kernel(NUM_BLOCKS: tl.constexpr,BLOCK_SIZE: tl.constexpr,):- token_idx = tl.program_id(0)+ token_idx = tl.program_id(0).to(tl.int64)# Load per-block scales [NUM_BLOCKS] respecting the actual tensor stridesscales = tl.load(diff --git a/packages/ltx-kernels/src/ltx_kernels/nvfp4/functional.py b/packages/ltx-kernels/src/ltx_kernels/nvfp4/functional.pyindex b27dbae..7b42ec6 100644--- a/packages/ltx-kernels/src/ltx_kernels/nvfp4/functional.py+++ b/packages/ltx-kernels/src/ltx_kernels/nvfp4/functional.py@@ -21,10 +21,12 @@ E2M1_MAX = 6.0GLOBAL_RANGE = E4M3_MAX * E2M1_MAX # 2688.0BLOCK_SIZE = 16-# Shared install hint used by extension/SM errors and by ``unavailable_reason``.+# Shared install hint used by extension/SM errors and by ``unavailable_reason``. The arch+# must match the target device -- 10.0 datacenter Blackwell, 11.0 Jetson Thor, 12.0 consumer+# Blackwell -- because each builds an arch-specific cubin that will not launch on the others.REBUILD_HINT = (- "TORCH_CUDA_ARCH_LIST='10.0' uv pip install -e packages/ltx-kernels --no-build-isolation "- "(or `uv sync --group kernels`)"+ "TORCH_CUDA_ARCH_LIST=<10.0|11.0|12.0> uv pip install -e packages/ltx-kernels "+ "--no-build-isolation (or `uv sync --group kernels`)")diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/__init__.py b/packages/ltx-kernels/src/ltx_kernels/vae/__init__.pyindex cffe8b3..6f78e98 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/__init__.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/__init__.py@@ -4,10 +4,10 @@ Two kernels sharing one attention half (``fna_attn_core.attention_tile``):``DiffusionNABlock`` in one launch, with no full-volume Q/K/V.- :func:`~ltx_kernels.vae.na_attn_dsl.run_na_attention` -- standalone 3D neighborhoodattention for the deterministic stages, a drop-in for ``natten.na3d``.-Both need datacenter Blackwell (sm_100 / sm_103): they are built on ``tcgen05`` UMMA-and Tensor Memory, which consumer Blackwell, Hopper and Ada do not have. Each launcher-enforces that itself; ``block_fna_available`` / ``na_attn_available`` let a caller ask-first and pick another path.+Both need datacenter Blackwell (sm_100 / sm_103) or Jetson Thor (sm_110): they+are built on ``tcgen05`` UMMA and Tensor Memory, which consumer Blackwell, Hopper+and Ada do not have. Each launcher enforces that itself; ``block_fna_available`` /+``na_attn_available`` let a caller ask first and pick another path."""from ltx_kernels.vae.block_fna_dsl import (diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/availability.py b/packages/ltx-kernels/src/ltx_kernels/vae/availability.pyindex 0fc7da8..4ebf404 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/availability.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/availability.py@@ -17,14 +17,15 @@ import torch# Consumer Blackwell (sm_120/sm_121, e.g. RTX 5090) has tcgen05 MMA but no TMEM, so a# tcgen05 test alone would pass there and then fail inside the JIT. Hopper and Ada have# neither: they are not a slower fallback, the instructions are not in the ISA.-_TCGEN05_CAPS = frozenset({(10, 0), (10, 1), (10, 3), (12, 0), (12, 1)})-_TMEM_CAPS = frozenset({(10, 0), (10, 1), (10, 3)})+# Jetson Thor (sm_110) has both tcgen05 MMA and TMEM, same as datacenter Blackwell.+_TCGEN05_CAPS = frozenset({(10, 0), (10, 1), (10, 3), (11, 0), (12, 0), (12, 1)})+_TMEM_CAPS = frozenset({(10, 0), (10, 1), (10, 3), (11, 0)})UNSUPPORTED_MESSAGE = ("the CuTe DSL VAE kernels need a GPU with both tcgen05 MMA and Tensor Memory "- "(sm_100/sm_101/sm_103, e.g. B200 or GB200) and nvidia-cutlass-dsl installed; "- "consumer Blackwell has tcgen05 but no TMEM, and these kernels hold all 512 "- "TMEM columns"+ "(sm_100/sm_101/sm_103, e.g. B200 or GB200, or sm_110 Jetson Thor) and "+ "nvidia-cutlass-dsl installed; consumer Blackwell has tcgen05 but no TMEM, "+ "and these kernels hold all 512 TMEM columns")diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py b/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.pyindex 5b52276..a6f3b24 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py@@ -18,9 +18,13 @@ Structure, in the order the kernel runs it:makes RMSNorm, RoPE, bias and the softmax register-local; splitting the *columns*keeps that while giving the CTA ``4 * NUM_WARPGROUPS`` warps to hide latency behind.* **A grid-shared K/V slab.** Panel tokens are shared by neighbouring query tiles, so- :func:`_fill_slab_kv_cache` projects a whole slab's halo box into a fixed K/V cache- once, a device-wide barrier follows, and :func:`_run_query_tile` gathers from it.+ :func:`_fill_slab_caches` projects a whole slab's halo box into a fixed K/V cache+ once, a device-wide barrier follows, and :func:`_run_tile` gathers from it.Per-query redundancy drops from ~27x (at an 11^3 window) to ~1.4x.+* **One body per stream pair.** The keyframe stream's rows go through the same fill and the+ same query tile as the video stream's, with :func:`ltx_kernels.vae.fna_smem.select_tensor`+ picking the buffer at runtime. Tracing either of them twice cost ~70 s of backend compile+ on a kernel whose plain build is already 25 s.* **The attention half is not here.** The window mask, the pipelined KV loop and thesoftmax are :func:`ltx_kernels.vae.fna_attn_core.attention_tile`, shared verbatimwith the standalone NA kernel.@@ -38,7 +42,7 @@ parts and why.import dataclassesimport functoolsimport os-from typing import Any+from typing import Any, NamedTupleimport cutlassimport cutlass.cute as cute@@ -54,6 +58,7 @@ from ltx_kernels.vae.fna_attn_core import (_dyn_act,_dyn_w,apply_rope,+ apply_rope_float_t,attention_tile,attn_epilogue,attn_zero_accumulators,@@ -82,6 +87,7 @@ from ltx_kernels.vae.fna_geometry import (query_row_indices,query_slot_in_tile,unflatten_3d,+ window_bounds_in_panel,window_origin_in_panel,)from ltx_kernels.vae.fna_smem import (@@ -92,6 +98,7 @@ from ltx_kernels.vae.fna_smem import (_scatter_a,_store_head_row,cooperative_copy_slot,+ select_tensor,)from ltx_kernels.vae.fna_types import (ACC,@@ -111,6 +118,12 @@ from ltx_kernels.vae.fna_types import (WARPGROUPS_PER_HEAD,M,)+from ltx_kernels.vae.keyframe_slots import (+ KEYFRAME_CONTEXT_SLOTS,+ nearest_keyframe_slots,+ nearest_video_frames,+ tile_plane_union,+)_COMPILED: "dict[tuple, Any]" = {}@@ -143,19 +156,22 @@ SLAB_BOX_MAX = (128, 128, 128)OUT_SLACK_ROWS = M-def _check_out(out: torch.Tensor, rows: int, channels: int, x_: torch.Tensor) -> torch.Tensor:- """Validate a caller-supplied output buffer for :func:`run_block_fna_dsl`."""+def _check_out(out: torch.Tensor, rows: int, channels: int, x_: torch.Tensor, name: str = "out") -> torch.Tensor:+ """Validate a caller-supplied output buffer for :func:`run_block_fna_dsl`.+ ``x_`` is the stream's own input rows -- the video volume for ``out``, the anchor+ planes for ``out_keyframes`` -- since that is what the buffer must not alias.+ """if tuple(out.shape) != (rows, channels):raise ValueError(- f"out must be {(rows, channels)} -- the volume plus {OUT_SLACK_ROWS} lane-slack "+ f"{name} must be {(rows, channels)} -- the volume plus {OUT_SLACK_ROWS} lane-slack "f"rows -- got {tuple(out.shape)}")if out.dtype != torch.bfloat16 or not out.is_contiguous():- raise ValueError(f"out must be contiguous bfloat16, got {out.dtype}, contiguous={out.is_contiguous()}")+ raise ValueError(f"{name} must be contiguous bfloat16, got {out.dtype}, contiguous={out.is_contiguous()}")if out.device != x_.device:- raise ValueError(f"out is on {out.device}, x on {x_.device}")+ raise ValueError(f"{name} is on {out.device}, its input on {x_.device}")if out.data_ptr() == x_.data_ptr():- raise ValueError("out must not alias x: the kernel reads neighborhoods of x while writing out")+ raise ValueError(f"{name} must not alias its input: the kernel reads neighborhoods while writing")return out@@ -270,6 +286,20 @@ class _Workspace:norm_cache: cute.Tensor # the slab's per-token RMSNorm factor for ``post``barrier: cute.Tensor+ # ---- the keyframe stream, mirroring the video tensors above ----+ x_kf: cute.Tensor+ stage4_kf: cute.Tensor+ y_kf: cute.Tensor+ kv_cache_kf: cute.Tensor+ norm_cache_kf: cute.Tensor+ kf_times: cute.Tensor+ kf_slots: cute.Tensor+ kf_planes: cute.Tensor+ kf_counts: cute.Tensor+ kf_video: cute.Tensor+ kf_video_counts: cute.Tensor+ kf_slab: cute.Tensor+# ---- SMEM operands, all aliased onto one pool; see the map in _fna_kernel ----s_a: cute.Tensor # the activation / A operands_b: cute.Tensor # the streamed weight tile / B operand@@ -335,6 +365,8 @@ class _Workspace:slab_tiles: tuple # query tiles per slab, per axismax_box: tuple # the largest halo box this call chosecache_row_stride: Any # rows between heads in kv_cache; one whole max box+ n_kf: Any+ kf_cache_row_stride: Any@propertydef n_volume_tokens(self):@@ -348,6 +380,7 @@ class _Slab:core_origin: tuple # first token of the core, per axiscore_end: tuple # one past its last, clamped into the volume+ t_index: Any # this slab's position along the temporal slab axisbox_origin: tuple # first token of the halo boxbox_shape: tuple # the box's extentsbox_hw: Any # box_shape[1] * box_shape[2], hoisted@@ -368,6 +401,19 @@ def _fna_kernel(kv_cache: cute.Tensor, # (2*NH*cache_row_stride, HD) bf16, K's heads then V'snorm_cache: cute.Tensor, # (cache_row_stride + M,) f32, post's RMSNorm factorbarrier: cute.Tensor, # (2,) int32 device-wide barrier: arrivals, then sense+ # ---- the keyframe stream; inert placeholders when KF is False ----+ x_kf: cute.Tensor, # (n_kf*H*W, C) bf16+ stage4_kf: cute.Tensor, # (n_kf*H_lo*W_lo, Ctx) bf16+ y_kf: cute.Tensor, # (n_kf*H*W + M, C) bf16+ kv_cache_kf: cute.Tensor, # (2*NH*kf_row_stride, HD) bf16+ norm_cache_kf: cute.Tensor, # (kf_row_stride + M,) f32+ kf_times: cute.Tensor, # (n_kf,) f32 stage-local chunk-center positions+ kf_slots: cute.Tensor, # (T*SLOTS,) i32+ kf_planes: cute.Tensor, # (n_t_tiles*P_MAX,) i32+ kf_counts: cute.Tensor, # (n_t_tiles,) i32+ kf_video: cute.Tensor, # (n_kf*SLOTS,) i32+ kf_video_counts: cute.Tensor, # (n_kf,) i32+ kf_slab: cute.Tensor, # (n_kf,) i32 -- which slab owns this plane's query tiles# ---- weights, each as its TMA atom and the tensor it reads ----a_ctx, # fused upsample x context projection, (P*C, Ctx)m_ctx,@@ -409,6 +455,8 @@ def _fna_kernel(max_box_h,max_box_w,cache_row_stride, # rows between heads in kv_cache == max_box_t*h*w+ n_kf, # keyframe planes carried alongside the video stream+ kf_cache_row_stride, # rows between heads in kv_cache_kf == n_kf*max_box_h*max_box_w# ---- compile-time block shape ----C: cutlass.Constexpr, # channelsCtx: cutlass.Constexpr, # stage-4 channels; a multiple of C@@ -434,6 +482,10 @@ def _fna_kernel(BT: cutlass.Constexpr, # SLAB_BOX_MAX; sizes the rope tables onlyBH: cutlass.Constexpr,BW: cutlass.Constexpr,+ KF: cutlass.Constexpr, # keyframe stream compiled in at all+ SLOTS: cutlass.Constexpr,+ P_MAX: cutlass.Constexpr, # cap on a query tile's keyframe-plane union+ NKV_KF: cutlass.Constexpr, # KV tiles over one keyframe panel, ceil(PH*PW / M)# ---- compile-time layouts ----mma128: cute.TiledMma,mma64: cute.TiledMma,@@ -546,6 +598,18 @@ def _fna_kernel(kv_cache=kv_cache,norm_cache=norm_cache,barrier=barrier,+ x_kf=x_kf,+ stage4_kf=stage4_kf,+ y_kf=y_kf,+ kv_cache_kf=kv_cache_kf,+ norm_cache_kf=norm_cache_kf,+ kf_times=kf_times,+ kf_slots=kf_slots,+ kf_planes=kf_planes,+ kf_counts=kf_counts,+ kf_video=kf_video,+ kf_video_counts=kf_video_counts,+ kf_slab=kf_slab,s_a=s_a,s_b=s_b,s_q=s_q,@@ -598,27 +662,45 @@ def _fna_kernel(slab_tiles=(slab_tiles_t, slab_tiles_h, slab_tiles_w),max_box=(max_box_t, max_box_h, max_box_w),cache_row_stride=cache_row_stride,+ n_kf=n_kf,+ kf_cache_row_stride=kf_cache_row_stride,)slab_index = 0while slab_index < slab_count:slab = _slab_geometry(ws, shape, slab_index)_build_rope_tables(ws, shape, slab)- _fill_slab_kv_cache(ws, shape, slab)+ _fill_slab_caches(ws, shape, slab, KF)# Every CTA must see the whole cache before any of them reads it.grid_barrier(barrier, tidx, n_ctas, 2 * slab_index)+ # One loop over both streams' tiles, video first. The keyframe stream's queries ride+ # this slab's barrier because both key sets they read -- their own plane, and the <=2+ # nearest video frames -- are single-plane panels in caches it has already filled.+ # A plane's tokens are split across slabs exactly like video tokens: the slab whose+ # *h/w core* holds the token, among those whose *temporal* core owns the plane. That+ # is what keeps every token written once and every read inside the box -- the h/w+ # panel is the core grown by the radius, and the plane's <=2 nearest video frames are+ # a step away from its own position, so the temporal box (radius >= 1) covers them.n_tiles, tile_plane, tile_row = _core_tile_grid(ws, shape, slab)tile_id = ids.cta- while tile_id < n_tiles:- local = unflatten_3d(tile_id, tile_plane, tile_row)- _run_query_tile(- ws,- shape,- slab,- tuple(slab.core_origin[i] + local[i] * shape.tile[i] for i in range(3)),- )- tile_id += n_ctas+ if cutlass.const_expr(KF):+ # The two call sites below are one binary each: ``KF`` is compile-time, so a+ # keyframe build traces only the guarded call and a plain build only the bare+ # one. Written as a single call under a runtime-or-constant guard instead, the+ # plain build would carry a branch it can never take.+ while tile_id < n_tiles + ws.n_kf * tile_plane:+ live = cutlass.Int32(1)+ if tile_id >= n_tiles:+ plane = unflatten_3d(tile_id - n_tiles, tile_plane, tile_row)[0]+ live = cutlass.Int32(1) if ws.kf_slab[plane] == slab.t_index else cutlass.Int32(0)+ if live != 0:+ _run_tile(ws, shape, slab, tile_id, n_tiles, tile_plane, tile_row, KF, SLOTS, P_MAX, NKV_KF)+ tile_id += n_ctas+ else:+ while tile_id < n_tiles:+ _run_tile(ws, shape, slab, tile_id, n_tiles, tile_plane, tile_row, KF, SLOTS, P_MAX, NKV_KF)+ tile_id += n_ctas# ... and no CTA may start the next slab's cache fill until they all have.grid_barrier(barrier, tidx, n_ctas, 2 * slab_index + 1)slab_index += 1@@ -656,6 +738,7 @@ def _slab_geometry(ws: _Workspace, shape: _BlockShape, slab_index) -> _Slab:return _Slab(core_origin=core_origin,core_end=core_end,+ t_index=slab_t,box_origin=box_origin,box_shape=box_shape,box_hw=box_hw,@@ -714,7 +797,7 @@ def _build_rope_tables(ws: _Workspace, shape: _BlockShape, slab: _Slab) -> None:@cute.jit-def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):+def _fill_slab_caches(ws, shape: cutlass.Constexpr, slab, KF: cutlass.Constexpr = False):"""Project the whole slab box into the K/V cache, ``M`` tokens per CTA per step.Every token of the box gets the block's front half run over it exactly once:``post = x + fused_ctx(stage4)``, its RMSNorm factor, AdaLN, then the K and V@@ -722,6 +805,11 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):and in ``norm_cache``, because every query tile in this slab's core needs the sametwo values and rebuilding them per tile would cost a context gather, the contextGEMM, an x gather and the residual add.+ With ``KF`` the keyframe planes' rows are walked by this same loop, after the video box's+ and appended to its step space: every weight, bias, norm and AdaLN constant is the video+ pass's -- which is exactly why the softmax bound stays a bound once these keys join a+ video query's row -- so a second copy of the body would only have cost compile time.+ :func:`_keyframe_fill_step` supplies the row indices and ``select_tensor`` the buffers.``fused_ctx`` is the stage-4 upsample composed with ``context_proj``: one Linear perpixel-shuffle subpixel, packed as ``P`` stacked N-tiles of one ``(C, Ctx)`` weight.So a token's context is the row of ``stage4`` at its parent cell projected by *its*@@ -744,9 +832,12 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):cells = tuple((slab.box_shape[i] + stride[i] - 1) // stride[i] for i in range(3))n_cells = cells[0] * cells[1] * cells[2]n_steps = shape.n_subpixels * ((n_cells + M - 1) // M)+ n_steps_kf = 0+ if cutlass.const_expr(KF):+ n_steps_kf = _keyframe_fill_steps(ws, shape, slab)step = ws.ids.cta- while step < n_steps:+ while step < n_steps + n_steps_kf:subpixel, box_offset, in_box = _subpixel_step(ws, shape, slab, step, cells, n_cells)pos = tuple(slab.box_origin[i] + box_offset[i] for i in range(3))row = flatten_3d(pos[0], pos[1], pos[2], vol_h, vol_w)@@ -757,8 +848,7 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):# clamped coordinates would otherwise target a real token, whose factor a# legitimate lane is already writing.norm_row = token if in_box else slab.n_box_tokens + lane- ws.rowix[lane] = row- ws.rowix_lo[lane] = flatten_3d(+ row_lo = flatten_3d((pos[0] + ws.drop_leading) // stride[0], pos[1] // stride[1], pos[2] // stride[2], lo_h, lo_w)# ``post`` is published only for the rows this slab owns. A halo row belongs to@@ -768,7 +858,40 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):owned = in_box and pos[0] >= slab.core_origin[0] and pos[0] < slab.core_end[0]owned = owned and pos[1] >= slab.core_origin[1] and pos[1] < slab.core_end[1]owned = owned and pos[2] >= slab.core_origin[2] and pos[2] < slab.core_end[2]- ws.rowix_w[lane] = row if owned else ws.n_volume_tokens + lane+ write_row = row if owned else ws.n_volume_tokens + lane+ src_x, src_ctx, out, norms = ws.x, ws.stage4, ws.y, ws.norm_cache+ cache, cache_stride, kf_time = ws.kv_cache, ws.cache_row_stride, None+ rope_offset = box_offset++ if cutlass.const_expr(KF):+ # The keyframe planes' rows, walked by the same loop. Every quantity above is+ # recomputed for a plane and then selected, which is a handful of instructions per+ # ``M``-token step; the body below -- three gathers, the context GEMM, the residual,+ # the AdaLN and ``n_heads`` K/V projections -- is traced once instead of twice.+ kf_row = step >= n_steps+ kf = _keyframe_fill_step(ws, shape, slab, step - n_steps)+ row = kf.row if kf_row else row+ token = kf.token if kf_row else token+ norm_row = kf.norm_row if kf_row else norm_row+ row_lo = kf.row_lo if kf_row else row_lo+ write_row = kf.write_row if kf_row else write_row+ subpixel = kf.subpixel if kf_row else subpixel+ rope_offset = (+ box_offset[0],+ kf.box_offset[1] if kf_row else box_offset[1],+ kf.box_offset[2] if kf_row else box_offset[2],+ )+ kf_time = kf.time+ src_x = select_tensor(kf_row, ws.x_kf, ws.x)+ src_ctx = select_tensor(kf_row, ws.stage4_kf, ws.stage4)+ out = select_tensor(kf_row, ws.y_kf, ws.y)+ norms = select_tensor(kf_row, ws.norm_cache_kf, ws.norm_cache)+ cache = select_tensor(kf_row, ws.kv_cache_kf, ws.kv_cache)+ cache_stride = ws.kf_cache_row_stride if kf_row else ws.cache_row_stride++ ws.rowix[lane] = row+ ws.rowix_lo[lane] = row_lo+ ws.rowix_w[lane] = write_rowcute.arch.sync_threads()# A ``Ctx``-wide stage-4 row does not fit one C-wide operand, so it lands in two:@@ -777,9 +900,9 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):# the barriers and the GEMM's own pipeline stand-up cost far more at these shapes# than the extra K-tiles do, so this is the whole difference between the deferred# context and a full-resolution one.- _fill_a_gather(ws.s_a, ws.stage4, ws.rowix_lo, ws.copy_slot, channels)+ _fill_a_gather(ws.s_a, src_ctx, ws.rowix_lo, ws.copy_slot, channels)if cutlass.const_expr(shape.ctx_groups > 1):- _fill_a_gather(ws.s_q, ws.stage4, ws.rowix_lo, ws.copy_slot, channels, channels)+ _fill_a_gather(ws.s_q, src_ctx, ws.rowix_lo, ws.copy_slot, channels, channels)cute.arch.sync_threads()for n in cutlass.range_constexpr(shape.n_chunks):_project(@@ -793,7 +916,7 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):a_split=shape.n_k_tiles if shape.ctx_groups > 1 else 0,)cute.arch.sync_threads()- _fill_a_gather(ws.s_a, ws.x, ws.rowix, ws.copy_slot, channels)+ _fill_a_gather(ws.s_a, src_x, ws.rowix, ws.copy_slot, channels)cute.arch.sync_threads()post_sq = _add_residual(ws, shape, ws.acc_main, param["ctx_bias"], subpixel * channels)@@ -801,8 +924,8 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):# Publish the factor with ``post``; both warpgroups hold the reduced value, so# one writes it. One f32 a token, a 256th of what caching the normed row costs.if wg == 0:- ws.norm_cache[norm_row] = rms_inv- _scatter_a(ws.s_a, ws.y, ws.rowix_w, ws.copy_slot, channels)+ norms[norm_row] = rms_inv+ _scatter_a(ws.s_a, out, ws.rowix_w, ws.copy_slot, channels)# A cooperative copy spans the whole operand -- every thread touches rows and# channels outside its own warpgroup's slice -- so it has to finish before the# per-warpgroup norm below rewrites s_a. Without this the two overlap whenever@@ -813,10 +936,107 @@ def _fill_slab_kv_cache(ws, shape: cutlass.Constexpr, slab):cute.arch.sync_threads()for head in cutlass.range_constexpr(shape.n_heads):- _project_head_kv(ws, shape, head, token, box_offset)+ if cutlass.const_expr(KF):+ _project_head_kv(ws, shape, head, token, rope_offset, cache, cache_stride, kf_time, kf_row)+ else:+ _project_head_kv(ws, shape, head, token, rope_offset)step += ws.n_ctas+class _KeyframeFillStep(NamedTuple):+ """Where one keyframe fill step reads and writes, mirroring the video walk's quantities."""++ row: Any # into ``x_kf`` / the output: (plane, h, w) over the whole volume grid+ row_lo: Any # into ``stage4_kf``: its parent stage-4 cell+ token: Any # into the keyframe K/V cache, and the norm cache+ norm_row: Any # ``token``, or a scratch entry for a lane past the end of the box+ write_row: Any # ``row`` if this slab owns it, else a scratch row past the output+ subpixel: Any # which fused-context N-tile this row's parent projects through+ box_offset: Any # (0, h, w) inside the slab box -- the spatial rope index+ time: Any # the plane's float chunk-center position, for the temporal rope+++def _keyframe_fill_steps(ws, shape: cutlass.Constexpr, slab):+ """How many fill steps the keyframe planes need in this slab.+ Only the slab box's ``h/w`` rectangle is filled: a query in the core reads a keyframe+ window around its own ``(h, w)``, and the box is the core grown by the NA radius, so that+ rectangle is already the whole reachable set. The temporal axis is the plane index, not a+ box offset -- a keyframe plane is one slice however wide the box is in ``t``, so the walk+ covers the spatial subpixels only.+ """+ stride = shape.stride+ cells_h = (slab.box_shape[1] + stride[1] - 1) // stride[1]+ cells_w = (slab.box_shape[2] + stride[2] - 1) // stride[2]+ n_cells = ws.n_kf * cells_h * cells_w+ return stride[1] * stride[2] * ((n_cells + M - 1) // M)+++def _keyframe_fill_step(ws, shape: cutlass.Constexpr, slab, step):+ """Locate keyframe fill step ``step``: the video walk's geometry, one plane deep.+ Two things differ from the video pass and both are forced by the plane being a single+ temporal slice. Its stage-4 parent is looked up without a temporal divide, and under a+ joint ``(2,2,2)`` upsample it takes the temporal subpixel a one-frame input would shuffle+ out to -- ``drop_leading % SP_T``, which is subpixel 1 for the shipped stride and 0 when+ the hop is spatial-only. Never both: a keyframe stays ``n_kf`` planes across every stage.+ Called for video steps too, whose results are then selected away, so ``step`` may be+ negative and ``plane`` out of range: both are clamped, and every table read below lands+ on a real entry (row 0 at worst) rather than off the end.+ """+ lane = ws.ids.lane+ _, vol_h, vol_w = ws.volume+ _, lo_h, lo_w = ws.ctx_volume+ stride = shape.stride+ zero = cutlass.Int32(0)+ cells_h = (slab.box_shape[1] + stride[1] - 1) // stride[1]+ cells_w = (slab.box_shape[2] + stride[2] - 1) // stride[2]+ n_cells = ws.n_kf * cells_h * cells_w+ sub_t = ws.drop_leading % stride[0]+ kf_hw = slab.box_shape[1] * slab.box_shape[2]++ step = at_least(step, zero)+ sub_hw = step % (stride[1] * stride[2])+ cell = (step // (stride[1] * stride[2])) * M + lane+ in_box = cell < n_cells+ plane, cell_h, cell_w = unflatten_3d(at_most(cell, at_least(n_cells - 1, zero)), cells_h * cells_w, cells_w)+ plane = at_most(plane, at_least(ws.n_kf - 1, zero))+ sub_h = sub_hw // stride[2]+ sub_w = sub_hw - sub_h * stride[2]+ # Smallest box offset whose absolute position carries this subpixel, then step by+ # the stride -- the video pass's rule with the temporal axis removed.+ first_h = (sub_h + stride[1] - slab.box_origin[1] % stride[1]) % stride[1]+ first_w = (sub_w + stride[2] - slab.box_origin[2] % stride[2]) % stride[2]+ off_h = first_h + stride[1] * at_most(cell_h, (slab.box_shape[1] - 1 - first_h) // stride[1])+ off_w = first_w + stride[2] * at_most(cell_w, (slab.box_shape[2] - 1 - first_w) // stride[2])+ in_box = in_box and first_h + stride[1] * cell_h < slab.box_shape[1]+ in_box = in_box and first_w + stride[2] * cell_w < slab.box_shape[2]+ pos_h = slab.box_origin[1] + off_h+ pos_w = slab.box_origin[2] + off_w++ row = flatten_3d(plane, pos_h, pos_w, vol_h, vol_w)+ token = flatten_3d(plane, off_h, off_w, slab.box_shape[1], slab.box_shape[2])+ # ``post`` is published only for the rows this slab owns -- same rule as the video+ # pass, and load-bearing for the same reason. Every slab projects every plane over+ # its own halo rectangle (that is what makes the keyframe keys available to its video+ # queries), so without the gate a later slab would overwrite the *finished* block+ # output an earlier slab left in ``y_kf`` with ``post`` again. A plane's rows belong+ # to the slab whose temporal core owns the plane and whose h/w core holds the token.+ owned = in_box and ws.kf_slab[plane] == slab.t_index+ owned = owned and pos_h >= slab.core_origin[1] and pos_h < slab.core_end[1]+ owned = owned and pos_w >= slab.core_origin[2] and pos_w < slab.core_end[2]+ return _KeyframeFillStep(+ row=row,+ row_lo=flatten_3d(plane, pos_h // stride[1], pos_w // stride[2], lo_h, lo_w),+ token=token,+ norm_row=token if in_box else ws.n_kf * kf_hw + lane,+ write_row=row if owned else ws.n_kf * vol_h * vol_w + lane,+ subpixel=sub_t * stride[1] * stride[2] + sub_hw,+ box_offset=(zero, off_h, off_w),+ time=ws.kf_times[plane],+ )++def _subpixel_step(ws, shape: cutlass.Constexpr, slab, step, cells, n_cells):"""Where fill step ``step`` sits: its subpixel, this lane's box offset, and validity.The box is walked as ``P`` passes over the stage-4 cells it spans, subpixel-minor so@@ -858,16 +1078,35 @@ def _subpixel_step(ws, shape: cutlass.Constexpr, slab, step, cells, n_cells):@cute.jit-def _project_head_kv(ws, shape: cutlass.Constexpr, head: cutlass.Constexpr, cache_row, box_offset):+def _project_head_kv(+ ws,+ shape: cutlass.Constexpr,+ head: cutlass.Constexpr,+ cache_row,+ box_offset,+ dst=None,+ row_stride=None,+ kf_time=None,+ kf_row=None,+):"""Project one head's K and V out of the normed row and store both to the cache.The packed K|V weight puts K in the accumulator's first ``HD`` columns and V inthe second, which lines the warpgroup split up with the two paths: the first``WARPGROUPS_PER_HEAD`` warpgroups take K (bias, RMSNorm, RoPE), the rest take V (bias only).+ ``dst`` / ``row_stride`` retarget the store, and ``kf_time`` swaps the temporal RoPE for a+ float chunk-center position: that is the whole difference between filling the video cache+ and filling the keyframe one. The projection, both biases, ``k_norm`` and the spatial RoPE+ are identical -- which is also what keeps the softmax bound a bound for keyframe keys.+ ``kf_row`` decides that swap at *runtime*, for the merged fill that walks both streams'+ rows in one loop. Given, both temporal ropes are traced and one is selected; left ``None``+ only the lattice one is, which is what a plain build gets."""lane, wg = ws.ids.lane, ws.ids.wgareg, params, param = ws.areg, ws.params, shape.paramn_heads, rope_dims = shape.n_heads, shape.rope_dimsacc = ws.acc_scratch+ dst = ws.kv_cache if dst is None else dst+ row_stride = ws.cache_row_stride if row_stride is None else row_stride_project(ws, shape, ws.w_kv, acc, head)k_sq = ACC(0.0)@@ -893,11 +1132,17 @@ def _project_head_kv(ws, shape: cutlass.Constexpr, head: cutlass.Constexpr, cachif cutlass.const_expr(g < WARPGROUPS_PER_HEAD):for d in cutlass.range(ACC_COLS, unroll_full=True):areg[d] = areg[d] * k_rms * params[param["k_norm"] + c0 + d]- apply_rope(areg, *rope_dims, ws.rope, *box_offset, c0, ACC_COLS)- _store_head_row(ws.kv_cache, head * ws.cache_row_stride + cache_row, areg, ACC_COLS, c0)+ if cutlass.const_expr(kf_time is None):+ apply_rope(areg, *rope_dims, ws.rope, *box_offset, c0, ACC_COLS)+ elif kf_row:+ apply_rope_float_t(+ areg, *rope_dims, ws.rope, kf_time, box_offset[1], box_offset[2], ws.rope_inv[0], c0, ACC_COLS+ )+ else:+ apply_rope(areg, *rope_dims, ws.rope, *box_offset, c0, ACC_COLS)+ _store_head_row(dst, head * row_stride + cache_row, areg, ACC_COLS, c0)else:- row = (n_heads + head) * ws.cache_row_stride + cache_row- _store_head_row(ws.kv_cache, row, areg, ACC_COLS, c0)+ _store_head_row(dst, (n_heads + head) * row_stride + cache_row, areg, ACC_COLS, c0)# --------------------------------------------------------------------------@@ -905,21 +1150,65 @@ def _project_head_kv(ws, shape: cutlass.Constexpr, head: cutlass.Constexpr, cach# --------------------------------------------------------------------------+class _TileGeometry(NamedTuple):+ """Where one query tile reads and writes, for either stream.+ Everything :func:`_run_tile` needs to locate itself, which is also the only part of it+ that differs between the two streams. Under ``KF`` the keyframe quantities are computed+ unconditionally -- pure arithmetic plus small table lookups, cheaper than branching+ around them -- so a video tile evaluates them too and selects the results away. That is+ why these are runtime selections rather than one branch's two exits.+ """++ kf_tile: Any # this tile is a keyframe plane's; None in a binary without that stream+ video_tile: Any # its complement, which the deep temporal panel keys off+ plane: Any # the anchor plane a keyframe tile carries, clamped into range+ query_pos: tuple # this lane's (t, h, w) in the volume+ read_row: Any # the row ``post`` is gathered from+ write_row: Any # where the result lands; a scratch row for an out-of-range lane+ norm_row: Any # into the stream's norm cache, indexed over the slab box+ panel_origin: tuple # the video halo panel's (t, h, w)+ panel_h0: Any # the panel's spatial origin for *this* stream+ panel_w0: Any+ window: tuple # the NA window's low bounds, panel-relative+ window_hi: Any # its high bounds under clamp-and-mask; None under the inward shift+ rope_pos: tuple # the box offset the rope tables are indexed by+ kf_time: Any # a plane's float chunk-center time; None for a video tile+ t_idx: Any # this tile's video temporal index, which the plane union is keyed by++@cute.jit-def _run_query_tile(ws, shape: cutlass.Constexpr, slab, tile_origin):- """The whole back half of the block for one ``M``-query tile.- Reads ``post`` and its RMSNorm factor back out of the slab's caches, projects Q,- runs windowed NA against the slab's K/V cache, then the out-projection, its- residual and AdaLN, the SwiGLU MLP and the closing residual. Every intermediate- lives in ``s_a`` or in TMEM; the only global traffic is the output row, read and- rewritten as each residual needs it.+def _tile_geometry(+ ws,+ shape: cutlass.Constexpr,+ slab,+ tile_id,+ n_core_tiles,+ tile_plane,+ tile_row,+ KF: cutlass.Constexpr = False,+):+ """Locate query tile ``tile_id``: which stream owns it, and every index it reads with.+ ``tile_id`` indexes the two grids end to end: ``[0, n_core_tiles)`` are this slab's+ video tiles and the rest are ``(plane, h, w)`` keyframe tiles. Both unflatten with the+ same divisors -- a keyframe grid is ``(n_kf, tiles_h, tiles_w)`` against the video's+ ``(tiles_t, tiles_h, tiles_w)`` -- so only the temporal component's *meaning* differs:+ a tile origin for video, a plane index for keyframes."""- ids, param = ws.ids, shape.param- lane, channels = ids.lane, shape.channels+ lane = ws.ids.lane+ zero = cutlass.Int32(0)+ _, vol_h, vol_w = ws.volume+ index = tile_id+ kf_tile, video_tile, plane = None, None, None+ if cutlass.const_expr(KF):+ kf_tile = tile_id >= n_core_tiles+ video_tile = tile_id < n_core_tiles+ index = tile_id - n_core_tiles if kf_tile else tile_id+ local = unflatten_3d(index, tile_plane, tile_row)# Tiles partition the volume: edge tiles are partial and their out-of-range lanes# write to scratch, so no output row is touched by two CTAs. (The MMA still runs at# full M; the extra rows are garbage.)+ tile_origin = tuple(slab.core_origin[i] + local[i] * shape.tile[i] for i in range(3))panel_origin = halo_panel_origin(tile_origin, shape.radius, shape.panel, ws.volume)cute.arch.sync_threads()query_pos, read_row, write_row = query_row_indices(@@ -928,54 +1217,269 @@ def _run_query_tile(ws, shape: cutlass.Constexpr, slab, tile_origin):lane,ws.n_volume_tokens,)- window = window_origin_in_panel(query_pos, panel_origin, shape.radius, shape.kernel, ws.volume)+ # Two window rules. The joint keyframe operator is defined on clamp-and-mask, every+ # other caller on NATTEN's inward shift, and ``KF`` is exactly that distinction -- keyed+ # off the compile flag so the no-keyframe binary keeps a byte-identical trace.+ if cutlass.const_expr(KF):+ bounds = window_bounds_in_panel(query_pos, panel_origin, shape.radius, shape.kernel, ws.volume)+ window = tuple(lo for lo, _ in bounds)+ window_hi = tuple(hi for _, hi in bounds)+ else:+ window = window_origin_in_panel(query_pos, panel_origin, shape.radius, shape.kernel, ws.volume)+ window_hi = None# Where this query sits inside the slab box: the index for both the rope tables,# which were built over the box, and the cached RMSNorm factor.box_pos = tuple(query_pos[i] - slab.box_origin[i] for i in range(3))+ norm_row = flatten_3d(box_pos[0], box_pos[1], box_pos[2], slab.box_shape[1], slab.box_shape[2])+ panel_h0, panel_w0 = panel_origin[1], panel_origin[2]+ rope_pos, kf_time = box_pos, None+ t_idx = tile_origin[0] // shape.tile[0]++ if cutlass.const_expr(KF):+ # The keyframe tile's geometry: the video tile's with the temporal axis replaced by+ # the plane. Its ``h/w`` origin is already ``tile_origin[1:]``, so only the temporal+ # half, the row indices and the buffers are recomputed. Every read below is index-+ # clamped because a video tile evaluates this arithmetic too -- it is pure arithmetic+ # plus small table lookups, and selecting the results is cheaper than branching+ # around them.+ plane = at_most(at_least(local[0], zero), at_least(ws.n_kf - 1, zero))+ slot_t, slot_h, slot_w = ws.query_slot+ q_h = tile_origin[1] + slot_h+ q_w = tile_origin[2] + slot_w+ r_h = q_h if q_h < vol_h else vol_h - 1+ r_w = q_w if q_w < vol_w else vol_w - 1+ kf_read = flatten_3d(plane, r_h, r_w, vol_h, vol_w)+ kf_write = kf_read+ # One plane per tile, so the borrowed tile's other temporal slots hold duplicates+ # of ``slot_t == 0``; they compute and park on a scratch row.+ if slot_t != 0 or q_h >= vol_h or q_w >= vol_w:+ kf_write = ws.n_kf * vol_h * vol_w + lane+ # The *panel* still shifts inward -- it only has to contain every key the tile can+ # reach, and the inward-shifted box is the larger of the two -- but the per-query+ # window is clamp-and-mask, like every window on the joint path.+ kf_panel_h0 = clamp_window_start(tile_origin[1] - shape.radius[1], shape.panel[1], vol_h)+ kf_panel_w0 = clamp_window_start(tile_origin[2] - shape.radius[2], shape.panel[2], vol_w)+ kf_bounds = window_bounds_in_panel(+ (zero, r_h, r_w),+ (zero, kf_panel_h0, kf_panel_w0),+ (0, shape.radius[1], shape.radius[2]),+ (1, shape.kernel[1], shape.kernel[2]),+ (cutlass.Int32(1), vol_h, vol_w),+ )+ kf_box_h = r_h - slab.box_origin[1]+ kf_box_w = r_w - slab.box_origin[2]++ read_row = kf_read if kf_tile else read_row+ write_row = kf_write if kf_tile else write_row+ norm_row = flatten_3d(plane, kf_box_h, kf_box_w, slab.box_shape[1], slab.box_shape[2]) if kf_tile else norm_row+ panel_h0 = kf_panel_h0 if kf_tile else panel_h0+ panel_w0 = kf_panel_w0 if kf_tile else panel_w0+ window = (window[0], kf_bounds[1][0] if kf_tile else window[1], kf_bounds[2][0] if kf_tile else window[2])+ window_hi = (+ window_hi[0],+ kf_bounds[1][1] if kf_tile else window_hi[1],+ kf_bounds[2][1] if kf_tile else window_hi[2],+ )+ rope_pos = (+ box_pos[0],+ kf_box_h if kf_tile else box_pos[1],+ kf_box_w if kf_tile else box_pos[2],+ )+ # A keyframe query sits at a float chunk-center time, off the lattice the slab's+ # temporal rope table was built over.+ kf_time = ws.kf_times[plane]+ # The tail's plane union is indexed by video temporal tile; a keyframe tile has no+ # such index, and reads row 0 whose value it then selects away.+ t_idx = zero if kf_tile else t_idx++ return _TileGeometry(+ kf_tile=kf_tile,+ video_tile=video_tile,+ plane=plane,+ query_pos=query_pos,+ read_row=read_row,+ write_row=write_row,+ norm_row=norm_row,+ panel_origin=panel_origin,+ panel_h0=panel_h0,+ panel_w0=panel_w0,+ window=window,+ window_hi=window_hi,+ rope_pos=rope_pos,+ kf_time=kf_time,+ t_idx=t_idx,+ )+++def _run_tile(+ ws,+ shape: cutlass.Constexpr,+ slab,+ tile_id,+ n_core_tiles,+ tile_plane,+ tile_row,+ KF: cutlass.Constexpr = False,+ SLOTS: cutlass.Constexpr = 2,+ P_MAX: cutlass.Constexpr = 1,+ NKV_KF: cutlass.Constexpr = 1,+):+ """The whole back half of the block for one ``M``-query tile, of either stream.+ Reads ``post`` and its RMSNorm factor back out of the slab's caches, projects Q,+ runs windowed NA against the slab's K/V cache, then the out-projection, its+ residual and AdaLN, the SwiGLU MLP and the closing residual. Every intermediate+ lives in ``s_a`` or in TMEM; the only global traffic is the output row, read and+ rewritten as each residual needs it.+ One body serves video and keyframe tiles, and that is a compile-time decision, not a+ tidiness one. Everything after the geometry is identical between the two streams --+ same weights, same AdaLN constants, same MLP -- so a second copy of it bought nothing+ and cost 60 s of ptxas and MLIR on a kernel that is already the compile-time floor.+ What differs is which buffers the rows live in, and :func:`select_tensor` makes that a+ runtime address rather than a second instantiation.+ :func:`_tile_geometry` carries the whole of that difference except the buffers, which+ stay here because there is nothing to compute about them: given its ``kf_tile``, each+ pair is one ``select_tensor``.+ """+ ids, param = ws.ids, shape.param+ lane, channels = ids.lane, shape.channels+ zero = cutlass.Int32(0)++ # ---------------- which tile, and where it reads ----------------------+ geom = _tile_geometry(ws, shape, slab, tile_id, n_core_tiles, tile_plane, tile_row, KF)+ out, norms = ws.y, ws.norm_cache+ if cutlass.const_expr(KF):+ out = select_tensor(geom.kf_tile, ws.y_kf, ws.y)+ norms = select_tensor(geom.kf_tile, ws.norm_cache_kf, ws.norm_cache)# ---------------- residual, AdaLN, Q ---------------------------------- ws.rowix[lane] = read_row- ws.rowix_w[lane] = write_row+ ws.rowix[lane] = geom.read_row+ ws.rowix_w[lane] = geom.write_row# The cache fill already built ``post = x + ctx_proj(context)`` for every row this# slab owns and left it in the output, so read it back instead of rebuilding it per# tile -- and its RMSNorm factor with it, sparing this tile a pass over the whole# row and the CTA-wide reduction that pass feeds.cute.arch.sync_threads()- _fill_a_gather(ws.s_a, ws.y, ws.rowix, ws.copy_slot, channels)+ _fill_a_gather(ws.s_a, out, ws.rowix, ws.copy_slot, channels)cute.arch.sync_threads()- rms_inv = ws.norm_cache[flatten_3d(box_pos[0], box_pos[1], box_pos[2], slab.box_shape[1], slab.box_shape[2])]+ rms_inv = norms[geom.norm_row]_apply_adaln(ws, shape, rms_inv, param["msa_weight"], param["msa_shift"])cute.arch.sync_threads()- _project_queries(ws, shape, box_pos)+ _project_queries(ws, shape, geom.rope_pos, geom.kf_time, geom.kf_tile)attn_zero_accumulators(ws.acc_o, ws.l_sm, ws.oreg, lane, ids.wg, shape.n_heads)# ---------------- windowed neighborhood attention --------------------# The K/V source is this slab's fused cache, so both halves are ``kv_cache`` --# K's heads first, then V's -- the head stride is the halo box this call chose, and# one panel row is one cache row.- attention_tile(- (ws.fr_q, ws.fr_k, ws.fr_p, ws.fr_v),- (ws.s_k, ws.s_v, ws.s_p),- ws.acc_qk,- ws.acc_o,- (ws.qkbar, ws.pvbar),- ws.m_sm,- ws.l_sm,- ws.areg,- ws.kvfrag,- (ws.kv_cache, ws.kv_cache),- (cutlass.Int32(0), shape.n_heads * ws.cache_row_stride),- ws.cache_row_stride,- (*panel_origin, *slab.box_origin, slab.box_shape[1], slab.box_shape[2]),- window,- (ids.tidx, lane, ids.wg, ids.warp),- shape.n_heads,- 1,- *shape.panel,- *shape.kernel,- shape.n_kv_tiles,- )+ # A video query runs this deep ``PT``-tall panel; a keyframe query has no local+ # temporal neighborhood at all, so it skips it and takes only the single-plane passes+ # below. That asymmetry is the reason the deep panel stays its own instantiation.+ deep = True+ if cutlass.const_expr(KF):+ deep = geom.video_tile+ if deep:+ attention_tile(+ (ws.fr_q, ws.fr_k, ws.fr_p, ws.fr_v),+ (ws.s_k, ws.s_v, ws.s_p),+ ws.acc_qk,+ ws.acc_o,+ (ws.qkbar, ws.pvbar),+ ws.m_sm,+ ws.l_sm,+ ws.areg,+ ws.kvfrag,+ (ws.kv_cache, ws.kv_cache),+ (cutlass.Int32(0), shape.n_heads * ws.cache_row_stride),+ ws.cache_row_stride,+ (*geom.panel_origin, *slab.box_origin, slab.box_shape[1], slab.box_shape[2]),+ geom.window,+ (ids.tidx, lane, ids.wg, ids.warp),+ shape.n_heads,+ 1,+ *shape.panel,+ *shape.kernel,+ shape.n_kv_tiles,+ None,+ geom.window_hi,+ )++ # Single-plane passes, into the same (m_sm, l_sm, acc_o). The fixed softmax offset means+ # continuing the accumulation *is* a joint softmax -- no rescale, no state merge -- and+ # the keyframe keys were normed by the same ``k_norm``, so the offset still bounds them.+ # Both streams' extra key sets are single planes on the query's own spatial window, so+ # one instantiation covers all three uses: a video query's selected keyframe planes, a+ # keyframe query's own plane, and its <=2 nearest video frames. Which cache a pass reads+ # is an address, and the pass count is runtime.+ if cutlass.const_expr(KF):+ pass_i = zero+ n_passes = ws.kf_counts[geom.t_idx]+ if geom.kf_tile:+ n_passes = 1 + ws.kf_video_counts[geom.plane]+ while pass_i < n_passes:+ # Video tail: this tile's plane union, with each lane gated out of the planes its+ # own ``t`` did not pick -- the plane is a per-tile gather but the nearest-S set+ # is per ``t``, and a tile spans ``TT`` of them.+ source = ws.kf_planes[geom.t_idx * P_MAX + at_most(pass_i, P_MAX - 1)]+ sel = zero+ for s in cutlass.range_constexpr(SLOTS):+ if ws.kf_slots[geom.query_pos[0] * SLOTS + s] == source:+ sel = cutlass.Int32(1)+ video_kv = zero+ if geom.kf_tile:+ # A keyframe query's passes are tile-uniform -- one plane per tile, and its+ # video frames are a property of the plane -- so no lane gating.+ sel = cutlass.Int32(1)+ if pass_i == 0:+ source = geom.plane+ else:+ source = ws.kf_video[geom.plane * SLOTS + at_most(pass_i - 1, SLOTS - 1)]+ video_kv = cutlass.Int32(1)+ cache = select_tensor(video_kv != 0, ws.kv_cache, ws.kv_cache_kf)+ row_stride = ws.cache_row_stride if video_kv != 0 else ws.kf_cache_row_stride+ # The keyframe cache is (n_kf, box_h, box_w): a plane index is absolute, so its+ # box origin is 0, while a video frame index is relative to the box.+ attention_tile(+ (ws.fr_q, ws.fr_k, ws.fr_p, ws.fr_v),+ (ws.s_k, ws.s_v, ws.s_p),+ ws.acc_qk,+ ws.acc_o,+ (ws.qkbar, ws.pvbar),+ ws.m_sm,+ ws.l_sm,+ ws.areg,+ ws.kvfrag,+ (cache, cache),+ (zero, shape.n_heads * row_stride),+ row_stride,+ (+ source,+ geom.panel_h0,+ geom.panel_w0,+ slab.box_origin[0] if video_kv != 0 else zero,+ slab.box_origin[1],+ slab.box_origin[2],+ slab.box_shape[1],+ slab.box_shape[2],+ ),+ (zero, geom.window[1], geom.window[2]),+ (ids.tidx, lane, ids.wg, ids.warp),+ shape.n_heads,+ 1,+ 1,+ shape.panel[1],+ shape.panel[2],+ 1,+ shape.kernel[1],+ shape.kernel[2],+ NKV_KF,+ sel,+ # One plane deep; the spatial pair is the query's own window, keeping both+ # key sets aligned for the query sharing a softmax over them.+ (cutlass.Int32(1), geom.window_hi[1], geom.window_hi[2]),+ )+ pass_i += 1# ---------------- out projection, residual, AdaLN --------------------cute.arch.sync_threads()@@ -986,12 +1490,12 @@ def _run_query_tile(ws, shape: cutlass.Constexpr, slab, tile_origin):# s_a is free once the out-projection has consumed it, so ``post`` comes back# through it coalesced rather than one cache line per lane.cute.arch.sync_threads()- _fill_a_gather(ws.s_a, ws.y, ws.rowix, ws.copy_slot, channels)+ _fill_a_gather(ws.s_a, out, ws.rowix, ws.copy_slot, channels)cute.arch.sync_threads()resid_sq = _add_residual(ws, shape, ws.acc_main, param["out_bias"])rms_inv = cute.rsqrt(row_sum(ws.red_c, lane, ids.wg, resid_sq) / ACC(channels) + ACC(EPS))cute.arch.sync_threads()- _scatter_a(ws.s_a, ws.y, ws.rowix_w, ws.copy_slot, channels)+ _scatter_a(ws.s_a, out, ws.rowix_w, ws.copy_slot, channels)# A cooperative copy spans the whole operand -- every thread touches rows and# channels outside its own warpgroup's slice -- so it has to finish before the# per-warpgroup norm below rewrites s_a. Without this the two overlap whenever the@@ -1006,16 +1510,21 @@ def _run_query_tile(ws, shape: cutlass.Constexpr, slab, tile_origin):# s_a is free again after the last gate/up, so the final residual add reloads and# stores through it, coalesced.cute.arch.sync_threads()- _fill_a_gather(ws.s_a, ws.y, ws.rowix, ws.copy_slot, channels)+ _fill_a_gather(ws.s_a, out, ws.rowix, ws.copy_slot, channels)cute.arch.sync_threads()_add_accumulator(ws, shape, ws.acc_down)cute.arch.sync_threads()- _scatter_a(ws.s_a, ws.y, ws.rowix_w, ws.copy_slot, channels)+ _scatter_a(ws.s_a, out, ws.rowix_w, ws.copy_slot, channels)@cute.jit-def _project_queries(ws, shape: cutlass.Constexpr, rope_pos):+def _project_queries(ws, shape: cutlass.Constexpr, rope_pos, kf_time=None, kf_tile=None):"""Project, normalise and rotate this tile's queries into ``s_q``.+ ``kf_time`` given, this tile may be a keyframe tile, and ``kf_tile`` says at runtime+ whether it is: a keyframe query sits at a float chunk-center time, off the lattice the+ slab's temporal rope table was built over, while h and w are still on it. Both temporal+ ropes are then traced, which is a few hundred instructions -- the alternative was tracing+ the whole projection twice.``HEADS_PER_TILE`` heads at a time: an N=128 tile of ``w_q`` is already``[head 2n | head 2n+1]``, so with one warpgroup per head the RMSNorm and RoPE stayinside a warpgroup -- no reduction, and half the GEMM calls of the per-head N=64@@ -1067,7 +1576,22 @@ def _project_queries(ws, shape: cutlass.Constexpr, rope_pos):ws.m_sm[lane, head] = cute.sqrt(q_norm_sq) * q_rms * params[param["k_bound"]] * LOG2Efor d in cutlass.range(ACC_COLS, unroll_full=True):areg[d] = areg[d] * q_rms * params[param["q_norm"] + c0 + d]- apply_rope(areg, *shape.rope_dims, ws.rope, *rope_pos, c0, ACC_COLS)+ if cutlass.const_expr(kf_time is None):+ apply_rope(areg, *shape.rope_dims, ws.rope, *rope_pos, c0, ACC_COLS)+ elif kf_tile:+ apply_rope_float_t(+ areg,+ *shape.rope_dims,+ ws.rope,+ kf_time,+ rope_pos[1],+ rope_pos[2],+ ws.rope_inv[0],+ c0,+ ACC_COLS,+ )+ else:+ apply_rope(areg, *shape.rope_dims, ws.rope, *rope_pos, c0, ACC_COLS)_fill_a_chunk(ws.s_q, lane, areg, head * HD + c0, ACC_COLS)@@ -1359,6 +1883,180 @@ def pack_fused_ctx_weights()[email protected]_cache(maxsize=8)+def _inert_keyframe_operands(channels: int, device: torch.device) -> "tuple":+ """Never-read stand-ins for the keyframe operands, wrapped once per device.+ Cached rather than built per call: the kernel takes all twelve unconditionally but reads+ none of them with the keyframe stream compiled out, so they only have to be *typed*+ right. Both the allocation and the ``from_dlpack`` wrap are hoisted here -- the wrap+ especially, since twelve of them on the hot path measured as ~9% of a small block launch.+ """+ act = _dyn_act(torch.zeros((1, channels), device=device, dtype=torch.bfloat16))+ f32 = _dyn(torch.zeros(1, device=device, dtype=torch.float32))+ i32 = _dyn(torch.zeros(1, device=device, dtype=torch.int32))+ return (act, act, act, act, f32, f32, i32, i32, i32, i32, i32, i32)+++class _KeyframeWorkspace(NamedTuple):+ """The keyframe half of one launch: its compile-key facts, its operands, its output."""++ #: The caller supplied a keyframe stream -- so this launch is the *joint* operator, whose+ #: window rule is clamp-and-mask rather than NATTEN's inward shift. Deliberately not+ #: conditioned on the plane count: the rule belongs to the operator, and keying both it+ #: and the tail off "has planes" quietly served two different window rules depending on+ #: whether a caller passed zero planes or planes nothing selected. With no planes the+ #: tail is a zero-trip loop over real, empty tables.+ enabled: bool+ n_kf: int+ cache_row_stride: int+ #: The twelve keyframe arguments, already DSL-wrapped and in signature order.+ operands: tuple+ #: ``operands``' output buffer, unwrapped, because the return value slices it. ``None``+ #: with the stream compiled out, where there is nothing to slice.+ y: "torch.Tensor | None"+++def _absent_keyframe_workspace(channels: int, device: torch.device) -> _KeyframeWorkspace:+ """No keyframe stream at all: inert operands, and nothing the kernel will read."""+ return _KeyframeWorkspace(+ enabled=False,+ n_kf=0,+ cache_row_stride=1,+ operands=_inert_keyframe_operands(channels, device),+ y=None,+ )+++def _keyframe_workspace(+ x_keyframes: torch.Tensor | None,+ stage4_keyframes: torch.Tensor | None,+ keyframe_times: torch.Tensor | None,+ t: int,+ h: int,+ w: int,+ channels: int,+ ctx_channels: int,+ num_heads: int,+ head_dim: int,+ tile: "tuple[int, int, int]",+ plan: _SlabPlan,+ device: torch.device,+ out: torch.Tensor | None = None,+) -> _KeyframeWorkspace:+ """Allocate the keyframe caches and precompute the two lookups, or hand back placeholders.+ The keyframe cache is the video cache with the box's temporal extent replaced by ``n_kf``:+ a plane is one slice however deep the slab is, and the box's ``h/w`` rectangle is already+ everything a core query can reach spatially. That makes it ``n_kf / box_t`` of the video+ cache -- a few percent at any real shape.+ ``out`` is the anchor stream's output buffer, ``(n_kf*H*W + OUT_SLACK_ROWS, C)``, so a+ chain can recycle it exactly as it recycles the video stream's.+ """+ supplied = (x_keyframes, stage4_keyframes, keyframe_times)+ if all(v is None for v in supplied):+ if out is not None:+ raise ValueError("out_keyframes needs a keyframe stream to write")+ return _absent_keyframe_workspace(channels, device)+ if any(v is None for v in supplied):+ raise ValueError("x_keyframes, stage4_keyframes and keyframe_times must be given together")++ n_kf = int(x_keyframes.shape[1])+ if n_kf == 0:+ # Still the joint operator, so still the joint binary -- only with nothing for the+ # tail to iterate. Everything the kernel indexes by *query tile* is real and sized;+ # everything it indexes by plane is a placeholder behind a zero-trip loop.+ inert = _dyn_act(torch.zeros((1, channels), device=device, dtype=torch.bfloat16))+ inert_f32 = _dyn(torch.zeros(1, device=device, dtype=torch.float32))+ n_tiles_t = -(-t // tile[0])+ # Only the lane slack, since there is no plane to store -- but still a real buffer+ # the out-of-range stores can land in, and still ``out``-able, so a chain does not+ # have to special-case an empty selection.+ empty_y = (+ torch.empty((M, channels), device=device, dtype=torch.bfloat16)+ if out is None+ else _check_out(out, M, channels, x_keyframes, "out_keyframes")+ )+ return _KeyframeWorkspace(+ enabled=True,+ n_kf=0,+ cache_row_stride=1,+ operands=(+ inert,+ inert,+ _dyn_act(empty_y),+ _dyn_act(torch.empty((2 * num_heads, head_dim), device=device, dtype=torch.bfloat16)),+ _dyn(torch.empty(1 + M, device=device, dtype=torch.float32)),+ inert_f32,+ _dyn(torch.full((t * KEYFRAME_CONTEXT_SLOTS,), -1, dtype=torch.int32, device=device)),+ _dyn(torch.full((n_tiles_t,), -1, dtype=torch.int32, device=device)),+ _dyn(torch.zeros(n_tiles_t, dtype=torch.int32, device=device)),+ _dyn(torch.zeros(1, dtype=torch.int32, device=device)),+ _dyn(torch.zeros(1, dtype=torch.int32, device=device)),+ _dyn(torch.zeros(1, dtype=torch.int32, device=device)),+ ),+ y=empty_y,+ )+ if tuple(x_keyframes.shape) != (1, n_kf, h, w, channels):+ raise ValueError(f"x_keyframes must be {(1, n_kf, h, w, channels)}, got {tuple(x_keyframes.shape)}")+ if tuple(stage4_keyframes.shape)[:2] != (1, n_kf) or int(stage4_keyframes.shape[-1]) != ctx_channels:+ raise ValueError(f"stage4_keyframes must be (1, {n_kf}, H_lo, W_lo, {ctx_channels})")+ if int(keyframe_times.numel()) != n_kf:+ raise ValueError(f"keyframe_times must have {n_kf} entries, got {int(keyframe_times.numel())}")++ slots = nearest_keyframe_slots(keyframe_times, t)+ # ``SLOTS * tile[0]``, not ``min(n_kf, ...)``: the stride into ``planes`` is a compile-time+ # constant of the tile and must not move with the anchor layout. Slack columns are -1.+ planes, _ = tile_plane_union(slots, tile_t=tile[0], max_planes=KEYFRAME_CONTEXT_SLOTS * tile[0])+ counts = (planes >= 0).sum(dim=-1).to(torch.int32)+ video = nearest_video_frames(keyframe_times, t)+ # Which slab owns each plane's query tiles: the one whose core holds the plane's own+ # position. Its box is that core grown by the NA radius (>=1 on every stage) and the <=2+ # nearest video frames are within a step, so the box always covers them.+ # ``plan.core`` counts query *tiles*, so the core's temporal extent in tokens is that+ # times the tile depth. Dividing by the tile count instead sends most planes to a slab+ # index that never comes up, and their query tiles silently never run.+ core_tokens = plan.core[0] * tile[0]+ positions = keyframe_times.detach().cpu().round().clamp_(0, t - 1).to(torch.int64)+ owner = (positions // core_tokens).clamp_(0, plan.grid[0] - 1).to(torch.int32)++ kf_rows = n_kf * h * w+ cache_row_stride = n_kf * plan.box[1] * plan.box[2]++ def rows(x: torch.Tensor, ch: int) -> torch.Tensor:+ return _as_rows(x[0].detach().to(dtype=torch.bfloat16)).reshape(-1, ch)++ def i32(x: torch.Tensor) -> torch.Tensor:+ return x.reshape(-1).contiguous().to(device=device, dtype=torch.int32)++ x_rows = rows(x_keyframes, channels)+ y = (+ torch.empty((kf_rows + M, channels), device=device, dtype=torch.bfloat16)+ if out is None+ # Against ``x_rows`` rather than ``x_keyframes``: what the kernel reads is the row+ # view, and for a non-contiguous input that is a copy the caller cannot alias anyway.+ else _check_out(out, kf_rows + M, channels, x_rows, "out_keyframes")+ )+ return _KeyframeWorkspace(+ enabled=True,+ n_kf=n_kf,+ cache_row_stride=cache_row_stride,+ operands=(+ _dyn_act(x_rows),+ _dyn_act(rows(stage4_keyframes, ctx_channels)),+ _dyn_act(y),+ _dyn_act(torch.empty((2 * num_heads * cache_row_stride, head_dim), device=device, dtype=torch.bfloat16)),+ _dyn(torch.empty(cache_row_stride + M, device=device, dtype=torch.float32)),+ _dyn(keyframe_times.detach().to(device=device, dtype=torch.float32).reshape(-1)),+ _dyn(i32(slots)),+ _dyn(i32(planes)),+ _dyn(i32(counts)),+ _dyn(i32(video)),+ _dyn(i32((video >= 0).sum(dim=-1))),+ _dyn(i32(owner)),+ ),+ y=y,+ )++def run_block_fna_dsl(x: torch.Tensor,stage4: torch.Tensor,@@ -1396,7 +2094,11 @@ def run_block_fna_dsl(kernel_size: "tuple[int, int, int]",tile_thw: "tuple[int, int, int] | None" = None,out: torch.Tensor | None = None,-) -> torch.Tensor:+ x_keyframes: torch.Tensor | None = None,+ stage4_keyframes: torch.Tensor | None = None,+ keyframe_times: torch.Tensor | None = None,+ out_keyframes: torch.Tensor | None = None,+) -> "torch.Tensor | tuple[torch.Tensor, torch.Tensor]":"""Run one fused ``DiffusionNABlock``. ``x`` is ``(1, T, H, W, C)``.``stage4`` is the context *before* its pixel-shuffle upsample,``(1, T/p_t, H/p_h, W/p_w, Ctx)``, and ``w_ctx`` / ``b_ctx`` are that upsample fused@@ -1417,6 +2119,9 @@ def run_block_fna_dsl(It must be ``(T*H*W + OUT_SLACK_ROWS, C)`` contiguous bf16: the kernel storesout-of-range lanes of partial tiles past the volume. It must not alias ``x`` --the kernel reads neighborhoods of ``x`` while writing, so in-place is not safe.+ ``out_keyframes`` is the same thing for the anchor stream, sized+ ``(n_kf*H*W + OUT_SLACK_ROWS, C)``; without it a joint launch allocates that stream's+ output itself and the chain's alternation stops one stream short."""if not block_fna_available(x.device.index or 0):raise RuntimeError(UNSUPPORTED_MESSAGE)@@ -1476,6 +2181,23 @@ def run_block_fna_dsl(norm_cache = torch.empty(plan.cache_row_stride + M, device=x_.device, dtype=torch.float32)barrier = torch.zeros(2, device=x_.device, dtype=torch.int32)+ kf = _keyframe_workspace(+ x_keyframes,+ stage4_keyframes,+ keyframe_times,+ T,+ H,+ W,+ C,+ Ctx,+ num_heads,+ hd,+ tile,+ plan,+ x_.device,+ out_keyframes,+ )+def f32(t: torch.Tensor):return _dyn(t.detach().contiguous().float().to(device=x_.device).view(-1))@@ -1513,6 +2235,7 @@ def run_block_fna_dsl(rope_dim_split=rope_dim_split,kernel_size=kernel_size,tile_thw=tile,+ keyframes=kf.enabled,)compiled(_dyn_act(_as_rows(x_)),@@ -1521,6 +2244,7 @@ def run_block_fna_dsl(_dyn_act(kv_cache),_dyn(norm_cache),_dyn(barrier),+ *kf.operands,bf(w_ctx),bf(w_q),bf(_pack_kv(w_k, w_v, num_heads)),@@ -1532,9 +2256,21 @@ def run_block_fna_dsl(f32(inv_t),f32(inv_h),f32(inv_w),- *_runtime_scalars(volume=(T, H, W), ctx_volume=(T_lo, H_lo, W_lo), drop_leading=drop, n_ctas=n_ctas, plan=plan),+ *_runtime_scalars(+ volume=(T, H, W),+ ctx_volume=(T_lo, H_lo, W_lo),+ drop_leading=drop,+ n_ctas=n_ctas,+ plan=plan,+ n_kf=kf.n_kf,+ kf_cache_row_stride=kf.cache_row_stride,+ ),)- return y_buf[: T * H * W].view(T, H, W, C).unsqueeze(0).to(dtype=x.dtype)+ video_out = y_buf[: T * H * W].view(T, H, W, C).unsqueeze(0).to(dtype=x.dtype)+ if not kf.enabled:+ return video_out+ # The arity follows the call, so an empty stream still returns a (possibly empty) pair.+ return video_out, kf.y[: kf.n_kf * H * W].view(kf.n_kf, H, W, C).unsqueeze(0).to(dtype=x.dtype)def block_fna_available(device_index: int = 0) -> bool:@@ -1586,6 +2322,18 @@ def _launch(kv_cache,norm_cache,barrier,+ x_kf,+ stage4_kf,+ y_kf,+ kv_cache_kf,+ norm_cache_kf,+ kf_times,+ kf_slots,+ kf_planes,+ kf_counts,+ kf_video,+ kf_video_counts,+ kf_slab,w_ctx,w_q,w_kv,@@ -1615,6 +2363,8 @@ def _launch(max_box_h,max_box_w,cache_row_stride,+ n_kf,+ kf_cache_row_stride,C: cutlass.Constexpr,Ctx: cutlass.Constexpr,SP_T: cutlass.Constexpr,@@ -1638,6 +2388,10 @@ def _launch(BT: cutlass.Constexpr,BH: cutlass.Constexpr,BW: cutlass.Constexpr,+ KF: cutlass.Constexpr,+ SLOTS: cutlass.Constexpr,+ P_MAX: cutlass.Constexpr,+ NKV_KF: cutlass.Constexpr,):mma128 = cute.make_tiled_mma(_mma_op("n128"))mma64 = cute.make_tiled_mma(_mma_op("pv"))@@ -1677,6 +2431,18 @@ def _launch(kv_cache,norm_cache,barrier,+ x_kf,+ stage4_kf,+ y_kf,+ kv_cache_kf,+ norm_cache_kf,+ kf_times,+ kf_slots,+ kf_planes,+ kf_counts,+ kf_video,+ kf_video_counts,+ kf_slab,a_ctx,m_ctx,a_q,@@ -1713,6 +2479,8 @@ def _launch(max_box_h,max_box_w,cache_row_stride,+ n_kf,+ kf_cache_row_stride,C,Ctx,SP_T,@@ -1736,6 +2504,10 @@ def _launch(BT,BH,BW,+ KF,+ SLOTS,+ P_MAX,+ NKV_KF,mma128,mma64,a_layout,@@ -1757,9 +2529,28 @@ def _compile(tile_thw: "tuple[int, int, int]",Ctx: int | None = None,upsample_stride: "tuple[int, int, int]" = (1, 1, 1),+ keyframes: bool = False,):Ctx = C if Ctx is None else Ctx- key = (C, Ctx, upsample_stride, Hidd, num_heads, rope_dim_split, tile_thw, kernel_size, MAXP_TOKENS, SLAB_BOX_MAX)+ # ``keyframes`` keys the binary so the no-keyframe kernel keeps exactly the trace, and+ # the register allocation, it had before the keyframe stream existed.+ # Everything else here is structural too, and must stay that way. The per-tile plane+ # union bound used to be in this key; because it moves with the clip length it recompiled+ # the ladder on every new duration, which cost 12+ minutes of in-process MLIR before a+ # 545-frame decode could start. It is now ``SLOTS * TT``, a constant of ``tile_thw``.+ key = (+ C,+ Ctx,+ upsample_stride,+ Hidd,+ num_heads,+ rope_dim_split,+ tile_thw,+ kernel_size,+ MAXP_TOKENS,+ SLAB_BOX_MAX,+ keyframes,+ )if key in _COMPILED:return _COMPILED[key]kt, kh, kw = kernel_size@@ -1801,6 +2592,13 @@ def _compile(act(2 * num_heads * M, hd), # kv_cache -- its head stride is a runtime argumentvec(2 * M), # norm_cache_dyn(torch.zeros(2, device=dev, dtype=torch.int32)), # barrier+ act(M, C), # x_kf+ act(M, Ctx), # stage4_kf+ act(M, C), # y_kf+ act(2 * num_heads * M, hd), # kv_cache_kf+ vec(2 * M), # norm_cache_kf+ vec(1), # kf_times+ *(_dyn(torch.zeros(max(n, 1), device=dev, dtype=torch.int32)) for n in (1, 1, 1, 1, 1, 1)),weight(subpixels * C, Ctx), # w_ctx -- the fused upsample x context_projweight(C, C), # w_qweight(2 * C, C), # w_kv@@ -1822,6 +2620,7 @@ def _compile(rope_dim_split=rope_dim_split,kernel_size=kernel_size,tile_thw=tile_thw,+ keyframes=keyframes,),**({"options": opts} if opts else {}),)@@ -1835,6 +2634,8 @@ def _runtime_scalars(drop_leading: int,n_ctas: int,plan: _SlabPlan,+ n_kf: int = 0,+ kf_cache_row_stride: int = 1,) -> tuple:"""The kernel's runtime scalar arguments, in signature order.Both :func:`_compile`'s trace call and the real call site build their argument@@ -1851,6 +2652,8 @@ def _runtime_scalars(*plan.core,*plan.box,plan.cache_row_stride,+ n_kf,+ kf_cache_row_stride,)@@ -1864,12 +2667,15 @@ def _static_shape(rope_dim_split: "tuple[int, int, int]",kernel_size: "tuple[int, int, int]",tile_thw: "tuple[int, int, int]",+ keyframes: bool = False,) -> tuple:"""The kernel's compile-time arguments, in signature order."""kt, kh, kw = kernel_sizett, th, tw = tile_thwpanel = (tt + kt - 1, th + kh - 1, tw + kw - 1)n_kv = (panel[0] * panel[1] * panel[2] + TILE_N - 1) // TILE_N+ # Keyframe panels drop the temporal axis: the video panel's h/w rectangle, one plane deep.+ n_kv_kf = (panel[1] * panel[2] + TILE_N - 1) // TILE_Nreturn (C,Ctx,@@ -1886,6 +2692,12 @@ def _static_shape(*panel,n_kv,*SLAB_BOX_MAX,+ keyframes,+ KEYFRAME_CONTEXT_SLOTS,+ # The stride into ``kf_planes``: a tile's ``TT`` timesteps contribute at most+ # ``SLOTS`` planes each, so this bounds the union without consulting the layout.+ KEYFRAME_CONTEXT_SLOTS * tt,+ n_kv_kf,)diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/fna_attn_core.py b/packages/ltx-kernels/src/ltx_kernels/vae/fna_attn_core.pyindex e016194..59e0c70 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/fna_attn_core.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/fna_attn_core.py@@ -63,6 +63,28 @@ def default_tile_thw(kernel_size: "tuple[int, int, int]") -> "tuple[int, int, inreturn best+def default_keyframe_tile_hw(kernel_size: "tuple[int, int, int]") -> "tuple[int, int]":+ """Pick the ``M``-token *spatial* query box for a keyframe query tile.+ Keyframe query tiles hold one plane each, not ``TT`` of them: every key set a keyframe+ query reads -- its own plane's window, and each of the <=2 nearest video frames' -- is a+ single-plane ``PT=1`` panel, and which video frames those are is a property of the+ plane. One plane per tile makes all of that tile-uniform, so the tail needs no per-lane+ ``sel`` and costs 1 self pass plus <=2 cross passes instead of scaling with ``TT``.+ The trade is a second compile-time tile geometry, which is why this is separate from+ :func:`default_tile_thw` rather than a ``tt=1`` call into it.+ """+ _, kh, kw = kernel_size+ best, best_panel = (8, 16), 1 << 60+ for th in (2, 4, 8, 16, 32):+ tw = M // th+ if tw < 1 or tw > 32:+ continue+ panel = (th + kh - 1) * (tw + kw - 1)+ if panel < best_panel:+ best, best_panel = (th, tw), panel+ return best++def cta_count(n_tiles: int, device: torch.device) -> int:"""Persistent grid size: one CTA per SM, capped by the work available.``block_fna_dsl``'s device-wide barrier requires every CTA to be resident, so the@@ -224,6 +246,41 @@ def apply_rope(reg, d_t, d_h, d_w, tbl, li_t, li_h, li_w, c0: int = 0, n: int =reg[c - c0 + 1] = e * sa + o * ca+def apply_rope_float_t(reg, d_t, d_h, d_w, tbl, t_value, li_h, li_w, inv_t, c0: int = 0, n: int = HD):+ """:func:`apply_rope` with the temporal axis at an arbitrary *float* position.+ Keyframe planes sit at chunk-center coordinates ``t_s(f) = (f + (r_s-1)/2) / r_s``, which+ are not on the integer lattice the slab's ``cos``/``sin`` tables are built over. The h and+ w axes still are, so only ``t`` is recomputed and the tables carry the other two.+ Done inline rather than through a keyframe ``t`` table on purpose: at ``head_dim=64`` the+ temporal axis is 8 pairs, so this is 16 MUFU per token hoisted outside the head loop, and+ SMEM in the fused kernel is the scarce resource -- see the pool/rope/params budget in+ ``block_fna_dsl``. A table would be small but the headroom is smaller.+ """+ (_, _, ch, sh, cw, sw) = tbl+ for rp in range(d_t // 2):+ c = 2 * rp+ if c < c0 or c + 1 >= c0 + n:+ continue+ ang = ACC(t_value) * inv_t[rp]+ ca = cute.cos(ang)+ sa = cute.sin(ang)+ e = reg[c - c0]+ o = reg[c - c0 + 1]+ reg[c - c0] = e * ca - o * sa+ reg[c - c0 + 1] = e * sa + o * ca+ for base, dim, cos_t, sin_t, li in ((d_t, d_h, ch, sh, li_h), (d_t + d_h, d_w, cw, sw, li_w)):+ for rp in range(dim // 2):+ c = base + 2 * rp+ if c < c0 or c + 1 >= c0 + n:+ continue+ ca = cos_t[li, rp]+ sa = sin_t[li, rp]+ e = reg[c - c0]+ o = reg[c - c0 + 1]+ reg[c - c0] = e * ca - o * sa+ reg[c - c0 + 1] = e * sa + o * ca++@cute.jitdef fill_rope_axis(cos_t, sin_t, tidx, origin, span, half: cutlass.Constexpr, inv):"""Cooperatively tabulate cos/sin for one axis over ``span`` positions."""@@ -279,6 +336,8 @@ def attention_tile(kh: cutlass.Constexpr,kw: cutlass.Constexpr,NKV: cutlass.Constexpr,+ sel=None,+ window_hi=None,):"""Windowed NA over one query tile's halo panel, for ``NHG`` heads.Args:@@ -296,13 +355,29 @@ def attention_tile(kv_hstride: rows between consecutive heads, in ``HD``-wide rows.panel: ``(t_s, h_s, w_s, pt0, ph0, pw0, bh2, bw2)`` -- the tile's halo panelorigin, the source box's origin, and that box's H and W extents.- window: ``(lt0, lh0, lw0)`` -- this query's clamped NA window, panel-relative.+ window: ``(lt0, lh0, lw0)`` -- this query's NA window origin, panel-relative.ids: ``(tidx, lane, wg, warp_i)``.NHG: heads processed per call; must be even (the pipeline's buffer parity).KVRM: rows between consecutive panel positions in the K/V source.PT, PH, PW: halo panel extents.kt, kh, kw: NA window extents.NKV: KV tiles spanning the panel, ``ceil(PT*PH*PW / M)``.+ sel: optional per-lane ``Int32`` 0/1 gating this lane's whole score row, for the+ keyframe tail (see the mask below). ``None`` -- the local pass -- traces to the+ pre-keyframe code exactly.+ window_hi: optional ``(hi_t, hi_h, hi_w)`` exclusive panel-relative upper bounds,+ from :func:`~ltx_kernels.vae.fna_geometry.window_bounds_in_panel`. Given, the+ window is **clamp-and-mask** -- the rule the joint keyframe operator is defined+ on, where a boundary query keeps a truncated window and renormalises over it.+ ``None`` is NATTEN's inward shift, ``[lt0, lt0 + kt)`` etc., and traces to the+ byte-identical pre-keyframe code. The two agree only in the interior, so the+ choice belongs to the caller's operator, not to this function.+ A keyframe tail is this same call with ``PT=1`` and ``kt=1``: ``panel_key_row`` then+ reduces to ``flatten_3d(plane, ...)`` and the mask's ``rdt`` test to ``0 <= 0 < 1``, so+ a spatial-only window over one keyframe plane needs no separate code. Because the+ softmax offset is fixed rather than an online max (see ``m_sm``), a tail called after+ the local pass -- same ``m_sm``/``l_sm``/``acc_o``, no re-zeroing -- *is* a joint+ softmax over both key sets, with no rescale.On return ``acc_o[nh]`` holds the unnormalised attention output and``l_sm[lane, wg, nh]`` this warpgroup's share of the denominator;:func:`attn_epilogue` divides them.@@ -325,6 +400,13 @@ def attention_tile(k_src, v_src = kv_srck_base, v_base = kv_baselt0, lh0, lw0 = window+ if cutlass.const_expr(window_hi is None):+ # NATTEN's inward shift: exactly ``k`` keys per axis, so the upper bounds are the+ # origins plus the compile-time kernel extents -- the same expressions the mask+ # tested inline before clamp-and-mask existed.+ hi_t, hi_h, hi_w = lt0 + kt, lh0 + kh, lw0 + kw+ else:+ hi_t, hi_h, hi_w = window_hi_tidx, lane, wg, warp_i = idsN_KEYS = PT * PH * PW # keys in the halo panel@@ -371,7 +453,21 @@ def attention_tile(# wherever that row starts in the word, and only when its (dt, dh) is inside# this query's window. Three rows per word against 32 keys per word. Only the# words covering this warpgroup's score columns are built.- wrun = cutlass.Int32((1 << kw) - 1) << lw0+ # Under clamp-and-mask the run is the surviving part of the kernel row, so both its+ # width and its start are per-lane; under the inward shift it is always ``kw`` wide+ # and the width folds into a compile-time constant.+ if cutlass.const_expr(window_hi is None):+ wrun = cutlass.Int32((1 << kw) - 1) << lw0+ else:+ wrun = ((cutlass.Int32(1) << (hi_w - lw0)) - cutlass.Int32(1)) << lw0+ # A keyframe tail pass hands each lane a 0/1 saying whether *its* query picked this+ # plane -- the plane is a per-tile choice but the nearest-2 set is per ``t``, and a+ # tile spans ``TT`` of them. Every mask bit below is a shifted copy of ``wrun``, so+ # folding the predicate in here zeroes the lane's whole row in one AND, and the+ # ``bw != 0`` arm downstream then skips its 32 exponentials. Left ``None`` this+ # traces to exactly the pre-keyframe code.+ if cutlass.const_expr(sel is not None):+ wrun = wrun & (cutlass.Int32(0) - sel)mask = [cutlass.Int32(0) for _ in range(NBW)]for bb in cutlass.range_constexpr(NBW):b = wg * NBW + bb@@ -382,7 +478,7 @@ def attention_tile(r = r0 + urdt = r // PHrdh = r - rdt * PH- if r < PT * PH and rdt >= lt0 and rdt < lt0 + kt and rdh >= lh0 and rdh < lh0 + kh:+ if r < PT * PH and rdt >= lt0 and rdt < hi_t and rdh >= lh0 and rdh < hi_h:# Where this row's dw=0 sits in the word. Negative for a row that# started in the previous word; past 31 for one spilling into the# next. Both shifts are guarded -- a shift wider than the type isdiff --git a/packages/ltx-kernels/src/ltx_kernels/vae/fna_geometry.py b/packages/ltx-kernels/src/ltx_kernels/vae/fna_geometry.pyindex ed87bc6..55c4be5 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/fna_geometry.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/fna_geometry.py@@ -169,6 +169,8 @@ def window_origin_in_panel(query_pos, panel_origin, radius, kernel_shape, volumeThe panel bounds every query in the tile; this is the ``(kt, kh, kw)`` box *this*query attends to. Returned panel-relative because that is the form the per-keymask consumes.+ NATTEN's inward shift. See :func:`window_bounds_in_panel` for the other rule and why+ both exist."""q_t, q_h, q_w = query_pospanel_t0, panel_h0, panel_w0 = panel_origin@@ -180,3 +182,30 @@ def window_origin_in_panel(query_pos, panel_origin, radius, kernel_shape, volumeclamp_window_start(q_h - radius_h, kernel_h, vol_h) - panel_h0,clamp_window_start(q_w - radius_w, kernel_w, vol_w) - panel_w0,)+++def window_bounds_in_panel(query_pos, panel_origin, radius, kernel_shape, volume):+ """One query's **clamp-and-mask** NA window, as half-open panel-relative bounds.+ The other window rule, and the one the joint keyframe operator is defined on: iterate+ the full configured kernel from ``q - radius`` and drop whatever falls outside the+ volume, so a boundary query attends to *fewer* keys and its softmax renormalises over+ them. NATTEN -- and therefore :func:`window_origin_in_panel` and every non-keyframe path+ here -- instead slides the window inward so every query sees exactly ``k`` keys.+ The two agree in the interior and genuinely differ at boundaries; at latent resolution+ with a ``(3, 7, 7)`` kernel that is about half the volume, so it is not a rounding+ detail. Which rule a call uses is a property of the operator, not of the hardware, hence+ two helpers rather than a flag buried here.+ Returns ``((lo_t, hi_t), (lo_h, hi_h), (lo_w, hi_w))``. Every bound is a subset of the+ inward-shifted window's span, so a panel sized for that rule already covers this one.+ """+ bounds = []+ for q, panel_0, radius_a, kernel_a, extent in zip(+ query_pos, panel_origin, radius, kernel_shape, volume, strict=True+ ):+ start = q - radius_a+ lo = start if start > 0 else cutlass.Int32(0)+ end = start + kernel_a+ hi = end if end < extent else extent+ bounds.append((lo - panel_0, hi - panel_0))+ return tuple(bounds)diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/fna_smem.py b/packages/ltx-kernels/src/ltx_kernels/vae/fna_smem.pyindex 3613a9a..0ccbc2f 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/fna_smem.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/fna_smem.py@@ -48,6 +48,30 @@ def _read_a_chunk(sA, row, vals, c0, n):vals[k * _KRUN + ki] = ACC(frag[ki])+def select_tensor(cond, when_true, when_false):+ """One tensor addressing ``when_true`` where ``cond`` holds and ``when_false`` elsewhere.+ This is what lets the video and keyframe streams share traced code instead of one+ instantiation each. A *device-value* ``if`` cannot select a tensor -- ``a if cond else b``+ reaches the NVVM backend as a select on a pointer type it rejects -- but it can select an+ *address*, which is one ``selp.b64``. So the pair becomes a single operand and everything+ downstream of it is traced once.+ The two must be interchangeable through that one layout: same element type, and the same+ row stride, since the layout comes from ``when_true``. Both hold by construction for every+ pair this is used on -- each is a contiguous row-major ``(rows, channels)`` buffer over the+ same ``channels`` -- and :func:`ltx_kernels.vae.block_fna_dsl._check_out` re-checks shape+ and contiguity for the one buffer a caller supplies, the output.+ Alignment is the element's. Every vectorised read of these buffers goes through+ :func:`_vec_ptr` or :func:`_row_vec_ptr`, which re-assert 16B on the offset pointer, so+ claiming more here would only move the same assertion earlier.+ """+ addr = when_true.iterator.toint() if cond else when_false.iterator.toint()+ return cute.make_tensor(+ cute.make_ptr(when_true.element_type, addr, cute.AddressSpace.gmem),+ when_true.layout,+ )++def _vec_ptr(t, coord):"""A ``VEC``-wide, 16B-aligned pointer at ``(row, col)`` of a row-major 2D tensor.Adding a dynamic offset to a pointer drops its alignment to one element, anddiff --git a/packages/ltx-kernels/src/ltx_kernels/vae/keyframe_slots.py b/packages/ltx-kernels/src/ltx_kernels/vae/keyframe_slots.pynew file mode 100644index 0000000..0eb5120--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/vae/keyframe_slots.py@@ -0,0 +1,132 @@+"""Which keyframe planes a video query -- and a whole query tile -- attends to.+Host-side geometry for the kernels' keyframe tail. Two maps, and the split between+them is the whole reason this module exists:+``nearest_keyframe_slots``+ Per video timestep ``t``, the ``S`` nearest keyframe planes. This is the model's+ contract: a query at ``t`` folds those planes' ``K_h x K_w`` spatial windows into+ the same softmax as its local video neighbors. Membership is by temporal distance+ only -- a plane may sit far outside the video kernel's ``K_t``.+``tile_plane_union``+ Per *query tile*, the union of those sets over the ``TT`` timesteps the tile spans.+ The kernels gather K/V one plane at a time for a whole tile, but the nearest-``S``+ set is per ``t``, and a tile holds more than one. So the tail iterates the union and+ each lane masks itself out of the planes its own ``t`` did not pick+ (``attention_tile``'s ``sel``).+The union is small because anchors are spaced: the set changes only where the ranking+of the ``S``-th nearest swaps, and those crossings are about as far apart as the+anchors themselves. At stage 5 (one latent step per pixel frame, gap 17) a 4-wide tile+crosses at most one, so three planes cover it. Coarse stages pack anchors into fewer+stage steps and churn faster, which is what ``max_planes`` is sized against -- and why+picking a tile with ``TT == 1`` there can be cheaper than a wider one (see+``default_tile_thw``).+"""++from __future__ import annotations++import torch++#: Keyframe slots per video query. Fixed at 2 by the model contract: capacity is a+#: property of the attention operator, not of the kernel window or the anchor spacing.+KEYFRAME_CONTEXT_SLOTS = 2+++def nearest_keyframe_slots(+ keyframe_times: torch.Tensor,+ video_length: int,+ *,+ slots: int = KEYFRAME_CONTEXT_SLOTS,+) -> torch.Tensor:+ """The ``slots`` nearest keyframe planes for each of ``video_length`` timesteps.+ Args:+ keyframe_times: ``(n_kf,)`` float stage-local plane positions -- the chunk-center+ coordinates, not pixel frame indices.+ video_length: ``T`` on the stage grid.+ slots: capacity per query.+ Returns:+ ``(video_length, slots)`` int32 plane ids, ``-1`` where a slot is unused (which+ happens only when ``n_kf < slots``). Ties break toward the lower plane id.+ """+ if video_length < 1:+ raise ValueError(f"video_length must be positive, got {video_length}")+ n_kf = int(keyframe_times.numel())+ if n_kf == 0:+ return torch.full((video_length, slots), -1, dtype=torch.int32)+ times = keyframe_times.detach().to(dtype=torch.float32, device="cpu").reshape(-1)+ query = torch.arange(video_length, dtype=torch.float32)+ return _rank_nearest(query, times, slots)+++def nearest_video_frames(+ keyframe_times: torch.Tensor,+ video_length: int,+ *,+ slots: int = KEYFRAME_CONTEXT_SLOTS,+) -> torch.Tensor:+ """The ``slots`` video timesteps nearest each keyframe plane -- the other direction.+ A keyframe *query* attends to its own plane's spatial window plus these frames' spatial+ windows, in one softmax. Deliberately not the video kernel's full ``K_t`` reach: the+ point is local motion context around the anchor, so the count is fixed at ``slots``+ however wide ``K_t`` happens to be.+ Returns ``(n_kf, slots)`` int32 timesteps, ``-1`` where the video is shorter than+ ``slots``. Ties break toward the earlier frame.+ """+ if video_length < 1:+ raise ValueError(f"video_length must be positive, got {video_length}")+ n_kf = int(keyframe_times.numel())+ if n_kf == 0:+ return torch.zeros((0, slots), dtype=torch.int32)+ times = keyframe_times.detach().to(dtype=torch.float32, device="cpu").reshape(-1)+ video = torch.arange(video_length, dtype=torch.float32)+ return _rank_nearest(times, video, slots)+++def tile_plane_union(keyframe_slots: torch.Tensor, tile_t: int, *, max_planes: int) -> tuple[torch.Tensor, int]:+ """Per query-tile row, the distinct planes any of its timesteps selected.+ Args:+ keyframe_slots: ``(T, S)`` from :func:`nearest_keyframe_slots`.+ tile_t: the query tile's temporal extent, ``TT``.+ max_planes: compile-time cap on the union; raises if a tile needs more, since+ silently dropping a plane would change the softmax rather than slow it down.+ Returns:+ ``(planes, used)`` -- ``planes`` is ``(ceil(T / tile_t), max_planes)`` int32,+ padded with ``-1``, and ``used`` is the largest union any tile actually needs, so+ a caller can loop that far instead of to ``max_planes``.+ """+ if tile_t < 1:+ raise ValueError(f"tile_t must be positive, got {tile_t}")+ video_length, _ = keyframe_slots.shape+ n_tiles = -(-video_length // tile_t)+ planes = torch.full((n_tiles, max_planes), -1, dtype=torch.int32)+ used = 0+ for tile in range(n_tiles):+ rows = keyframe_slots[tile * tile_t : (tile + 1) * tile_t]+ distinct = sorted({int(p) for p in rows.reshape(-1).tolist() if p >= 0})+ if len(distinct) > max_planes:+ raise ValueError(+ f"query tile {tile} spans timesteps selecting {len(distinct)} distinct keyframe "+ f"planes, over the max_planes={max_planes} cap; raise the cap or use a tile with "+ f"a smaller temporal extent"+ )+ used = max(used, len(distinct))+ if distinct:+ planes[tile, : len(distinct)] = torch.tensor(distinct, dtype=torch.int32)+ return planes, used+++def _rank_nearest(query_times: torch.Tensor, candidate_times: torch.Tensor, slots: int) -> torch.Tensor:+ """``(Q, slots)`` candidate indices ranked by ``(|dt|, index)``, ``-1`` where unfilled.+ A **stable argsort** on ``|dt|`` gives the index tie-break exactly. The obvious+ alternative -- ``|dt| + arange * 1e-6`` before a topk, which is how upstream writes it --+ is only approximately that: at ``|dt|`` of a few hundred the perturbation is below+ float32 eps and the tie-break silently stops ordering anything. Measured on random+ layouts that disagreed with a stable sort on 91 of 400 trials, so the two are not+ interchangeable even though they agree on the evenly spaced production layouts.+ """+ distances = (query_times[:, None] - candidate_times[None, :]).abs()+ order = torch.argsort(distances, dim=-1, stable=True)+ take = min(slots, candidate_times.numel())+ chosen = order[:, :take].to(torch.int32)+ if take == slots:+ return chosen+ pad = torch.full((chosen.shape[0], slots - take), -1, dtype=torch.int32)+ return torch.cat((chosen, pad), dim=-1)diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py b/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.pyindex a6d500b..7ea07fb 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py@@ -17,8 +17,9 @@ W are all runtime -- so the four deterministic stages share two binaries.# NOTE: no `from __future__ import annotations` -- cute.struct needs real types.+import functoolsimport os-from typing import Any+from typing import Any, NamedTupleimport cutlassimport cutlass.cute as cute@@ -39,10 +40,15 @@ from ltx_kernels.vae.fna_attn_core import ()from ltx_kernels.vae.fna_gemm import UmmaSharedStorage, _mma_op, _reg_shape, acquire_tmem, release_tmemfrom ltx_kernels.vae.fna_geometry import (+ at_least,+ at_most,+ clamp_window_start,+ flatten_3d,halo_panel_origin,query_row_indices,query_slot_in_tile,unflatten_3d,+ window_bounds_in_panel,window_origin_in_panel,)from ltx_kernels.vae.fna_smem import (@@ -51,6 +57,7 @@ from ltx_kernels.vae.fna_smem import (_read_a_chunk,_scatter_a,cooperative_copy_slot,+ select_tensor,)from ltx_kernels.vae.fna_types import (ACC,@@ -66,6 +73,7 @@ from ltx_kernels.vae.fna_types import (TILER_N128,M,)+from ltx_kernels.vae.keyframe_slots import KEYFRAME_CONTEXT_SLOTS, nearest_video_frames, tile_plane_unionfrom ltx_kernels.vae.softmax_bound import softmax_row_bound_COMPILED: "dict[tuple, Any]" = {}@@ -78,6 +86,31 @@ _COMPILED: "dict[tuple, Any]" = {}HG = 4+def _stage_queries(sQ, src, rowix, copy_slot, m_sm, areg, k_bound_t, lane, wg, c_off, HPG: cutlass.Constexpr):+ """Gather this head group's queries into ``sQ`` and fill their fixed softmax offsets.+ Shared by the video and keyframe query tiles: both read an already normed, scaled and+ RoPE'd query row, so the only difference is which tensor it comes from. Ends on the+ barrier inside ``attn_zero_accumulators``, which is what publishes ``m_sm``.+ """+ _fill_a_gather(sQ, src, rowix, copy_slot, HG * HD, c_off)+ cute.arch.sync_threads()+ # ``||q||`` per (row, head) -- the fixed softmax offset. Each lane owns its own row, so+ # a head's channels are register-local and this needs no reduction at all; the+ # warpgroups split the heads.+ for h_loc in cutlass.range_constexpr(HPG):+ for g in cutlass.range_constexpr(NUM_WARPGROUPS):+ if wg == g:+ nh = g * HPG + h_loc+ _read_a_chunk(sQ, lane, areg, nh * HD, HD)+ s = ACC(0.0)+ for d in cutlass.range(HD, unroll_full=True):+ s += areg[d] * areg[d]+ # Read at the point of use rather than hoisted: this runs once per head+ # group, and a hoisted value would hold a register live across the KV loop.+ m_sm[lane, nh] = cute.sqrt(s) * k_bound_t[0] * LOG2E++@cute.kerneldef _na_kernel(q: cute.Tensor, # (T*H*W, NH*HD) bf16, RMS-normed, scaled and RoPE'd@@ -85,6 +118,15 @@ def _na_kernel(v: cute.Tensor, # (T*H*W*NH, HD) bf16y: cute.Tensor, # (T*H*W + M, NH*HD) bf16k_bound_t: cute.Tensor, # (1,) f32, see ltx_kernels.vae.softmax_bound+ k_kf: cute.Tensor, # (n_kf*H*W*NH, HD) bf16, same norm as k, float-t RoPE+ v_kf: cute.Tensor, # (n_kf*H*W*NH, HD) bf16+ kf_slots: cute.Tensor, # (T*SLOTS,) i32 -- plane per (t, slot), -1 unused+ kf_planes: cute.Tensor, # (n_t_tiles*P_MAX,) i32 -- per-tile union, -1 padded+ kf_counts: cute.Tensor, # (n_t_tiles,) i32 -- how much of each union row is real+ q_kf: cute.Tensor, # (n_kf*H*W, NH*HD) bf16, normed/scaled/float-t RoPE'd+ y_kf: cute.Tensor, # (n_kf*H*W + M, NH*HD) bf16, the keyframe stream's output+ kf_video: cute.Tensor, # (n_kf*SLOTS,) i32 -- nearest video frames per plane+ kf_video_counts: cute.Tensor, # (n_kf,) i32T,H,W,@@ -94,6 +136,8 @@ def _na_kernel(n_ctas,grid_hw,grid_w_,+ n_kf,+ n_kfq_tiles,kt: cutlass.Constexpr,kh: cutlass.Constexpr,kw: cutlass.Constexpr,@@ -104,6 +148,11 @@ def _na_kernel(PH: cutlass.Constexpr,PW: cutlass.Constexpr,NKV: cutlass.Constexpr,+ KF: cutlass.Constexpr, # keyframe tail compiled in at all+ SLOTS: cutlass.Constexpr,+ P_MAX: cutlass.Constexpr, # cap on a tile's plane union+ NKV_KF: cutlass.Constexpr, # KV tiles spanning one keyframe panel, ceil(PH*PW / M)+ KFQ: cutlass.Constexpr, # keyframe *query* tiles compiled inmma128: cute.TiledMma,mma64: cute.TiledMma,p_layout: cute.ComposedLayout,@@ -169,10 +218,21 @@ def _na_kernel(copy_slot = cooperative_copy_slot(tidx)slot_t, slot_h, slot_w = query_slot_in_tile(lane, TH, TW)+ zero_k = cutlass.Int32(0)+ # One loop over both streams' tiles, video first, so the single-plane pass below is one+ # instantiation rather than one per stream. A keyframe query tile is a plane on the video+ # tile's spatial shape, so both grids unflatten with the same divisors and only the+ # temporal component's meaning differs: a tile index for video, a plane for keyframes.+ kf_rows = n_kf * H * Wtile_id = cta_index- while tile_id < n_tiles:- tile_i, tile_j, tile_k = unflatten_3d(tile_id, grid_hw, grid_w_)+ while tile_id < n_tiles + n_kfq_tiles:+ index = tile_id+ if cutlass.const_expr(KFQ):+ kfq_tile = tile_id >= n_tiles+ video_tile = tile_id < n_tiles+ index = tile_id - n_tiles if kfq_tile else tile_id+ tile_i, tile_j, tile_k = unflatten_3d(index, grid_hw, grid_w_)tile_origin = (tile_i * TT, tile_j * TH, tile_k * TW)panel_origin = halo_panel_origin(tile_origin, radius, panel_shape, volume)@@ -182,10 +242,65 @@ def _na_kernel(lane,T * H * W,)- window = window_origin_in_panel(query_pos, panel_origin, radius, kernel_shape, volume)+ # Two window rules, picked by whether this binary carries the keyframe tail: the+ # joint operator is defined on clamp-and-mask, every other caller on NATTEN's inward+ # shift, and ``KF`` is exactly the distinction. Keying it off the compile flag rather+ # than a runtime branch keeps the no-keyframe binary's trace byte-identical.+ if cutlass.const_expr(KF):+ bounds = window_bounds_in_panel(query_pos, panel_origin, radius, kernel_shape, volume)+ window = tuple(lo for lo, _ in bounds)+ window_hi = tuple(hi for _, hi in bounds)+ else:+ window = window_origin_in_panel(query_pos, panel_origin, radius, kernel_shape, volume)+ window_hi = None+ q_src, y_dst = q, y+ panel_h0, panel_w0 = panel_origin[1], panel_origin[2]+ # The tail's plane union is indexed by video temporal tile; a keyframe tile has no+ # such index, and reads row 0 whose value it then selects away.+ t_idx = tile_i++ if cutlass.const_expr(KFQ):+ # The keyframe tile's geometry: one plane, on this tile's spatial box. The *panel*+ # still shifts inward -- it only has to contain every key the tile can reach, and+ # the inward-shifted box is the larger of the two -- but the per-query window is+ # clamp-and-mask, like every window on the joint path.+ plane = at_most(tile_i, at_least(n_kf - 1, zero_k))+ q_h = tile_origin[1] + slot_h+ q_w = tile_origin[2] + slot_w+ r_h = q_h if q_h < H else H - 1+ r_w = q_w if q_w < W else W - 1+ kf_read = flatten_3d(plane, r_h, r_w, H, W)+ # A tile is one plane, so the borrowed tile's other temporal slots hold duplicates+ # of ``slot_t == 0``; they compute and park on a scratch row.+ kf_write = kf_read+ if slot_t != 0 or q_h >= H or q_w >= W:+ kf_write = kf_rows + lane+ kf_ph0 = clamp_window_start(tile_origin[1] - radius[1], PH, H)+ kf_pw0 = clamp_window_start(tile_origin[2] - radius[2], PW, W)+ kf_bounds = window_bounds_in_panel(+ (zero_k, r_h, r_w),+ (zero_k, kf_ph0, kf_pw0),+ (0, radius[1], radius[2]),+ (1, kh, kw),+ (cutlass.Int32(1), H, W),+ )+ read_row = kf_read if kfq_tile else read_row+ write_row = kf_write if kfq_tile else write_row+ panel_h0 = kf_ph0 if kfq_tile else panel_h0+ panel_w0 = kf_pw0 if kfq_tile else panel_w0+ window = (window[0], kf_bounds[1][0] if kfq_tile else window[1], kf_bounds[2][0] if kfq_tile else window[2])+ window_hi = (+ window_hi[0],+ kf_bounds[1][1] if kfq_tile else window_hi[1],+ kf_bounds[2][1] if kfq_tile else window_hi[2],+ )+ t_idx = zero_k if kfq_tile else t_idx+ q_src = select_tensor(kfq_tile, q_kf, q)+ y_dst = select_tensor(kfq_tile, y_kf, y)+# ``panel_key_row`` indexes the caller's K/V directly, so the box it walks is# the whole volume: origin zero, extents H and W.- panel = (*panel_origin, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int32(0), H, W)+ panel = (*panel_origin, zero_k, zero_k, zero_k, H, W)cute.arch.sync_threads()rowix[lane] = read_row@@ -197,59 +312,121 @@ def _na_kernel(c_off = hg * (HG * HD)# This group's queries: one coalesced gather straight into the swizzled# operand. The channel window moves with the group; the operand does not.- _fill_a_gather(sQ, q, rowix, copy_slot, HG * HD, c_off)- cute.arch.sync_threads()- # ``||q||`` per (row, head) -- the fixed softmax offset. Each lane owns its- # own row, so a head's channels are register-local and this needs no- # reduction at all; the warpgroups split the heads.- for h_loc in cutlass.range_constexpr(HPG):- for g in cutlass.range_constexpr(NUM_WARPGROUPS):- if wg == g:- nh = g * HPG + h_loc- _read_a_chunk(sQ, lane, areg, nh * HD, HD)- s = ACC(0.0)- for d in cutlass.range(HD, unroll_full=True):- s += areg[d] * areg[d]- # Read at the point of use rather than hoisted: this runs- # once per head group, and a hoisted value would hold a- # register live across the KV loop.- m_sm[lane, nh] = cute.sqrt(s) * k_bound_t[0] * LOG2E- # Ends on a barrier, which is also what publishes ``m_sm``.+ _stage_queries(sQ, q_src, rowix, copy_slot, m_sm, areg, k_bound_t, lane, wg, c_off, HPG)attn_zero_accumulators(acc_o, l_sm, oreg, lane, wg, HG)# K and V are the caller's own tensors: consecutive heads are one# ``HD``-row apart and one panel row is ``NH`` of them.- attention_tile(- (frQ, frK, frP, frV),- (sK, sV, sP),- acc_qk,- acc_o,- (qkbar, pvbar),- m_sm,- l_sm,- areg,- kvfrag,- (k, v),- (hg * HG, hg * HG),- cutlass.Int32(1),- panel,- window,- (tidx, lane, wg, warp_i),- HG,- NH,- PT,- PH,- PW,- kt,- kh,- kw,- NKV,- )+ # A video query runs this deep ``PT``-tall panel; a keyframe query has no local+ # temporal neighborhood at all and takes only the single-plane passes below.+ deep = True+ if cutlass.const_expr(KFQ):+ deep = video_tile+ if deep:+ attention_tile(+ (frQ, frK, frP, frV),+ (sK, sV, sP),+ acc_qk,+ acc_o,+ (qkbar, pvbar),+ m_sm,+ l_sm,+ areg,+ kvfrag,+ (k, v),+ (hg * HG, hg * HG),+ cutlass.Int32(1),+ panel,+ window,+ (tidx, lane, wg, warp_i),+ HG,+ NH,+ PT,+ PH,+ PW,+ kt,+ kh,+ kw,+ NKV,+ None,+ window_hi,+ )++ # Single-plane passes, into the *same* (m_sm, l_sm, acc_o). The softmax offset is+ # fixed rather than an online max, so continuing the accumulation is already a+ # joint softmax over local and keyframe keys -- no rescale, no state merge.+ # A video query's passes are the planes in its tile's union: a plane is a per-tile+ # gather but the nearest-S set is per t, so each lane gates itself with ``sel``,+ # and an unselected lane's mask words are zero so it skips its exponentials. A+ # keyframe query's are its own plane and then the <=2 nearest video latent frames+ # -- local motion context around the anchor, deliberately not the video kernel's+ # full ``kt`` reach -- all tile-uniform, so no gating. Both are ``(1, PH, PW)``+ # panels on the query's own spatial window over the caller's whole K/V, and+ # ``attention_tile`` needs nothing else: at PT=1 its panel walk and its dt mask+ # both collapse to the single plane.+ if cutlass.const_expr(KF):+ pass_i = cutlass.Int32(0)+ n_passes = kf_counts[t_idx]+ if cutlass.const_expr(KFQ):+ n_passes = (1 + kf_video_counts[plane]) if kfq_tile else n_passes+ while pass_i < n_passes:+ source = kf_planes[t_idx * P_MAX + at_most(pass_i, P_MAX - 1)]+ sel = cutlass.Int32(0)+ for s in cutlass.range_constexpr(SLOTS):+ if kf_slots[query_pos[0] * SLOTS + s] == source:+ sel = cutlass.Int32(1)+ k_src, v_src = k_kf, v_kf+ if cutlass.const_expr(KFQ):+ # Pass 0 is the keyframe query's own plane, the rest its nearest video+ # frames. Selected rather than branched: a tensor bound inside a+ # runtime ``if`` would differ in structure between the arms, which the+ # DSL rejects, and a select is one ``selp`` either way.+ own = pass_i == 0+ video_kv = cutlass.Int32(0) if own else cutlass.Int32(1)+ frame = kf_video[plane * SLOTS + at_most(at_least(pass_i - 1, zero_k), SLOTS - 1)]+ kfq_source = plane if own else frame+ video_kv = video_kv if kfq_tile else cutlass.Int32(0)+ source = kfq_source if kfq_tile else source+ sel = cutlass.Int32(1) if kfq_tile else sel+ k_src = select_tensor(video_kv != 0, k, k_kf)+ v_src = select_tensor(video_kv != 0, v, v_kf)+ attention_tile(+ (frQ, frK, frP, frV),+ (sK, sV, sP),+ acc_qk,+ acc_o,+ (qkbar, pvbar),+ m_sm,+ l_sm,+ areg,+ kvfrag,+ (k_src, v_src),+ (hg * HG, hg * HG),+ cutlass.Int32(1),+ (source, panel_h0, panel_w0, zero_k, zero_k, zero_k, H, W),+ (zero_k, window[1], window[2]),+ (tidx, lane, wg, warp_i),+ HG,+ NH,+ 1,+ PH,+ PW,+ 1,+ kh,+ kw,+ NKV_KF,+ sel,+ # One plane deep, so the temporal bound is the single slice; the+ # spatial pair is the query's own window, which is what keeps the two+ # key sets aligned for the query sharing a softmax over them.+ (cutlass.Int32(1), window_hi[1], window_hi[2]),+ )+ pass_i += 1cute.arch.sync_threads()attn_epilogue(acc_o, l_sm, oreg, sO, lane, wg, HG)cute.arch.sync_threads()- _scatter_a(sO, y, rowix_w, copy_slot, HG * HD, c_off)+ _scatter_a(sO, y_dst, rowix_w, copy_slot, HG * HD, c_off)cute.arch.sync_threads()hg += 1@@ -265,6 +442,15 @@ def _launch(v,y,k_bound_t,+ k_kf,+ v_kf,+ kf_slots,+ kf_planes,+ kf_counts,+ q_kf,+ y_kf,+ kf_video,+ kf_video_counts,T,H,W,@@ -274,6 +460,8 @@ def _launch(n_ctas,grid_hw,grid_w_,+ n_kf,+ n_kfq_tiles,kt: cutlass.Constexpr,kh: cutlass.Constexpr,kw: cutlass.Constexpr,@@ -284,6 +472,11 @@ def _launch(PH: cutlass.Constexpr,PW: cutlass.Constexpr,NKV: cutlass.Constexpr,+ KF: cutlass.Constexpr,+ SLOTS: cutlass.Constexpr,+ P_MAX: cutlass.Constexpr,+ NKV_KF: cutlass.Constexpr,+ KFQ: cutlass.Constexpr,):mma128 = cute.make_tiled_mma(_mma_op("n128"))mma64 = cute.make_tiled_mma(_mma_op("pv"))@@ -301,6 +494,15 @@ def _launch(v,y,k_bound_t,+ k_kf,+ v_kf,+ kf_slots,+ kf_planes,+ kf_counts,+ q_kf,+ y_kf,+ kf_video,+ kf_video_counts,T,H,W,@@ -310,6 +512,8 @@ def _launch(n_ctas,grid_hw,grid_w_,+ n_kf,+ n_kfq_tiles,kt,kh,kw,@@ -320,6 +524,11 @@ def _launch(PH,PW,NKV,+ KF,+ SLOTS,+ P_MAX,+ NKV_KF,+ KFQ,mma128,mma64,p_layout,@@ -356,8 +565,23 @@ def na_supported(return pt <= T and ph <= H and pw <= W-def _compile(*, kernel_size: "tuple[int, int, int]", tile_thw: "tuple[int, int, int]"):- key = (kernel_size, tile_thw)+def _compile(+ *,+ kernel_size: "tuple[int, int, int]",+ tile_thw: "tuple[int, int, int]",+ keyframes: bool = False,+ keyframe_queries: bool = False,+):+ # ``keyframes`` is part of the key so the no-keyframe binary keeps the exact trace it+ # had before the tail existed -- ``n_kf = 0`` must stay bit-identical, and a runtime+ # zero-trip loop would still perturb the codegen around it.+ # Everything in this key is *structural*. Nothing derived from the anchor layout may join+ # it: the per-tile plane union bound used to, and since it moves with the clip length it+ # recompiled the whole stage ladder on every new duration -- 12+ minutes of in-process+ # MLIR before a 545-frame decode could start. It is now ``SLOTS * TT``, the true upper+ # bound (each of a tile's ``TT`` timesteps contributes at most ``SLOTS`` planes), which is+ # a constant of ``tile_thw`` and so already covered here.+ key = (kernel_size, tile_thw, keyframes, keyframe_queries)if key in _COMPILED:return _COMPILED[key]kt, kh, kw = kernel_size@@ -367,11 +591,18 @@ def _compile(*, kernel_size: "tuple[int, int, int]", tile_thw: "tuple[int, int,if max(pt, ph, pw) > 32:raise ValueError(f"halo panel {(pt, ph, pw)} exceeds the packed-offset limit of 32")nkv = (pt * ph * pw + TILE_N - 1) // TILE_N+ # A keyframe panel is the same spatial box with the temporal axis collapsed. Keyframe+ # *query* tiles borrow it too, which is what keeps them on one instantiation with the+ # video tail (see the keyframe query loop in ``_na_kernel``).+ nkv_kf = (ph * pw + TILE_N - 1) // TILE_Ndev = torch.device("cuda")def za(a: int, b: int):return _dyn_act(torch.zeros(a, b, device=dev, dtype=torch.bfloat16))+ def zi(n: int):+ return _dyn(torch.zeros(n, device=dev, dtype=torch.int32))+# Pass-through for CuTe DSL compiler flags, e.g. --keep-sass / --ptxas-options=-v.opts = os.environ.get("CUTE_DSL_OPTS")_COMPILED[key] = cute.compile(@@ -381,6 +612,15 @@ def _compile(*, kernel_size: "tuple[int, int, int]", tile_thw: "tuple[int, int,za(M, HD),za(M, HG * HD),_dyn(torch.zeros(1, device=dev, dtype=torch.float32)),+ za(M, HD),+ za(M, HD),+ zi(KEYFRAME_CONTEXT_SLOTS),+ zi(1),+ zi(1),+ za(M, HG * HD),+ za(M, HG * HD),+ zi(KEYFRAME_CONTEXT_SLOTS),+ zi(1),4,4,4,@@ -390,6 +630,8 @@ def _compile(*, kernel_size: "tuple[int, int, int]", tile_thw: "tuple[int, int,1,1,1,+ 1,+ 1,kt,kh,kw,@@ -400,11 +642,129 @@ def _compile(*, kernel_size: "tuple[int, int, int]", tile_thw: "tuple[int, int,ph,pw,nkv,+ keyframes,+ KEYFRAME_CONTEXT_SLOTS,+ KEYFRAME_CONTEXT_SLOTS * tt,+ nkv_kf,+ keyframe_queries,**({"options": opts} if opts else {}),)return _COMPILED[key][email protected]_cache(maxsize=8)+def _inert_operands(head_dim: int, channels: int, device: torch.device) -> "tuple":+ """Never-read stand-ins for the keyframe operands, wrapped once per device.+ The kernel takes the keyframe tensors unconditionally but reads none of them when the+ tail is compiled out, so these only have to be *typed* right -- and since they never+ change, both the allocation and the ``from_dlpack`` wrap are hoisted here. That matters:+ a deterministic-stage launch is well under a millisecond, and seven per-call allocations+ and wraps measured as a fifth of it.+ """+ kv = _dyn_act(torch.zeros((1, head_dim), device=device, dtype=torch.bfloat16))+ i32 = _dyn(torch.zeros(1, device=device, dtype=torch.int32))+ q_kf = _dyn_act(torch.zeros((M, channels), device=device, dtype=torch.bfloat16))+ y_kf = _dyn_act(torch.zeros((M, channels), device=device, dtype=torch.bfloat16))+ return kv, i32, q_kf, y_kf+++class _KeyframeOperands(NamedTuple):+ """The five keyframe tensors the kernel takes, plus the two compile-key facts."""++ #: The caller supplied keyframe tensors -- so this launch is the *joint* operator, whose+ #: window rule is clamp-and-mask rather than NATTEN's inward shift. Deliberately not+ #: conditioned on the plane count: the rule is a property of the operator, and an earlier+ #: version keyed both it and the tail off "has planes", which quietly served two different+ #: window rules depending on whether a caller passed zero planes or planes nothing+ #: selected. With no planes the tail is a zero-trip loop over real, empty tables.+ enabled: bool+ k: torch.Tensor+ v: torch.Tensor+ slots: torch.Tensor+ planes: torch.Tensor+ counts: torch.Tensor+++def _keyframe_operands(+ k_keyframes: torch.Tensor | None,+ v_keyframes: torch.Tensor | None,+ keyframe_slots: torch.Tensor | None,+ t: int,+ h: int,+ w: int,+ num_heads: int,+ head_dim: int,+ tile_t: int,+ device: torch.device,+) -> _KeyframeOperands:+ """Validate and lay out the keyframe operands, or hand back inert placeholders.+ Disabled is not "n_kf = 0 planes": it compiles the tail out entirely, so the+ no-keyframe kernel keeps the trace it had before this existed. The placeholder+ tensors below are never read.+ """++ if k_keyframes is None or v_keyframes is None or keyframe_slots is None:+ if not (k_keyframes is None and v_keyframes is None and keyframe_slots is None):+ raise ValueError("k_keyframes, v_keyframes and keyframe_slots must be given together or not at all")+ inert_kv, inert_i32, _, _ = _inert_operands(head_dim, 1, device)+ return _KeyframeOperands(False, inert_kv, inert_kv, inert_i32, inert_i32, inert_i32)++ if k_keyframes.shape != v_keyframes.shape:+ raise ValueError(f"keyframe k/v shapes differ: {tuple(k_keyframes.shape)} {tuple(v_keyframes.shape)}")+ if k_keyframes.ndim != 6 or k_keyframes.shape[0] != 1:+ raise ValueError(f"keyframe k/v must be (1, n_kf, H, W, NH, HD), got {tuple(k_keyframes.shape)}")+ n_kf, kf_h, kf_w, kf_nh, kf_hd = (int(s) for s in k_keyframes.shape[1:])+ if n_kf == 0:+ # Still the joint operator, so still the joint binary -- only with nothing for the+ # tail to iterate. The tables are real and correctly sized (every one of them is+ # indexed by a query tile, not by a plane) so the loop is a zero-trip, not an+ # out-of-bounds read on a placeholder.+ n_tiles_t = -(-t // tile_t)+ inert_kv, _, _, _ = _inert_operands(head_dim, 1, device)+ return _KeyframeOperands(+ enabled=True,+ k=inert_kv,+ v=inert_kv,+ slots=_dyn(torch.full((t * KEYFRAME_CONTEXT_SLOTS,), -1, dtype=torch.int32, device=device)),+ planes=_dyn(torch.full((n_tiles_t,), -1, dtype=torch.int32, device=device)),+ counts=_dyn(torch.zeros(n_tiles_t, dtype=torch.int32, device=device)),+ )+ if (kf_h, kf_w, kf_nh, kf_hd) != (h, w, num_heads, head_dim):+ raise ValueError(+ f"keyframe k/v must share the video grid and head layout: got {(kf_h, kf_w, kf_nh, kf_hd)}, "+ f"expected {(h, w, num_heads, head_dim)}"+ )+ if tuple(keyframe_slots.shape) != (t, KEYFRAME_CONTEXT_SLOTS):+ raise ValueError(f"keyframe_slots must be {(t, KEYFRAME_CONTEXT_SLOTS)}, got {tuple(keyframe_slots.shape)}")+ slots_cpu = keyframe_slots.detach().to(device="cpu", dtype=torch.int32)+ if int(slots_cpu.max()) >= n_kf:+ raise ValueError(f"keyframe_slots names a plane past n_kf={n_kf}")+ # A repeated plane in one row would be counted twice by the local pass's own logic --+ # the tail visits distinct planes, so a duplicate silently loses a slot instead.+ for row in range(t):+ live = [int(p) for p in slots_cpu[row].tolist() if p >= 0]+ if len(set(live)) != len(live):+ raise ValueError(f"keyframe_slots row {row} repeats a plane: {live}")++ # ``SLOTS * tile_t``, not ``min(n_kf, ...)``: the stride into ``planes`` is a compile-time+ # constant of the tile, so it must not move with the anchor layout. Slack columns are -1+ # and cost one int32 each; a data-dependent stride costs a recompile.+ planes, _ = tile_plane_union(slots_cpu, tile_t=tile_t, max_planes=KEYFRAME_CONTEXT_SLOTS * tile_t)+ counts = (planes >= 0).sum(dim=-1).to(torch.int32)++ def rows(x: torch.Tensor) -> torch.Tensor:+ return x[0].reshape(n_kf, h, w, num_heads * head_dim).to(dtype=torch.bfloat16).contiguous().view(-1, head_dim)++ return _KeyframeOperands(+ enabled=True,+ k=_dyn_act(rows(k_keyframes)),+ v=_dyn_act(rows(v_keyframes)),+ slots=_dyn(slots_cpu.reshape(-1).to(device=device)),+ planes=_dyn(planes.reshape(-1).to(device=device)),+ counts=_dyn(counts.to(device=device)),+ )++def run_na_attention(q: torch.Tensor,k: torch.Tensor,@@ -433,10 +793,29 @@ def run_na_attention_bound(kernel_size: "tuple[int, int, int]",k_bound: torch.Tensor,tile_thw: "tuple[int, int, int] | None" = None,-) -> torch.Tensor:+ k_keyframes: torch.Tensor | None = None,+ v_keyframes: torch.Tensor | None = None,+ keyframe_slots: torch.Tensor | None = None,+ q_keyframes: torch.Tensor | None = None,+ keyframe_times: torch.Tensor | None = None,+) -> "torch.Tensor | tuple[torch.Tensor, torch.Tensor]":""":func:`run_na_attention` with the softmax bound already computed.``k_bound`` is the 0-d tensor :func:`ltx_kernels.vae.softmax_row_bound` returns; itis read by the kernel as an operand, so it never leaves the device.+ Keyframe context is optional and all-or-nothing. ``k_keyframes`` / ``v_keyframes`` are+ ``(1, n_kf, H, W, NH, HD)`` -- single-frame planes on the query grid's spatial lattice,+ projected by the *same* QKV and normed by the same ``k_norm`` as ``k`` (the softmax+ bound is only a bound because of that), and already carrying their float chunk-center+ temporal RoPE. ``keyframe_slots`` is the ``(T, S)`` int32 map from+ :func:`ltx_kernels.vae.keyframe_slots.nearest_keyframe_slots`.+ Each video query then attends, in one softmax, to its local ``kt x kh x kw`` window and+ to the ``kh x kw`` spatial window of every plane its row of ``keyframe_slots`` names --+ with no bound on how far those planes are in time.+ Passing ``q_keyframes`` (and ``keyframe_times``) additionally runs the *keyframe* stream's+ own queries, and the return becomes ``(video_out, keyframe_out)``. A keyframe query shares+ one softmax over its own plane's ``kh x kw`` window and that window on each of the <=2+ nearest video latent frames -- local motion context around the anchor, deliberately not+ the video kernel's full ``kt`` reach."""if not na_attn_available(q.device.index or 0):raise RuntimeError(UNSUPPORTED_MESSAGE)@@ -462,13 +841,54 @@ def run_na_attention_bound(# M extra rows absorb the stores of out-of-range lanes in partial tiles.y_buf = torch.empty((T * H * W + M, NH * hd), device=q_.device, dtype=torch.bfloat16)- compiled = _compile(kernel_size=kernel_size, tile_thw=(tt, th, tw))+ kf = _keyframe_operands(k_keyframes, v_keyframes, keyframe_slots, T, H, W, NH, hd, tt, q_.device)++ n_kf = int(k_keyframes.shape[1]) if k_keyframes is not None else 0+ # Keyframe query tiles: one plane each, on the video tile's spatial shape. Compiled in+ # only when there is a plane to run -- unlike ``kf.enabled``, which selects the *window+ # rule* and so must not depend on the plane count.+ # A keyframe query tile borrows the video tile's spatial shape, so the two grids share+ # their h/w divisors and the kernel unflattens both with ``grid_h * grid_w``.+ kfq = q_keyframes is not None and kf.enabled and n_kf > 0+ if kfq:+ if tuple(q_keyframes.shape) != (1, n_kf, H, W, NH, hd):+ raise ValueError(f"q_keyframes must be {(1, n_kf, H, W, NH, hd)}, got {tuple(q_keyframes.shape)}")+ q_kf_rows = _as_rows(q_keyframes[0].reshape(n_kf, H, W, NH * hd).to(dtype=torch.bfloat16))+ video_frames = nearest_video_frames(keyframe_times, T) if keyframe_times is not None else None+ if video_frames is None:+ raise ValueError("q_keyframes requires keyframe_times, to place each plane on the video grid")+ y_kf_buf = torch.empty((n_kf * H * W + M, NH * hd), device=q_.device, dtype=torch.bfloat16)+ y_kf_dyn = _dyn_act(y_kf_buf)+ q_kf_ = _dyn_act(q_kf_rows)+ kfv = _dyn(video_frames.reshape(-1).to(device=q_.device))+ kfv_counts = _dyn((video_frames >= 0).sum(dim=-1).to(dtype=torch.int32, device=q_.device))+ n_kfq_tiles = n_kf * grid_h * grid_w+ else:+ _, _, q_kf_, y_kf_dyn = _inert_operands(hd, NH * hd, q_.device)+ kfv = kfv_counts = kf.counts+ n_kfq_tiles = 0++ compiled = _compile(+ kernel_size=kernel_size,+ tile_thw=(tt, th, tw),+ keyframes=kf.enabled,+ keyframe_queries=kfq,+ )compiled(_dyn_act(q_),_dyn_act(k_),_dyn_act(v_),_dyn_act(y_buf),_dyn(k_bound.detach().reshape(1).float().to(device=q_.device)),+ kf.k,+ kf.v,+ kf.slots,+ kf.planes,+ kf.counts,+ q_kf_,+ y_kf_dyn,+ kfv,+ kfv_counts,T,H,W,@@ -478,5 +898,14 @@ def run_na_attention_bound(n_ctas,grid_h * grid_w,grid_w,+ n_kf,+ n_kfq_tiles,)- return y_buf[: T * H * W].view(1, T, H, W, NH * hd).to(dtype=q.dtype)+ video_out = y_buf[: T * H * W].view(1, T, H, W, NH * hd).to(dtype=q.dtype)+ if q_keyframes is None:+ return video_out+ if not kfq:+ # Keyframe queries asked for over an empty stream: no output buffer was allocated,+ # so return the empty shape rather than an arity the call site cannot predict.+ return video_out, q.new_empty((1, 0, H, W, NH * hd))+ return video_out, y_kf_buf[: n_kf * H * W].view(1, n_kf, H, W, NH * hd).to(dtype=q.dtype)diff --git a/packages/ltx-pipelines/CLAUDE.md b/packages/ltx-pipelines/CLAUDE.mdindex aa74c39..e6b28a0 100644--- a/packages/ltx-pipelines/CLAUDE.md+++ b/packages/ltx-pipelines/CLAUDE.md@@ -18,11 +18,11 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for|----------|------|--------|-------|---------|----------|| `TI2VidOneStagePipeline` | `ti2vid_one_stage.py` | 1 | Full | Euler | Simple text/image-to-video || `T2AOneStagePipeline` | `t2a_one_stage.py` | 1 | Full | Euler | Text-to-audio (audio-only output, no video branch) |-| `TI2VidTwoStagesPipeline` | `ti2vid_two_stages.py` | 2 | Full + distilled LoRA | Euler | Production quality |-| `TI2VidTwoStagesHQPipeline` | `ti2vid_two_stages_hq.py` | 2 | Full + distilled LoRA (both stages) | Res2s | Highest quality, fewer steps |+| `TI2VidTwoStagesPipeline` | `ti2vid_two_stages.py` | 2 | Full + distilled LoRA | Euler | Guided two-stage (CFG/STG) |+| `TI2VidTwoStagesHQPipeline` | `ti2vid_two_stages_hq.py` | 2 | Full + distilled LoRA (both stages) | Res2s | Guided two-stage, res_2s, fewer steps || `A2VidPipelineTwoStage` | `a2vid_two_stage.py` | 2 | Full + distilled LoRA | Euler | Audio-conditioned video || `KeyframeInterpolationPipeline` | `keyframe_interpolation.py` | 2 | Full + distilled LoRA | Euler | Keyframe interpolation |-| `DFRPipeline` | `dfr_pipeline.py` | 2 (+ optional tiled temporal) | Keyframe-slot SFT + distilled LoRA (+ detailing IC-LoRA stage 2) | Euler | Keyframe slots → spatial detailing → optional tiled temporal x2 |+| `DFRPipeline` | `dfr_pipeline.py` | 2 (+ optional tiled temporal) | Distilled checkpoint + detailing IC-LoRA stage 2 | Euler | Production quality (keyframes + detailing + optional temporal x2) || `DistilledPipeline` | `distilled.py` | 2 | Distilled only | Euler (stage 1: ancestral on 2.5+) | Fastest inference || `ICLoraPipeline` | `ic_lora.py` | 2 | Distilled only | Euler | Video-to-video with IC-LoRA control || `DubItPipeline` | `dubit.py` | 2 | Distilled only | Euler | Dub-It with IC-LoRA + audio ref conditioning |@@ -47,8 +47,7 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for- No default LoRAs. `loras` param defaults to empty list/tuple. `DEFAULT_LORA_STRENGTH = 1.0`.- Two-stage non-distilled pipelines require `distilled_lora` (applied to stage 2 only in TI2Vid/A2Vid/Keyframe).- HQ applies distilled LoRA to **both** stages with separate `distilled_lora_strength_stage_1` / `_stage_2` params.-- DFR also applies distilled LoRA to **both** stages (shared stage object for stage 1 /- temporal rounds; stage 2 may add a detailing IC-LoRA via `with_loras`).+- DFR loads a distilled checkpoint (no distilled LoRA). Stage 2 adds a detailing IC-LoRA via `with_loras`.## Shared building blocks (`utils/blocks.py`)@@ -57,7 +56,7 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for- `ImageConditioner` / `AudioConditioner` -- temporary encoder scope; builds encoder, passes to callable, frees. `ImageConditioner` is additionally the single owner of the image-conditioning CRF: `resolve_crf(images)` (called near the top of every pipeline's `__call__`) fills in the H.264 CRF of any `ImageConditioningInput` that left it unset, reading it from the checkpoint's `model_version` (`detect_params`, lazily and cached). So omitting `crf` means "use what matches this model" (33 through LTX-2.3, 18 from 2.4), while an explicit `crf` -- including `0` for no re-compression -- is always honoured.- `VideoUpsampler` -- 2x spatial upsampling via encoder + upsampler.- `VideoDecoder` / `AudioDecoder` -- latent-to-pixel decoding (iterator for video, `Audio` for audio). `VideoDecoder` takes a single decoder `checkpoint_path` and `diffvae_optimization` (`DiffVAEMode`, default `CHUNKED_EAGER`); pipelines pass `model_paths.video_vae()`, the same file `ImageConditioner` and `VideoUpsampler` build their encoder from -- a video VAE checkpoint carries encoder and decoder together. Decoder kind (conv vs diffusion) is chosen from checkpoint metadata (`is_diffusion_video_vae`); distilled DiffVAE uses fixed 2 Euler steps. CLI: `--video-vae-path` is the video VAE slot in both monolith (optional override; defaults via `ModelPaths.from_monolith`) and split modes; `--diffvae-optimization` (see `docs/optimization.md#diffusion-vae-decoder` for mode meanings and relative compile/runtime/VRAM factors). Multi-GPU pipelines (`*_mgpu.py`) accept the same flags and wrap the loaded decoder in `DistributedVideoDecoder`.-- `DurationPredictor` -- predicts a frame count from `PromptEncoder`'s connector token outputs via `DurationHead` (`ltx_core.duration_head`), snapped to the VAE's temporal grid. Unlike other blocks, it holds the built model directly (`__init__` takes a `DurationHead`, not a builder) since the checkpoint is only a few MB -- no build-on-call/free-on-exit needed. Pipelines construct it via `DurationPredictor.from_checkpoint(checkpoint_path, dtype, device)`, which returns `None` instead of a predictor if the checkpoint has no `duration_head.*` weights (checkpoints predating LTX-2.5 / gemma4). Called with `(video_encoding, audio_encoding, frame_rate=...)` -- either may be `None` but not both. Wired into `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, and `T2AOneStagePipeline` (audio-only: `video_encoding=None`), plus their MGPU runners: when `num_frames` is omitted (`None`), `require_num_frames_source` (called at the top of `__call__`, before any work) raises immediately if no `DurationPredictor` is available, otherwise it's auto-predicted from the caption. The two-stage pipelines (`TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`) and their MGPU runners return the resolved `num_frames` as a third tuple element from `__call__`, so callers can compute `get_video_chunks_number` for the progress bar without duplicating the auto-duration fallback logic.+- `DurationPredictor` -- predicts a frame count from `PromptEncoder`'s connector token outputs via `DurationHead` (`ltx_core.duration_head`), snapped to the VAE's temporal grid. Unlike other blocks, it holds the built model directly (`__init__` takes a `DurationHead`, not a builder) since the checkpoint is only a few MB -- no build-on-call/free-on-exit needed. Pipelines construct it via `DurationPredictor.from_checkpoint(checkpoint_path, dtype, device)`, which returns `None` instead of a predictor if the checkpoint has no `duration_head.*` weights (checkpoints predating LTX-2.5 / gemma4). Called with `(video_encoding, audio_encoding, frame_rate=...)` -- either may be `None` but not both. Wired into `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, and `T2AOneStagePipeline` (audio-only: `video_encoding=None`), plus their MGPU runners: when `num_frames` is omitted (`None`), `require_num_frames_source` (called at the top of `__call__`, before any work) raises immediately if no `DurationPredictor` is available, otherwise it's auto-predicted from the caption. The two-stage pipelines (`TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, `A2VidPipelineTwoStage`) and their MGPU runners return the resolved `num_frames` as a third tuple element from `__call__`, so callers can compute `get_video_chunks_number` for the progress bar without duplicating the auto-duration fallback logic.### Memory management@@ -80,47 +79,83 @@ Guided denoisers batch all guidance passes into a **single transformer call**: s## Per-pipeline unique features- **HQ**: Res2s second-order sampler for **both** stages, latent-dependent sigma schedule, distilled LoRA on both stages with separate strengths.-- **A2Vid**: Audio frozen in both stages (`frozen=True, noise_scale=0.0`). That zeros `denoise_mask` and forces audio `Modality.sigma=0` (prompt AdaLN / a2v gate). Returns original audio (not VAE-decoded); no `AudioDecoder`.+- **A2Vid**: Audio frozen in both stages (`frozen=True, noise_scale=0.0`). That zeros `denoise_mask` and forces audio `Modality.sigma=0` (prompt AdaLN / a2v gate). Returns original audio (not VAE-decoded); no `AudioDecoder`. CLI `--num-frames` and `--audio-max-duration` are mutually exclusive: with `--audio-max-duration`, `num_frames` is omitted (`None`) and derived from the decoded clip (capped by remaining audio after `--audio-start-time`); with `--num-frames` or neither, that frame count is used and audio is clipped to match. `__call__` returns `(video, audio, num_frames, tiling_config)` like the other two-stage pipelines.- **IC-LoRA**: `VideoConditionByReferenceLatent`, `reference_downscale_factor` from LoRA metadata, `skip_stage_2`, attention mask downsampling. Stage 2 is LoRA-free and uses `combined_image_conditionings` (no IC-LoRA conditioning).- **Dub-It**: Standalone pipeline; IC reference **video** helpers in `iclora_utils.py`, Dub-It-only **audio** patchify/negative positions in `dubit.py`. Appends frozen audio-reference tokens via `AudioConditionByReferenceLatent` (ltx-core), matching video token order (`[target | ref]`) while keeping reference RoPE positions negative (training-compatible). Single IC-LoRA on both stages; full IC-LoRA video conditioning at stage 1 and 2; stage-2 audio is frozen with S1 latent as initial state and uses S1-derived ref. Final audio decoded from stage 1 latent. The Dub-It CLI does not expose `--conditioning-attention-mask`; use `ic_lora.py` if you need spatial IC attention masking.- **Keyframe**: Uses `image_conditionings_by_adding_guiding_latent` in both stages (all frames as keyframe guidance, no replacement) -- unlike TI2Vid which uses `combined_image_conditionings` (frame_idx=0 replaces, others guide).- **Retake**: `TemporalRegionMask` for selective time-window regeneration. `regenerate_video`/`regenerate_audio` flags. Conditional distilled/full behavior.- **Distilled**: Single `self.stage` reused for both stages (not `stage_1`/`stage_2`). Stage 1's sampler is resolved in `__init__` from the checkpoint generation -- `should_use_ancestral_sampler(path)` (`detect_model_version(...) >= (2, 5)`) sets `self.use_ancestral_sampler`, so LTX-2.5+ uses `EulerAncestralDiffusionStep(eta=1.0, s_noise=1.0)` (the reference sampler's own defaults) + `euler_ancestral_denoising_loop` and older checkpoints keep plain Euler. There is no per-call override; assign the attribute before calling to pin a sampler (e.g. to A/B both on one checkpoint). `distilled_mgpu.py` detects per rank from the same checkpoint, so ranks stay symmetric. Stage 2 is always plain Euler -- its 3-step schedule is too short to remove freshly injected noise. The loop's noise seed is offset (`ANCESTRAL_NOISE_SEED_OFFSET`) so its first draw is not bit-identical to the initial `GaussianNoiser` noise.- **DFR** (Diffusion Fidelity Rendering, `dfr_pipeline.py` + its `dfr_layout.py` sidecar):- distilled-schedule pipeline on a keyframe-slot-capable **SFT** base with a **distilled LoRA**- (strength 1.0). Stage 1 (half-res) generates video + keyframe slots on an **x8-border segment+ operator how-to (resolution, fps, memory) is [Running DFR](docs/pipelines.md#running-dfr).+ distilled-schedule pipeline on a keyframe-slot-capable **distilled checkpoint**, plus an x2+ detailing IC-LoRA (required; ``--detailing-lora``). Stage 1 (half-res) generates video + keyframe slots on an **x8-border segmentgrid**: pad ``(num_frames-1)`` up to a multiple of S (prefer S=32 unless S=24 pads strictly less);positions ``S, 2S, …, N'-1``. Half-res video is reserved for IC-LoRA; video and slot keyframes are- spatially latent-upsampled. Stage 2 jointly denoises with distilled LoRA and an optional x2- detailing IC-LoRA (no default -- pass ``--detailing-lora`` to enable it; ``VideoConditionByReferenceLatent`` on the+ spatially latent-upsampled. Stage 2 jointly denoises with the distilled weights and the x2+ detailing IC-LoRA (``VideoConditionByReferenceLatent`` on thereserved half-res stage-1 video, ``STAGE_2_DISTILLED_SIGMAS``). Shipped audio is **stage 1's**:stage 2 still runs an audio pass (video needs the cross-modal attention) but re-noises audio under- the detailing LoRA, and the temporal rounds pass ``audio=None``, so nothing refines it afterwards.- Optional ``temporal_upsample_rounds`` (0–2): each round temporally x2-upsamples, partitions into+ the detailing LoRA. Temporal tiles pass frozen stage-1 audio sliced to the tile's playback+ *time* window (uncapped fps vs stage-1 duration) and retiled onto the snapped-fps token count+ for cross-attention only; they do not refine or ship audio.+ Optional ``temporal_upscalings`` (0–2): each round temporally x2-upsamples, partitions into``2**round`` keyframe-seam tiles with a one-segment lead-in on non-first tiles, invents- mid-segment slots per tile, and densifies with ancestral Euler (η=0.5).+ mid-segment slots per tile, and densifies with ancestral Euler (η=0.5). Partition/stitch uses+ ``dfr_layout.split_canvas_at_seams`` (remainder segments go to the leading tiles; core+ ``split_at_seams`` uses the same remainder rule). Optional+ ``spatial_upscalings`` (1 or 2, CLI ``--spatial-upscalings``): ``1`` is stage 1 at ``h/2`` and+ stage 2 at ``h``; ``2`` is stage 1 at ``h/4``, stage 2 at ``h/2``, then a full-res spatial+ detailing epilogue at ``h``. Carry keyframes are decoded one plane at a time, Lanczos-stretched+ x2 in RGB, and encoded as ``VideoConditionByKeyframeIndex`` (strength 1); only the video latent is+ spatially upsampled, and the previous-stage video is the IC-LoRA reference. Detailing LoRA+ strength is hardcoded to 0.5. The epilogue is a single denoising loop over the full-res canvas,+ tiled *inside* the transformer call by ``_TiledModelWrapper`` -- the single-GPU twin of the+ multi-GPU ``TiledDataParallelModelWrapper``, sharing ``VideoModalityTilingHelper`` and its blend+ masks, installed via ``DiffusionStage.with_model_wrapper``. So every Euler step reconciles the+ overlap, and conditionings are filtered per tile at the token level rather than cropped by hand.+ Wrap the *model*, not the builder: a wrapping builder hides ``StreamingModelBuilder`` from+ ``_is_streaming``, so ``--offload`` would skip the streaming teardown. Temporal tiles are cut on the last round's window seams,+ which makes their masks rectangular (lead-in denoised for context, then dropped; the earlier tile+ keeps the seam cell), so time windows never blend into each other; 2x2 spatial tiles use 12 latent+ cells of blended overlap.+ ``height``/``width`` are always the **final** output; ``2`` requires they divide 128.+Three invariants worth knowing before touching the temporal rounds:- **Stitch handover is exactly at the shared keyframe.** A tile's local latent 0 is an *image*latent (1 pixel frame) and local latent 1 was denoised against it; neither may be spliced intothe mid-canvas stream. The earlier tile keeps through its trailing seam latent and the later tileresumes strictly after the KF (``drop_latent_prefix`` covers lead-in + shared seam). Handing over*before* the KF loses the synchronization point and shows as a jump just before the seam.- - **Conditioning fps is capped at 60** (``_MAX_CONDITIONING_FPS``), independently of playback fps.- RoPE time is ``pixel_frame / fps``, so a 120 fps time base halves every token's temporal span- versus the trained distribution and the model can no longer lay out the 8 pixel frames inside a- latent -- it decodes as a motion spike at each 8-frame latent border followed by a stall. Only- decode/encode use playback fps.- - **Image conditioning is tile-local.** ``frame_idx=0`` means the *tile's* first frame, so- re-applying the opening image on a non-first tile pins the wrong frame onto the seam; only images- that fall inside the window are re-attached, remapped to local indices.+ - **Conditioning fps snaps to 60 above 30** (``_conditioning_fps``), independently of playback fps.+ RoPE time is ``pixel_frame / fps``, so a 48 or 120 fps time base is outside the trained+ distribution and the model can no longer lay out the 8 pixel frames inside a latent -- it+ decodes as a motion spike at each 8-frame latent border followed by a stall. 24 fps plus one+ temporal upsample still ships 48 fps; only the transformer uses 60. Decode/encode use playback fps.+ Audio duration is ``frames / fps`` too, so stages 1 and 2 pass ``audio_fps=frame_rate`` -- otherwise+ a 48 fps run would ship 121/60 s of sound against a 121/48 s picture.+ - **Image conditioning is tile-local.** ``frame_idx`` is a pixel index on the canvas the caller+ requested; each temporal round maps it to ``frame_idx * 2**round`` before the window test.+ After re-basing, ``frame_idx=0`` means the *tile's* first frame, so only images that fall+ inside the window are re-attached. The spatial epilogue uses the same scale+ (``2**temporal_upscalings``).The canvas may pad the tail up to a whole segment, but the caller always gets``(requested_frames - 1) * 2**rounds + 1`` frames: the excess is trimmed before decode (always ona latent boundary, since ``requested - 1`` is a multiple of the VAE temporal scale), and audio iscut to the video's duration. CLI: ``--detailing-lora``, ``--temporal-upsampler-path``,- ``--temporal-upsample-rounds``.+ ``--temporal-upscalings``, ``--spatial-upscalings``.No ``--num-generated-keyframes``.+ Returns ``PipelineOutput`` (same type as the other video pipelines): ``video``, ``audio``,+ ``num_frames``, ``tiling_config``, ``keyframes``, ``video_latent``. Prefer attribute access.+ ``video`` is decoded with ``decode_video(keyframes=)`` when slots exist. Re-decode needs the+ latent and the keyframes together (both optional fields; DFR fills them).+ ``keyframes.pixel_frame_indices`` are on the+ **final** (post-round) pixel grid, and keyframes landing past the tail trim are dropped rather+ than shipped pointing off-canvas. Other pipelines fill ``keyframes`` only when they produced+ generated slots already at final output resolution; ``video_latent`` may be ``None`` when the+ pipeline does not retain the latent for re-decode.+## Image conditioning helpers (`utils/helpers.py`)- `combined_image_conditionings()` -- images with `frame_idx==0` replace latent (`VideoConditionByLatentIndex`), others guide (`VideoConditionByKeyframeIndex`).@@ -145,18 +180,23 @@ compression at those positions. Slots may optionally carry ``initial_keyframes``(an `int` requests evenly spaced **interior** keyframes; a sequence gives explicit indices).CLI: `--num-generated-keyframes` via `add_generated_keyframes_arg`. `DFRPipeline` always usesthe x8-border segment grid from `dfr_layout.resolve_canvas` and does **not** expose that arg;- it adds `--detailing-lora` (optional, no default),- `--temporal-upsampler-path`, `--temporal-upsample-rounds`.+ it adds `--detailing-lora` (required),+ `--temporal-upsampler-path`, `--temporal-upscalings`.- **Validation**: `DiffusionStage.supports_generated_keyframes` reads the checkpoint config, and`__call__` raises if slots are requested without it -- each keyframe costs a full latent frame oftokens, so silently degrading would waste 16-31% of the token budget.- **Cost**: one latent frame of tokens per keyframe, yielding 1 pixel frame instead of 8. At512x768/241f, 5 keyframes is +16% tokens (~1.35x attention); at 1088x1920/121f it is +31% (~1.72x).+- **On ``PipelineOutput``**: ``result.keyframes`` is filled only when those slots already sit at+ final output resolution (DFR after upsample/rounds; TI2Vid one-stage when requested). Two-stage+ / distilled leave it ``None`` -- stage-1 half-res leftovers are not shipped. ``result.video_latent``+ is the tensor passed to the video decoder when retained, otherwise ``None``.- **Reading the keyframes back**: `LatentState.generated_keyframes` (`(B, C, K, H, W)`), extracted by`clear_conditioning` using the `generated_keyframe_layout` recorded on the state -- exact, notpositional slicing. From outside a pipeline, substitute `RecordingDiffusionStage` for- `pipeline.stage`. Decode each keyframe as a standalone one-frame clip; a K-frame causal decode- would blend slots that were never adjacent. See `internal/scripts/generated_keyframe_diagnostics.py`.+ `pipeline.stage` to inspect per-stage states (including half-res leftovers). Decode each keyframe+ as a standalone one-frame clip; a K-frame causal decode would blend slots that were never adjacent.+ See `internal/scripts/generated_keyframe_diagnostics.py`.- **Invariants**: slots are *appended* (which preserves target noise across a same-seedkeyframes/no-keyframes A/B at B=1) and pass `attention_mask=None` (a dense `(B, T, T)` mask wouldbe ~1.8 GB at 30k tokens and would disable FA3/FA4).diff --git a/packages/ltx-pipelines/README.md b/packages/ltx-pipelines/README.mdindex b8b0494..a088df2 100644--- a/packages/ltx-pipelines/README.md+++ b/packages/ltx-pipelines/README.md@@ -9,7 +9,7 @@ Pipelines are built using building blocks from [`ltx-core`](../ltx-core/) (sched- 🎬 **Multiple Pipeline Types**: Text-to-video, image-to-video, video-to-video, audio-to-video, keyframe interpolation, detail-fidelity rendering, and retake- 🎥 **HDR / EXR**: Native `--hdr` EXR conditioning with EXR + BT.2020/HLG output, plus dedicated HDR IC-LoRA- ⚡ **Optimized Performance**: Support for FP8 transformers, gradient estimation, and memory optimization-- 🎯 **Production Ready**: Two-stage pipelines for best quality output+- 🎯 **Production quality**: [`DFRPipeline`](docs/pipelines.md#12-dfrpipeline) for best output; DistilledPipeline for speed- 🔧 **LoRA Support**: Easy integration with trained LoRA adapters- 📦 **Self-Contained**: Handles model loading, encoding, decoding, and file I/O- 🚀 **CLI Support**: All pipelines can be run as command-line scripts@@ -30,6 +30,8 @@ python -m ltx_pipelines.ti2vid_two_stages \--output-path output.mp4```+DFR uses the **same distilled transformer** as DistilledPipeline, plus `--detailing-lora` (no `--distilled-lora`). Copy-paste commands, 4K sizes, fps, and memory: [Running DFR](docs/pipelines.md#running-dfr).+See [Installation & Usage](docs/installation.md) for full setup, CLI modules, and shared flags.## 📚 Documentation@@ -38,7 +40,7 @@ See [Installation & Usage](docs/installation.md) for full setup, CLI modules, an| ----- | ----------- || [Installation & Usage](docs/installation.md) | Install, requirements, running pipelines from the CLI, common flags || [Pipeline Selection Guide](docs/pipeline-selection.md) | Decision tree + feature comparison to pick the right pipeline |-| [Available Pipelines](docs/pipelines.md) | Full reference for all 11 pipelines |+| [Available Pipelines](docs/pipelines.md) | Full reference for all 12 pipelines, including [Running DFR](docs/pipelines.md#running-dfr) || [Conditioning Types](docs/conditioning.md) | Image and video conditioning methods || [HDR Support](docs/hdr.md) | Native EXR/`--hdr` colour spaces, I/O, and examples || [Multimodal Guidance](docs/multimodal-guidance.md) | CFG / STG / modality guidance parameters and tuning |diff --git a/packages/ltx-pipelines/docs/installation.md b/packages/ltx-pipelines/docs/installation.mdindex d8c08c7..7a3a182 100644--- a/packages/ltx-pipelines/docs/installation.md+++ b/packages/ltx-pipelines/docs/installation.md@@ -15,7 +15,9 @@ pip install -e packages/ltx-pipelines- **LTX-2 Model Checkpoint** - Local `.safetensors` file- **Gemma Text Encoder** - Local Gemma model directory- **Spatial Upscaler** - Required by two-stage pipelines, for the upsampling stage-- **Distilled LoRA** - Required by two-stage non-distilled pipelines, used for the stage-2 refinement+- **Distilled LoRA** - Required by two-stage non-distilled pipelines (TI2Vid, Keyframe, A2Vid), used for the stage-2 refinement. Not used by DFR.+- **Detailing IC-LoRA** - Required by DFR (`--detailing-lora`)+- **Temporal Upscaler** - Required by DFR when `--temporal-upscalings` is 1 or 2## Running Pipelines@@ -45,6 +47,8 @@ Every pipeline CLI accepts one of two mutually exclusive path sets.--checkpoint-path path/to/checkpoint.safetensors --gemma-root path/to/gemma```+DistilledPipeline and DFR use `--distilled-checkpoint-path` instead of `--checkpoint-path`.+**Split** (Comfy-aligned) -- one file per component. Pass the subset this pipeline needs(unused flags may be omitted; the pipeline validates required slots on `ModelPaths`):@@ -65,8 +69,9 @@ what pipeline constructors take.### Available pipeline modules-- `ltx_pipelines.distilled` - Fast text/image-to-video pipeline using only the distilled model (recommended). ([docs](pipelines.md#4-distilledpipeline), [source](../src/ltx_pipelines/distilled.py))-- `ltx_pipelines.dfr_pipeline` - Detail-fidelity rendering: generated keyframes, spatial detailing, optional temporal 2x/4x. ([docs](pipelines.md#12-dfrpipeline), [source](../src/ltx_pipelines/dfr_pipeline.py))+- `ltx_pipelines.distilled` - Fast text/image-to-video pipeline using only the distilled model (starting point). ([docs](pipelines.md#4-distilledpipeline), [source](../src/ltx_pipelines/distilled.py))+- `ltx_pipelines.dfr_pipeline` - Production-quality text/image-to-video: distilled checkpoint, generated keyframes, spatial detailing, optional temporal 2x/4x. ([docs](pipelines.md#12-dfrpipeline), [how to run](pipelines.md#running-dfr), [source](../src/ltx_pipelines/dfr_pipeline.py))+- `ltx_pipelines.dfr_mgpu` - Multi-GPU DFR: sequence parallelism on both stages. ([docs](multigpu/README.md), [source](../src/ltx_pipelines/dfr_mgpu.py))- `ltx_pipelines.ti2vid_two_stages` - Two-stage text/image-to-video. ([docs](pipelines.md#1-ti2vidtwostagespipeline), [source](../src/ltx_pipelines/ti2vid_two_stages.py))- `ltx_pipelines.ti2vid_two_stages_hq` - Two-stage text/image-to-video (different sampler, better quality). ([docs](pipelines.md#2-ti2vidtwostageshqpipeline), [source](../src/ltx_pipelines/ti2vid_two_stages_hq.py))- `ltx_pipelines.ti2vid_one_stage` - Single-stage text/image-to-video. ([docs](pipelines.md#3-ti2vidonestagepipeline), [source](../src/ltx_pipelines/ti2vid_one_stage.py))@@ -90,9 +95,9 @@ These flags are shared across the pipeline CLIs (they come from a common base pa- `--offload {none,cpu,disk}` - offload transformer weights to reduce peak GPU memory. `cpu` holds them in system RAM; `disk` streams them from disk when RAM is also limited (slower). Default `none`.- `--quantization {fp8-cast,fp8-scaled-mm}` - run the transformer in FP8 to cut memory. `fp8-cast` downcasts a bf16 checkpoint on the fly (any FP8-capable GPU); `fp8-scaled-mm` expects an fp8 checkpoint and native FP8 support (best on Hopper+).- `--max-batch-size <int>` - max batch per transformer forward pass (default 1). Higher values reduce layer-streaming transfers at the cost of peak memory.-- `--compile [key=value ...]` - enable `torch.compile`, optionally overriding the compilation config.+- `--compile [key=value ...]` - enable `torch.compile`. Bare `--compile` compiles without CUDA graphs. CUDA-graph modes (`capture=true`, `mode=reduce-overhead`, `mode=max-autotune`) need `--offload cpu` or `disk` on single GPU (streaming reuses GPU weight slots; a registry by itself does not). `capture=true` captures one graph per (shape, perturbation); `max_video_tokens` / `max_audio_tokens` size a shared **static input** pool so those graphs do not each allocate their own activation buffers. See [Compilation](optimization.md#compilation-torchcompile).- `--lora <path> [strength]` - apply a LoRA (repeatable; default strength 1.0).- `--enhance-prompt` - rewrite the prompt with the built-in enhancer before generation.- `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}` - on pipelines that accept image / video conditioning (not Dub-It, HDR IC-LoRA, or T2A): declare the source colour space for EXR stills / EXR-frame folders. Required whenever any EXR input is passed; omit for SDR. With `--hdr` set, encode writes half EXR frames plus a BT.2020/HLG master. See [HDR Support](hdr.md).- `--video-vae-path <path>` - video VAE `.safetensors` (encoder + decoder). Split: the `vae/` component. Monolith: optional override of the VAE bundled in `--checkpoint-path`/`--distilled-checkpoint-path`. When it is a diffusion VAE, decoding builds a `DiffusionVideoDecoder`, which for best performance requires the `natten` extra. See [Optimization Tips](optimization.md#diffusion-vae-decoder).-- `--diffvae-optimization {chunked_eager,chunked_compile,combined_compile}` - DiffVAE decode preset (ignored for convolutional VAEs).+- `--diffvae-optimization {chunked_eager,chunked_compile,combined_compile,blackwell_dsl}` - DiffVAE decode preset (ignored for convolutional VAEs). `blackwell_dsl` is the fast path on datacenter Blackwell.diff --git a/packages/ltx-pipelines/docs/multigpu/README.md b/packages/ltx-pipelines/docs/multigpu/README.mdindex d42f0ae..7a829aa 100644--- a/packages/ltx-pipelines/docs/multigpu/README.md+++ b/packages/ltx-pipelines/docs/multigpu/README.md@@ -52,10 +52,12 @@ user-defined **runner** (a subclass of `MGPURunner`) in SPMD lockstep. A runner'builder (SP / TDP / distributed decoder / distributed Gemma). All builders share one`ModelRegistry` so the checkpoint loads from disk once per process.-Two runners are provided, each with a CLI:+Four runners are provided, each with a CLI:- [`ltx_pipelines.ti2vid_two_stages_mgpu`](../../src/ltx_pipelines/ti2vid_two_stages_mgpu.py) — SP stage 1 + TDP stage 2 + Accelerate Gemma + distributed VAE.+- [`ltx_pipelines.ti2vid_two_stages_hq_mgpu`](../../src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py) — SP stage 1 + TDP stage 2 (HQ sampler) + Accelerate Gemma + distributed VAE.- [`ltx_pipelines.distilled_mgpu`](../../src/ltx_pipelines/distilled_mgpu.py) — SP (shared stage) + Accelerate Gemma + distributed VAE.+- [`ltx_pipelines.dfr_mgpu`](../../src/ltx_pipelines/dfr_mgpu.py) — SP on both DFR stages (base + detailing) + Accelerate Gemma + distributed VAE.Checkpoint paths follow the same monolith **XOR** split contract as single-GPU CLIs:the parser builds a `ModelPaths` object and runners read only that (see@@ -72,7 +74,16 @@ python -m ltx_pipelines.ti2vid_two_stages_mgpu \--prompt "A beautiful sunset over the ocean" \--output-path output.mp4-# Same entrypoint with a Comfy-aligned split pack (subset of flags as needed)+# DFR on all visible GPUs (distilled checkpoint)+python -m ltx_pipelines.dfr_mgpu \+ --distilled-checkpoint-path path/to/distilled_checkpoint.safetensors \+ --detailing-lora path/to/detailing_lora.safetensors \+ --spatial-upsampler-path path/to/upsampler.safetensors \+ --gemma-root path/to/gemma \+ --prompt "A beautiful sunset over the ocean" \+ --output-path output.mp4++# Same entrypoint with a Comfy-aligned split pack (subset of flags as needed; TI2Vid shown)python -m ltx_pipelines.ti2vid_two_stages_mgpu \--transformer-path path/to/diffusion_models/ltx-….safetensors \--text-encoder-path path/to/text_encoders/gemma-….safetensors \diff --git a/packages/ltx-pipelines/docs/multigpu/controller.md b/packages/ltx-pipelines/docs/multigpu/controller.mdindex 1d0d0fe..b78dfd4 100644--- a/packages/ltx-pipelines/docs/multigpu/controller.md+++ b/packages/ltx-pipelines/docs/multigpu/controller.md@@ -48,7 +48,7 @@ class MyRunner(MGPURunner):@torch.inference_mode()def __call__(self, *, prompt: str, ...) -> Iterator[...]:- video, audio = self._pipeline(...)+ result = self._pipeline(...)yield output_path # __call__ MUST be a generator (use `yield`, even once)```diff --git a/packages/ltx-pipelines/docs/multigpu/pipeline-setup.md b/packages/ltx-pipelines/docs/multigpu/pipeline-setup.mdindex afebb9a..29d2c87 100644--- a/packages/ltx-pipelines/docs/multigpu/pipeline-setup.md+++ b/packages/ltx-pipelines/docs/multigpu/pipeline-setup.md@@ -114,7 +114,8 @@ skipped (`stored_sd` becomes a zero-copy view) and any swap/reset raises — savThe shipped runners are the reference: read[`ti2vid_two_stages_mgpu.py`](../../src/ltx_pipelines/ti2vid_two_stages_mgpu.py)-(`setup()` lines ~54–132) and-[`distilled_mgpu.py`](../../src/ltx_pipelines/distilled_mgpu.py). Each ends with a+(`setup()` lines ~54–132),+[`distilled_mgpu.py`](../../src/ltx_pipelines/distilled_mgpu.py), and+[`dfr_mgpu.py`](../../src/ltx_pipelines/dfr_mgpu.py). Each ends with a`__main__` block wiring the runner into an `MGPUController` behind the standardtwo-stage CLI parser.diff --git a/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md b/packages/ltx-pipelines/docs/multigpu/sequence-parallel.mdindex 8a5b427..95f2a5f 100644--- a/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md+++ b/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md@@ -17,8 +17,10 @@ reduction order changes. The all2all kernels move bytes only — the round-trip`gather(send(x)) == x` is byte-exact. SP is the appropriate choice whenever thesingle-GPU result is required at lower latency.-This is the default for **stage 1** (`ti2vid_two_stages_mgpu`) and the **shared stage**-(`distilled_mgpu`, where one SP wrapping covers both the half-res and full-res calls).+This is the default for **stage 1** (`ti2vid_two_stages_mgpu`), the **shared stage**+(`distilled_mgpu`, where one SP wrapping covers both the half-res and full-res calls),+and **both DFR stages** (`dfr_mgpu`: `stage` and `stage_detailing` share one+`AttentionManager`, sized for 4K ~300-frame generation).## How the forward pass works@@ -96,5 +98,7 @@ pipeline.stage_1._transformer_builder = SequenceParallelBuilder(`max_tokens` must cover the largest step. Reference: stage 1 at 512x768x121 is~6k video tokens; the distilled shared stage's full-res call (1024x1536x121) is-~24k — both ship with `sp_max_tokens=32768`. Exceeding it raises with a clear+~24k — both ship with `sp_max_tokens=32768`. DFR stage 2 at 4K (3840x2176, ~300+frames after canvas padding, plus keyframe slots and the x2 IC-LoRA reference) is+~514k and ships with `sp_max_tokens=524288`. Exceeding it raises with a clear"use a smaller resolution or fewer frames" message.diff --git a/packages/ltx-pipelines/docs/optimization.md b/packages/ltx-pipelines/docs/optimization.mdindex f02190d..525b6db 100644--- a/packages/ltx-pipelines/docs/optimization.md+++ b/packages/ltx-pipelines/docs/optimization.md@@ -82,24 +82,29 @@ Compiling the transformer blocks with `torch.compile` speeds up inference. It is| `--compile KEY=VALUE ...` | compile, overriding individual fields |```bash-# Defaults+# Defaults (compile only; no CUDA graphs). Fine with --offload none.python -m ltx_pipelines.ti2vid_two_stages --compile --checkpoint-path=...-# reduce-overhead / max-autotune / capture all need GPU-resident weights-# (keeps_gpu_resident_weights -- SP/TDP + weight tracker, or streaming).-python -m ltx_pipelines.ti2vid_two_stages --compile mode=reduce-overhead --checkpoint-path=...--# Several overrides at once+# CUDA-graph inductor modes: on single GPU add --offload cpu (or disk)python -m ltx_pipelines.ti2vid_two_stages \- --compile mode=max-autotune fullgraph=true dynamic=true --checkpoint-path=...--# Self-managed block-loop CUDA-graph capture-python -m ltx_pipelines.ti2vid_two_stages --compile capture=true --checkpoint-path=...+ --compile mode=max-autotune fullgraph=true dynamic=true --checkpoint-path=... \+ --offload cpu++# Self-managed block-loop CUDA-graph capture (private static inputs per captured shape)+python -m ltx_pipelines.distilled \+ --compile capture=true --distilled-checkpoint-path=... \+ --offload cpu++# Same, with one shared static-input pool sized for this rank's largest shape+python -m ltx_pipelines.distilled \+ --compile capture=true max_video_tokens=24576 max_audio_tokens=128 \+ --distilled-checkpoint-path=... \+ --offload cpu```| Field | Values | Default | Notes || ----- | ------ | ------- | ----- |-| `mode` | `none`, `reduce-overhead`, `max-autotune`, … | `none` | `reduce-overhead`/`max-autotune` enable CUDA graphs; require `keeps_gpu_resident_weights=True` or the stage raises |+| `mode` | `none`, `reduce-overhead`, `max-autotune`, … | `none` | `reduce-overhead`/`max-autotune` enable PyTorch CUDA graphs. On single GPU they need `--offload cpu` or `disk` (see below); the SP/TDP runners already qualify || `backend` | `inductor`, `eager`, … | `inductor` | || `fullgraph` | `true`/`false` | `false` | || `dynamic` | `auto`/`true`/`false` | `auto` | the seq dim is marked dynamic separately (see `seq_dim_dynamic`) |@@ -107,7 +112,37 @@ python -m ltx_pipelines.ti2vid_two_stages --compile capture=true --checkpoint-pa| `dynamo_config` | JSON object or path to a `.json` | `{"inline_inbuilt_nn_modules": true, "cache_size_limit": 256}` | `torch._dynamo.config` overrides || `seq_dim_dynamic` | `true`/`false` | `true` | mark the block's sequence dim dynamic so one artifact serves any token count; `false` recompiles per token count || `recompile_perturbed_block` | `true`/`false` | `true` | `true` recompiles a separate block graph for the STG-perturbed pass; `false` attaches unconditional runtime masks so the block traces once (single graph) |-| `capture` | `true`/`false` | `false` | per-block compile + one CUDA graph over the block loop (keyed by shape / perturbation signature). Requires `keeps_gpu_resident_weights=True`. Faster cold-start and smaller new-shape penalty than `mode=reduce-overhead` |+| `capture` | `true`/`false` | `false` | per-block compile + one CUDA graph over the block loop (keyed by shape and perturbation signature). Faster cold-start than `mode=reduce-overhead`. Same single-GPU `--offload` requirement as those modes. Each replay copies activations into **static input buffers**, then runs the graph |+| `max_video_tokens` | positive integer | `0` | `capture` only: size of the shared **video input** pool (latent tokens, not pixels). `0`: each captured shape keeps its own input buffers. Set to this rank's largest video token count so every shape copies into one pool |+| `max_audio_tokens` | positive integer | `0` | same, for the audio-input pool. For audio+video jobs that share pools, set both |++**CUDA-graph capture (`capture=true`).** `--compile` by itself compiles blocks and does not capture graphs. `mode=reduce-overhead` lets PyTorch graph the 48-block tree (slow cold start). `capture=true` compiles each block once, then captures **one** CUDA graph around the whole block loop per (input shape, perturbation signature). Distilled has no STG pass, so that is one graph per shape; CFG/STG pipelines can capture a second graph at the same shape. A replay copies the current video/audio `TransformerArgs` (activations, RoPE, masks) into **static input buffers** and runs that graph — the graph always reads the same input addresses.++Capture freezes two kinds of GPU address. They are independent:++**Weight storages (whether capture can run).** Default `--offload none` rebuilds each stage onto **new** GPU weight tensors and raises (`keeps_gpu_resident_weights`). On single GPU, `--offload cpu` or `--offload disk` selects the streaming builder, which reuses the same GPU weight slots across rebuilds. The SP/TDP multi-GPU runners already do this via the weight tracker. A model registry by itself does not: the CLI already uses one, and it still raises. `--offload` is not sizing activations.++**Static input pool (`max_video_tokens` / `max_audio_tokens`).** These flags size the **input** buffers every capture copies into — not the weights. Leave both at `0` and each captured shape allocates its own input set (cost grows with the number of shapes: stage-1, stage-2, DFR tiles, …). Set them to this rank's **largest** token counts and every capture shares one pool sized for that max, so input-buffer VRAM is one shape, not the sum. Too small raises (the capture does not fit the pool). Too large only wastes VRAM. Multi-GPU: the count is what **this rank** denoises after the sequence split, overlap included. Perturbation `block_masks` always share one process-wide pool.++A video token is one latent cell after the default 8×32×32 VAE (not a pixel). The formula is the **target** sequence:++```text+video_tokens = ((num_frames - 1) / 8 + 1) * (height / 32) * (width / 32)+audio_tokens ≈ round((num_frames / frame_rate) * 25)+```++Conditioning **appends** tokens (generated-keyframe slots, IC-LoRA reference, image keyframes). Size the pool for the full transformer sequence, not the target alone.++Use the **largest denoise** this rank sees (usually stage-2 / final `height`×`width`, not the half-res stage-1). Examples at 121 frames, 24 fps, **no extra conditioning** (DistilledPipeline defaults):++| Output | Video tokens | Audio tokens |+| --- | --- | --- |+| 1024×1536 (pipeline default) | 16 × 32 × 48 = **24576** | ~126 |+| 3840×2176 (4K) | 16 × 68 × 120 = **130560** | ~126 |++Text-only DFR (`--spatial-upscalings 1`) always appends five full-res keyframe planes plus the half-res IC-LoRA reference, so stage 2 is **38400** at 1024×1536 and **204000** at 3840×2176. Image inputs and temporal tiles add more.++Round audio up (128 is enough for a ~5 s clip). CFG batching repeats the batch dim; it does not change these sequence counts.**Controlling inductor / dynamo configs.** `inductor_config` and `dynamo_config` take either an inline JSON object or a path to a `.json` file, applied via `torch._inductor.config.patch(...)` / `torch._dynamo.config.patch(...)` around the compiled forward. They **replace the defaults wholesale - they do not merge**, so when overriding `dynamo_config` re-include any defaults you want to keep:@@ -122,10 +157,12 @@ python -m ltx_pipelines.ti2vid_two_stages \```pythonfrom ltx_core.model.transformer.compiling import CompilationConfig+from ltx_pipelines.utils.types import OffloadModepipeline = TI2VidTwoStagesPipeline(...,compilation_config=CompilationConfig(mode="reduce-overhead"),+ offload_mode=OffloadMode.CPU, # required on single GPU for CUDA-graph modes)```@@ -152,6 +189,8 @@ By default, the video VAE comes from `--checkpoint-path`/`--distilled-checkpoint| **Triton** `na3d` | CUDA + working Triton (incl. [triton-windows](https://github.com/triton-lang/triton-windows)); natten missing | Compatibility fallback. || **eager** tiled SDPA | Always | Slowest; last resort when Triton is unavailable. |+**Keyframe-aware decode** (`decode_video(keyframes=)`) has its own ladder, because NATTEN cannot express a joint video+keyframe window: **CuTe DSL** (under `blackwell_dsl`) then **Triton** on CUDA tensors then **pure-torch** brick-batched SDPA, which is the backend macOS/MPS and Windows-without-an-extra get and costs roughly 4% against Triton end to end. No natten warning is emitted there - that ladder is not a degraded path, it is the only one.+```bash# Recommended for DiffVAE production decode on non-B200 GPUsuv sync --package ltx-core --extra natten@@ -165,10 +204,27 @@ That `natten` extra pins `natten==0.21.7+torch2130cu132` with `torch==2.13.0` (c**Mode × backend rules:**- `blackwell_dsl` uses CuTe DSL NA + fused stage-5 (requires datacenter Blackwell + `uv sync --group kernels`). Independent of natten.-- `combined_compile` **requires natten** (full-volume NA + `torch.compile`). Without it, apply raises.-- `chunked_eager` / `chunked_compile` remapped to Triton/eager when natten is missing (compile is disabled on the fallback path). Triton/eager are for compatibility only.+- `chunked_eager` / `chunked_compile` remap to Triton/eager when natten is missing, and `chunked_compile` also drops `torch.compile` there (it would only cover the attn+mlp region, which is what its extra memory coefficient pays for).+- `combined_compile` remaps the same way but **keeps** its compilation: both fallbacks are opaque custom ops, so Dynamo traces over them. It no longer raises without natten.++**Mode x keyframes grid.** The full resolved recipe, including what auto-tiling budgets for it:++| | `chunked_eager` | `chunked_compile` | `combined_compile` | `blackwell_dsl` |+| --- | --- | --- | --- | --- |+| compiled region | - | `forward_attn_mlp` (no-keyframe pathway) | `forward_combined` + det stages (no-keyframe pathway) | det stages only |+| block class | `ChunkedDiffusionNABlock` | `ChunkedDiffusionNABlock` | `CombinedDiffusionNABlock` | `DSLDiffusionNABlock` |+| `na3d`, no keyframes | natten `cutlass-fna` > Triton > eager | natten (auto backend) > Triton > eager | natten (auto backend) > Triton > eager | `na_attention_dsl` |+| stage-5 VRAM coefficient | 5 | 7 | 11 | 2.5 |+| withheld reserve | 1 GiB | 2 GiB | 2 GiB | 2 GiB |+| `joint_na3d`, with keyframes | Triton > pure-torch | Triton > pure-torch | Triton > pure-torch | `na_attention_joint_dsl` |+| stage-5 VRAM coefficient | 5 | **5** | **15** | 2.5 |+| withheld reserve | 1 GiB (2 on MATH SDPA) | 1 GiB (2 on MATH SDPA) | 1 GiB (2 on MATH SDPA) | 2 GiB |++A keyframe decode is **not** compiled -- the compiled entry points are the keyframe-free ones -- so its diff blocks run eager whatever the mode asked for, and the budget follows that: `chunked_compile` drops to the `chunked_eager` coefficient, and `combined_compile` needs **15** rather than 11 because it holds several live full-volume intermediates where the compiled path holds one fused buffer. On a host whose joint attention falls back to torch's MATH SDPA kernel (no CUDA, e.g. MPS) the reserve grows by a GiB, since that kernel materializes its score block.++Pipeline `AUTO_TILING` resolves via `tiling_config_for_vae`: for a **Conv VAE** that is aspect-coupled long-side `768/64` spatial tiles plus temporal `80/24` (`TileSizeConfig.from_long_side`). For **DiffVAE**, recommended decode tiling enumerates legal per-axis tile **sizes** on the VAE grid (via the same `split_by_size` path decode uses) and emits a `TileSizeConfig` with independent `frames` / `height` / `width` `DimensionSizeConfig` values. Tile sizes are floored at ``2xOverlap`` so blend masks stay complementary. Stage-5 coefficients and reserves come from the grid above; `tiling_config_for_vae(..., keyframes=True)` selects the keyframe column, and a `chunked_compile` remapped to the Triton/eager fallback uses the `chunked_eager` row.-Pipeline `AUTO_TILING` resolves via `tiling_config_for_vae`: for a **Conv VAE** that is aspect-coupled long-side `768/64` spatial tiles plus temporal `80/24` (`TileSizeConfig.from_long_side`). For **DiffVAE**, recommended decode tiling enumerates legal per-axis tile **sizes** on the VAE grid (via the same `split_by_size` path decode uses) and emits a `TileSizeConfig` with independent `frames` / `height` / `width` `DimensionSizeConfig` values. Tile sizes are floored at ``2xOverlap`` so blend masks stay complementary. Stage-5 VRAM coef for `chunked_compile` is **7** with natten; with Triton/eager fallback it uses the `chunked_eager` coef (**5**).+**DFR** always keyframe-decodes (`decode_video(keyframes=)`), so `AUTO_TILING` uses the **keyframe** VRAM column. At 4K with temporal rounds, decode is usually the memory cliff, not the denoise; there is no decode-tile CLI flag. `--spatial-upscalings 2` keeps stage-2 denoise at half resolution. Each temporal tile reloads the transformer. See [Running DFR](pipelines.md#running-dfr).**CLI:**@@ -183,7 +239,7 @@ Pipeline `AUTO_TILING` resolves via `tiling_config_for_vae`: for a **Conv VAE**| ---- | -------- || `chunked_eager` | Deferred stage-4 inject (sequential upsample then `context_proj`), W-chunks=4, cutlass-fna (or Triton/eager fallback), no `torch.compile`. Lowest compile cost; lower peak VRAM. || `chunked_compile` | Same deferred/chunked pathway + `torch.compile` on attn+mlp only when natten is present (det stages stay eager). Without natten: same as `chunked_eager` fallback path. |-| `combined_compile` | Combined `context_and_x` buffer, full-volume attention, compile blocks + det stages. **Requires natten.** Fastest warm decode on non-B200; highest VRAM. |+| `combined_compile` | Combined `context_and_x` buffer, full-volume attention, compile blocks + det stages. Fastest warm decode on non-B200; highest VRAM. || `blackwell_dsl` | Deferred stage-4 + CuTe DSL NA / fused stage-5. Fastest on datacenter Blackwell (B200). Needs `uv sync --group kernels`. |**Relative performance** (order-of-magnitude; hardware varies - no absolute timings or VRAM figures):diff --git a/packages/ltx-pipelines/docs/pipeline-selection.md b/packages/ltx-pipelines/docs/pipeline-selection.mdindex 5e09fea..0c8584f 100644--- a/packages/ltx-pipelines/docs/pipeline-selection.md+++ b/packages/ltx-pipelines/docs/pipeline-selection.md@@ -20,29 +20,31 @@ Do you need to condition on existing images/videos?│ ├─ YES → Use ICLoraPipeline│ └─ NO → Do you have multiple keyframe images to interpolate?│ ├─ YES → Use KeyframeInterpolationPipeline-│ └─ NO → Use TI2VidTwoStagesPipeline (image conditioning only)+│ └─ NO → Image-to-video (one still)+│ ├─ Production quality / higher fps → DFRPipeline+│ └─ Guided CFG/STG two-stage → TI2VidTwoStagesPipeline│└─ NO → Text-to-video only- ├─ Do you need best quality?- │ └─ YES → Use TI2VidTwoStagesPipeline (highest quality, guided two-stage)+ ├─ Do you need fastest inference?+ │ └─ YES → Use DistilledPipeline (starting point; 8 predefined sigmas)│- ├─ Do you need maximum detail, or a higher frame rate than the base model?- │ └─ YES → Use DFRPipeline (detailing pass + optional temporal 2x/4x)+ ├─ Do you need production quality, or a higher frame rate than the base model?+ │ └─ YES → Use DFRPipeline (distilled checkpoint + detailing pass + optional temporal 2x/4x)│- └─ Do you need fastest inference?- └─ YES → Use DistilledPipeline (recommended; 8 predefined sigmas)+ └─ Guided two-stage with CFG/STG+ └─ Use TI2VidTwoStagesPipeline```-> **Note:** [`TI2VidOneStagePipeline`](../src/ltx_pipelines/ti2vid_one_stage.py) is primarily for educational purposes. For best quality, use two-stage pipelines ([`TI2VidTwoStagesPipeline`](../src/ltx_pipelines/ti2vid_two_stages.py), [`TI2VidTwoStagesHQPipeline`](../src/ltx_pipelines/ti2vid_two_stages_hq.py), [`ICLoraPipeline`](../src/ltx_pipelines/ic_lora.py), [`KeyframeInterpolationPipeline`](../src/ltx_pipelines/keyframe_interpolation.py), [`A2VidPipelineTwoStage`](../src/ltx_pipelines/a2vid_two_stage.py), or [`DistilledPipeline`](../src/ltx_pipelines/distilled.py)). For editing existing videos, use [`RetakePipeline`](../src/ltx_pipelines/retake.py).+> **Note:** [`TI2VidOneStagePipeline`](../src/ltx_pipelines/ti2vid_one_stage.py) is primarily for educational purposes. For production quality, use [`DFRPipeline`](../src/ltx_pipelines/dfr_pipeline.py). For guided CFG/STG two-stage, use [`TI2VidTwoStagesPipeline`](../src/ltx_pipelines/ti2vid_two_stages.py) or [`TI2VidTwoStagesHQPipeline`](../src/ltx_pipelines/ti2vid_two_stages_hq.py). For editing existing videos, use [`RetakePipeline`](../src/ltx_pipelines/retake.py). See [Running DFR](pipelines.md#running-dfr) for DFR resolution, fps, and memory notes.## Features Comparison| Pipeline | Stages | [Multimodal Guidance](multimodal-guidance.md) | Upsampling | Conditioning | Best For || -------- | ------ | --- | ---------- | ------------- | -------- |-| [**DistilledPipeline**](pipelines.md#4-distilledpipeline) | 2 | ❌ | ✅ | Image | **Recommended**; fastest inference (8 sigmas) |-| [**DFRPipeline**](pipelines.md#12-dfrpipeline) | 2 (+ optional temporal rounds) | ❌ | ✅ spatial + optional temporal 2x | Image + [generated keyframes](conditioning.md#generated-keyframe-slots) | Maximum detail fidelity, higher effective frame rate |-| [**TI2VidTwoStagesPipeline**](pipelines.md#1-ti2vidtwostagespipeline) | 2 | ✅ | ✅ | Image | Production quality |-| [**TI2VidTwoStagesHQPipeline**](pipelines.md#2-ti2vidtwostageshqpipeline) | 2 | ✅ | ✅ | Image | Same as above, res_2s sampler (higher quality) |+| [**DistilledPipeline**](pipelines.md#4-distilledpipeline) | 2 | ❌ | ✅ | Image | Fastest inference (starting point) |+| [**DFRPipeline**](pipelines.md#12-dfrpipeline) | 2 (+ optional temporal rounds) | ❌ | ✅ spatial + optional temporal 2x | Image + [generated keyframes](conditioning.md#generated-keyframe-slots) | **Production quality**; higher effective frame rate |+| [**TI2VidTwoStagesPipeline**](pipelines.md#1-ti2vidtwostagespipeline) | 2 | ✅ | ✅ | Image | Guided two-stage with CFG/STG |+| [**TI2VidTwoStagesHQPipeline**](pipelines.md#2-ti2vidtwostageshqpipeline) | 2 | ✅ | ✅ | Image | Same guided flow, res_2s sampler || [**TI2VidOneStagePipeline**](pipelines.md#3-ti2vidonestagepipeline) | 1 | ✅ | ❌ | Image | Educational, prototyping || [**ICLoraPipeline**](pipelines.md#5-iclorapipeline) | 2 | ✅ | ✅ | Image + Video | Video-to-video transformations || [**KeyframeInterpolationPipeline**](pipelines.md#6-keyframeinterpolationpipeline) | 2 | ✅ | ✅ | Keyframes | Animation, interpolation |diff --git a/packages/ltx-pipelines/docs/pipelines.md b/packages/ltx-pipelines/docs/pipelines.mdindex bea419b..d6739f4 100644--- a/packages/ltx-pipelines/docs/pipelines.md+++ b/packages/ltx-pipelines/docs/pipelines.md@@ -6,13 +6,13 @@ Full reference for each pipeline. See the [Pipeline Selection Guide](pipeline-se## 1. TI2VidTwoStagesPipeline-**Best for:** High-quality text/image-to-video generation with upsampling.+**Best for:** Guided two-stage text/image-to-video with CFG/STG and 2x upsampling.**Source**: [`src/ltx_pipelines/ti2vid_two_stages.py`](../src/ltx_pipelines/ti2vid_two_stages.py)-Two-stage generation: Stage 1 generates low-resolution video with [multimodal guidance](multimodal-guidance.md), Stage 2 upsamples to 2x resolution with distilled LoRA refinement. Supports image conditioning. Highest quality output, slower than one-stage but significantly better quality.+Two-stage generation: Stage 1 generates low-resolution video with [multimodal guidance](multimodal-guidance.md), Stage 2 upsamples to 2x resolution with distilled LoRA refinement. Supports image conditioning. Slower than DistilledPipeline; for production quality use [`DFRPipeline`](#12-dfrpipeline).-**Use when:** Production-quality video generation, higher resolution needed, quality over speed, text-to-video with image conditioning.+**Use when:** You want CFG/STG-guided two-stage text/image-to-video, not the DFR detailing path.---@@ -34,7 +34,7 @@ Uses the **res_2s** second-order sampler instead of Euler. Same stage structure**Source**: [`src/ltx_pipelines/ti2vid_one_stage.py`](../src/ltx_pipelines/ti2vid_one_stage.py)-> **⚠️ Important:** This pipeline is primarily for educational purposes. For production-quality results, use `TI2VidTwoStagesPipeline` or other two-stage pipelines.+> **⚠️ Important:** This pipeline is primarily for educational purposes. For production-quality results, use [`DFRPipeline`](#12-dfrpipeline). For guided CFG/STG two-stage, use `TI2VidTwoStagesPipeline`.Single-stage generation (no upsampling) with [multimodal guidance](multimodal-guidance.md) and image conditioning support. Faster inference but lower resolution output (typically 512x768).@@ -44,7 +44,7 @@ Single-stage generation (no upsampling) with [multimodal guidance](multimodal-gu## 4. DistilledPipeline-**Best for:** Fastest inference with good quality using a distilled model with predefined sigma schedule. **Recommended default.**+**Best for:** Fastest inference with good quality using a distilled model with predefined sigma schedule. **Starting point.****Source**: [`src/ltx_pipelines/distilled.py`](../src/ltx_pipelines/distilled.py)@@ -88,7 +88,7 @@ Two-stage generation with keyframe interpolation. Uses guiding latents (additiveTwo-stage audio-to-video generation. Stage 1 generates video at half resolution with audio conditioning (video-only denoising with the audio frozen), then Stage 2 upsamples by 2x and refines the video while keeping the audio fixed, using a distilled LoRA. The input audio is encoded via the audio VAE and used as the initial audio latent, but the original audio waveform is passed through and returned in the output to preserve fidelity. Supports image conditioning and prompt enhancement.-**Extra CLI arguments:** `--audio-path` (required), `--audio-start-time`, `--audio-max-duration`.+**Extra CLI arguments:** `--audio-path` (required), `--audio-start-time`, `--audio-max-duration`. `--num-frames` and `--audio-max-duration` are mutually exclusive. With `--audio-max-duration`, video length is derived from the effective clip (`min(--audio-max-duration, remaining audio after --audio-start-time)`) at `--frame-rate`, snapped to the VAE temporal grid (`8k+1`). With `--num-frames` (or neither), audio is clipped to `--num-frames / --frame-rate`.**Use when:** You have an audio clip and want to generate a matching video, audio-reactive video generation, or music visualization.@@ -156,28 +156,66 @@ Single-stage, **audio-only** generation: the video branch is absent (`video=None## 12. DFRPipeline-**Best for:** Maximum detail fidelity — generating at half resolution with extra generated keyframes, then re-rendering at full resolution with a spatial detailing LoRA, optionally densifying time by 2x or 4x.+**Best for:** Production-quality text/image-to-video — generating at half resolution with extra generated keyframes, then re-rendering at full resolution with a spatial detailing LoRA, optionally densifying time by 2x or 4x.**Source**: [`src/ltx_pipelines/dfr_pipeline.py`](../src/ltx_pipelines/dfr_pipeline.py)-Diffusion Fidelity Rendering runs the distilled sigma schedule on a full checkpoint with a distilled LoRA. Stage 1 generates video **and [generated keyframe slots](conditioning.md#generated-keyframe-slots)** at half resolution, placing slots on an 8-frame-border segment grid; the half-resolution result is kept as a reference while video and keyframes are upsampled in latent space. Stage 2 re-denoises at full resolution with the distilled LoRA plus an optional 2x spatial detailing IC-LoRA, conditioned on the stage-1 reference.+Diffusion Fidelity Rendering runs the distilled sigma schedule on a **distilled checkpoint** (the same transformer as DistilledPipeline). Stage 1 generates video **and [generated keyframe slots](conditioning.md#generated-keyframe-slots)** at half resolution, placing slots on an 8-frame-border segment grid; the half-resolution result is kept as a reference while video and keyframes are upsampled in latent space. Stage 2 re-denoises at full resolution with a 2x spatial detailing IC-LoRA, conditioned on the stage-1 reference.Audio comes from **stage 1**. Stage 2 still runs an audio pass, because the video branch needs the cross-modal attention, but nothing refines audio after stage 1.-**Temporal refinement (optional).** `--temporal-upsample-rounds {0,1,2}` adds rounds that each double the frame rate: the canvas is upsampled temporally, split into `2**round` tiles that meet at shared keyframes, given fresh mid-segment slots, and densified with ancestral Euler. Whatever padding the canvas needs internally, you always get `(num_frames - 1) * 2**rounds + 1` frames back.+**Temporal refinement (optional, default `0`).** `--temporal-upscalings {0,1,2}` adds rounds that each double the **playback** frame rate: the canvas is upsampled temporally, split into `2**round` tiles that meet at shared keyframes, given fresh mid-segment slots, and densified with ancestral Euler. Whatever padding the canvas needs internally, you always get `(num_frames - 1) * 2**rounds + 1` frames back. `--temporal-upsampler-path` is required when the count is greater than 0.-**Extra CLI arguments:** `--detailing-lora PATH [STRENGTH]` (optional, off by default), `--temporal-upsampler-path` (required when rounds > 0), `--temporal-upsample-rounds {0,1,2}`. Unlike the other keyframe-capable pipelines, DFR does **not** take `--num-generated-keyframes` — it derives slot positions from its own segment grid.+**Spatial epilogue (`--spatial-upscalings 2`).** Default `--spatial-upscalings` is `1`: stage 1 at `h/2`, stage 2 at the final `h×w`. With `2`, stage 1 is at `h/4` and stage 2 at `h/2`. The epilogue decodes each carry keyframe as its own latent, Lanczos-stretches the RGB x2, and encodes it again. Only the video latent is spatially upsampled. Time windows are seam-cut and 2x2-tiled (12 latent cells of overlap); the 3-step detailing schedule runs with those keyframes as strength-1 conditions, the previous-stage video as the IC-LoRA reference, and frozen stage-1 audio so video-audio cross-attention still has a stream. The pipeline still ships the original stage-1 audio. Spatial tiles blend after every Euler step. Detailing LoRA strength is fixed at 0.5. The same encoded keyframes are used for keyframe-aware DiffVAE decode.++**Extra CLI arguments:** `--detailing-lora PATH [STRENGTH]` (required; strength is ignored and hardcoded to 0.5), `--spatial-upscalings {1,2}` (default `1`), `--temporal-upsampler-path` (required when `--temporal-upscalings` > 0), `--temporal-upscalings {0,1,2}` (default `0`). Unlike the other keyframe-capable pipelines, DFR does **not** take `--num-generated-keyframes` — it derives slot positions from its own segment grid. There is no `--distilled-lora`; the distilled weights are the checkpoint.++### Running DFR++`--height` / `--width` are the **final** output size. They must be divisible by **64** (by **128** when `--spatial-upscalings 2`). UHD 4K is `3840×2176`, not `3840×2160` (2160 is not on the 64-pixel grid).++`--num-frames` is the **stage-1** count on the VAE temporal grid (`8k+1`). `--num-frames 121` at the default 24 fps is about 5.04 s. Output length is still that wall-clock duration; extra temporal rounds add frames, not seconds:++| `--temporal-upscalings` | Frames from 121 | Playback fps | Duration |+| --- | --- | --- | --- |+| `0` (default) | 121 | 24 | ~5.04 s |+| `1` | 241 | 48 | ~5.02 s |+| `2` | 481 | 96 | ~5.01 s |++The file is encoded at that playback fps. The transformer independently snaps conditioning fps to 60 whenever playback fps is above 30 (so a 48 fps clip still ships at 48 fps). Some players treat unusual H.264 rates such as 96 fps as 24 fps and play the file in slow motion.++Shared memory flags (`--quantization`, `--offload`, `--compile`, `--diffvae-optimization`) work the same as on other pipelines; see [Optimization Tips](optimization.md). Defaults are no compile, no quant, no offload, and DiffVAE `chunked_eager`. CUDA-graph compile (`capture=true`, `reduce-overhead`, `max-autotune`) on single GPU needs `--offload cpu` or `disk` so stage rebuilds reuse the same GPU weight slots — that is not the static input pool. DFR hits several transformer shapes (half-res stage 1, full-res stage 2, temporal tiles). With `--compile capture=true`, each shape still gets its own CUDA graph, but `max_video_tokens` / `max_audio_tokens` can size **one** static input pool for all of them. Count the **full** stage-2 sequence: target tokens from the final `height`×`width` **plus** five keyframe planes **plus** the half-res IC-LoRA reference (text-only defaults: 38400 at 1024×1536, 204000 at 3840×2176; see [token budgets](optimization.md#compilation-torchcompile)).++**Cost.** Stage 2 at `--spatial-upscalings 1` denoises the full output resolution. `--spatial-upscalings 2` keeps stage 2 at half res and finishes 4K in the tiled epilogue — use that if stage 2 OOMs at 4K. Each temporal round splits the canvas into `2**round` tiles and **reloads the transformer per tile**, so wall-clock grows much faster than the four Euler steps suggest. After denoising, DFR always **keyframe-decodes**; that is usually the VRAM cliff, not the denoise. `AUTO_TILING` sizes decode tiles for the keyframe path automatically — there is no decode-tile CLI flag. Install the `natten` extra for production DiffVAE decode (`uv sync --package ltx-core --extra natten`); without it the decoder falls back to Triton. On datacenter Blackwell, `--diffvae-optimization blackwell_dsl` is the fast decode path.++Monolith (fat distilled checkpoint + Gemma directory):++```bash+uv run python -m ltx_pipelines.dfr_pipeline \+ --distilled-checkpoint-path path/to/distilled-checkpoint.safetensors \+ --gemma-root path/to/gemma \+ --detailing-lora models/ltx-2.5/loras/ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors \+ --spatial-upsampler-path models/ltx-2.5/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors \+ --width 3840 --height 2176 --num-frames 121 \+ --output-path output.mp4 --prompt "..."+```++Split (Comfy-aligned files; omit `--gemma-root`). Same distilled transformer as DistilledPipeline. Add `--temporal-upsampler-path` and `--temporal-upscalings 1` or `2` for 48 / 96 fps:```bashuv run python -m ltx_pipelines.dfr_pipeline \- --checkpoint-path models/ltx-2.5/diffusion_models/ltx-2.5-22b-dev-transformer-bf16.safetensors \- --distilled-lora models/ltx-2.5/loras/ltx-2.5-22b-distilled-lora-450-bf16.safetensors \+ --transformer-path models/ltx-2.5/diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors \+ --text-encoder-path models/ltx-2.5/text_encoders/gemma4-12b-with-proj-ltx-2.5-bf16.safetensors \+ --video-vae-path models/ltx-2.5/vae/ltx-2.5-video-vae-bf16.safetensors \+ --audio-vae-path models/ltx-2.5/vae/ltx-2.5-audio-vae-bf16.safetensors \+ --detailing-lora models/ltx-2.5/loras/ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors \--spatial-upsampler-path models/ltx-2.5/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors \--temporal-upsampler-path models/ltx-2.5/latent_upscale_models/ltx-2.5-latent-temporal-upscaler-x2-bf16-1.0.safetensors \- --temporal-upsample-rounds 1 \- --num-frames 121 --output-path output.mp4 --prompt "..."+ --temporal-upscalings 1 \+ --width 3840 --height 2176 --num-frames 121 \+ --output-path output.mp4 --prompt "..."```-**Note:** Requires a checkpoint that supports generated keyframe slots (LTX-2.5 and later) and a distilled LoRA.+**Note:** Requires a distilled checkpoint that supports generated keyframe slots (LTX-2.5 and later). Do not pass the full (dev) transformer. Multi-GPU: `python -m ltx_pipelines.dfr_mgpu` with the same flags; both stages use sequence parallelism.-**Use when:** Detail fidelity matters more than wall-clock time, or you want a higher effective frame rate than the base model produces.+**Use when:** You want production-quality output, quality over wall-clock time, or a higher effective frame rate than the base model produces.diff --git a/packages/ltx-pipelines/pyproject.toml b/packages/ltx-pipelines/pyproject.tomlindex 59f2c99..d9e2f75 100644--- a/packages/ltx-pipelines/pyproject.toml+++ b/packages/ltx-pipelines/pyproject.toml@@ -1,6 +1,6 @@[project]name = "ltx-pipelines"-version = "1.2.0"+version = "1.3.0"description = "Pipelines implementation for Lightricks' LTX-2 model"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/ltx-pipelines/src/ltx_pipelines/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/__init__.pyindex 23eb542..4a6af55 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/__init__.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/__init__.py@@ -32,11 +32,13 @@ if TYPE_CHECKING:from ltx_pipelines.t2a_one_stage import T2AOneStagePipelinefrom ltx_pipelines.ti2vid_one_stage import TI2VidOneStagePipelinefrom ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipeline+ from ltx_pipelines.utils.types import PipelineOutput# Public name -> module that defines it. Used for lazy resolution in __getattr__._EXPORTS = {"A2VidPipelineTwoStage": "ltx_pipelines.a2vid_two_stage","DFRPipeline": "ltx_pipelines.dfr_pipeline",+ "PipelineOutput": "ltx_pipelines.utils.types","DistilledPipeline": "ltx_pipelines.distilled","DubItPipeline": "ltx_pipelines.dubit","ICLoraPipeline": "ltx_pipelines.ic_lora",@@ -54,6 +56,7 @@ __all__ = ["DubItPipeline","ICLoraPipeline","KeyframeInterpolationPipeline",+ "PipelineOutput","RetakePipeline","T2AOneStagePipeline","TI2VidOneStagePipeline",diff --git a/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.pyindex 5d65208..1f5e995 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py@@ -1,5 +1,5 @@+import argparseimport logging-from collections.abc import Iteratorimport torch@@ -30,13 +30,16 @@ from ltx_pipelines.utils.blocks import ()from ltx_pipelines.utils.constants import (STAGE_2_DISTILLED_SIGMAS,+ PipelineParams,)from ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiserfrom ltx_pipelines.utils.helpers import (assert_resolution,+ audio_duration_seconds,combined_image_conditionings,ensure_tiling_config,get_device,+ num_frames_from_audio_duration,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (@@ -47,7 +50,9 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput++logger = logging.getLogger(__name__)class A2VidPipelineTwoStage:@@ -56,6 +61,9 @@ class A2VidPipelineTwoStage:Stage 1 generates video at half the target resolution with audio conditioning(video-only denoising, audio frozen), then Stage 2 upsamples by 2x and refinesboth video and audio using a distilled LoRA for higher quality output.+ When ``num_frames`` is omitted, the frame count is derived from the effective+ conditioning-audio duration (``min(audio_max_duration, remaining audio after+ audio_start_time)``) at ``frame_rate``, snapped to the VAE temporal grid."""def __init__( # noqa: PLR0913@@ -147,7 +155,7 @@ class A2VidPipelineTwoStage:seed: int,height: int,width: int,- num_frames: int,+ num_frames: int | None,frame_rate: float,num_inference_steps: int,video_guider_params: MultiModalGuiderParams,@@ -163,7 +171,7 @@ class A2VidPipelineTwoStage:stage_1_sigmas: torch.Tensor | None = None,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,- ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]:+ ) -> PipelineOutput:images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -173,6 +181,20 @@ class A2VidPipelineTwoStage:if vae_dtype is None:vae_dtype = dtype+ # Decode audio first so the frame count can follow the effective clip length+ # (``audio_max_duration`` capped by remaining audio after ``audio_start_time``).+ decoded_audio = decode_audio_from_file(audio_path, self.device, audio_start_time, audio_max_duration)+ if decoded_audio is None:+ raise ValueError(f"Failed to decode audio from {audio_path}. Please check the file and try again.")+ if num_frames is None:+ num_frames = num_frames_from_audio_duration(decoded_audio, frame_rate=frame_rate)+ logger.info(+ "Derived num_frames=%d from %.2fs of audio @ %.2f fps",+ num_frames,+ audio_duration_seconds(decoded_audio),+ frame_rate,+ )+ctx_p, ctx_n = self.prompt_encoder([prompt, negative_prompt],enhance_first_prompt=enhance_prompt,@@ -192,11 +214,6 @@ class A2VidPipelineTwoStage:device=self.device,)- # Encode audio.- decoded_audio = decode_audio_from_file(audio_path, self.device, audio_start_time, audio_max_duration)- if decoded_audio is None:- raise ValueError(f"Failed to decode audio from {audio_path}. Please check the file and try again.")-encoded_audio_latent = self.audio_conditioner(lambda enc: vae_encode_audio(decoded_audio, enc, None))audio_shape = AudioLatentShape.from_duration(batch=1, duration=num_frames / frame_rate, channels=8, mel_bins=16)encoded_audio_latent = encoded_audio_latent[:, :, : audio_shape.frames]@@ -300,15 +317,47 @@ class A2VidPipelineTwoStage:# Return the original input audio instead of VAE-decoded audio to preserve fidelity.# decode_audio_from_file already returns normalised [-1, 1] float values.- original_audio = Audio(waveform=decoded_audio.waveform.squeeze(0), sampling_rate=decoded_audio.sampling_rate)+ # Trim to the snapped video duration so a slightly longer clip cannot freeze+ # the last frames. Floor so a half-sample leftover cannot outlast the video.+ video_samples = max(1, int((num_frames / frame_rate) * decoded_audio.sampling_rate))+ original_audio = Audio(+ waveform=decoded_audio.waveform.squeeze(0)[..., :video_samples],+ sampling_rate=decoded_audio.sampling_rate,+ )- return decoded_video, original_audio, tiling_config+ return PipelineOutput(decoded_video, original_audio, num_frames, tiling_config, None, video_state.latent)[email protected]_mode()-def main() -> None:- logging.basicConfig(level=logging.INFO)- parser = default_2_stage_arg_parser(params=resolve_cli_params())+def resolve_a2vid_cli_duration(+ *,+ num_frames: int | None,+ audio_max_duration: float | None,+ frame_rate: float,+ default_num_frames: int,+) -> tuple[int | None, float]:+ """Pick the single duration driver for the A2Vid CLI.+ ``--num-frames`` and ``--audio-max-duration`` are mutually exclusive. Returns+ ``(num_frames_for_pipeline, audio_max_duration)``:+ * only ``--audio-max-duration``: ``num_frames`` is ``None`` so the pipeline derives+ frames from the decoded clip (capped by remaining audio after start time).+ * only ``--num-frames``, or neither: use that frame count (defaulting to+ ``default_num_frames``) and clip audio to ``num_frames / frame_rate``.+ """+ if num_frames is not None and audio_max_duration is not None:+ raise ValueError("argument --num-frames: not allowed with argument --audio-max-duration")+ if audio_max_duration is not None:+ return None, audio_max_duration+ frames = default_num_frames if num_frames is None else num_frames+ return frames, frames / frame_rate+++def build_a2vid_arg_parser(params: PipelineParams) -> argparse.ArgumentParser:+ """Two-stage parser plus A2Vid audio flags; ``--num-frames`` default is unset.+ Leaving ``--num-frames`` as ``None`` when omitted is what lets+ ``resolve_a2vid_cli_duration`` tell "user passed --audio-max-duration" apart from+ "user passed both" (the shared parser would otherwise fill in ``params.num_frames``).+ """+ parser = default_2_stage_arg_parser(params=params)parser.add_argument("--audio-path",type=str,@@ -325,9 +374,53 @@ def main() -> None:"--audio-max-duration",type=float,default=None,- help="Maximum audio duration in seconds. Defaults to video duration (num_frames / frame_rate).",+ help=(+ "Maximum audio duration in seconds, measured from --audio-start-time. "+ "The video length is derived from the effective clip "+ "(this value capped by remaining audio in the file) at --frame-rate. "+ "Mutually exclusive with --num-frames. "+ f"If neither is given, audio is clipped to the default "+ f"--num-frames / --frame-rate ({params.num_frames} frames)."+ ),)+ for action in parser._actions:+ if "--num-frames" in action.option_strings:+ action.default = None+ action.help = (+ "Number of frames to generate, num_frames = 8 * k + 1 "+ f"(default: {params.num_frames}). Mutually exclusive with --audio-max-duration; "+ "when set, audio is clipped to this length / --frame-rate."+ )+ break+ return parser+++def resolve_a2vid_duration_or_exit(+ parser: argparse.ArgumentParser,+ args: argparse.Namespace,+ *,+ default_num_frames: int,+) -> tuple[int | None, float]:+ """Resolve duration knobs, or ``parser.error`` if both flags were given."""+ try:+ return resolve_a2vid_cli_duration(+ num_frames=args.num_frames,+ audio_max_duration=args.audio_max_duration,+ frame_rate=args.frame_rate,+ default_num_frames=default_num_frames,+ )+ except ValueError as e:+ parser.error(str(e))+ raise # parser.error always exits; keep the type checker happy++[email protected]_mode()+def main() -> None:+ logging.basicConfig(level=logging.INFO)+ params = resolve_cli_params()+ parser = build_a2vid_arg_parser(params)args = parser.parse_args()+ num_frames, audio_max_duration = resolve_a2vid_duration_or_exit(parser, args, default_num_frames=params.num_frames)pipeline = A2VidPipelineTwoStage(model_paths=args.model_paths,distilled_lora=args.distilled_lora,@@ -341,13 +434,13 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,height=args.height,width=args.width,- num_frames=args.num_frames,+ num_frames=num_frames,frame_rate=args.frame_rate,num_inference_steps=args.num_inference_steps,video_guider_params=MultiModalGuiderParams(@@ -366,19 +459,15 @@ def main() -> None:enhance_static_cache=args.enhance_static_cache,audio_path=args.audio_path,audio_start_time=args.audio_start_time,- audio_max_duration=args.audio_max_duration- if args.audio_max_duration is not None- else args.num_frames / args.frame_rate,+ audio_max_duration=audio_max_duration,max_batch_size=args.max_batch_size,)- video_chunks_number = get_video_chunks_number(args.num_frames, tiling_config)-encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=video_chunks_number,+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.pyindex 4b5006b..c0b33c7 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.py@@ -1,60 +1,29 @@-"""DFR canvas layout: keyframe segment grid, temporal tile ranges, and the latent stitch."""+"""DFR canvas layout: keyframe segment grid and coordinate helpers."""from __future__ import annotations-from collections.abc import Sequence-from typing import NamedTuple--import torch+import itertools+from collections.abc import Iterator, Sequence+from typing import NamedTuple, overload+from ltx_core.tiling import DimensionInterval, split_at_seamsfrom ltx_core.types import VIDEO_SCALE_FACTORSSEGMENT_CANDIDATES = (24, 32)-# Lead-in for non-first tiles, in canvas segments. A tile's local latent 0 is an *image* latent (one-# pixel frame) and its local latent 1 was denoised against that image; neither may be spliced into the-# mid-canvas stream. One segment of lead-in puts both inside the discarded prefix while keeping the-# window start on a keyframe anchor, which the KeyFrame@0 lock requires.-TILE_LEAD_SEGMENTS = 1---class TileRange(NamedTuple):- """One temporal denoise tile in global pixel / latent coordinates.- ``pixel_start`` / ``pixel_end`` are inclusive, ``latent_end_exclusive`` is half-open. Non-first- tiles start ``TILE_LEAD_SEGMENTS`` segments before the region they own, so the seam shared with the- previous tile falls inside the window. ``anchor_kf_global`` are the seam keyframes in the window,- which includes ``pixel_start`` on every tile but the first -- frame 0 is not a keyframe, so the- first tile's window start contributes no anchor. ``slot_kf_global`` are the mid-segment positions- this window invents.- """- pixel_start: int- pixel_end: int- latent_start: int- latent_end_exclusive: int- anchor_kf_global: tuple[int, ...]- slot_kf_global: tuple[int, ...]- drop_latent_prefix: int+def padding_to_segment(content_frames: int, segment: int) -> int:+ """Frames needed to round ``content_frames`` up to a whole number of ``segment``."""+ return (-content_frames) % segmentdef choose_segment_length(content_frames: int) -> int:"""Pick the keyframe segment length from ``SEGMENT_CANDIDATES``, preferring whichever pads least.- ``content_frames`` is ``num_frames - 1``. Ties keep the larger segment.+ ``content_frames`` is ``num_frames - 1``. Ties keep the larger segment (``-segment`` breaks them)."""if content_frames < 1:raise ValueError(f"content_frames must be >= 1, got {content_frames}")-- def _pad(segment: int) -> int:- return (segment - content_frames % segment) % segment-- best = int(SEGMENT_CANDIDATES[0])- best_pad = _pad(best)- for candidate in SEGMENT_CANDIDATES[1:]:- segment = int(candidate)- pad = _pad(segment)- if pad < best_pad or (pad == best_pad and segment > best):- best, best_pad = segment, pad- return best+ return min(SEGMENT_CANDIDATES, key=lambda segment: (padding_to_segment(content_frames, segment), -segment))def resolve_canvas(@@ -76,7 +45,7 @@ def resolve_canvas(raise ValueError("The canvas needs at least 2 pixel frames")segment = choose_segment_length(content)- content_padded = content + (segment - content % segment) % segment+ content_padded = content + padding_to_segment(content, segment)positions = [segment * index for index in range(1, content_padded // segment + 1)]return content_padded + 1, segment, positions@@ -90,124 +59,70 @@ def pixel_to_latent_index(pixel_frame: int, temporal_scale: int = VIDEO_SCALE_FAreturn pixel_frame // temporal_scale-def _owned_segment_counts(n_segments: int, num_tiles: int) -> list[int]:- """Split ``n_segments`` into ``num_tiles`` contiguous owned runs, largest first."""- if n_segments < 1:- raise ValueError(f"n_segments must be >= 1, got {n_segments}")- if num_tiles < 1:- raise ValueError(f"num_tiles must be >= 1, got {num_tiles}")- base, remainder = divmod(n_segments, num_tiles)- return [base + (1 if index < remainder else 0) for index in range(num_tiles)]---def _build_tile(- boundaries: Sequence[int],- own_lo: int,- own_hi: int,- *,- lead_segments: int,- temporal_scale: int,-) -> TileRange:- """One window owning segments ``[own_lo, own_hi)``, preceded by ``lead_segments`` of lead-in."""- window_lo = max(0, own_lo - lead_segments)- pixel_start = int(boundaries[window_lo])- pixel_end = int(boundaries[own_hi])- latent_start = pixel_to_latent_index(pixel_start, temporal_scale)-- # Handover is exactly at the shared keyframe: the previous tile keeps the seam latent (the 8-frame- # token ending on the KF mark) and this tile resumes strictly after it, so the prefix drops the- # lead-in plus that seam latent.- drop_latent_prefix = pixel_to_latent_index(int(boundaries[own_lo]), temporal_scale) - latent_start- if own_lo > 0:- drop_latent_prefix += 1-- return TileRange(- pixel_start=pixel_start,- pixel_end=pixel_end,- latent_start=latent_start,- latent_end_exclusive=pixel_to_latent_index(pixel_end, temporal_scale) + 1,- anchor_kf_global=tuple(int(boundaries[index]) for index in range(window_lo, own_hi + 1) if boundaries[index]),- slot_kf_global=tuple(- (int(boundaries[index]) + int(boundaries[index + 1])) // 2 for index in range(window_lo, own_hi)- ),- drop_latent_prefix=drop_latent_prefix,- )---def tile_ranges(- seam_positions: Sequence[int],- num_frames: int,+def split_canvas_at_seams(+ seams: Sequence[int],num_tiles: int,- *,- temporal_scale: int = VIDEO_SCALE_FACTORS.time,- lead_segments: int = TILE_LEAD_SEGMENTS,-) -> list[TileRange]:- """Partition the canvas into ``num_tiles`` keyframe-seam tiles, gapless, with a lead-in.- Owned segment runs are contiguous; each non-first window additionally reaches ``lead_segments``- back so it denoises through the shared seam keyframe. ``num_tiles`` is clamped to the segment count.+ overlap: int,+ dim_size: int,+) -> list[DimensionInterval]:+ """Split a DFR canvas on keyframe boundary cells, allowing a remainder segment count.+ Same handover as :func:`ltx_core.tiling.split_at_seams` (lead-in plus the shared seam cell+ land in ``left_ramp``); leftover segments go to the leading tiles."""- if num_frames < 2:- raise ValueError(f"num_frames must be >= 2, got {num_frames}")- if not seam_positions:- raise ValueError("seam_positions must be non-empty")- if int(seam_positions[-1]) != num_frames - 1:- raise ValueError(f"Last seam must be the terminal frame {num_frames - 1}, got {seam_positions[-1]}")- if lead_segments < 1:- raise ValueError(f"lead_segments must be >= 1, got {lead_segments}")-- boundaries = [0, *[int(position) for position in seam_positions]]- for index in range(1, len(boundaries)):- span = boundaries[index] - boundaries[index - 1]- if span <= 0:- raise ValueError(f"seam_positions must be strictly increasing, got {list(seam_positions)}")- if span % temporal_scale != 0:- raise ValueError(f"Segment span {span} is not a multiple of temporal scale {temporal_scale}")- if span // temporal_scale < 2:- raise ValueError(f"Segment span {span} is under 2 latent frames, too short to carry a tile lead-in")-- n_segments = len(boundaries) - 1- tiles: list[TileRange] = []- own_lo = 0- for index, count in enumerate(_owned_segment_counts(n_segments, min(num_tiles, n_segments))):- tiles.append(- _build_tile(- boundaries,- own_lo,- own_lo + count,- lead_segments=lead_segments if index > 0 else 0,- temporal_scale=temporal_scale,- )- )- own_lo += count- return tiles---def stitch_tile_latents(- tile_latents: Sequence[torch.Tensor],- ranges: Sequence[TileRange],-) -> torch.Tensor:- """Concatenate tile video latents along T, each tile contributing ``latent[drop_latent_prefix:]``."""- if len(tile_latents) != len(ranges):- raise ValueError(f"Expected {len(ranges)} tile latents, got {len(tile_latents)}")- if not tile_latents:- raise ValueError("tile_latents must be non-empty")-- pieces: list[torch.Tensor] = []- for latent, tile in zip(tile_latents, ranges, strict=True):- if latent.ndim != 5:- raise ValueError(f"Expected tile latent (B, C, T, H, W), got {tuple(latent.shape)}")- expected_t = tile.latent_end_exclusive - tile.latent_start- if latent.shape[2] != expected_t:- raise ValueError(- f"Tile latent T={latent.shape[2]} != expected {expected_t} "- f"for range [{tile.latent_start}, {tile.latent_end_exclusive})"- )- if not 0 <= tile.drop_latent_prefix < latent.shape[2]:- raise ValueError(f"drop_latent_prefix={tile.drop_latent_prefix} invalid for tile T={latent.shape[2]}")- pieces.append(latent[:, :, tile.drop_latent_prefix :])- return torch.cat(pieces, dim=2)---def remap_positions_to_local(positions: Sequence[int], pixel_start: int) -> list[int]:- """Shift global pixel indices into a tile-local frame (``local = global - pixel_start``)."""- return [int(position) - pixel_start for position in positions]+ return list(split_at_seams(seams, num_tiles, overlap)(dim_size).intervals)+++class TemporalTile(NamedTuple):+ """One temporal-upsample window: latent interval plus pixel-frame anchors and slots."""++ interval: DimensionInterval+ pixel_start: int+ pixel_end: int+ anchors: tuple[int, ...]+ slots: tuple[int, ...]+++class TemporalTilePlan:+ """Keyframe-seam tiles for one temporal-upsample round. Each window is a :class:`TemporalTile`."""++ tiles: tuple[TemporalTile, ...]++ def __init__(+ self,+ seam_positions: Sequence[int],+ num_frames: int,+ num_tiles: int,+ temporal_scale: int = VIDEO_SCALE_FACTORS.time,+ ) -> None:+ """Partition the canvas with :func:`split_canvas_at_seams` and attach per-window anchors/slots.+ Overlap is one canvas segment in latent cells plus the shared seam cell, matching the old+ lead-in + ``drop_latent_prefix += 1`` handover. Remainder segments go to the leading tiles.+ """+ seams = [0, *(pixel_to_latent_index(position, temporal_scale) for position in seam_positions)]+ latent_len = (num_frames - 1) // temporal_scale + 1+ overlap = (seams[1] - seams[0]) + 1 if len(seams) > 1 else 0+ intervals = split_canvas_at_seams(seams, num_tiles, overlap, latent_len)+ tiles: list[TemporalTile] = []+ for interval in intervals:+ pixel_start = interval.start * temporal_scale+ pixel_end = (interval.end - 1) * temporal_scale+ anchors = tuple(position for position in seam_positions if pixel_start <= position <= pixel_end)+ marks = [pixel_start, *[position for position in seam_positions if pixel_start < position <= pixel_end]]+ slots = tuple((left + right) // 2 for left, right in itertools.pairwise(marks))+ tiles.append(TemporalTile(interval, pixel_start, pixel_end, anchors, slots))+ self.tiles = tuple(tiles)++ def __iter__(self) -> Iterator[TemporalTile]:+ return iter(self.tiles)++ def __len__(self) -> int:+ return len(self.tiles)++ @overload+ def __getitem__(self, index: int) -> TemporalTile: ...++ @overload+ def __getitem__(self, index: slice) -> tuple[TemporalTile, ...]: ...++ def __getitem__(self, index: int | slice) -> TemporalTile | tuple[TemporalTile, ...]:+ return self.tiles[index]diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.pynew file mode 100644index 0000000..198669c--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.py@@ -0,0 +1,326 @@+"""Multi-GPU DFR (Diffusion Fidelity Rendering) runner.+Runs :class:`DFRPipeline` across multiple GPUs with:+- **Stage 1 and stage 2 (detailing)** -- sequence parallelism (SP) on both+ ``stage`` and ``stage_detailing`` (including temporal tiles and the spatial+ epilogue, which reuse those two objects)+- **Gemma** -- Accelerate-based parallelization+- **VAE** -- distributed decoding+Requires ``ltx-kernels`` to be installed (transitive via SP builder).+"""++from __future__ import annotations++import logging+from collections.abc import Callable, Iterator, Sequence+from contextlib import contextmanager, nullcontext+from functools import wraps+from multiprocessing import SimpleQueue+from typing import Any++import torch+import torch.distributed as dist++from ltx_core.allocator_trim_strategy import AllocatorTrimStrategy+from ltx_core.loader import LoraPathStrengthAndSDOps+from ltx_core.loader.registry import ModelRegistry+from ltx_core.model.transformer.compiling import CompilationConfig+from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_number+from ltx_core.model.video_vae.transformer import DiffVAEMode+from ltx_core.multigpu.transformer.attention import AttentionManager+from ltx_core.multigpu.vae.distributed_decoder import dist_rank_tile_pixel_shape+from ltx_core.quantization import QuantizationPolicy+from ltx_core.quantization.fp8_cast import build_policy as _build_fp8_cast_policy+from ltx_core.tiling import DimensionTilingConfig, TileCountConfig, balanced_tile_split+from ltx_core.types import VIDEO_SCALE_FACTORS, SpatioTemporalScaleFactors, VideoLatentShape, VideoPixelShape+from ltx_pipelines.dfr_pipeline import DFRPipeline, add_dfr_cli_args+from ltx_pipelines.multigpu.controller import MGPUController+from ltx_pipelines.multigpu.gemma_builders import AccelerateGemmaBuilder+from ltx_pipelines.multigpu.runner import MGPURunner+from ltx_pipelines.multigpu.sp_builder import SequenceParallelBuilder+from ltx_pipelines.multigpu.vae_builders import DistributedDecoderBuilder+from ltx_pipelines.multigpu.weight_tracker import TransformerWeightTracker+from ltx_pipelines.utils.media_io import encode_video+from ltx_pipelines.utils.model_paths import ModelPaths+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration++logger = logging.getLogger(__name__)++# Stage 2 at 4K dominates. 3840x2176 (4K UHD height snapped to the 32x VAE grid)+# with 301 pixel frames pads to a 313-frame DFR canvas (F_lat=40, 13 keyframe+# slots) plus the x2 IC-LoRA half-res reference:+# 40*68*120 + 13*68*120 + 40*34*60 = 514080 video tokens.+_DEFAULT_SP_MAX_TOKENS = 524288+# Rank that collects distributed-VAE tiles and encodes the assembled video.+_DRIVER_RANK = 0+# Temporal batches the driver assembles the decoded canvas in. One batch per rank (the Dist+# default) is 129 frames of 3840x2176 RGB bf16 -- 6.5 GiB on top of a driver already holding+# every rank's decoded tile. 16 keeps a batch near 1.7 GiB; the encoder consumes them one at a time.+_DEFAULT_VAE_TEMPORAL_BATCHES = 16+++@contextmanager+def _dfr_dist_tile_auto_tiling(+ vae_tiling: TileCountConfig,+ *,+ rank: int,+ world_size: int,+ scale: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> Iterator[None]:+ """Rewrite ``DFRPipeline`` AUTO recommend to this rank's Dist-tile pixel shape.+ Patches ``ltx_pipelines.dfr_pipeline.ensure_tiling_config`` (the name+ ``DFRPipeline.__call__`` looks up) for the duration of the ``with`` block.+ Dist stays a pass-through; the pipeline still returns the resolved+ ``TilingConfig``. Explicit configs and ``None`` are unchanged.+ """+ import ltx_pipelines.dfr_pipeline as dfr_mod # noqa: PLC0415++ orig = dfr_mod.ensure_tiling_config++ @wraps(orig)+ def ensure_tiling_config_dist_tile(+ tiling_config: TilingConfig | AutoTiling | None,+ *,+ video_shape: VideoPixelShape,+ scale_factors: SpatioTemporalScaleFactors,+ vae_checkpoint_path: str,+ diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,+ device: torch.device | None = None,+ free_bytes: int | None = None,+ keyframes: bool = False,+ ) -> TilingConfig | None:+ if isinstance(tiling_config, AutoTiling):+ latent_shape = VideoLatentShape.from_pixel_shape(video_shape, scale_factors=scale)+ tile_shape = dist_rank_tile_pixel_shape(+ vae_tiling,+ latent_shape,+ scale,+ rank,+ world_size,+ fps=video_shape.fps,+ batch=video_shape.batch,+ )+ logger.info(+ "rank=%s AUTO_TILING Dist tile video_shape=%s (full canvas %s)",+ rank,+ tile_shape,+ video_shape,+ )+ video_shape = tile_shape+ return orig(+ tiling_config,+ video_shape=video_shape,+ scale_factors=scale_factors,+ vae_checkpoint_path=vae_checkpoint_path,+ diffvae_optimization=diffvae_optimization,+ device=device,+ free_bytes=free_bytes,+ keyframes=keyframes,+ )++ dfr_mod.ensure_tiling_config = ensure_tiling_config_dist_tile+ try:+ yield+ finally:+ dfr_mod.ensure_tiling_config = orig+++class DFRRunner(MGPURunner):+ """Distributed :class:`DFRPipeline`: SP on both stages + Accelerate Gemma + distributed VAE."""++ _vae_tiling: TileCountConfig | None = None++ @torch.inference_mode()+ def setup( # noqa: PLR0913+ self,+ *,+ model_paths: ModelPaths,+ spatial_upsampler_path: str,+ vae_queue: SimpleQueue,+ detailing_lora: Sequence[LoraPathStrengthAndSDOps],+ prompt_enhancer_gemma_root: str | None = None,+ temporal_upsampler_path: str | None = None,+ loras: Sequence[LoraPathStrengthAndSDOps] = (),+ compilation_config: CompilationConfig | None = None,+ sp_max_tokens: int = _DEFAULT_SP_MAX_TOKENS,+ quantization: Callable[[], QuantizationPolicy] | None = None,+ diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,+ vae_temporal_batches: int = _DEFAULT_VAE_TEMPORAL_BATCHES,+ ) -> None:+ # quantization is a picklable zero-arg builder (built per worker, post-spawn); default fp8-cast.+ quantization_policy = (+ quantization() if quantization is not None else _build_fp8_cast_policy(model_paths.transformer())+ )+ registry = ModelRegistry(cache_models=True, cache_weights=True)+ pipeline = DFRPipeline(+ model_paths=model_paths,+ spatial_upsampler_path=spatial_upsampler_path,+ loras=list(loras),+ detailing_lora=list(detailing_lora),+ temporal_upsampler_path=temporal_upsampler_path,+ prompt_enhancer_gemma_root=prompt_enhancer_gemma_root,+ registry=registry,+ quantization=quantization_policy,+ compilation_config=compilation_config,+ alloc_trim_strategy=AllocatorTrimStrategy.DEFER,+ diffvae_optimization=diffvae_optimization,+ )+ tracker = TransformerWeightTracker(group=self.groups.transformer_group)++ # SP on both stages: stage 1 / temporal rounds share ``stage``; stage 2 /+ # the spatial epilogue use ``stage_detailing`` (same checkpoint, extra IC-LoRA).+ model_cfg = pipeline.stage._transformer_builder.model_config().get("transformer", {})+ attn_mgr = AttentionManager(+ max_tokens=sp_max_tokens,+ num_heads=model_cfg["num_attention_heads"],+ head_dim=model_cfg["attention_head_dim"],+ tensor_dtype=pipeline.dtype,+ group=self.groups.transformer_group,+ )+ for stage in (pipeline.stage, pipeline.stage_detailing):+ stage._transformer_builder = SequenceParallelBuilder(+ inner=stage._transformer_builder,+ attn_mgr=attn_mgr,+ registry=registry,+ tracker=tracker,+ )++ # Accelerate Gemma parallelization. Capture shared-vs-separate before replacing+ # the encode builder so a shared alias is re-bound to the new instance.+ pe = pipeline.prompt_encoder+ separate_enhancer = pe._enhancer_text_encoder_builder is not pe._text_encoder_builder+ pe._text_encoder_builder = AccelerateGemmaBuilder(+ gemma_root_path=model_paths.text_encoder(),+ gemma_group=self.groups.gemma_group,+ broadcast_group=self.groups.transformer_group,+ registry=registry,+ src_rank=_DRIVER_RANK,+ dtype=pipeline.dtype,+ )+ if separate_enhancer:+ assert prompt_enhancer_gemma_root is not None+ pe._enhancer_text_encoder_builder = AccelerateGemmaBuilder(+ gemma_root_path=prompt_enhancer_gemma_root,+ gemma_group=self.groups.gemma_group,+ broadcast_group=self.groups.transformer_group,+ registry=registry,+ src_rank=_DRIVER_RANK,+ dtype=pipeline.dtype,+ )+ else:+ pe._enhancer_text_encoder_builder = pe._text_encoder_builder++ # Distributed VAE decoding: balanced 2D spatial grid over the group (one tile/rank).+ # height takes the smaller factor of world_size, width the larger; size-aware split is a follow-up.+ vae_height_tiles, vae_width_tiles = balanced_tile_split(dist.get_world_size(self.groups.vae_group))+ vae_tiling = TileCountConfig(+ height=DimensionTilingConfig(num_tiles=vae_height_tiles, overlap=4),+ width=DimensionTilingConfig(num_tiles=vae_width_tiles, overlap=4),+ )+ pipeline.video_decoder._decoder_builder = DistributedDecoderBuilder( # type: ignore[assignment]+ inner=pipeline.video_decoder._decoder_builder,+ queue=vae_queue,+ vae_group=self.groups.vae_group,+ vae_tiling=vae_tiling,+ driver_rank=_DRIVER_RANK,+ registry=registry,+ num_temporal_batches=vae_temporal_batches,+ )+ self._vae_tiling = vae_tiling+ self._pipeline = pipeline++ @torch.inference_mode()+ def __call__( # noqa: PLR0913+ self,+ *,+ output_path: str,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ frame_rate: float,+ num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,+ images: list[Any] | None = None,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ temporal_upscalings: int = 0,+ spatial_upscalings: int = 1,+ ) -> Iterator[str | None]:+ # The pipeline raises ValueError on invalid input (symmetric across ranks); the controller+ # catches that and turns it into a recoverable RunnerError. Anything else is fatal.+ vae_tiling = self._vae_tiling+ auto_tile = (+ _dfr_dist_tile_auto_tiling(+ vae_tiling,+ rank=dist.get_rank(self.groups.vae_group),+ world_size=dist.get_world_size(self.groups.vae_group),+ )+ if vae_tiling is not None+ else nullcontext()+ )+ with auto_tile:+ result = self._pipeline(+ prompt=prompt,+ seed=seed,+ height=height,+ width=width,+ num_frames=num_frames,+ frame_rate=frame_rate,+ images=images or [],+ tiling_config=AUTO_TILING,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ temporal_upscalings=temporal_upscalings,+ spatial_upscalings=spatial_upscalings,+ )+ if dist.get_rank() != _DRIVER_RANK:+ yield None # workers: nothing to encode+ return+ encode_video(+ video=result.video,+ fps=int(frame_rate * (2**temporal_upscalings)),+ audio=result.audio,+ output_path=output_path,+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ )+ yield output_path+++if __name__ == "__main__":+ from ltx_pipelines.utils.args import default_2_stage_distilled_arg_parser, resolve_cli_params++ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")+ params = resolve_cli_params(distilled=True)+ parser = add_dfr_cli_args(default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True))+ args = parser.parse_args()++ vae_queue = torch.multiprocessing.get_context("spawn").SimpleQueue()+ controller = MGPUController(DFRRunner)+ controller.start(+ model_paths=args.model_paths,+ prompt_enhancer_gemma_root=args.prompt_enhancer_gemma_root,+ spatial_upsampler_path=args.spatial_upsampler_path,+ vae_queue=vae_queue,+ detailing_lora=args.detailing_lora,+ temporal_upsampler_path=args.temporal_upsampler_path,+ loras=tuple(args.lora) if args.lora else (),+ compilation_config=args.compile,+ diffvae_optimization=args.diffvae_optimization,+ )+ try:+ for _ in controller.stream(+ output_path=args.output_path,+ prompt=args.prompt,+ seed=args.seed,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ frame_rate=args.frame_rate,+ images=args.images,+ enhance_prompt=args.enhance_prompt,+ enhance_static_cache=args.enhance_static_cache,+ temporal_upscalings=args.temporal_upscalings,+ spatial_upscalings=args.spatial_upscalings,+ ):+ pass # drive the job to completion; the runner writes the file as a side effect+ finally:+ controller.shutdown()diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.pyindex 69db24d..6bd066d 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py@@ -2,13 +2,16 @@from __future__ import annotations+import argparseimport logging-from collections.abc import Iterator, Sequence-from dataclasses import replace as dataclass_replace+from collections.abc import Sequence+from dataclasses import replacefrom functools import partial+from typing import TYPE_CHECKING+import numpy as npimport torch-from safetensors import safe_open+from PIL import Imagefrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.components.diffusion_steps import EulerAncestralDiffusionStep@@ -21,22 +24,31 @@ from ltx_core.conditioning import ()from ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registry+from ltx_core.modality_tiling import VideoModalityTilingHelperfrom ltx_core.model.transformer.compiling import CompilationConfig-from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_number+from ltx_core.model.transformer.modality import Modality+from ltx_core.model.video_vae import (+ AUTO_TILING,+ AutoTiling,+ TilingConfig,+ VideoEncoder,+ get_video_chunks_number,+)from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import VIDEO_SCALE_FACTORS, Audio, LatentState, VideoPixelShape+from ltx_core.tiling import DimensionTilingConfig, Tile, TileCountConfig+from ltx_core.tools import LatentTools, VideoLatentTools+from ltx_core.types import VIDEO_SCALE_FACTORS, AudioLatentShape, LatentState, VideoPixelShapefrom ltx_pipelines.dfr_layout import (- remap_positions_to_local,+ TemporalTilePlan,+ pixel_to_latent_index,resolve_canvas,- stitch_tile_latents,- tile_ranges,)from ltx_pipelines.iclora_utils import read_lora_reference_downscale_factorfrom ltx_pipelines.utils.args import (ImageConditioningInput,LoraAction,- default_2_stage_arg_parser,+ default_2_stage_distilled_arg_parser,resolve_cli_params,resolve_existing_path,)@@ -56,14 +68,18 @@ from ltx_pipelines.utils.denoisers import SimpleDenoiserfrom ltx_pipelines.utils.helpers import (assert_resolution,combined_image_conditionings,+ decode_keyframes_from_slots,ensure_tiling_config,get_device,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import encode_video+from ltx_pipelines.utils.media_io import encode_video, to_vae_rangefrom ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput++if TYPE_CHECKING:+ from ltx_core.guidance.perturbations import BatchedPerturbationConfiglogger = logging.getLogger(__name__)@@ -71,11 +87,213 @@ logger = logging.getLogger(__name__)# tile can still settle its seam frame._ANCHOR_KEYFRAME_STRENGTH = 0.95_TEMPORAL_ANCESTRAL_ETA = 0.5-# Conditioning fps is capped independently of playback fps. RoPE time is ``pixel_frame / fps``, so a-# 120 fps time base halves every token's temporal span versus the trained distribution and the model-# can no longer lay out the 8 pixel frames inside one latent token -- it decodes as a motion spike at-# each latent border followed by a stall. Playback fps is used for decoding only.+# Transformer fps is independent of playback fps. RoPE time is ``pixel_frame / fps``, so rates the+# model never saw (48, 50, 120, ...) cannot lay out the 8 pixel frames inside one latent token --+# they decode as a motion spike at each latent border followed by a stall. Anything above 30 snaps+# to 60; playback fps is used for decoding only._MAX_CONDITIONING_FPS = 60.0+_SNAP_CONDITIONING_FPS_ABOVE = 30.0+++def _conditioning_fps(playback_fps: float) -> float:+ """RoPE/token fps for the transformer. Values above 30 snap to 60; playback fps is unchanged."""+ return _MAX_CONDITIONING_FPS if playback_fps > _SNAP_CONDITIONING_FPS_ABOVE else playback_fps+++# HDR stage-2 spatial overlap. Temporal epilogue tiles cut on the last t-round's window+# seams (same lead-in dropout; the earlier tile keeps the seam cell). Spatial tiles inside+# a time window blend and retile after every Euler step; time windows are not blended.+_EPILOGUE_SPATIAL_OVERLAP = 12+_EPILOGUE_KEYFRAME_STRENGTH = 1.0+_DETAILING_LORA_STRENGTH = 0.5+++def _lanczos_x2_fhwc(frames: torch.Tensor) -> torch.Tensor:+ """Stretch each RGB frame 2x with Lanczos. ``frames`` is ``(F, H, W, C)`` in ``[0, 1]``."""+ if frames.ndim != 4:+ raise ValueError(f"Expected (F, H, W, C) RGB, got shape {tuple(frames.shape)}")+ if frames.shape[0] < 1:+ raise ValueError("Need at least one frame to Lanczos-upsample")+ out: list[torch.Tensor] = []+ for frame in frames:+ height, width, channels = frame.shape+ array = (frame.detach().float().clamp(0, 1).cpu().numpy() * 255.0).round().astype(np.uint8)+ if channels == 1:+ image = Image.fromarray(array[..., 0], mode="L")+ elif channels == 3:+ image = Image.fromarray(array, mode="RGB")+ else:+ raise ValueError(f"Lanczos x2 expects 1 or 3 channels, got {channels}")+ image = image.resize((width * 2, height * 2), resample=Image.Resampling.LANCZOS)+ resized = torch.from_numpy(np.asarray(image, dtype=np.float32) / 255.0)+ if resized.ndim == 2:+ resized = resized.unsqueeze(-1)+ out.append(resized)+ return torch.stack(out, dim=0)+++def _clamp_dim_tiling(cfg: DimensionTilingConfig, dim_size: int, axis: str) -> DimensionTilingConfig:+ """Clamp a single dim's tile count and overlap to the latent's extent.+ ``split_by_count`` requires ``overlap < tile_size``; with+ ``tile_size = (dim_size + overlap*(n-1)) // n`` this reduces to+ ``overlap <= dim_size - n``. When the configured overlap exceeds this+ bound it is clamped; if the latent is too small to hold ``n`` tiles+ at all, tiling falls back to a single tile on this axis.+ """+ n = cfg.num_tiles+ if n <= 1:+ return cfg+ if dim_size < n:+ logger.warning(+ "%s tiling: dim_size=%d < num_tiles=%d; falling back to 1 tile on this axis.",+ axis,+ dim_size,+ n,+ )+ return DimensionTilingConfig(1, 0)+ max_overlap = dim_size - n+ if cfg.overlap <= max_overlap:+ return cfg+ logger.warning(+ "%s tiling: overlap=%d exceeds latent bound (%d); clamping to %d.",+ axis,+ cfg.overlap,+ max_overlap,+ max_overlap,+ )+ return DimensionTilingConfig(n, max_overlap)+++def _clamp_tile_to_latent(tiling: TileCountConfig, latent_shape: tuple[int, int, int]) -> TileCountConfig:+ """Clamp frame, height, and width tilings to the latent's extents.+ ``latent_shape`` is ``(F, H, W)`` in latent units.+ """+ frames, height, width = latent_shape+ return replace(+ tiling,+ frames=_clamp_dim_tiling(tiling.frames, frames, "Frame"),+ height=_clamp_dim_tiling(tiling.height, height, "Height"),+ width=_clamp_dim_tiling(tiling.width, width, "Width"),+ )+++class _TiledModelWrapper(torch.nn.Module):+ """Runs the transformer once per latent tile and blends the tiles into one prediction.+ The single-GPU counterpart of+ :class:`~ltx_core.multigpu.transformer.tiled_data_parallel.TiledDataParallelModelWrapper`:+ same :class:`VideoModalityTilingHelper`, same trapezoidal blend masks, same+ conditioning-token filtering. Two differences: every tile runs here rather than round-robin+ across ranks, so the ranks' ``all_reduce`` is just the accumulator; and this wraps the+ ``X0Model`` instead of the bare velocity model, so it blends x0 predictions rather than+ velocities. ``to_denoised`` is affine in the velocity and every tile sees the same+ per-token timesteps, so with blend weights summing to 1 the two are the same value.+ Tiling inside the model call is what makes the overlap agree at *every* denoising step: the+ sampler above still sees one full-canvas latent and takes one Euler step on it.+ """++ def __init__(+ self,+ model: torch.nn.Module,+ *,+ video_tools: VideoLatentTools,+ tiling: TileCountConfig,+ seams: Sequence[int] = (),+ normalize_positions: bool = True,+ ) -> None:+ super().__init__()+ self.model = model+ self._normalize_positions = normalize_positions+ self._helper = VideoModalityTilingHelper(tiling, video_tools, seams=seams)++ @property+ def num_blocks(self) -> int:+ return self.model.num_blocks++ @property+ def tiles(self) -> list[Tile]:+ """The tiles every forward pass walks, in blend order."""+ return self._helper.tiles++ def forward(+ self,+ video: Modality | None,+ audio: Modality | None,+ perturbations: BatchedPerturbationConfig | None,+ ) -> tuple[torch.Tensor | None, torch.Tensor | None]:+ if video is None:+ return self.model(video, audio, perturbations)++ denoised_video: torch.Tensor | None = None+ denoised_audio: torch.Tensor | None = None+ for tile in self._helper.tiles:+ tiled_video, ctx = self._helper.tile_modality(video, tile, normalize_positions=self._normalize_positions)+ tile_out, audio_out = self.model(tiled_video, audio, perturbations)+ denoised_video = self._helper.blend(tile_out, tile, ctx, denoised_video)+ if audio_out is not None:+ denoised_audio = audio_out if denoised_audio is None else denoised_audio + audio_out++ assert denoised_video is not None+ if denoised_audio is not None:+ # Every tile saw the whole audio but a different video context; average as TDP does.+ denoised_audio = denoised_audio / len(self._helper.tiles)+ return denoised_video, denoised_audio+++def _resample_audio_time(+ audio_latent: torch.Tensor,+ src_start: float,+ src_end: float,+ out_frames: int,+) -> torch.Tensor:+ """Linearly sample ``audio_latent`` along T over ``[src_start, src_end)`` latent cells."""+ if out_frames < 1:+ raise ValueError(f"out_frames must be >= 1, got {out_frames}")+ full_t = audio_latent.shape[2]+ if full_t < 1:+ raise ValueError("Cannot resample an empty audio latent")+ span = src_end - src_start+ if span <= 0:+ raise ValueError(f"Audio window is empty: [{src_start}, {src_end})")+ step = span / out_frames+ positions = src_start + step * torch.arange(out_frames, device=audio_latent.device, dtype=torch.float32)+ positions = positions.clamp(0, full_t - 1)+ lo = positions.floor().long()+ hi = (lo + 1).clamp(max=full_t - 1)+ weight = (positions - lo.to(torch.float32)).to(dtype=audio_latent.dtype).view(1, 1, -1, 1)+ return audio_latent[:, :, lo] * (1 - weight) + audio_latent[:, :, hi] * weight+++def _audio_latent_for_tile(+ audio_latent: torch.Tensor,+ *,+ pixel_start: int,+ local_frames: int,+ playback_fps: float,+ source_duration: float,+ cond_fps: float,+) -> torch.Tensor:+ """Stage-1 audio for one temporal tile: playback window, resampled to the stage's token count.+ Source bounds are wall-clock: ``pixel_start / playback_fps`` through+ ``(pixel_start + local_frames) / playback_fps``, as a fraction of ``source_duration`` (stage 1's+ ``N / fps``). Temporal upsample uses ``N -> 2(N-1)+1`` while fps doubles, so the new canvas is+ slightly shorter than ``2x``; a fraction of *canvas frames* would therefore pull audio from past+ the tile's playback. ``cond_fps`` sizes only the *output* token count DiffusionStage allocates.+ """+ if local_frames <= 0:+ raise ValueError(f"local_frames must be >= 1, got {local_frames}")+ if playback_fps <= 0:+ raise ValueError(f"playback_fps must be > 0, got {playback_fps}")+ if source_duration <= 0:+ raise ValueError(f"source_duration must be > 0, got {source_duration}")+ full_t = audio_latent.shape[2]+ if full_t <= 0:+ raise ValueError("Cannot slice audio for a tile with an empty audio latent")+ src_start = pixel_start / playback_fps / source_duration * full_t+ src_end = (pixel_start + local_frames) / playback_fps / source_duration * full_t+ target_frames = AudioLatentShape.from_video_pixel_shape(+ VideoPixelShape(batch=1, frames=local_frames, height=1, width=1, fps=cond_fps)+ ).frames+ return _resample_audio_time(audio_latent, src_start, src_end, target_frames)def _keyframe_conditionings_from_latents(@@ -139,41 +357,55 @@ def _merge_carry_forward_keyframes(return ordered, torch.cat([by_position[position] for position in ordered], dim=2)-def _detailing_downscale_factor(lora_path: str) -> int:- """Prefer LoRA metadata; default to 2 for x2 spatial detailing."""- try:- with safe_open(lora_path, framework="pt") as handle:- metadata = handle.metadata() or {}- if "reference_downscale_factor" in metadata:- return int(metadata["reference_downscale_factor"])- except Exception as exc:- logger.warning("Failed to read detailing LoRA metadata from %s: %s", lora_path, exc)- factor = read_lora_reference_downscale_factor(lora_path)- return factor if factor != 1 else 2+def _rebase_image_conditionings(+ images: Sequence[ImageConditioningInput],+ *,+ pixel_scale: int,+ pixel_start: int = 0,+ pixel_end: int | None = None,+) -> list[ImageConditioningInput]:+ """Map user ``frame_idx`` values from the requested canvas onto a temporally-upsampled grid.+ After ``r`` temporal rounds the same moment sits at ``frame_idx * 2**r``. When ``pixel_end`` is+ set, only images inside ``[pixel_start, pixel_end]`` are kept and indices become tile-local.+ """+ rebased: list[ImageConditioningInput] = []+ for image in images:+ scaled = image.frame_idx * pixel_scale+ if pixel_end is not None and not (pixel_start <= scaled <= pixel_end):+ continue+ rebased.append(ImageConditioningInput(image.path, scaled - pixel_start, image.strength, image.crf))+ return rebasedclass DFRPipeline:"""- DFR pipeline on a keyframe-slot-capable SFT base plus a distilled LoRA.+ DFR pipeline on a keyframe-slot-capable distilled checkpoint.Stage 1 (half-res) generates video and keyframe slots on an x8-border segment grid; the half-resvideo is reserved as the IC-LoRA reference while video and slots are spatially latent-upsampled.- Stage 2 re-denoises at full resolution with the distilled LoRA and an optional x2 detailing+ Stage 2 re-denoises at full resolution with an x2 detailingIC-LoRA. Shipped audio comes from stage 1: stage 2 still runs an audio pass because video needs- the cross-modal attention, but it re-noises audio under the detailing LoRA and no later stage- refines it.- Optional ``temporal_upsample_rounds`` (0-2): each round temporally x2-upsamples, splits the canvas+ the cross-modal attention, but it re-noises audio under the detailing LoRA. Temporal tiles pass+ frozen stage-1 audio sliced to the tile's playback window (retiled onto the snapped-fps token+ count) for cross-attention only; they do not refine or ship audio.+ Optional ``temporal_upscalings`` (0-2): each round temporally x2-upsamples, splits the canvasinto ``2**round`` keyframe-seam tiles, invents mid-segment slots per tile, densifies with ancestral- Euler, and stitches. The caller always gets ``(num_frames - 1) * 2**rounds + 1`` frames even when- the canvas padded its tail.+ Euler, and stitches. Optional ``spatial_upscalings`` (1 or 2): ``1`` is stage 1 at ``h/2`` and+ stage 2 at ``h``; ``2`` is stage 1 at ``h/4``, stage 2 at ``h/2``, then a full-res spatial+ detailing epilogue at ``h``. Carry keyframes are decoded one plane at a time, Lanczos-stretched+ x2 in RGB, and encoded again; only the video latent is spatially upsampled. The epilogue runs+ the 3-step detailing schedule with those keyframes as strength-1 conditions and the previous-stage+ video as the IC-LoRA reference. Temporal tiles are seam-cut (lead-in dropped, earlier tile+ keeps the seam). Spatial tiles inside a time window blend and retile after every Euler+ step; time windows are not blended into each other. The caller always+ gets ``(num_frames - 1) * 2**rounds + 1`` frames even when the canvas padded its tail."""def __init__( # noqa: PLR0913self,model_paths: ModelPaths,- distilled_lora: list[LoraPathStrengthAndSDOps],spatial_upsampler_path: str,loras: list[LoraPathStrengthAndSDOps],- detailing_lora: list[LoraPathStrengthAndSDOps] | None = None,+ detailing_lora: list[LoraPathStrengthAndSDOps],temporal_upsampler_path: str | None = None,device: torch.device | None = None,quantization: QuantizationPolicy | None = None,@@ -186,12 +418,13 @@ class DFRPipeline:):self.device = device or get_device()self.dtype = torch.bfloat16- self._distilled_lora = tuple(distilled_lora)self._user_loras = tuple(loras)- self._detailing_lora = tuple(detailing_lora or ())- self._detailing_downscale = (- _detailing_downscale_factor(self._detailing_lora[0].path) if self._detailing_lora else 2+ if not detailing_lora:+ raise ValueError("detailing_lora is required")+ self._detailing_lora = tuple(+ LoraPathStrengthAndSDOps(item.path, _DETAILING_LORA_STRENGTH, item.sd_ops) for item in detailing_lora)+ self._detailing_downscale = read_lora_reference_downscale_factor(self._detailing_lora[0].path)self.prompt_encoder = PromptEncoder(model_paths,@@ -209,7 +442,7 @@ class DFRPipeline:registry=registry,alloc_trim_strategy=alloc_trim_strategy,)- stage_loras = (*self._user_loras, *self._distilled_lora)+ stage_loras = self._user_lorasself.stage = DiffusionStage.from_checkpoint(model_paths.transformer(),self.dtype,@@ -221,9 +454,7 @@ class DFRPipeline:offload_mode=offload_mode,alloc_trim_strategy=alloc_trim_strategy,)- self.stage_detailing = (- self.stage.with_loras((*stage_loras, *self._detailing_lora)) if self._detailing_lora else self.stage- )+ self.stage_detailing = self.stage.with_loras((*stage_loras, *self._detailing_lora))self.upsampler = VideoUpsampler(model_paths.video_vae(),spatial_upsampler_path,@@ -265,6 +496,33 @@ class DFRPipeline:self.device,)+ def _emit_stage(+ self,+ name: str,+ *,+ latent: torch.Tensor,+ keyframes: torch.Tensor | None,+ positions: Sequence[int],+ height: int,+ width: int,+ num_frames: int,+ fps: float,+ ) -> None:+ """Optional dump hook. No-op unless the caller set ``_stage_latent_sink``."""+ sink = getattr(self, "_stage_latent_sink", None)+ if sink is None:+ return+ sink(+ name,+ latent=latent,+ keyframes=keyframes,+ positions=positions,+ height=height,+ width=width,+ num_frames=num_frames,+ fps=fps,+ )+def __call__( # noqa: PLR0912, PLR0913, PLR0915self,prompt: str,@@ -274,21 +532,29 @@ class DFRPipeline:frame_rate: float,images: list[ImageConditioningInput],num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,- temporal_upsample_rounds: int = 0,+ temporal_upscalings: int = 0,+ spatial_upscalings: int = 1,tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,enhance_prompt: bool = False,enhance_static_cache: bool = False,stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- ) -> tuple[Iterator[torch.Tensor], Audio, int, TilingConfig | None]:- if temporal_upsample_rounds not in (0, 1, 2):- raise ValueError(f"temporal_upsample_rounds must be 0, 1, or 2, got {temporal_upsample_rounds}")- if temporal_upsample_rounds > 0 and self.temporal_upsampler is None:- raise ValueError("temporal_upsample_rounds > 0 requires temporal_upsampler_path")+ ) -> PipelineOutput:+ if temporal_upscalings not in (0, 1, 2):+ raise ValueError(f"temporal_upscalings must be 0, 1, or 2, got {temporal_upscalings}")+ if temporal_upscalings > 0 and self.temporal_upsampler is None:+ raise ValueError("temporal_upscalings > 0 requires temporal_upsampler_path")+ if spatial_upscalings not in (1, 2):+ raise ValueError(f"spatial_upscalings must be 1 or 2, got {spatial_upscalings}")require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)- assert_resolution(height=height, width=width, is_two_stage=True)+ assert_resolution(+ height=height,+ width=width,+ is_two_stage=True,+ divisor=64 if spatial_upscalings == 1 else 128,+ )generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)@@ -311,12 +577,17 @@ class DFRPipeline:frame_rate=frame_rate,)requested_frames = num_frames- num_frames, _segment, positions = resolve_canvas(num_frames)+ num_frames, _, positions = resolve_canvas(num_frames)+ stage_1_frames = num_frames+ stage_1_duration = stage_1_frames / frame_rateself.stage.assert_generated_keyframes_supported()- # --- Stage 1: half-res base + keyframe slots -----------------------------------+ spatial_div = 2**spatial_upscalings+ stage_1_w, stage_1_h = width // spatial_div, height // spatial_div+ stage_2_w, stage_2_h = width // (spatial_div // 2), height // (spatial_div // 2)++ # --- Stage 1: half-res (or quarter-res) base + keyframe slots -------------------stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)- stage_1_w, stage_1_h = width // 2, height // 2stage_1_conditionings = self.image_conditioner(lambda enc: combined_image_conditionings(images=images,@@ -336,7 +607,10 @@ class DFRPipeline:width=stage_1_w,height=stage_1_h,frames=num_frames,- fps=frame_rate,+ fps=_conditioning_fps(frame_rate),+ # Shipped audio is stage 1's, so it must be as long as the clip plays. The snapped+ # transformer fps would otherwise size it from ``num_frames / 60``.+ audio_fps=frame_rate,video=ModalitySpec(context=video_context, conditionings=stage_1_conditionings),audio=ModalitySpec(context=audio_context),)@@ -353,8 +627,8 @@ class DFRPipeline:stage_2_conditionings = self.image_conditioner(lambda enc: combined_image_conditionings(images=images,- height=height,- width=width,+ height=stage_2_h,+ width=stage_2_w,video_encoder=enc,dtype=dtype,device=self.device,@@ -363,23 +637,24 @@ class DFRPipeline:stage_2_conditionings.append(VideoGeneratedKeyframeSlots(pixel_frame_indices=positions, initial_keyframes=upsampled_slot_keyframes))- if self._detailing_lora:- stage_2_conditionings.append(- VideoConditionByReferenceLatent(- latent=reserved_half_res_video,- downscale_factor=self._detailing_downscale,- strength=1.0,- )+ stage_2_conditionings.append(+ VideoConditionByReferenceLatent(+ latent=reserved_half_res_video,+ downscale_factor=self._detailing_downscale,+ strength=1.0,)+ )video_state, audio_state = self.stage_detailing(denoiser=SimpleDenoiser(video_context, audio_context),sigmas=stage_2_sigmas,noiser=noiser,- width=width,- height=height,+ width=stage_2_w,+ height=stage_2_h,frames=num_frames,- fps=frame_rate,+ fps=_conditioning_fps(frame_rate),+ # Same basis as stage 1: this pass re-noises stage 1's audio latent.+ audio_fps=frame_rate,video=ModalitySpec(context=video_context,conditionings=stage_2_conditionings,@@ -398,8 +673,19 @@ class DFRPipeline:carry_keyframes = video_state.generated_keyframescurrent_fps = frame_ratetemporal_sigmas = DISTILLED_SIGMAS[4:].to(dtype=torch.float32, device=self.device)+ last_window_seams: list[int] = []+ self._emit_stage(+ "s2",+ latent=video_state.latent,+ keyframes=carry_keyframes,+ positions=carry_positions,+ height=stage_2_h,+ width=stage_2_w,+ num_frames=num_frames,+ fps=current_fps,+ )- for round_idx in range(1, temporal_upsample_rounds + 1):+ for round_idx in range(1, temporal_upscalings + 1):assert self.temporal_upsampler is not Noneif carry_keyframes is None or not carry_positions:raise RuntimeError(f"Temporal round {round_idx}: missing carry-forward keyframes")@@ -411,36 +697,36 @@ class DFRPipeline:seam_positions = [2 * position for position in carry_positions]anchor_keyframes = carry_keyframesseam_to_index = {seam: index for index, seam in enumerate(seam_positions)}- cond_fps = min(current_fps, _MAX_CONDITIONING_FPS)- tiles = tile_ranges(seam_positions, num_frames, 2**round_idx, temporal_scale=temporal_scale)+ cond_fps = _conditioning_fps(current_fps)+ windows = TemporalTilePlan(seam_positions, num_frames, 2**round_idx, temporal_scale)+ last_window_seams = list(seam_positions)tile_latents: list[torch.Tensor] = []slot_positions: list[int] = []slot_latent_slices: list[torch.Tensor] = []+ if stage_1_audio_latent is None:+ raise RuntimeError("DFR temporal tiles need the frozen stage-1 audio latent")- for tile_index, tile in enumerate(tiles):- local_frames = (tile.latent_end_exclusive - tile.latent_start - 1) * temporal_scale + 1- tile_video = video_latent[:, :, tile.latent_start : tile.latent_end_exclusive]-- # Image conditioning is tile-local: ``frame_idx=0`` means this tile's first frame, so- # re-applying the opening image on a non-first tile would pin the wrong frame onto the- # seam. Only images that actually fall inside the window are re-attached.- if tile.pixel_start == 0:- tile_images = images- else:- tile_images = [- ImageConditioningInput(- image.path, image.frame_idx - tile.pixel_start, image.strength, image.crf- )- for image in images- if tile.pixel_start <= image.frame_idx <= tile.pixel_end- ]+ for tile_index, (interval, pixel_start, pixel_end, anchor_global, slot_global) in enumerate(windows):+ local_frames = (interval.end - interval.start - 1) * temporal_scale + 1+ tile_video = video_latent[:, :, interval.start : interval.end]++ # Image conditioning is tile-local: ``frame_idx`` is on the requested canvas, so+ # scale onto this round's grid (``* 2**round``) before the window test and re-base.+ # ``frame_idx=0`` still means this tile's first frame after re-basing, so only+ # images that actually fall inside the window are re-attached.+ tile_images = _rebase_image_conditionings(+ images,+ pixel_scale=2**round_idx,+ pixel_start=pixel_start,+ pixel_end=pixel_end,+ )round_conditionings = (self.image_conditioner(lambda enc, _images=tile_images: combined_image_conditionings(images=_images,- height=height,- width=width,+ height=stage_2_h,+ width=stage_2_w,video_encoder=enc,dtype=dtype,device=self.device,@@ -451,7 +737,6 @@ class DFRPipeline:)# Every seam in the window is a hard keyframe, including the one at local frame 0.- anchor_global = list(tile.anchor_kf_global)if anchor_global:missing = [position for position in anchor_global if position not in seam_to_index]if missing:@@ -462,14 +747,13 @@ class DFRPipeline:round_conditionings.extend(_keyframe_conditionings_from_latents(anchor_latents,- remap_positions_to_local(anchor_global, tile.pixel_start),+ [int(position) - pixel_start for position in anchor_global],strength=_ANCHOR_KEYFRAME_STRENGTH,))- slot_global = list(tile.slot_kf_global)if slot_global:- slot_local = remap_positions_to_local(slot_global, tile.pixel_start)+ slot_local = [int(position) - pixel_start for position in slot_global]round_conditionings.append(VideoGeneratedKeyframeSlots(pixel_frame_indices=slot_local,@@ -481,8 +765,8 @@ class DFRPipeline:denoiser=SimpleDenoiser(video_context, audio_context),sigmas=temporal_sigmas,noiser=noiser,- width=width,- height=height,+ width=stage_2_w,+ height=stage_2_h,frames=local_frames,fps=cond_fps,video=ModalitySpec(@@ -491,13 +775,25 @@ class DFRPipeline:noise_scale=temporal_sigmas[0].item(),initial_latent=tile_video,),- audio=None,+ audio=ModalitySpec(+ context=audio_context,+ frozen=True,+ noise_scale=0.0,+ initial_latent=_audio_latent_for_tile(+ stage_1_audio_latent,+ pixel_start=pixel_start,+ local_frames=local_frames,+ playback_fps=current_fps,+ source_duration=stage_1_duration,+ cond_fps=cond_fps,+ ),+ ),stepper=EulerAncestralDiffusionStep(eta=_TEMPORAL_ANCESTRAL_ETA),# Tiles are positionally identical, so a shared ancestral seed would inject# byte-identical noise into every one of them.loop=partial(euler_ancestral_denoising_loop, noise_seed=seed + 1000 * round_idx + tile_index),)- tile_latents.append(tile_state.latent[:1])+ tile_latents.append(tile_state.latent[:1, :, interval.left_ramp :])if slot_global:if tile_state.generated_keyframes is None:@@ -505,13 +801,13 @@ class DFRPipeline:slot_positions.extend(slot_global)slot_latent_slices.append(tile_state.generated_keyframes)- stitched = stitch_tile_latents(tile_latents, tiles)+ stitched = torch.cat(tile_latents, dim=2)expected_t = (num_frames - 1) // temporal_scale + 1if stitched.shape[2] != expected_t:raise RuntimeError(f"Stitched latent T={stitched.shape[2]} != expected {expected_t}")if not isinstance(video_state, LatentState):raise TypeError(f"Expected LatentState, got {type(video_state)}")- video_state = dataclass_replace(video_state, latent=stitched, generated_keyframes=None)+ video_state = replace(video_state, latent=stitched, generated_keyframes=None)slot_latents = torch.cat(slot_latent_slices, dim=2) if slot_latent_slices else Noneif slot_positions and slot_latents is not None:@@ -527,19 +823,101 @@ class DFRPipeline:carry_positions, carry_keyframes = _merge_carry_forward_keyframes(seam_positions, anchor_keyframes, slot_positions, slot_latents)+ self._emit_stage(+ f"t{round_idx}",+ latent=video_state.latent,+ keyframes=carry_keyframes,+ positions=carry_positions,+ height=stage_2_h,+ width=stage_2_w,+ num_frames=num_frames,+ fps=current_fps,+ )++ # --- Spatial epilogue (spatial_upscalings == 2): s2 is h/2; this pass is final H x W ---+ if spatial_upscalings == 2:+ if carry_keyframes is None or not carry_positions:+ raise RuntimeError("Spatial epilogue: missing carry-forward keyframes")+ guide = video_state.latent[:1]+ pixel_keyframes = self._decode_lanczos_carry_keyframes(carry_keyframes, seed)+ upscaled_video = self.upsampler(guide)++ def _encode_epilogue_keyframes(enc: VideoEncoder) -> tuple[list[ConditioningItem], torch.Tensor]:+ image_conds = combined_image_conditionings(+ images=_rebase_image_conditionings(images, pixel_scale=2**temporal_upscalings),+ height=height,+ width=width,+ video_encoder=enc,+ dtype=dtype,+ device=self.device,+ )+ planes = []+ for rgb in pixel_keyframes:+ sample = to_vae_range(rgb.to(device=self.device, dtype=torch.float32))+ sample = sample.permute(3, 0, 1, 2).unsqueeze(0).contiguous().to(dtype=dtype)+ planes.append(enc(sample))+ return image_conds, torch.cat(planes, dim=2)++ epi_conditionings, encoded_kfs = self.image_conditioner(_encode_epilogue_keyframes)+ epi_conditionings.extend(+ _keyframe_conditionings_from_latents(encoded_kfs, carry_positions, strength=_EPILOGUE_KEYFRAME_STRENGTH)+ )+ epi_conditionings.append(+ VideoConditionByReferenceLatent(+ latent=guide,+ downscale_factor=self._detailing_downscale,+ strength=1.0,+ )+ )+ n_time_tiles = max(1, 2**temporal_upscalings)+ epi_seams = [pixel_to_latent_index(position, temporal_scale) for position in last_window_seams]+ temporal_overlap = (epi_seams[0] + 1) if n_time_tiles > 1 and epi_seams else 0+ epi_tiling = TileCountConfig(+ frames=DimensionTilingConfig(n_time_tiles, overlap=temporal_overlap),+ height=DimensionTilingConfig(2, _EPILOGUE_SPATIAL_OVERLAP),+ width=DimensionTilingConfig(2, _EPILOGUE_SPATIAL_OVERLAP),+ )+ if stage_1_audio_latent is None:+ raise RuntimeError("Spatial epilogue: missing stage-1 audio latent")+ cond_fps = _conditioning_fps(current_fps)+ epi_pixel_frames = (upscaled_video.shape[2] - 1) * temporal_scale + 1+ epi_latent = self._run_spatial_epilogue(+ latent=upscaled_video,+ conditionings=epi_conditionings,+ tiling=epi_tiling,+ sigmas=stage_2_sigmas,+ v_ctx=video_context,+ a_ctx=audio_context,+ audio_latent=_audio_latent_for_tile(+ stage_1_audio_latent,+ pixel_start=0,+ local_frames=epi_pixel_frames,+ playback_fps=current_fps,+ source_duration=stage_1_duration,+ cond_fps=cond_fps,+ ),+ fps=cond_fps,+ seed=seed,+ seams=epi_seams,+ )+ video_state = replace(video_state, latent=epi_latent, generated_keyframes=None)+ carry_keyframes = encoded_kfs# The canvas may have padded its tail, and each round maps N -> 2(N-1)+1, so the caller's# contract is ``(requested - 1) * 2**rounds + 1``. ``requested - 1`` is a multiple of the VAE# temporal scale, so the trim always lands on a latent boundary.- target_frames = (requested_frames - 1) * 2**temporal_upsample_rounds + 1+ target_frames = (requested_frames - 1) * 2**temporal_upscalings + 1if target_frames > num_frames:raise RuntimeError(f"Target {target_frames} frames exceeds the generated canvas {num_frames}")if target_frames != num_frames:keep_latents = (target_frames - 1) // temporal_scale + 1- video_state = dataclass_replace(video_state, latent=video_state.latent[:, :, :keep_latents])+ video_state = replace(video_state, latent=video_state.latent[:, :, :keep_latents])num_frames = target_frames+ # After the trim, so keyframes past the caller's last frame are dropped rather than+ # shipped pointing off-canvas.+ final_keyframes = decode_keyframes_from_slots(carry_keyframes, carry_positions, num_frames)- playback_fps = frame_rate * 2**temporal_upsample_rounds+ playback_fps = frame_rate * 2**temporal_upscalingstiling_config = ensure_tiling_config(tiling_config,scale_factors=tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path),@@ -547,8 +925,9 @@ class DFRPipeline:video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=playback_fps),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=final_keyframes is not None,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator)+ decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, keyframes=final_keyframes)if stage_1_audio_latent is None:raise RuntimeError("Stage 1 produced no audio latent to ship")decoded_audio = self.audio_decoder(stage_1_audio_latent)@@ -557,42 +936,148 @@ class DFRPipeline:video_seconds = num_frames / playback_fpsaudio_samples = min(decoded_audio.waveform.shape[-1], round(video_seconds * decoded_audio.sampling_rate))if audio_samples != decoded_audio.waveform.shape[-1]:- decoded_audio = dataclass_replace(decoded_audio, waveform=decoded_audio.waveform[..., :audio_samples])- return decoded_video, decoded_audio, num_frames, tiling_config+ decoded_audio = replace(decoded_audio, waveform=decoded_audio.waveform[..., :audio_samples])+ return PipelineOutput(+ decoded_video, decoded_audio, num_frames, tiling_config, final_keyframes, video_state.latent+ )+ def _decode_lanczos_carry_keyframes(self, keyframe_latents: torch.Tensor, seed: int) -> list[torch.Tensor]:+ """Decode each carry keyframe as its own 1-frame clip, then Lanczos-x2 the RGB.+ The VAE is causal, so a stacked encode/decode would bleed neighbouring planes. Each+ plane is a standalone one-pixel-frame latent, matching ``DecodeKeyframes``. Dist+ ``decode_single_frames`` is a local SGPU passthrough, so every rank gets pixels+ instead of the empty worker yield from ``decode_video``.+ """+ if keyframe_latents.ndim != 5:+ raise ValueError(f"Expected carry keyframes (B, C, K, H, W), got {tuple(keyframe_latents.shape)}")+ n_planes = keyframe_latents.shape[2]+ logger.info("Epilogue: decoding %d carry keyframes separately, then Lanczos x2", n_planes)+ planes = [keyframe_latents[:, :, index : index + 1] for index in range(n_planes)]+ generators = [torch.Generator(device=self.device).manual_seed(seed + 4000 + index) for index in range(n_planes)]+ rgb_planes: list[torch.Tensor] = []+ for index, rgb in enumerate(self.video_decoder.decode_single_frames(planes, generators)):+ if rgb.shape[0] < 1:+ raise RuntimeError(f"Decoder returned no pixels for carry keyframe {index}")+ rgb_planes.append(_lanczos_x2_fhwc(rgb.detach().cpu()))+ if len(rgb_planes) != n_planes:+ raise RuntimeError(f"Expected {n_planes} decoded carry keyframes, got {len(rgb_planes)}")+ return rgb_planes[email protected]_mode()-def main() -> None:- logging.basicConfig(level=logging.INFO)- params = resolve_cli_params()- parser = default_2_stage_arg_parser(params=params, supports_auto_duration=True)+ def _run_spatial_epilogue(+ self,+ *,+ latent: torch.Tensor,+ conditionings: list[ConditioningItem],+ tiling: TileCountConfig,+ sigmas: torch.Tensor,+ v_ctx: torch.Tensor,+ a_ctx: torch.Tensor,+ audio_latent: torch.Tensor,+ fps: float,+ seed: int,+ seams: Sequence[int] = (),+ ) -> torch.Tensor:+ """Full-res spatial detailing: one denoising loop over a canvas tiled inside the model.+ :class:`_TiledModelWrapper` tiles each transformer call and blends the per-tile+ predictions, so the sampler steps a single full-resolution canvas and the spatial overlap+ is reconciled at every Euler step rather than once at the end. Temporal tiles are cut on+ ``seams``, which makes their blend masks rectangular: the lead-in is denoised for context+ and then discarded, and the earlier tile keeps the seam cell. Conditionings are filtered+ per tile at the token level, so they are passed here on the full canvas.+ Audio is the frozen stage-1 latent, resampled onto this canvas, so video-audio cross+ attention still sees it. The returned audio state is discarded; the pipeline ships the+ original stage-1 audio.+ """+ tiling = _clamp_tile_to_latent(tiling, tuple(latent.shape[2:5]))+ _, _, n_frames, n_height, n_width = latent.shape+ scale_factors = self.stage_detailing.video_scale_factors+ pixel_frames = (n_frames - 1) * scale_factors.time + 1++ def _tile(model: torch.nn.Module, tools: LatentTools | None) -> torch.nn.Module:+ if not isinstance(tools, VideoLatentTools):+ raise TypeError(f"Spatial epilogue needs video tools to tile, got {type(tools).__name__}")+ return _TiledModelWrapper(model, video_tools=tools, tiling=tiling, seams=seams)++ stage = self.stage_detailing.with_model_wrapper(_tile)+ logger.info(+ "Spatial epilogue: %d step(s) over %s tiles (frames=%s height=%s width=%s, seams=%s)",+ sigmas.numel() - 1,+ tiling.frames.num_tiles * tiling.height.num_tiles * tiling.width.num_tiles,+ tiling.frames,+ tiling.height,+ tiling.width,+ list(seams),+ )+ video_state, _ = stage(+ denoiser=SimpleDenoiser(v_ctx, a_ctx),+ sigmas=sigmas.to(dtype=torch.float32, device=self.device),+ noiser=GaussianNoiser(generator=torch.Generator(device=self.device).manual_seed(seed + 2000)),+ width=n_width * scale_factors.width,+ height=n_height * scale_factors.height,+ frames=pixel_frames,+ fps=fps,+ video=ModalitySpec(+ context=v_ctx,+ conditionings=conditionings,+ noise_scale=float(sigmas[0].item()),+ initial_latent=latent.to(device=self.device, dtype=self.dtype),+ ),+ audio=ModalitySpec(+ context=a_ctx,+ frozen=True,+ noise_scale=0.0,+ initial_latent=audio_latent,+ ),+ )+ if video_state is None:+ raise RuntimeError("Spatial epilogue produced no video state")+ return video_state.latent+++def add_dfr_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """DFR-specific flags shared by the single-GPU and MGPU CLIs."""parser.add_argument("--detailing-lora",dest="detailing_lora",action=LoraAction,nargs="+",metavar=("PATH", "STRENGTH"),- default=[],- help="Stage-2 x2 spatial detailing IC-LoRA (path and optional strength). Omit to run without it.",+ required=True,+ help="Stage-2 x2 spatial detailing IC-LoRA (path; strength is hardcoded to 0.5).",)parser.add_argument("--temporal-upsampler-path",type=resolve_existing_path,default=None,- help="Path to the temporal x2 latent upsampler (required when --temporal-upsample-rounds > 0).",+ help="Path to the temporal x2 latent upsampler (required when --temporal-upscalings > 0).",)parser.add_argument(- "--temporal-upsample-rounds",+ "--temporal-upscalings",type=int,choices=(0, 1, 2),default=0,help="Number of temporal x2 refine rounds (0->base fps, 1->2x with 2 tiles, 2->4x with 4 tiles).",)+ parser.add_argument(+ "--spatial-upscalings",+ type=int,+ choices=(1, 2),+ default=1,+ help="Spatial upsample count: 1 is stage 1 at h/2 and stage 2 at h; 2 adds a full-res spatial "+ "detailing epilogue after the temporal rounds (stage 1 at h/4, stage 2 at h/2, epilogue at h).",+ )+ return parser++[email protected]_mode()+def main() -> None:+ logging.basicConfig(level=logging.INFO)+ params = resolve_cli_params(distilled=True)+ parser = add_dfr_cli_args(default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True))args = parser.parse_args()pipeline = DFRPipeline(model_paths=args.model_paths,- distilled_lora=args.distilled_lora,spatial_upsampler_path=args.spatial_upsampler_path,loras=tuple(args.lora) if args.lora else (),detailing_lora=args.detailing_lora,@@ -603,7 +1088,7 @@ def main() -> None:prompt_enhancer_gemma_root=args.prompt_enhancer_gemma_root,diffvae_optimization=args.diffvae_optimization,)- video, audio, num_frames, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,seed=args.seed,height=args.height,@@ -614,15 +1099,16 @@ def main() -> None:tiling_config=AUTO_TILING,enhance_prompt=args.enhance_prompt,enhance_static_cache=args.enhance_static_cache,- temporal_upsample_rounds=args.temporal_upsample_rounds,+ temporal_upscalings=args.temporal_upscalings,+ spatial_upscalings=args.spatial_upscalings,)encode_video(- video=video,- fps=int(args.frame_rate * (2**args.temporal_upsample_rounds)),- audio=audio,+ video=result.video,+ fps=int(args.frame_rate * (2**args.temporal_upscalings)),+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/distilled.py b/packages/ltx-pipelines/src/ltx_pipelines/distilled.pyindex 70e8efe..58e3c12 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/distilled.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/distilled.py@@ -1,5 +1,5 @@import logging-from collections.abc import Iterator, Sequence+from collections.abc import Sequencefrom functools import partialfrom typing import Any@@ -14,7 +14,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoPixelShape+from ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (ImageConditioningInput,add_generated_keyframes_arg,@@ -55,7 +55,7 @@ from ltx_pipelines.utils.media_io import ()from ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput# Generation from which stage 1 is sampled with the ancestral (SDE) Euler sampler instead of the# deterministic one.@@ -201,7 +201,7 @@ class DistilledPipeline:stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,- ) -> tuple[Iterator[torch.Tensor], Audio, int, TilingConfig | None]:+ ) -> PipelineOutput:"""Generate a video.Stage 1 samples with the ancestral (SDE) Euler sampler or the deterministic one accordingto ``self.use_ancestral_sampler``, detected from the checkpoint generation. Stage 2 is@@ -314,7 +314,7 @@ class DistilledPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, num_frames, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)@torch.inference_mode()@@ -337,7 +337,7 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,seed=args.seed,height=args.height,@@ -354,11 +354,11 @@ def main() -> None:)encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.pyindex 868a231..24efee6 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py@@ -160,7 +160,7 @@ class DistilledRunner(MGPURunner):# catches that and turns it into a recoverable RunnerError. Anything else is fatal.hdr = resolve_hdr_color_space(images=images or [], hdr=hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = self._pipeline(+ result = self._pipeline(prompt=prompt,seed=seed,height=height,@@ -179,11 +179,11 @@ class DistilledRunner(MGPURunner):yield None # workers: nothing to encodereturnencode_video(- video=video,+ video=result.video,fps=frame_rate,- audio=audio,+ audio=result.audio,output_path=output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)yield output_pathdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/dubit.py b/packages/ltx-pipelines/src/ltx_pipelines/dubit.pyindex 3956713..3316fc0 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dubit.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dubit.py@@ -3,7 +3,6 @@from __future__ import annotationsimport logging-from collections.abc import Iteratorimport torch@@ -25,7 +24,7 @@ from ltx_core.model.video_vae import ()from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape+from ltx_core.types import AudioLatentShape, VideoPixelShapefrom ltx_pipelines.iclora_utils import (append_ic_lora_reference_video_conditionings,read_lora_reference_downscale_factor,@@ -61,7 +60,7 @@ from ltx_pipelines.utils.media_io import (get_videostream_metadata,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutputclass DubItPipeline:@@ -207,7 +206,7 @@ class DubItPipeline:stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,- ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]:+ ) -> PipelineOutput:images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -225,7 +224,6 @@ class DubItPipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding@@ -329,7 +327,7 @@ class DubItPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(s1_audio_latent)- return decoded_video, decoded_audio, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)def patchify_dubit_audio_reference_latent(@@ -376,7 +374,7 @@ def main() -> None:)src = get_videostream_metadata(args.reference_video)# Dub-It is SDR-only (no ``--hdr``); EXR references are rejected in arg validation.- video, audio, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,seed=args.seed,height=args.height,@@ -389,11 +387,11 @@ def main() -> None:enhance_static_cache=args.enhance_static_cache,)encode_video(- video=video,+ video=result.video,fps=int(src.fps),- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(snap_frames_to_grid(src.frames), tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py b/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.pyindex e020c88..b427e5a 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py@@ -1,5 +1,4 @@import logging-from collections.abc import Iteratorimport torch@@ -12,7 +11,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, VideoEncoder, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoPixelShape+from ltx_core.types import VideoPixelShapefrom ltx_pipelines.iclora_utils import (append_ic_lora_reference_video_conditionings,read_lora_reference_downscale_factor,@@ -54,7 +53,7 @@ from ltx_pipelines.utils.media_io import (video_preprocess,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutputclass ICLoraPipeline:@@ -192,7 +191,7 @@ class ICLoraPipeline:stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,- ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]:+ ) -> PipelineOutput:"""Generate video with IC-LoRA conditioning.Args:@@ -223,7 +222,7 @@ class ICLoraPipeline:When None (default): scalar conditioning_attention_strength is useddirectly.Returns:- Tuple of (video_iterator, audio_tensor).+ PipelineOutput with decoded video and audio. ``keyframes`` is ``None``."""images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -242,7 +241,6 @@ class ICLoraPipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding@@ -304,7 +302,7 @@ class ICLoraPipeline:logging.info("[IC-LoRA] Skipping Stage 2 (--skip-stage-2 enabled)")decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)# Stage 2: Upsample and refine the video at higher resolution with distilled LORA.upscaled_video_latent = self.upsampler(video_state.latent[:1])@@ -346,7 +344,7 @@ class ICLoraPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)def _create_conditionings(self,@@ -478,7 +476,7 @@ def main() -> None:hdr=args.hdr,)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,seed=args.seed,height=args.height,@@ -496,14 +494,12 @@ def main() -> None:skip_stage_2=args.skip_stage_2,conditioning_attention_mask=conditioning_attention_mask,)- video_chunks_number = get_video_chunks_number(args.num_frames, tiling_config)-encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=video_chunks_number,+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py b/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.pyindex b3901fb..cca1dd5 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py@@ -1,5 +1,4 @@import logging-from collections.abc import Iteratorimport torch@@ -17,7 +16,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoPixelShape+from ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (ImageConditioningInput,default_2_stage_arg_parser,@@ -49,7 +48,7 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutputclass KeyframeInterpolationPipeline:@@ -165,7 +164,7 @@ class KeyframeInterpolationPipeline:stage_1_sigmas: torch.Tensor | None = None,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,- ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]:+ ) -> PipelineOutput:images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -180,7 +179,6 @@ class KeyframeInterpolationPipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encodingv_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding@@ -291,7 +289,7 @@ class KeyframeInterpolationPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)@torch.inference_mode()@@ -313,7 +311,7 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -346,14 +344,12 @@ def main() -> None:tiling_config=AUTO_TILING,max_batch_size=args.max_batch_size,)- video_chunks_number = get_video_chunks_number(args.num_frames, tiling_config)-encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=video_chunks_number,+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/multigpu/fleet.py b/packages/ltx-pipelines/src/ltx_pipelines/multigpu/fleet.pyindex d80379e..420a191 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/multigpu/fleet.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/multigpu/fleet.py@@ -350,15 +350,39 @@ class _RunnersFleet:def poll(self) -> RuntimeError | None:"""None while all workers are alive. Once any has exited, an error describing it.- Used only mid-job, where ANY exit is unexpected (workers only exit on the- shutdown sentinel), so a clean exit is reported as an error too.+ Used only mid-job and at startup, where ANY exit is unexpected (workers only exit on+ the shutdown sentinel), so a clean exit is reported as an error too."""result = self._pcontext.wait(timeout=0)- if result is None:- return None- if result.failures:- return _format_failures(result.failures)- return RuntimeError("MGPU workers exited unexpectedly")+ if result is not None:+ if result.failures:+ return _format_failures(result.failures)+ return RuntimeError("MGPU workers exited unexpectedly")+ # wait() is all-or-nothing: a rank that exits WITHOUT recording a return value -- e.g.+ # killed by a signal that torch's wrapper swallows -- leaves it reporting "still+ # running" forever, with no failure and no traceback. That is exactly how a dead fleet+ # turns into a hang, so check the processes themselves.+ dead = self._dead_ranks()+ if dead:+ return RuntimeError(+ f"MGPU worker(s) {dead} exited with no result and no error -- killed by a signal? "+ "Check the worker logs. (A known cause: the thread that called start() returned, "+ "and torch arms a thread-scoped parent-death signal in every rank.)"+ )+ return None++ def _dead_ranks(self) -> list[int]:+ """Ranks whose process is no longer running. is_alive() reaps zombies, so an exited+ rank reads as dead here even when nothing has collected its status.+ Reaching past the public API is deliberate: elastic exposes no liveness check (only+ start/wait/close/pids), and the obvious public substitute -- pids() plus+ os.kill(pid, 0) -- reports an unreaped zombie as ALIVE, so it would miss exactly the+ exit this exists to catch. This mirrors elastic's own liveness check in _close().+ """+ pc = getattr(self._pcontext, "_pc", None) # MultiprocessContext's ProcessContext+ if pc is None:+ return []+ return [rank for rank, proc in enumerate(pc.processes) if not proc.is_alive()]def drain(self, timeout: float) -> bool:"""Wait up to `timeout` for all workers to exit on their own. True if they did."""diff --git a/packages/ltx-pipelines/src/ltx_pipelines/multigpu/vae_builders.py b/packages/ltx-pipelines/src/ltx_pipelines/multigpu/vae_builders.pyindex e0dcc3c..ad06cad 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/multigpu/vae_builders.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/multigpu/vae_builders.py@@ -37,12 +37,14 @@ class DistributedDecoderBuilder(BuilderProtocol):vae_tiling: TileCountConfig,driver_rank: int,registry: Registry,+ num_temporal_batches: int | None = None,) -> None:self._inner = inner.with_registry(registry)self._queue = queueself._vae_group = vae_groupself._vae_tiling = vae_tilingself._driver_rank = driver_rank+ self._num_temporal_batches = num_temporal_batches@propertydef registry(self) -> Registry:@@ -71,6 +73,16 @@ class DistributedDecoderBuilder(BuilderProtocol):clone._inner = self._inner.with_module_ops(module_ops)return clone+ def with_tiling(self, vae_tiling: TileCountConfig) -> Self:+ """Return a new builder that splits decode with ``vae_tiling``.+ Functional: never mutates ``self``; shares the inner builder, queue, and+ process group. Mirrors stage ``with_*`` helpers so pipelines can swap+ count-based Dist tiling per request without holding one decoder per config.+ """+ clone = copy.copy(self)+ clone._vae_tiling = vae_tiling+ return clone+def build(self,device: torch.device | None = None,@@ -84,4 +96,5 @@ class DistributedDecoderBuilder(BuilderProtocol):vae_group=self._vae_group,vae_tiling=self._vae_tiling,driver_rank=dist.get_group_rank(self._vae_group, self._driver_rank),+ num_temporal_batches=self._num_temporal_batches,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/retake.py b/packages/ltx-pipelines/src/ltx_pipelines/retake.pyindex c1cf48b..b86745a 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/retake.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/retake.py@@ -1,7 +1,6 @@from __future__ import annotationsimport logging-from collections.abc import Iteratorimport torch@@ -47,7 +46,7 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutputclass RetakePipeline:@@ -170,7 +169,7 @@ class RetakePipeline:max_batch_size: int = 1,sigmas: torch.Tensor | None = None,color_space: HDRColorSpace | None = None,- ) -> tuple[Iterator[torch.Tensor], torch.Tensor, TilingConfig | None]:+ ) -> PipelineOutput:"""Regenerate ``[start_time, end_time]`` of the source video (retake).Parameters----------@@ -205,8 +204,9 @@ class RetakePipeline:Whether to enhance the prompt via the text encoder.Returns-------- tuple[Iterator[torch.Tensor], torch.Tensor, TilingConfig]- ``(video_frames_iterator, audio_waveform, tiling_config)``+ PipelineOutput+ Decoded video, audio, frame count, tiling, ``keyframes=None``, and the+ video latent used for decode when retained (may be ``None``)."""if start_time >= end_time:raise ValueError(f"start_time ({start_time}) must be less than end_time ({end_time})")@@ -261,7 +261,6 @@ class RetakePipeline:prompts_to_encode,enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,- enhance_prompt_seed=seed,)v_context_p, a_context_p = contexts[0].video_encoding, contexts[0].audio_encoding@@ -326,7 +325,9 @@ class RetakePipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, tiling_config+ return PipelineOutput(+ decoded_video, decoded_audio, output_shape.frames, tiling_config, None, video_state.latent+ )@torch.inference_mode()@@ -365,7 +366,7 @@ def main() -> None:params = detect_params(args.model_paths.transformer())hdr = resolve_hdr_color_space(video_paths=[args.video_path], hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video_iter, audio, tiling_config = pipeline(+ result = pipeline(video_path=args.video_path,prompt=args.prompt,start_time=args.start_time,@@ -382,13 +383,12 @@ def main() -> None:max_batch_size=args.max_batch_size,)- video_chunks_number = get_video_chunks_number(src.frames, tiling_config)encode_video(- video=video_iter,+ video=result.video,fps=int(src.fps),- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=video_chunks_number,+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.pyindex 7d5e965..4d9a6d6 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py@@ -129,7 +129,6 @@ class T2AOneStagePipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=None,- enhance_prompt_seed=seed,)a_context_p = ctx_p.audio_encodinga_context_n = ctx_n.audio_encodingdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.pyindex c5f1873..f8407a2 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py@@ -1,5 +1,5 @@import logging-from collections.abc import Iterator, Sequence+from collections.abc import Sequenceimport torch@@ -17,7 +17,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoPixelShape+from ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (ImageConditioningInput,add_generated_keyframes_arg,@@ -38,10 +38,12 @@ from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiserfrom ltx_pipelines.utils.helpers import (assert_resolution,combined_image_conditionings,+ decode_keyframes_from_slots,ensure_tiling_config,generated_keyframe_conditionings,get_device,has_generated_keyframes,+ resolve_generated_keyframes,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (@@ -51,7 +53,7 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutputclass TI2VidOneStagePipeline:@@ -150,7 +152,7 @@ class TI2VidOneStagePipeline:sigmas: torch.Tensor | None = None,color_space: HDRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,- ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]:+ ) -> PipelineOutput:require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=False)@@ -168,7 +170,6 @@ class TI2VidOneStagePipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encodingv_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding@@ -242,7 +243,12 @@ class TI2VidOneStagePipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator=generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, tiling_config+ keyframes = decode_keyframes_from_slots(+ video_state.generated_keyframes,+ resolve_generated_keyframes(generated_keyframes, num_frames),+ num_frames,+ )+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, keyframes, video_state.latent)@torch.inference_mode()@@ -262,7 +268,7 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -298,11 +304,11 @@ def main() -> None:)encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(args.num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.pyindex c99ff7d..08454dd 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py@@ -1,5 +1,5 @@import logging-from collections.abc import Iterator, Sequence+from collections.abc import Sequenceimport torch@@ -17,7 +17,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoPixelShape+from ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (ImageConditioningInput,add_generated_keyframes_arg,@@ -55,7 +55,7 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutputclass TI2VidTwoStagesPipeline:@@ -178,7 +178,7 @@ class TI2VidTwoStagesPipeline:stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,- ) -> tuple[Iterator[torch.Tensor], Audio, int, TilingConfig | None]:+ ) -> PipelineOutput:require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -196,7 +196,6 @@ class TI2VidTwoStagesPipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encodingv_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding@@ -309,7 +308,7 @@ class TI2VidTwoStagesPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, num_frames, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)@torch.inference_mode()@@ -331,7 +330,7 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -367,11 +366,11 @@ def main() -> None:)encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.pyindex e6662bd..824df73 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py@@ -1,5 +1,5 @@import logging-from collections.abc import Iterator, Sequence+from collections.abc import Sequenceimport torch@@ -14,7 +14,7 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio, VideoLatentShape, VideoPixelShape+from ltx_core.types import VideoLatentShape, VideoPixelShapefrom ltx_pipelines.utils.args import (ImageConditioningInput,add_generated_keyframes_arg,@@ -53,7 +53,7 @@ from ltx_pipelines.utils.media_io import ()from ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import res2s_audio_video_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutputclass TI2VidTwoStagesHQPipeline:@@ -193,7 +193,7 @@ class TI2VidTwoStagesHQPipeline:stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,color_space: HDRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,- ) -> tuple[Iterator[torch.Tensor], Audio, int, TilingConfig | None]:+ ) -> PipelineOutput:require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -211,7 +211,6 @@ class TI2VidTwoStagesHQPipeline:enhance_first_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,enhance_prompt_image=images[0][0] if len(images) > 0 else None,- enhance_prompt_seed=seed,)v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encodingv_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding@@ -337,7 +336,7 @@ class TI2VidTwoStagesHQPipeline:decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return decoded_video, decoded_audio, num_frames, tiling_config+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)@torch.inference_mode()@@ -360,7 +359,7 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = pipeline(+ result = pipeline(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -396,11 +395,11 @@ def main() -> None:)encode_video(- video=video,+ video=result.video,fps=args.frame_rate,- audio=audio,+ audio=result.audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.pyindex f1588e0..b9ed69f 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py@@ -185,7 +185,7 @@ class TI2VidTwoStagesHQRunner(MGPURunner):# catches that and turns it into a recoverable RunnerError. Anything else is fatal.hdr = resolve_hdr_color_space(images=images or [], hdr=hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = self._pipeline(+ result = self._pipeline(prompt=prompt,negative_prompt=negative_prompt,seed=seed,@@ -209,11 +209,11 @@ class TI2VidTwoStagesHQRunner(MGPURunner):yield None # workers: nothing to encodereturnencode_video(- video=video,+ video=result.video,fps=frame_rate,- audio=audio,+ audio=result.audio,output_path=output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)yield output_pathdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.pyindex 4fb0627..5699d42 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py@@ -184,7 +184,7 @@ class TI2VidTwoStagesRunner(MGPURunner):# catches that and turns it into a recoverable RunnerError. Anything else is fatal.hdr = resolve_hdr_color_space(images=images or [], hdr=hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- video, audio, num_frames, tiling_config = self._pipeline(+ result = self._pipeline(prompt=prompt,negative_prompt=negative_prompt,seed=seed,@@ -208,11 +208,11 @@ class TI2VidTwoStagesRunner(MGPURunner):yield None # workers: nothing to encodereturnencode_video(- video=video,+ video=result.video,fps=frame_rate,- audio=audio,+ audio=result.audio,output_path=output_path,- video_chunks_number=get_video_chunks_number(num_frames, tiling_config),+ video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),color_space=hdr,)yield output_pathdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.pyindex ab79873..af47961 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py@@ -12,6 +12,7 @@ from ltx_pipelines.utils.helpers import (assert_resolution,cleanup_memory,combined_image_conditionings,+ decode_keyframes_from_slots,evenly_spaced_keyframe_positions,generated_keyframe_conditionings,get_device,@@ -25,7 +26,7 @@ from ltx_pipelines.utils.samplers import (gradient_estimating_euler_denoising_loop,res2s_audio_video_denoising_loop,)-from ltx_pipelines.utils.types import DenoisedLatentResult, Denoiser, ModalitySpec+from ltx_pipelines.utils.types import DenoisedLatentResult, Denoiser, ModalitySpec, PipelineOutput__all__ = ["AudioConditioner",@@ -37,6 +38,7 @@ __all__ = ["GuidedDenoiser","ImageConditioner","ModalitySpec",+ "PipelineOutput","PromptEncoder","SimpleDenoiser","VideoDecoder",@@ -44,6 +46,7 @@ __all__ = ["assert_resolution","cleanup_memory","combined_image_conditionings",+ "decode_keyframes_from_slots","euler_ancestral_denoising_loop","euler_cfg_pp_denoising_loop","euler_denoising_loop",diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/args.pyindex 2f7e9dc..1a98735 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py@@ -194,6 +194,8 @@ class CompileAction(argparse.Action):"seq_dim_dynamic","recompile_perturbed_block","capture",+ "max_video_tokens",+ "max_audio_tokens",})@@ -227,6 +229,8 @@ class CompileAction(argparse.Action):overrides[key] = self._parse_dynamic(raw)elif key in ("inductor_config", "dynamo_config"):overrides[key] = self._parse_json_dict(key, raw)+ elif key in ("max_video_tokens", "max_audio_tokens"):+ overrides[key] = self._parse_positive_int(key, raw)setattr(namespace, self.dest, CompilationConfig(**overrides))def _parse_mode(self, raw: str) -> str | None:@@ -251,6 +255,12 @@ class CompileAction(argparse.Action):return Falseraise argparse.ArgumentError(self, f"{key}=... must be true or false; got {raw!r}")+ def _parse_positive_int(self, key: str, raw: str) -> int:+ stripped = raw.strip()+ if not stripped.isdigit() or int(stripped) == 0:+ raise argparse.ArgumentError(self, f"{key}=... must be a positive integer; got {raw!r}")+ return int(stripped)+def _parse_dynamic(self, raw: str) -> bool | None:normalized = raw.strip().lower()if normalized in ("auto", "none"):diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.pyindex 9d2d7d6..03d41de 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py@@ -74,6 +74,7 @@ from ltx_core.model.video_vae import (is_diffusion_video_vae,video_decoder_sd_ops_for_checkpoint,)+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.transformer import (DiffVAEMode,NAttentionKind,@@ -117,6 +118,11 @@ _ENCODE_MODEL_TYPES = frozenset({"gemma3", "gemma4", "gemma4_unified"})logger = logging.getLogger(__name__)+ModelWrapper = Callable[[torch.nn.Module, "LatentTools | None"], torch.nn.Module]+"""Wraps a built transformer for one :meth:`DiffusionStage.__call__` (see+:meth:`DiffusionStage.with_model_wrapper`). Must keep the+``(video, audio, perturbations) -> (video, audio)`` forward signature."""+T = TypeVar("T")_M = TypeVar("_M", bound=torch.nn.Module)@@ -286,6 +292,7 @@ class DiffusionStage:self._compilation_config = compilation_configself._alloc_trim_strategy = alloc_trim_strategyself.video_scale_factors = scale_factors+ self._model_wrapper: ModelWrapper | None = None@classmethoddef from_checkpoint( # noqa: PLR0913@@ -449,6 +456,20 @@ class DiffusionStage:new._transformer_builder = builderreturn new+ def with_model_wrapper(self, wrapper: "ModelWrapper | None") -> "DiffusionStage":+ """Return a new stage that passes each built transformer through ``wrapper``.+ Functional: never mutates ``self``. The wrapper is applied inside the transformer+ context -- after the model is built, before the denoising loop -- on both the standard+ and block-streaming paths, and it receives the call's video tools. Wrapping *here*+ rather than around the builder is what lets a wrapper compose with offloading: a+ wrapping builder would hide a :class:`StreamingModelBuilder` from :attr:`_is_streaming`,+ so the stage would take the plain ``gpu_model`` path and never tear the stream down.+ ``wrapper=None`` clears any previously set wrapper.+ """+ new = copy.copy(self)+ new._model_wrapper = wrapper+ return new+def with_loras(self, loras: tuple[LoraPathStrengthAndSDOps, ...]) -> "DiffusionStage":"""Return a new ``DiffusionStage`` built with exactly ``loras`` (replacing the current set)."""return self.with_builder(self._transformer_builder.with_loras(loras))@@ -512,10 +533,16 @@ class DiffusionStage:stepper: DiffusionStepProtocol | None = None,loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,max_batch_size: int = 1,+ audio_fps: float | None = None,) -> tuple[LatentState | None, LatentState | None]:"""Build transformer -> run denoising loop -> free transformer.Returns ``(video_state | None, audio_state | None)`` with clearedconditionings and unpatchified latents for present modalities.+ ``fps`` is the transformer's time base: it sets RoPE time (``pixel_frame / fps``)+ and, by default, the audio latent's duration (``frames / fps``). ``audio_fps``+ decouples the two for callers that hand the transformer a time base other than the+ clip's real frame rate -- audio is then sized from ``frames / audio_fps``, so its+ duration still matches playback. Omitted -> same as ``fps``."""if video is None and audio is None:raise ValueError("At least one of `video` or `audio` must be provided")@@ -527,6 +554,7 @@ class DiffusionStage:stepper = EulerDiffusionStep()pixel_shape = VideoPixelShape(batch=1, frames=frames, height=height, width=width, fps=fps)+ audio_pixel_shape = pixel_shape if audio_fps is None else pixel_shape._replace(fps=audio_fps)# Build video_tools up front so it can be forwarded to the transformer# context (required by TiledDataParallelBuilder in multi-GPU mode).@@ -542,7 +570,8 @@ class DiffusionStage:mode = "streaming" if self._is_streaming else "standard"logger.info("Building transformer (%s) from %s", mode, self._transformer_builder.checkpoint)- with self._transformer_ctx(video_tools=video_tools) as transformer:+ with self._transformer_ctx(video_tools=video_tools) as built:+ transformer = built if self._model_wrapper is None else self._model_wrapper(built, video_tools)logger.info("Running denoising loop (%d steps, %dx%d %d frames @ %.1f fps)",len(sigmas) - 1,@@ -558,7 +587,7 @@ class DiffusionStage:audio_tools: LatentTools | None = Noneaudio_state: LatentState | None = Noneif audio is not None:- a_shape = AudioLatentShape.from_video_pixel_shape(pixel_shape)+ a_shape = AudioLatentShape.from_video_pixel_shape(audio_pixel_shape)audio_tools = AudioLatentTools(AudioPatchifier(patch_size=1), a_shape)audio_state = _build_state(audio, audio_tools, noiser, self._dtype, self._device)@@ -584,13 +613,14 @@ class DiffusionStage:class RecordingDiffusionStage:"""Wraps a :class:`DiffusionStage` and records the states each call produced.- The supported way to reach a stage's non-video outputs -- currently the generated keyframe- latents on ``LatentState.generated_keyframes`` -- from *outside* a pipeline, without the- pipeline having to grow a diagnostics return value or a lifecycle callback. Pipelines hold- their stage in a plain attribute, so a caller substitutes this in::+ Diagnostics wrapper for a stage's intermediate ``LatentState``s. Generated keyframes that+ already sit at final output resolution are on ``PipelineOutput.keyframes``; this wrapper+ remains the way to inspect per-stage states (including half-res stage-1 slots) without a+ lifecycle callback. Pipelines hold their stage in a plain attribute, so a caller+ substitutes this in::pipeline.stage = RecordingDiffusionStage(pipeline.stage)- video, audio = pipeline(...)- keyframes = pipeline.stage.video_states[0].generated_keyframes+ result = pipeline(...)+ keyframes = pipeline.stage.generated_keyframesDelegates every other attribute to the wrapped stage, so a substituted stage stays usablewherever the original was. Recording holds references to the returned states, which keepstheir latents alive -- fine for diagnostics on one run, not something to leave enabled in a@@ -1066,6 +1096,7 @@ class VideoDecoder:self._device = deviceself._diffvae_optimization = diffvae_optimizationdiffusion_vae = is_diffusion_video_vae(self._checkpoint_path)+ self._diffusion_vae = diffusion_vaecfg = diffvae_optimization.resolve() if diffusion_vae else Noneuse_dsl = cfg is not None and cfg.attention is NAttentionKind.BLACKWELL_DSLif decoder_builder is not None:@@ -1100,17 +1131,6 @@ class VideoDecoder:registry=registry or ModelRegistry(cache_models=True, cache_weights=False),module_ops=module_ops,)- # DiffVAE ModuleOps from ``diffvae_optimization`` policy (default ChunkedEager).- # MGPU wraps this builder in ``DistributedDecoderBuilder`` — keep the op on the- # inner builder so it still runs before the distributed wrapper is constructed.- if diffusion_vae:- op = build_diffvae_mode_op(- diffvae_optimization,- CompilationConfig() if diffvae_optimization.resolve().compile_blocks else None,- )- self._decoder_builder = self._decoder_builder.with_module_ops(- (*self._decoder_builder.module_ops, op),- )self._alloc_trim_strategy = alloc_trim_strategy@property@@ -1121,6 +1141,31 @@ class VideoDecoder:def diffvae_optimization(self) -> DiffVAEMode:return self._diffvae_optimization+ def with_builder(self, builder: BuilderProtocol) -> "VideoDecoder":+ """Return a new ``VideoDecoder`` that builds from ``builder``.+ Functional: never mutates ``self``; shares checkpoint, dtype, device, and+ trim strategy. Mirrors :meth:`DiffusionStage.with_builder`.+ """+ new = copy.copy(self)+ new._decoder_builder = builder+ return new++ def _prepared_builder(self) -> BuilderProtocol:+ """Return the builder with DiffVAE mode ops applied at build time.+ DiffVAE ``module_ops`` live on the decoder (not on the caller-held builder),+ matching :meth:`DiffusionStage._prepared_builder`. That keeps+ ``with_builder`` / Dist ``with_tiling`` swaps on the raw builder, while+ every build still installs the configured DiffVAE policy.+ """+ builder = self._decoder_builder+ if not self._diffusion_vae:+ return builder+ op = build_diffvae_mode_op(+ self._diffvae_optimization,+ CompilationConfig() if self._diffvae_optimization.resolve().compile_blocks else None,+ )+ return builder.with_module_ops((*builder.module_ops, op))+def __call__(self,latent: torch.Tensor,@@ -1128,17 +1173,50 @@ class VideoDecoder:generator: torch.Generator | None = None,*,dtype: torch.dtype | None = None,+ keyframes: DecodeKeyframes | None = None,) -> Iterator[torch.Tensor]:"""Decode *latent* to pixel-space video chunks. Decoder freed after exhaustion.``dtype`` overrides the constructor dtype for this call only (e.g. float32 forHDR raw-in/raw-out). Omitted → same dtype as on construction (SDR default).+ ``keyframes`` anchors the decode on already-encoded planes. Every decoder in this repo+ takes it, so this never branches on which VAE was built: a diffusion VAE uses the planes,+ a conv VAE logs that it is dropping them, and a distributed decoder splits them across+ its ranks. The keyword is only passed when there is something to pass, so a decoder+ written against the older signature still serves plain decodes."""build_dtype = self._dtype if dtype is None else dtypelatent = latent.to(dtype=build_dtype)logger.info("Building video decoder from %s", self._checkpoint_path)- decoder = self._decoder_builder.build(device=self._device, dtype=build_dtype).eval()+ decoder = self._prepared_builder().build(device=self._device, dtype=build_dtype).eval()+ extra = {} if keyframes is None else {"keyframes": keyframes}+ chunks = decoder.decode_video(latent, tiling_config, generator, **extra)+ return _cleanup_iter(+ chunks,+ decoder,+ alloc_trim_strategy=self._alloc_trim_strategy,+ )++ def decode_single_frames(+ self,+ latents: Sequence[torch.Tensor],+ generator: torch.Generator | Sequence[torch.Generator | None] | None = None,+ *,+ dtype: torch.dtype | None = None,+ ) -> Iterator[torch.Tensor]:+ """Decode each latent as its own one-frame clip on one VAE build, then free it.+ A causal VAE cannot decode stacked independent planes without bleeding neighbours.+ Dist builds still decode locally on every rank; this does not go through the+ split/gather ``decode_video`` path whose workers yield nothing.+ """+ if not latents:+ return iter(())+ build_dtype = self._dtype if dtype is None else dtype+ moved = [latent.to(dtype=build_dtype) for latent in latents]+ logger.info("Building video decoder from %s", self._checkpoint_path)+ decoder = self._prepared_builder().build(device=self._device, dtype=build_dtype).eval()+ chunks = decoder.decode_single_frames(moved, generator)return _cleanup_iter(- decoder.decode_video(latent, tiling_config, generator),+ chunks,decoder,alloc_trim_strategy=self._alloc_trim_strategy,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.pyindex a0bd85a..2025029 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py@@ -10,23 +10,26 @@ from ltx_core.conditioning import (VideoConditionByLatentIndex,VideoGeneratedKeyframeSlots,)-from ltx_core.devices import cleanup_accelerator_memory, cuda_activation_budget_bytes, get_preferred_device+from ltx_core.devices import activation_budget_bytes, cleanup_accelerator_memory, get_preferred_devicefrom ltx_core.loader.sft_loader import SafetensorsModelStateDictLoaderfrom ltx_core.model.audio_vae import encode_audiofrom ltx_core.model.transformer import Modality-from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TileSizeConfig, TilingConfig, VideoEncoder+from ltx_core.model.video_vae import AutoTiling, TileSizeConfig, TilingConfig, VideoEncoderfrom ltx_core.model.video_vae.diffusion_tiling import recommended_decode_tiling_config+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.model_configurator import (diffvae_tiling_geometry_from_vae_config,estimate_diffusion_decoder_weight_bytes,is_diffusion_video_vae,)from ltx_core.model.video_vae.transformer.config import DiffVAEMode+from ltx_core.model.video_vae.transformer.fallback_na import joint_sdpa_materializes_scoresfrom ltx_core.text_encoders.gemma import LTXGemmaTextEncoderfrom ltx_core.tiling import DimensionSizeConfigfrom ltx_core.tools import LatentToolsfrom ltx_core.types import (VIDEO_SCALE_FACTORS,+ Audio,AudioLatentShape,LatentState,SpatioTemporalScaleFactors,@@ -48,6 +51,8 @@ from ltx_pipelines.utils.media_io import ()from ltx_pipelines.utils.media_io.color_config import HDRColorSpace+logger = logging.getLogger(__name__)+def get_device() -> torch.device:return get_preferred_device()@@ -81,10 +86,13 @@ def tiling_config_for_vae(diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,device: torch.device | None = None,free_bytes: int | None = None,+ keyframes: bool = False,) -> TilingConfig:"""Decode tiling for pipelines.Conv VAE: aspect-coupled long-side 768/64 + temporal 80/24.DiffVAE: halo/memory-aware :func:`recommended_decode_tiling_config`.+ Pass ``keyframes=True`` for a keyframe-aware ``decode_video(keyframes=)`` decode: joint attention runs+ eager blocks, which changes both the stage-5 coefficient and the withheld reserve."""if not is_diffusion_video_vae(vae_checkpoint_path):_ = num_frames # API parity with DiffVAE; Conv auto layout is aspect-only.@@ -101,9 +109,9 @@ def tiling_config_for_vae(geometry = diffvae_tiling_geometry_from_vae_config(vae_config)model_bytes = estimate_diffusion_decoder_weight_bytes(vae_checkpoint_path)+ resolved_device = device if device is not None else get_device()if free_bytes is None:- dev = device if device is not None else get_device()- free_bytes = cuda_activation_budget_bytes(dev) if dev.type == "cuda" and torch.cuda.is_available() else 0+ free_bytes = activation_budget_bytes(resolved_device)return recommended_decode_tiling_config(**geometry,@@ -113,6 +121,8 @@ def tiling_config_for_vae(mode=diffvae_optimization,free_bytes=free_bytes,model_bytes=model_bytes,+ keyframes=keyframes,+ joint_sdpa_materializes=keyframes and joint_sdpa_materializes_scores(resolved_device),)@@ -125,14 +135,16 @@ def ensure_tiling_config(diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,device: torch.device | None = None,free_bytes: int | None = None,+ keyframes: bool = False,) -> TilingConfig | None:"""Resolve pipeline tiling: ``AUTO_TILING`` → recommend; ``None`` → untiled; else validate.``scale_factors`` must be the same factors decode will pass to ``to_splitters``(from :func:`tiling_scale_factors_for_vae`). Call only after ``video_shape.frames`` is known.+ Pass ``keyframes=True`` when the decode will use the keyframe-aware VAE path."""if tiling_config is None:return None- if tiling_config is AUTO_TILING:+ if isinstance(tiling_config, AutoTiling):return tiling_config_for_vae(vae_checkpoint_path,height=video_shape.height,@@ -141,6 +153,7 @@ def ensure_tiling_config(diffvae_optimization=diffvae_optimization,device=device,free_bytes=free_bytes,+ keyframes=keyframes,)tiling_config.validate(scale_factors, video_shape)return tiling_config@@ -425,6 +438,29 @@ def generated_keyframe_conditionings(return [VideoGeneratedKeyframeSlots(pixel_frame_indices=positions)]+def decode_keyframes_from_slots(+ latents: torch.Tensor | None,+ positions: Sequence[int],+ num_frames: int,+) -> DecodeKeyframes | None:+ """Build ``DecodeKeyframes`` for slots that still land inside a ``num_frames`` canvas.+ The canvas may pad its tail and be trimmed back to the caller's frame count, so a+ carried keyframe can sit past the end. Those must be dropped rather than handed on: a+ decode indexes keyframes by pixel frame and would otherwise anchor off-canvas.+ """+ if latents is None or not positions:+ return None+ kept = [(index, int(position)) for index, position in enumerate(positions) if 0 <= int(position) < num_frames]+ if not kept:+ return None+ if len(kept) != len(positions):+ logger.info("Dropping %d keyframe(s) past the trimmed %d-frame canvas.", len(positions) - len(kept), num_frames)+ return DecodeKeyframes(+ latents=torch.cat([latents[:, :, index : index + 1] for index, _ in kept], dim=2),+ pixel_frame_indices=torch.tensor([position for _, position in kept], dtype=torch.long),+ )++def create_noised_state(tools: LatentTools,conditionings: list[ConditioningItem],@@ -537,12 +573,14 @@ def generate_enhanced_prompt(return clean_response(prompt)-def assert_resolution(height: int, width: int, is_two_stage: bool) -> None:+def assert_resolution(height: int, width: int, is_two_stage: bool, *, divisor: int | None = None) -> None:"""Assert that the resolution is divisible by the required divisor.For two-stage pipelines, the resolution must be divisible by 64.For one-stage pipelines, the resolution must be divisible by 32.+ Pass ``divisor`` to override (e.g. 128 for a two-spatial-upsample DFR run)."""- divisor = 64 if is_two_stage else 32+ if divisor is None:+ divisor = 64 if is_two_stage else 32if height % divisor != 0 or width % divisor != 0:raise ValueError(f"Resolution ({height}x{width}) is not divisible by {divisor}. "@@ -583,3 +621,22 @@ def seconds_to_clamped_num_frames(time_scale = scale_factors.timeframes = min(-(-(min_frames - 1) // time_scale) * time_scale + 1, max_frames)return frames+++def audio_duration_seconds(audio: Audio) -> float:+ """Wall-clock duration of ``audio`` from its last waveform axis and sample rate."""+ return audio.waveform.shape[-1] / float(audio.sampling_rate)+++def num_frames_from_audio_duration(audio: Audio, *, frame_rate: float) -> int:+ """Convert decoded audio length to a VAE-grid frame count at ``frame_rate``.+ ``decode_audio_from_file`` already applies ``audio_max_duration`` and stops at+ EOF, so this uses the *effective* clip duration: ``min(requested max, remaining+ audio after start time)``.+ The raw frame count is floored (not rounded) before snapping so a leftover+ half-frame cannot jump onto the next ``8k+1`` grid point and request more+ video than the clip can cover.+ """+ raw_frames = int(audio_duration_seconds(audio) * frame_rate)+ raw_frames = max(1, min(raw_frames, 1024))+ return snap_frames_to_grid(raw_frames)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.pyindex 561baca..2fd19f1 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py@@ -11,7 +11,7 @@ import avimport numpy as npimport OpenImageIOimport torch-from PIL import ExifTags, Image, ImageCms+from PIL import ExifTags, Image, ImageCms, UnidentifiedImageErrorfrom torch._prims_common import DeviceLikeTypefrom ltx_core.hdr import HDRTransfer@@ -138,36 +138,39 @@ def load_video_conditioning_hdr(def decode_image(image_path: str) -> np.ndarray:"""Load an image as an oriented, sRGB, three-channel uint8 RGB array."""- with Image.open(image_path) as source_image:- image = source_image- orientation = image.getexif().get(_ORIENTATION_EXIF_KEY)- if orientation in _ORIENTATION_TO_ROTATION:- image = image.rotate(_ORIENTATION_TO_ROTATION[orientation], expand=True)-- icc_profile = image.info.get("icc_profile")-- if image.mode == "RGBA":- image = image.convert("RGB")- elif image.mode == "LA":- image = image.convert("L")-- if icc_profile:- try:- source_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile))- destination_profile = ImageCms.ImageCmsProfile(_SRGB_PROFILE)- image = ImageCms.profileToProfile(- image,- source_profile,- destination_profile,- outputMode="RGB",- )- except (ImageCms.PyCMSError, OSError, ValueError) as error:- logger.warning("Failed to convert image to sRGB: %s", error)+ try:+ with Image.open(image_path) as source_image:+ image = source_image+ orientation = image.getexif().get(_ORIENTATION_EXIF_KEY)+ if orientation in _ORIENTATION_TO_ROTATION:+ image = image.rotate(_ORIENTATION_TO_ROTATION[orientation], expand=True)++ icc_profile = image.info.get("icc_profile")++ if image.mode == "RGBA":+ image = image.convert("RGB")+ elif image.mode == "LA":+ image = image.convert("L")++ if icc_profile:+ try:+ source_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile))+ destination_profile = ImageCms.ImageCmsProfile(_SRGB_PROFILE)+ image = ImageCms.profileToProfile(+ image,+ source_profile,+ destination_profile,+ outputMode="RGB",+ )+ except (ImageCms.PyCMSError, OSError, ValueError) as error:+ logger.warning("Failed to convert image to sRGB: %s", error)+ image = image.convert("RGB")+ else:image = image.convert("RGB")- else:- image = image.convert("RGB")- return np.array(image, dtype=np.uint8)+ return np.array(image, dtype=np.uint8)+ except UnidentifiedImageError as err:+ raise ValueError(f"Cannot decode image file '{image_path}'.") from errdef _audio_frame_to_float(frame: av.AudioFrame) -> np.ndarray:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/types.pyindex 6ac6c24..8bc372b 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py@@ -1,18 +1,49 @@from __future__ import annotations+from collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Protocol+from typing import NamedTuple, Protocolimport torchfrom ltx_core.components.patchifiers import AudioPatchifier, VideoLatentPatchifierfrom ltx_core.conditioning import ConditioningItemfrom ltx_core.model.transformer import X0Model-from ltx_core.types import LatentState+from ltx_core.model.video_vae import TilingConfig+from ltx_core.model.video_vae.keyframes import DecodeKeyframes+from ltx_core.types import Audio, LatentStatefrom ltx_pipelines.utils.constants import VIDEO_LATENT_CHANNELS, VIDEO_SCALE_FACTORS+class PipelineOutput(NamedTuple):+ """Return type of every video pipeline ``__call__``.+ A ``NamedTuple`` rather than a bare tuple so adding fields fails loudly at any+ call site that unpacks a fixed arity. Prefer attribute access+ (``result.video``, ``result.audio``, ...) over positional unpack.+ Trailing extras are optional:+ * ``keyframes`` -- filled only when the run produced generated slots already at+ **final** output resolution. ``keyframes.pixel_frame_indices`` stay on that+ pixel grid. Half-res stage-1 slots are not a substitute: if the pipeline never+ upscaled them to the final canvas, this field is ``None``.+ * ``video_latent`` -- the final video latent ``video`` was decoded from, when the+ pipeline retains it for keyframe-aware re-decode. ``None`` when not retained.+ """++ video: Iterator[torch.Tensor]+ audio: Audio+ num_frames: int+ tiling_config: TilingConfig | None+ #: Generated keyframe slots already at **final** output resolution, with+ #: ``pixel_frame_indices`` on that pixel grid. ``None`` when the run produced none, or+ #: when slots exist only at a coarser scale the pipeline never upscaled.+ keyframes: DecodeKeyframes | None+ #: The final video latent ``video`` was decoded from, when retained. Re-decoding through+ #: ``decode_video(keyframes=)`` needs this together with ``keyframes``; re-encoding decoded+ #: pixels would not reproduce it. ``None`` when the pipeline does not keep the latent.+ video_latent: torch.Tensor | None++class PipelineComponents:"""Container class for pipeline components used throughout the LTX pipelines.diff --git a/packages/ltx-trainer/pyproject.toml b/packages/ltx-trainer/pyproject.tomlindex d802680..84cfa6c 100644--- a/packages/ltx-trainer/pyproject.toml+++ b/packages/ltx-trainer/pyproject.toml@@ -1,6 +1,6 @@[project]name = "ltx-trainer"-version = "1.2.0"+version = "1.3.0"description = "LTX-2 training, democratized."readme = "README.md"authors = [@@ -42,8 +42,9 @@ dependencies = [][tool.uv.sources]-torchcodec = { index = "torch" }-torchaudio = { index = "torch-test" }+# macOS: the cu132 indexes ship no darwin wheels, so fall back to PyPI there.+torchcodec = [{ index = "torch", marker = "sys_platform != 'darwin'" }]+torchaudio = [{ index = "torch-test", marker = "sys_platform != 'darwin'" }][[tool.uv.index]]name = "torch"diff --git a/packages/ltx-trainer/src/ltx_trainer/validation_runner.py b/packages/ltx-trainer/src/ltx_trainer/validation_runner.pyindex 8573d40..a5f3fb0 100644--- a/packages/ltx-trainer/src/ltx_trainer/validation_runner.py+++ b/packages/ltx-trainer/src/ltx_trainer/validation_runner.py@@ -27,7 +27,7 @@ from ltx_core.conditioning.mask_utils import extend_keyframes_maskfrom ltx_core.conditioning.types.latent_cond import VideoConditionByLatentIndexfrom ltx_core.conditioning.types.mask_cond import VideoConditionByMaskfrom ltx_core.conditioning.types.reference_video_cond import VideoConditionByReferenceLatent-from ltx_core.devices import cuda_activation_budget_bytes+from ltx_core.devices import activation_budget_bytesfrom ltx_core.guidance.perturbations import (BatchedPerturbationConfig,Perturbation,@@ -1029,7 +1029,7 @@ class ValidationRunner:num_frames=(latent_frames - 1) * scale.time + 1,# Matches the ModuleOps that load_video_vae_decoder applies to the diffusion decoder.mode=DiffVAEMode.CHUNKED_EAGER,- free_bytes=cuda_activation_budget_bytes(device) if device.type == "cuda" else 0,+ free_bytes=activation_budget_bytes(device),)def _decode_audio(self, audio_state: LatentState, device: torch.device) -> Tensor:diff --git a/pyproject.toml b/pyproject.tomlindex 817a864..658a59b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -6,10 +6,13 @@ ltx-kernels = { path = "packages/ltx-kernels", editable = true }[tool.uv]no-build-isolation-package = ["ltx-kernels"]# torch 2.13+cu132 pins nvidia-cudnn-cu13==9.20.0.48, which omits-# libcudnn_engines_tensor_ir; the system/apt cuDNN is 9.21.1 and that soname-# then resolves from /usr/lib, causing CUDNN_STATUS_SUBLIBRARY_VERSION_MISMATCH.-# Force a wheel that ships tensor_ir and matches the host cuDNN series.-override-dependencies = ["nvidia-cudnn-cu13==9.21.1.3"]+# libcudnn_engines_tensor_ir; the system/apt cuDNN then resolves that soname from+# /usr/lib, causing CUDNN_STATUS_SUBLIBRARY_VERSION_MISMATCH. A wheel *older* than the+# cuDNN torch was built against additionally aborts the process -- not an exception --+# with `Cannot load symbol cublasLtGetVersion` the first time torch selects its cuDNN+# SDPA backend. 9.24.0.43 ships tensor_ir and matches torch 2.13 / cuDNN 9.24;+# 9.25.0.15 is yanked. Linux-only: the wheel is CUDA and has no darwin build.+override-dependencies = ["nvidia-cudnn-cu13==9.24.0.43; sys_platform == 'linux'"][tool.uv.workspace]members = ["packages/*"]@@ -28,6 +31,7 @@ dev = ["pre-commit>=4.3.0","ruff>=0.14.3","pytest~=9.0",+ "pytest-xdist~=3.8",# Match torch's cu132 index (see packages/ltx-core pyproject): kernel builds must use# the venv nvcc, not a mismatched system toolkit (CI runners often ship CUDA 12.8).# `cccl` provides <nv/target> (pulled by cuda_fp16.h); `nvcc` alone is not enough.@@ -86,7 +90,6 @@ ignore = [[tool.ruff.lint.per-file-ignores]# CI gates: stand-alone CLIs whose whole job is printing a report / GitHub annotations.-".github/actions/test-collection-completeness/check_test_collection.py" = ["T201"]".github/actions/golden-pairing-gate/check_golden_pairing.py" = ["T201"]# Emits `export …` lines for eval by kernels-build.".github/actions/kernels-build/export_cuda_home.py" = ["T201"]