Run this model with HF Jobs
Run FastVideo/FastH3-Omni-Comfy on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/FastVideo/FastH3-Omni-Comfy. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/FastVideo/FastH3-Omni-Comfy on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use FastVideo/FastH3-Omni-Comfy with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusion Single File
How to use FastVideo/FastH3-Omni-Comfy with Diffusion Single File:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Add native ComfyUI OmniRef checkpoints
Browse filesPackage canonical OmniRef BF16 with rank-8 AdaLN curves and reuse the verified Comfy-produced INT8 payload unchanged. Copy pinned shared Comfy text encoders and VAEs. Include conversion code, hashes, source matching and explicit validation limits.
Files changed (36)
- MANIFEST.jsonAdded+188
- README.mdAdded+136
- conversion/CONVERSION.mdAdded+139
- conversion/QUANTIZATION_COMPATIBILITY.mdAdded+89
- conversion/audit_native_geometry.pyAdded+54
- conversion/convert_omniref_comfy.pyAdded+367
- conversion/test_conversion.pyAdded+170
- conversion/upstream/COMFY_LICENSEAdded+674
- conversion/upstream/SOURCE_PINS.jsonAdded+32
- conversion/upstream/TOOLS_LICENSEAdded+674
- conversion/upstream/comfy_model.pyAdded+792
- conversion/upstream/comfy_model_detection.pyAdded+1664
- conversion/upstream/quant_int8_convrot.pyAdded+441
- diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensorsAdded+3
- diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors.receipt.jsonAdded+403
- diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensorsAdded+3
- diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors.receipt.jsonAdded+13
- provenance/COMFY_KITCHEN_SOURCE_AUDIT.jsonAdded+28
- provenance/FP8_SOURCE_SAMPLE_HEADER.jsonAdded+34
- provenance/FULL_NATIVE_BF16_SCHEMA.jsonAdded+34
- provenance/NVFP4_QKV_SCALAR_AUDIT.jsonAdded+33
- provenance/NVFP4_SOURCE_HEADER.jsonAdded
- provenance/PREVIEW_HEADER.jsonAdded
- provenance/PREVIEW_PDD_SAMPLE_VALIDATION.jsonAdded+80
- provenance/PREVIEW_QUANTIZED_SAMPLE_VALIDATION.jsonAdded+121
- provenance/PREVIEW_SOURCE_MATCH.jsonAdded+88
- provenance/SOURCE_VERIFICATION.jsonAdded+78
- provenance/VALIDATION.jsonAdded+45
- provenance/fastvideo_inference.jsonAdded+31
- provenance/shared-copy-plan.jsonAdded+40
- text_encoders/qwen3vl_32b_minimax_h3_bf16.safetensorsAdded+3
- text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensorsAdded+3
- text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensorsAdded+3
- vae/minimax_h3_audio_vae_fp32.safetensorsAdded+3
- vae/minimax_h3_video_vae_fp16.safetensorsAdded+3
- vae/minimax_h3_video_vae_int8_convrot.safetensorsAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188{ "schema_version": 1, "repository": "FastVideo/FastH3-OmniRef-Comfy", "private": true, "files": [ { "path": "README.md", "bytes": 7499, "sha256": "2c733fd5713198afa0c3c9356da7d3146d5cd135163175e3c5b7f2c616c435c1" }, { "path": "conversion/CONVERSION.md", "bytes": 7709, "sha256": "059ae17d24fdd36ebabe0703101fdd01114deb035a09b72e8f9c8ea388f9b7a0" }, { "path": "conversion/QUANTIZATION_COMPATIBILITY.md", "bytes": 4949, "sha256": "a725703458ffea784acbb482638eadff20130bb947a389b164bc67ca59ca803d" }, { "path": "conversion/audit_native_geometry.py", "bytes": 2421, "sha256": "d084a5a4c461208453133f65c57000b49e18b7ccf6dba50f69ff0a4e502c51d4" }, { "path": "conversion/convert_omniref_comfy.py", "bytes": 19113, "sha256": "96b745f3fae81450eac777d60c7f3452d24d61384f18877fe4f1fc4e930320a3" }, { "path": "conversion/test_conversion.py", "bytes": 8926, "sha256": "704386dc881cb6ae50fecd8d95783949e84b36b1f2549509730cf1cceb83e8a7" }, { "path": "conversion/upstream/COMFY_LICENSE", "bytes": 35149, "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" }, { "path": "conversion/upstream/SOURCE_PINS.json", "bytes": 1363, "sha256": "2ee8ebe5211e5f865e0115f1e512d9ebecd99bd7e5553c8f0bd80b294f4a8b45" }, { "path": "conversion/upstream/TOOLS_LICENSE", "bytes": 35149, "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" }, { "path": "conversion/upstream/comfy_model.py", "bytes": 41140, "sha256": "bdf1c2121a94ae8ef3da72dba6caf120eb6255457cecf569af32ff91d34c5fda" }, { "path": "conversion/upstream/comfy_model_detection.py", "bytes": 93877, "sha256": "b0f615387a1808eb01edf92bc301bb79e02c42112b566cf6826b67c45e7d71ed" }, { "path": "conversion/upstream/quant_int8_convrot.py", "bytes": 24249, "sha256": "dd85ca376b985222719f052acbe47081c6fdf54742791ac1b44209923828146a" }, { "path": "diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors", "bytes": 44240780704, "sha256": "c0fac98c0317eb85215bd186b250be9b113675baab1323add40f26262f552ed9" }, { "path": "diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors.receipt.json", "bytes": 12940, "sha256": "c7ed9b6b19a1cc7c579ecd22009a625513b85120da63581f63c500cb7403d06d" }, { "path": "diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors", "bytes": 22213723064, "sha256": "851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80" }, { "path": "diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors.receipt.json", "bytes": 779, "sha256": "642a0c4aeaace397d762cfc604f00a02044373e2c85b2d81e1a5b3dc6d02dce6" }, { "path": "provenance/COMFY_KITCHEN_SOURCE_AUDIT.json", "bytes": 1335, "sha256": "f4e190cd18324deeb171da115ca95eff863efc8dfc2bd43eda6f409c35c45fdc" }, { "path": "provenance/FP8_SOURCE_SAMPLE_HEADER.json", "bytes": 742, "sha256": "f030180c9320a05a0c473d3af2b8591f819c15092b9d63acf0df2d2cdfc3c109" }, { "path": "provenance/FULL_NATIVE_BF16_SCHEMA.json", "bytes": 1085, "sha256": "c66fa1b2c1f8b18a018d01e1aee7284761a294df06faf14f17529ad6c54955ac" }, { "path": "provenance/NVFP4_QKV_SCALAR_AUDIT.json", "bytes": 917, "sha256": "823f0fc81500b3656d0586c7487c6913a7c107c19713d5f35ee976c9a5c52536" }, { "path": "provenance/NVFP4_SOURCE_HEADER.json", "bytes": 253735, "sha256": "55759635953e4c102ecc094204ca70a718691b02515795afe8db001f5fa7d57a" }, { "path": "provenance/PREVIEW_HEADER.json", "bytes": 180405, "sha256": "82a1df3c9956beb675b2e58afba915f78311bd008f68eb10df5ffd3ff49c64b7" }, { "path": "provenance/PREVIEW_PDD_SAMPLE_VALIDATION.json", "bytes": 2043, "sha256": "5153829b66b7e3073a62cbd0d40f5070bd948cd9572af35a4cceee1751cf291d" }, { "path": "provenance/PREVIEW_QUANTIZED_SAMPLE_VALIDATION.json", "bytes": 3700, "sha256": "79317938048bb1adfdc4467ce0857254705217a41155c41ec5f08b561776b2c5" }, { "path": "provenance/PREVIEW_SOURCE_MATCH.json", "bytes": 3736, "sha256": "d2ec2ad8350f185dad50cfc80ab3283d240054d2c18b41714a1c7b08db8e680f" }, { "path": "provenance/SOURCE_VERIFICATION.json", "bytes": 3113, "sha256": "8e846b036a9f170cbae70b57cb63a55acfe67b617bf30dd53e9d31c79628f34e" }, { "path": "provenance/VALIDATION.json", "bytes": 1216, "sha256": "eeb4fff2ef2f27cf1abe42ac1360c5bcce995fcbab4cdc92133e1b3fe0277b4d" }, { "path": "provenance/fastvideo_inference.json", "bytes": 776, "sha256": "68577f23f0c866e329aa8a578b2455e4ca9a26a3ca1d15ddd6d0e99091007e18" }, { "path": "provenance/shared-copy-plan.json", "bytes": 1607, "sha256": "0acd5b43aafee675eb8aea7fcb0ab352e0f5d56b727a5276edf2027f12cf416c" }, { "path": "text_encoders/qwen3vl_32b_minimax_h3_bf16.safetensors", "bytes": 51506295256, "sha256": "600d567f6a9629c8574e8e7041b199bdd9c59a986afa7906910a81919610607d" }, { "path": "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors", "bytes": 27141342152, "sha256": "bc2ced0fbea64757fa9acddccfc0b3f4819d1dcf1da6c124d690d368be283923" }, { "path": "text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors", "bytes": 15687142551, "sha256": "35a88d51044231fe332301d7a62aa81e3f2cba62febeb446e2c1e3e0ef76f2c6" }, { "path": "vae/minimax_h3_audio_vae_fp32.safetensors", "bytes": 605254808, "sha256": "8e505d95dd1561d47abd43d4238fd40d9bb1ae9e147ed0a4cba778d76ae4db48" }, { "path": "vae/minimax_h3_video_vae_fp16.safetensors", "bytes": 5207808496, "sha256": "7c1f131492e7eddacaac9069a61b81bdd39de5cc96561e677c5eab1cdce5e522" }, { "path": "vae/minimax_h3_video_vae_int8_convrot.safetensors", "bytes": 2811065184, "sha256": "52a2c8c73583c86e4f41cdcce3a6ad0ea562987bc0bf3d60a0cef5f5c8e60c0e" } ], "notes": [ "Shared text encoder and VAE bytes are copied from pinned V2 Comfy repo.", "INT8 payload is the unchanged Comfy-produced preview file.", "BF16 payload is the separately validated bounded-memory export.", "GPU clip generation was not performed for this packaging release." ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136---license: otherlicense_name: minimax-h3-community-license-agreementlicense_link: https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSElibrary_name: diffusion-single-filetags:- comfyui- diffusion-single-file- minimax-h3- omnirefbase_model:- MiniMaxAI/MiniMax-H3- FastVideo/FastVideo-FastH3-Omni-8-Step-V1---
# FastH3 OmniRef for ComfyUI
Native ComfyUI checkpoint packaging of the eight-forward FastH3 OmniRef student.OmniRef generates video and audio from a prompt and ordered image, video andaudio references. This is a **private release candidate** derived from theprivate canonical OmniRef checkpoint.
This export follows the V2 Comfy packaging technique: a single diffusion-modelfile, shared Qwen3-VL text encoders and video/audio VAEs, and INT8 ConvRotweights. Both diffusion variants retain all 50 transformer blocks, bothtoken-refiner blocks and all 32 PDD heads, with a rank-8, 1025-point AdaLNtimestep curve. The BF16 export is newly converted with FP32 reduced AdaLNweights. The INT8 export preserves the existing Comfy-produced file byte forbyte and stores reduced AdaLN weights in FP16. Both curve tables are FP32.
## Files and installation
Place the files in these ComfyUI model directories:
```textComfyUI/models/├── diffusion_models/│ ├── fasth3_omniref_8step_pruned_bf16.safetensors│ └── fasth3_omniref_8step_pruned_int8_convrot.safetensors├── text_encoders/│ ├── qwen3vl_32b_minimax_h3_bf16.safetensors│ ├── qwen3vl_32b_minimax_h3_int8_convrot.safetensors│ └── qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors└── vae/ ├── minimax_h3_audio_vae_fp32.safetensors ├── minimax_h3_video_vae_fp16.safetensors └── minimax_h3_video_vae_int8_convrot.safetensors```
| Diffusion checkpoint | Size | Packaging || --- | ---: | --- || `fasth3_omniref_8step_pruned_bf16.safetensors` | 44.24 GB | New BF16 export; reduced AdaLN and PDD output heads stored in FP32 || `fasth3_omniref_8step_pruned_int8_convrot.safetensors` | 22.21 GB | Existing Comfy-produced conversion, copied byte for byte |
Choose one diffusion checkpoint, one text encoder and one video VAE; the audioVAE is also required. The shared files are unchanged Comfy-format artifactsfrom [FastVideo/FastVideo-FastH3-Comfy](https://huggingface.co/FastVideo/FastVideo-FastH3-Comfy).The text encoder includes the vision tower for reference conditioning, and thevideo VAE includes both the original reference encoder and 36-layer decoder.The NVFP4 AWQ option in this list is a **text encoder**, not an OmniRef NVFP4diffusion-model export or the separately trained NVFP4 output decoder.
Use native ComfyUI's `MiniMaxH3ReferenceToVideo` conditioning node with thematching video/audio VAEs. Prompts identify references with `<Picture 1>`,`<Video 1>` and `<Audio 1>` tags. The source contract uses eight forwards,guidance 1, video shift 12 and audio shift 3. The checkpoint records the32-head PDD layout in its model metadata. V2's text-to-video template and videoshift 10 are not an OmniRef recipe.
## Provenance and conversion
| Component | Frozen source ||---|---|| OmniRef diffusion model | `FastVideo/FastVideo-FastH3-Omni-8-Step-V1`, revision `88d512c5e7cc38dda499fbb65688ce58611f9c80`, `transformer_ref` || Existing Comfy-produced INT8 conversion | Revision `2d04fd2e79c633f514c3a14310bdf5cdf67f9147`; copied without modifying its checkpoint bytes. SHA-256: `851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80` || Shared Comfy text encoders and VAEs | `FastVideo/FastVideo-FastH3-Comfy`, revision `ec1e3aa374a91c57b0b94a1623b7e657c0498cf2` || Native ComfyUI architecture and detector | [`b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c`](https://github.com/Comfy-Org/ComfyUI/tree/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c) || Official Comfy model tools | [`d6797787e6bdb1a1fb0094d588a26f8e71a1c757`](https://github.com/Comfy-Org/comfy-model-tools/tree/d6797787e6bdb1a1fb0094d588a26f8e71a1c757) |
The new BF16 conversion fuses Q/K/V in order, swaps the source SwiGLU halvesand converts independent PDD heads to native Comfy's FP32first-head-plus-offset layout. AdaLN curve compression is a numericalapproximation. Its receipt records the output hash and sampled modulationerrors. The existing Comfy INT8 file uses native ConvRot markers, with denseoutput heads and reduced AdaLN. Its original 14 student shards match thecanonical source's file hashes. Sampled PDD output-head rows match the requirednative offset representation exactly. Sampled Q/K/V and SwiGLU rows and scalesalso match the official absmax ConvRot recipe applied to the canonical source.The INT8 file is reused rather than quantized again.
The new BF16 curve fit has relative residual 0.0001013. Across 129 held-outtimesteps and 64 sampled rows per modulation projection, the largest relativeL2 error is 0.0003073. These are modulation checks, not video-quality scores.The conversion source, full source-shard hash checks and copy receipts areincluded under `conversion/` and `provenance/`.
## Validation status
Six CPU regression checks pass, including the actual pinned native detectorand strict model loading, QKV order, SwiGLU output and PDD reconstruction.Every real-source key and shape also passes native model skeleton loading:688 source tensors become 582 tensors in the new compressed BF16 export.The existing Comfy INT8 checkpoint has 1,098 tensors, including 258 nativequantization markers. The new BF16 file also passes strict schema loadingthrough the full pinned ComfyUI modules and operations on the meta device.These checks do not validate a generated clip.**GPU inference, quantized-kernel parity and end-to-end output quality havenot yet been validated as part of this repository's release checks.**
Native Comfy behavior also differs from the source FastVideo inferencecontract: its PDD integrates a unit grid instead of the source maximum 0.999,and its native VSA patch uses 64-token video cubes instead of the source128-token tiling and reference policy. Attention remains dense until a sparsepatch is selected. The new BF16 file embeds the complete source contract inmetadata; the unchanged INT8 file embeds the 32-head PDD configuration. Thefull source contract and provenance are supplied separately for both. Neitherform of documentation changes native runtime choices. Do not treat theseexports as bit-identical FastVideo inference or attach FastVideo benchmarknumbers to them.
## Other OmniRef checkpoint formats
The FastVideo FP8 and NVFP4-QAD diffusion checkpoints need additional runtimesupport before they can preserve their numerical behavior in native ComfyUI.The FP8 source uses per-channel weight scales and per-token activationquantization; the inspected native Comfy FP8 path uses scalar/tensorwisescales. The NVFP4 source has different Q/K/V global scales, while nativefused QKV accepts one scalar. No renamed or requantized substitute is included.See `conversion/QUANTIZATION_COMPATIBILITY.md` for the concrete source valuesand consumer interfaces. The shared NVFP4-AWQ text encoder listed above isalready in the supported Comfy format.
The model weights remain subject to the[MiniMax-H3 Community License](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE).The supplied Comfy-derived conversion code and upstream tools use GPL-3.0;their license texts are included under `conversion/upstream/`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# OmniRef native ComfyUI export
The INT8 file packaged in this repository is an unchanged copy of the existingComfy-produced artifact, SHA256`851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80`.Its source identity and sampled PDD/quantized-row checks are in `../provenance/`.The converter below produced the BF16 variant. Running the optional quantizercommands below creates a new PTQ variant; they are not a claim of byte-for-bytereproduction of the supplied INT8 file, whose reduced AdaLN weights are FP16rather than this converter's FP32.
Source: `FastVideo/FastVideo-FastH3-Omni-8-Step-V1` at`88d512c5e7cc38dda499fbb65688ce58611f9c80`, component `transformer_ref`.The caller must verify the source shards against the frozen source identitybefore conversion. The converter checks every indexed tensor and its geometry;that check alone does not prove the files match the Hub revision.
The target is native ComfyUI's MiniMax H3 architecture, pinned to[`b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c`](https://github.com/Comfy-Org/ComfyUI/tree/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c).Official model tools are pinned to[`d6797787e6bdb1a1fb0094d588a26f8e71a1c757`](https://github.com/Comfy-Org/comfy-model-tools/tree/d6797787e6bdb1a1fb0094d588a26f8e71a1c757).The small pinned architecture, detector, quantizer, source URLs, hashes and GPLlicenses are under `upstream/`. No upstream source tree or local virtualenv isrequired in the model repository.
## Transformations
- Rename all 688 source tensors to the consumer's names; unknown/missing keys or mismatched geometry abort conversion.- Fuse Q, K, V in that row order, including the token refiner. Swap the two SwiGLU input halves from source value/gate to native Comfy gate/value.- Preserve all 32 PDD heads. Native Comfy stores the first full head and each later head's offset from the first. Compute those offsets in FP32; source BF16 values and their differences are exactly representable at this stage.- Generate the nonpersistent source RoPE frequencies as the persistent buffer expected by Comfy, using the original FP32 formula.- Preserve source dtypes otherwise. Native Comfy casts its input, timestep and output projection islands to FP32 when loading.- `--adaln-curve-rank 0` retains the dense timestep MLP and full AdaLN matrices. `--adaln-curve-rank 8 --curve-grid 1025` uses the same kind of time-embedding curve compression as the V2 Comfy pruned checkpoint: fit a shared SVD basis, project all 51 modulation matrices and replace the timestep MLP by a linearly interpolated coordinate table on `[0,1]`. This is an approximation, not removal of unused model blocks. The export stores table and reduced matrices in FP32; the V2 checkpoint stores reduced matrices in FP16. Its receipt records fit residual and 129 independent holdout timesteps on 64 sampled output rows per projection. No output-quality claim follows from these modulation checks alone.
Every source tensor contributes to the output or the curve projection; notrained transformer blocks or PDD heads are discarded. The four timestep-MLPtensors are replaced only in the explicit curve variant.
## Run
The conversion requires CPU PyTorch, NumPy and safetensors. It uses boundedbuffers and a scratch directory, instead of loading the 70.1 GB source intoRAM. The output writer hashes bytes as it streams them. A partial file isrenamed only after a complete write; existing outputs and scratch directoriesare not overwritten.
```bashpython convert_omniref_comfy.py \ --src /verified/source/transformer_ref \ --contract /verified/source/fastvideo_inference.json \ --output /staging/diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors \ --scratch /allocated/scratch/omniref-comfy-curve-r8 \ --adaln-curve-rank 8 --curve-grid 1025 --threads 4```
This produces 582 tensors with the curve recipe or 585 without it. The fullsource contains 688 tensors and 70,142,174,464 tensor bytes. Source and outputheads are not interchangeable by renaming: the PDD representation differs.
After validating the BF16-format export, run the pinned official quantizer's`--dry-run`, then quantize on an allocated GPU:
```bashpython upstream/quant_int8_convrot.py \ /staging/diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors \ --dry-runpython upstream/quant_int8_convrot.py \ /staging/diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors \ /staging/diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors \ --verify-report /staging/int8-convrot-verification.txt```
The tool defaults to absmax INT8, a minimum GEMM dimension of 256 and the largesteligible ConvRot group in 256/64/16. Do not add MSE clipping, FP32 downcasting,W4A8 or W6A8 when claiming this default recipe. Final/output heads and thesmall reduced AdaLN matrices pass through. Execution is CUDA-only in thisversion and retains the output dictionary in CPU RAM; allocate enough RAM forthe roughly 22 GB INT8 result plus work buffers. The dry run itself is CPU.
## Validation and inference limits
`python test_conversion.py` runs six CPU regression checks against actualpinned ComfyUI architecture and detector definitions. Ordinary CPU Linear andRMSNorm replace CUDA operations for these checks. Tests cover strict state-dictloading for dense and curve forms, fused QKV order, native SwiGLU output,native PDD head reconstruction, rejected unexpected tensors and streamed-filehash/overwrite protection. `audit_native_geometry.py --src ...` additionallychecks every real-source key and shape against dense and rank-8 native modelskeletons on the meta device, without allocating model weights.
These are checkpoint format and CPU arithmetic checks. They do not validateCUDA quantization kernels or an end-to-end generated clip.
Native Comfy inference differs from the frozen FastVideo source contract:
- Native PDD uses a unit `[1,0]` fine grid; the source's grid maximum is 0.999. Native PDD storage is handled by this converter, but its sampler grid is consumer behavior and is not changed by model metadata.- Native Comfy's VSA node uses `(4,4,4)` video cubes, while the source contract specifies tile size 128 and reference policy `p2_multi_region`.- Native attention is dense until a sparse-attention patch is selected.- Source generation requires 8 forwards, guidance 1, video/audio shifts 12/3 and the declared 32-interval head partition. Do not copy V2's video shift 10 or present the V2 text-to-video template as an OmniRef workflow.
The original inference contract is retained verbatim in safetensors metadataand in the conversion receipt. Do not claim bit-identical inference or reuseGB200 benchmark numbers for native Comfy without a matched runtime check.
## Other checkpoints
The existing V2 Comfy text encoders and complete original 36L video/audio VAEsare valid native-Comfy artifacts and can be copied with their original hashesand license attribution. MiniMax-H3 weights retain the MiniMax-H3 CommunityLicense; the tooling's GPL license is separate from the model license.
The FastVideo FP8 source needs a separate format bridge for fused QKV/scales,SwiGLU/scales and native quantization metadata. The QAD NVFP4 source usesFlashInfer packed weights, swizzled block scales and per-linear global scales;it cannot be copied or renamed into native Comfy's fused format. In particular,Q/K/V may have different global scales. Requantizing BF16 masters would be anew PTQ treatment, not byte-preserving conversion of the released QAD kernelrepresentation. Neither unimplemented bridge should be advertised as aworking Comfy checkpoint.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Native Comfy quantization compatibility audit
The ComfyUI checkout is pinned to`b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c`. Its requirements pin`comfy-kitchen==0.2.39`; installed relevant files match tag `v0.2.39`, commit`e40e76d9c544b3f74c3b9ea923f7bc3d45a96372`, byte for byte. See`../provenance/COMFY_KITCHEN_SOURCE_AUDIT.json` for hashes.
## Existing Comfy-produced OmniRef INT8: reuse
Preview revision `2d04fd2e79c633f514c3a14310bdf5cdf67f9147` contains an existing22,213,723,064-byte Comfy checkpoint, SHA-256`851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80`.Its 1,098 tensors include 258 native `int8_tensorwise` ConvRot markers, a`[1025,8]` FP32 AdaLN coordinate table, FP16 reduced AdaLN matrices and FP32PDD output heads. Metadata declares `transformer.pdd_steps=32`.
The parent matched all 14 original student-shard hashes to canonical revision`88d512c5e7cc38dda499fbb65688ce58611f9c80`. Additional remote byte-range checks:
- Eight output-head rows, from heads 0/1/7/31 of video and audio, exactly equal canonical head0 / (headj−head0), 43,008 FP32 values total.- Seven quantized rows spanning Q/K/V, both SwiGLU halves, and blocks 0/49 exactly match the pinned official absmax ConvRot quantizer applied to the corresponding canonical source rows. Both INT8 bytes and FP32 row scales match. This checks the fused QKV order and the SwiGLU swap.
Evidence: `../provenance/PREVIEW_PDD_SAMPLE_VALIDATION.json`,`../provenance/PREVIEW_QUANTIZED_SAMPLE_VALIDATION.json`, `../provenance/PREVIEW_HEADER.json`.These are sampled format/identity checks; no CUDA forward or output-qualitycomparison has been run by this audit. Reuse the file without requantization.
## FastVideo OmniRef FP8: not an exact native fast-path repack
Source revision `58c4d2ac52f366ac268149334da282341c747003` uses E4M3 weightswith per-output-channel FP32 scales and dynamic per-token activation scales.`../provenance/FP8_SOURCE_SAMPLE_HEADER.json` records the actual first Q projection'sweight and scale shapes.
Native Comfy's `float8_e4m3fn` format selects `TensorCoreFP8E4M3Layout` in[`comfy/quant_ops.py`](https://github.com/Comfy-Org/ComfyUI/blob/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c/comfy/quant_ops.py#L211).The Kitchen layout is explicitly per-tensor. Its GEMM helper invokes`scaled_mm_v2` with the default `ScalingType.TensorWise`; native activationquantization derives one tensor amax, rather than one amax per token.Critically, the CUDA fallback's[`dequantize_per_tensor_fp8`](https://github.com/Comfy-Org/comfy-kitchen/blob/e40e76d9c544b3f74c3b9ea923f7bc3d45a96372/comfy_kitchen/backends/cuda/__init__.py#L623)asserts `scale.numel() == 1`.
The generic loader can construct a scale tensor without checking its shape,and the CPU eager fallback can broadcast a row vector. Those facts do notestablish a valid native CUDA FP8 treatment. Merely concatenating Q/K/V weightsand row scales would not preserve the source's activation quantization, andthe native CUDA scalar-scale interface is incompatible with those row scales.
Options are a custom per-row-weight/per-token-activation runtime, or a newper-tensor FP8 requantization with a separate accuracy assessment. A densedequantized export is another format but provides neither the FP8 storage northe original W8A8 computation. Do not label any of these an unchanged nativerepack of the current FP8 release.
## FastVideo OmniRef QAD NVFP4: fused QKV scalar mismatch
Source revision `33349824181060ffc0f736e33dcead1b21dd24c8` stores separate Q/K/Vpacked matrices and a separate scalar `_nvfp4_alpha` for each. Actual firstblock values are:
| Projection | `_nvfp4_alpha` ||---|---:|| Q | 0.0009068080107681453 || K | 0.0013427734375 || V | 0.0006626674439758062 |
See `../provenance/NVFP4_QKV_SCALAR_AUDIT.json` and `../provenance/NVFP4_SOURCE_HEADER.json`.
Native Comfy's architecture has one fused `qkv_proj`. Its NVFP4 layout takesone `weight_scale_2` for that linear. Kitchen's[`scaled_mm_nvfp4` CUDA implementation](https://github.com/Comfy-Org/comfy-kitchen/blob/e40e76d9c544b3f74c3b9ea923f7bc3d45a96372/comfy_kitchen/backends/cuda/__init__.py#L1871)forms one alpha from the input and weight tensor scales and asserts`alpha.numel() == 1`. The three measured source scalars are unequal, so thethree packed Q/K/V matrices cannot simply be concatenated under one nativeweight scalar while preserving their values.
An exact bridge would need separate Q/K/V native modules or another runtimechange retaining their independent scales. For the current fused module,rescaling/requantizing block scales or BF16 masters is a new numericaltreatment and needs validation; it is not preservation of the QAD kernelrepresentation. Nibble packing, block-scale swizzle and activation-scaleconventions also need explicit checks in any future bridge, but the measuredscalar mismatch already rules out the simple unchanged repack.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#!/usr/bin/env python3"""Check every real checkpoint key/shape against native Comfy on the meta device."""import argparseimport jsonfrom pathlib import Path
import torch
import convert_omniref_comfy as convfrom test_conversion import native_namespace
def audit(src): c, source = conv.load_source(src) expected = conv.expected_shapes(c) assert set(source) == set(expected) assert all(source[k].shape == shape for k, shape in expected.items()) native = native_namespace() receipts = [] for rank in [0, 8]: target = {} for name, tensor in source.items(): if ".attn.to_k." in name or ".attn.to_v." in name: continue shape = list(tensor.shape) output_name = conv.renamed(name) if ".attn.to_q." in name: output_name = output_name.replace(".attn.to_q.", ".attn.qkv_proj.") shape[0] *= 3 if rank and name.startswith("time_embedder."): continue if rank and (name == "norm_out.linear.weight" or name.endswith(".adaln_proj.linear.weight")): shape[-1] = rank target[output_name] = torch.empty(shape, device="meta") target["rope.inv_freq"] = torch.empty([c["rope_freq_dim"]], device="meta") if rank: target["adaln_t_table"] = torch.empty([1025, rank], device="meta") metadata = conv.metadata_for(c, {"video_scheduler_shift": 12.0, "audio_scheduler_shift": 3.0}, rank) detected = native["detect_unet_config"](target, "", metadata=metadata) model = native["MiniMaxH3Model"](**detected, dtype=torch.float32, device="meta", operations=torch.nn) result = model.load_state_dict(target, strict=True, assign=True) assert not result.missing_keys and not result.unexpected_keys assert all(target[k].shape == model.state_dict()[k].shape for k in target) receipts.append({"source_tensors": len(source), "target_tensors": len(target), "curve_rank": rank, "detected_config": detected, "native_strict_meta_load": "passed", "gpu_inference": "not_run"}) return receipts
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--src", required=True, type=Path) args = parser.parse_args() print(json.dumps(audit(args.src), indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367#!/usr/bin/env python3"""Bounded-memory FastVideo H3 OmniRef -> native ComfyUI single-file export.
Dense BF16/F16/F32 source only. All source tensors are accounted for. QKV fusionand SwiGLU reordering copy bytes. PDD full heads become FP32 baseline+offsetheads because that is the native ComfyUI consumer's representation. Optionalrank-reduced AdaLN curves are an explicitly reported numerical approximation."""from __future__ import annotations
import argparsefrom dataclasses import dataclassimport hashlibimport jsonimport mathfrom pathlib import Pathimport reimport structimport sys
COMFY_COMMIT = "b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c"TOOLS_COMMIT = "d6797787e6bdb1a1fb0094d588a26f8e71a1c757"SOURCE_REPO = "FastVideo/FastVideo-FastH3-Omni-8-Step-V1"SOURCE_REVISION = "88d512c5e7cc38dda499fbb65688ce58611f9c80"DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4}CHUNK = 8 * 1024 * 1024
@dataclassclass Tensor: dtype: str shape: list[int] path: Path offset: int size: int
@dataclassclass Output: dtype: str shape: list[int] # File ranges, kept in order; generated tensors are small scratch files. parts: list[tuple[Path, int, int]]
def header(path: Path) -> tuple[dict, int]: with path.open("rb") as f: raw = f.read(8) if len(raw) != 8: raise ValueError(f"Truncated safetensors file: {path}") length, = struct.unpack("<Q", raw) if length > 100 * 1024 * 1024: raise ValueError(f"Unreasonable header length: {path}") data = f.read(length) if len(data) != length: raise ValueError(f"Truncated safetensors header: {path}") return json.loads(data), 8 + length
def load_source(src: Path) -> tuple[dict, dict[str, Tensor]]: config = json.loads((src / "config.json").read_text()) if config.get("quantization_config") or config.get("adaln_rank"): raise ValueError("Only the dense canonical OmniRef source is accepted") index = json.loads((src / "diffusion_pytorch_model.safetensors.index.json").read_text()) weight_map = index["weight_map"] tensors: dict[str, Tensor] = {} for filename in sorted(set(weight_map.values())): path = src / filename if Path(filename).name != filename: raise ValueError(f"Unsafe shard name: {filename}") items, start = header(path) for name, item in items.items(): if name == "__metadata__": continue if name in tensors or weight_map.get(name) != filename: raise ValueError(f"Duplicate/unindexed tensor: {name}") dtype, shape = item["dtype"], item["shape"] if dtype not in DTYPE_BYTES: raise ValueError(f"Unexpected non-dense dtype {dtype}: {name}") begin, end = item["data_offsets"] size = math.prod(shape) * DTYPE_BYTES[dtype] if begin < 0 or end - begin != size or start + end > path.stat().st_size: raise ValueError(f"Invalid/truncated tensor range: {name}") tensors[name] = Tensor(dtype, shape, path, start + begin, size) if set(tensors) != set(weight_map): raise ValueError("Source tensor keys do not match the frozen index") return config, tensors
def expected_shapes(c: dict) -> dict[str, list[int]]: h, q = c["hidden_size"], c["num_attention_heads"] * c["attention_head_dim"] f, t, p = c["ffn_dim"], c["time_embed_dim"], c["pdd_steps"] video = c["in_channels"] * math.prod(c["patch_size"]) audio = c["audio_in_channels"] result = {} for name, rows, cols in [("proj_in", h, video), ("audio_proj_in", h, audio), ("context_embedder", h, c["text_dim"]), ("proj_out", video * p, h), ("audio_proj_out", audio * p, h), ("time_embedder.linear_1", c["time_embed_hidden_dim"], c["freq_dim"]), ("time_embedder.linear_2", t, c["time_embed_hidden_dim"]), ("norm_out.linear", 2 * h, t)]: result[name + ".weight"] = [rows, cols] result[name + ".bias"] = [rows] result["norm_out.norm.weight"] = [h] result["token_refiner.final_norm.weight"] = [h] for prefix, count in [("transformer_blocks", c["num_layers"]), ("token_refiner.refiner_blocks", c["num_refiner_layers"])]: for i in range(count): stem = f"{prefix}.{i}." result.update({stem + "norm1.weight": [h], stem + "norm2.weight": [h], stem + "attn.norm_q.weight": [c["attention_head_dim"]], stem + "attn.norm_k.weight": [c["attention_head_dim"]], stem + "attn.to_q.weight": [q, h], stem + "attn.to_k.weight": [q, h], stem + "attn.to_v.weight": [q, h], stem + "attn.to_out.0.weight": [h, q], stem + "ff.net.0.proj.weight": [2 * f, h], stem + "ff.net.2.weight": [h, f]}) if prefix == "transformer_blocks": result[stem + "adaln_proj.linear.weight"] = [18 * h, t] result[stem + "adaln_proj.linear.bias"] = [18 * h] result[stem + "attn.to_gate_compress.weight"] = [q, h] return result
def renamed(name: str) -> str: roots = {"proj_in": "video_patch_proj", "audio_proj_in": "audio_patch_proj", "context_embedder": "condition_proj", "proj_out": "final_layer.video_out", "audio_proj_out": "final_layer.audio_out", "norm_out.linear": "final_layer.adaln_proj.linear", "norm_out.norm": "final_layer.norm", "time_embedder.linear_1": "time_embedder.proj_in", "time_embedder.linear_2": "time_embedder.proj_out"} for before in sorted(roots, key=len, reverse=True): if name.startswith(before + "."): return roots[before] + name[len(before):] name = name.replace("token_refiner.refiner_blocks.", "token_refiner.blocks.") name = re.sub(r"^transformer_blocks\.", "blocks.", name) return (name.replace(".attn.norm_q.", ".attn.q_norm.").replace(".attn.norm_k.", ".attn.k_norm.") .replace(".attn.to_out.0.", ".attn.out_proj.").replace(".ff.net.2.", ".mlp.fc2.") .replace(".ff.net.0.proj.", ".mlp.fc1."))
def torch_tensor(t: Tensor, first: int = 0, rows: int | None = None): import torch stride = math.prod(t.shape[1:]) * DTYPE_BYTES[t.dtype] count = (t.shape[0] - first) if rows is None else rows with t.path.open("rb") as f: f.seek(t.offset + first * stride) raw = bytearray(f.read(count * stride)) if len(raw) != count * stride: raise ValueError(f"Source truncated while reading {t.path}") dtype = {"BF16": torch.bfloat16, "F16": torch.float16, "F32": torch.float32}[t.dtype] return torch.frombuffer(raw, dtype=dtype).reshape(count, *t.shape[1:])
def raw_tensor(tensor) -> bytes: import torch return tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes()
def generated(path: Path, tensor) -> Output: import torch dtype = {torch.float32: "F32", torch.float16: "F16", torch.bfloat16: "BF16"}[tensor.dtype] path.write_bytes(raw_tensor(tensor)) return Output(dtype, list(tensor.shape), [(path, 0, path.stat().st_size)])
def convert_heads(t: Tensor, n: int, scratch: Path, name: str) -> Output: """Native Comfy stores head0 and (headj-head0). Differences stay FP32.""" per_head = t.shape[0] // n output = scratch / (name.replace(".", "_") + ".bin") with output.open("wb") as f: for j in range(n): for row in range(0, per_head, 256): count = min(256, per_head - row) x = torch_tensor(t, j * per_head + row, count).float() if j: x -= torch_tensor(t, row, count).float() f.write(raw_tensor(x)) return Output("F32", t.shape, [(output, 0, output.stat().st_size)])
def time_curve(t, c: dict, tensors: dict[str, Tensor]): import torch half = c["freq_dim"] // 2 freq = torch.exp(-math.log(10000.0) * torch.arange(half, dtype=torch.float64) / half) embed = torch.cat(((t[:, None] * freq).cos(), (t[:, None] * freq).sin()), dim=1) w1, b1, w2, b2 = [torch_tensor(tensors[k]).double() for k in ["time_embedder.linear_1.weight", "time_embedder.linear_1.bias", "time_embedder.linear_2.weight", "time_embedder.linear_2.bias"]] return torch.nn.functional.silu(torch.nn.functional.linear( torch.nn.functional.silu(torch.nn.functional.linear(embed, w1, b1)), w2, b2))
def prune_curves(c, tensors, output, rank, grid, scratch): import torch if rank < 1 or rank > min(c["time_embed_dim"], grid): raise ValueError("Invalid AdaLN curve rank") train_t = torch.linspace(0, 1, grid, dtype=torch.float64) curve = time_curve(train_t, c, tensors) _, singular, vh = torch.linalg.svd(curve, full_matrices=False) basis = vh[:rank].T.contiguous() coordinates = (curve @ basis).float() # Independent offset grid exercises table interpolation, including near endpoints. hold_t = (torch.arange(129, dtype=torch.float64) + 0.37) / 129 hold = time_curve(hold_t, c, tensors) pos = hold_t * (grid - 1) i0 = pos.floor().long().clamp(max=grid - 2) interpolated = torch.lerp(coordinates[i0], coordinates[i0 + 1], (pos - i0).float()[:, None]).double() errors = [] for source_name, tensor in tensors.items(): if source_name != "norm_out.linear.weight" and not source_name.endswith(".adaln_proj.linear.weight"): continue path = scratch / (renamed(source_name).replace(".", "_") + ".curve.bin") with path.open("wb") as f: for row in range(0, tensor.shape[0], 2048): dense = torch_tensor(tensor, row, min(2048, tensor.shape[0] - row)).double() f.write(raw_tensor((dense @ basis).float())) output[renamed(source_name)] = Output("F32", [tensor.shape[0], rank], [(path, 0, path.stat().st_size)]) sample_rows = torch.linspace(0, tensor.shape[0] - 1, min(64, tensor.shape[0])).long().tolist() sample = torch.cat([torch_tensor(tensor, row, 1) for row in sample_rows]).double() reference = hold @ sample.T approximate = interpolated @ (sample @ basis).float().double().T errors.append({"tensor": source_name, "sampled_rows": len(sample_rows), "relative_l2": float((approximate - reference).norm() / reference.norm().clamp(min=1e-30)), "max_abs": float((approximate - reference).abs().max())}) for key in list(output): if key.startswith("time_embedder."): del output[key] output["adaln_t_table"] = generated(scratch / "adaln_t_table.bin", coordinates) return {"kind": "time-embedding-curve-svd-and-linear-interpolation", "rank": rank, "grid": grid, "table_dtype": "F32", "projected_weight_dtype": "F32", "fit_domain": [0.0, 1.0], "fit_relative_residual": float(singular[rank:].norm() / singular.norm()), "holdout_timesteps": len(hold_t), "holdout_modulation_samples": errors, "approximation": True, "end_to_end_quality_validated": False}
def make_plan(c: dict, tensors: dict[str, Tensor], scratch: Path, rank: int = 0, grid: int = 1025): import torch expected = expected_shapes(c) if set(tensors) != set(expected): raise ValueError(f"Unexpected source keys: missing={sorted(set(expected)-set(tensors))}; " f"extra={sorted(set(tensors)-set(expected))}") for name, shape in expected.items(): if tensors[name].shape != shape: raise ValueError(f"{name}: expected {shape}, got {tensors[name].shape}") output = {} for name, t in sorted(tensors.items()): if ".attn.to_k." in name or ".attn.to_v." in name: continue if ".attn.to_q." in name: group = [tensors[name.replace(".attn.to_q.", f".attn.to_{p}.")] for p in ("q", "k", "v")] if len({g.dtype for g in group}) != 1: raise ValueError(f"QKV dtype mismatch: {name}") out_name = renamed(name).replace(".attn.to_q.", ".attn.qkv_proj.") output[out_name] = Output(t.dtype, [3 * t.shape[0], *t.shape[1:]], [(g.path, g.offset, g.size) for g in group]) elif ".ff.net.0.proj." in name: half = t.size // 2 output[renamed(name)] = Output(t.dtype, t.shape, [(t.path, t.offset + half, half), (t.path, t.offset, half)]) elif name.startswith(("proj_out.", "audio_proj_out.")): output[renamed(name)] = convert_heads(t, c["pdd_steps"], scratch, name) else: output[renamed(name)] = Output(t.dtype, t.shape, [(t.path, t.offset, t.size)]) inv = 1.0 / (c["rope_theta"] ** (torch.arange(0, 2 * c["rope_freq_dim"], 2, dtype=torch.float32) / (2 * c["rope_freq_dim"]))) output["rope.inv_freq"] = generated(scratch / "rope.bin", inv) curve = prune_curves(c, tensors, output, rank, grid, scratch) if rank else None return output, curve
def write_file(path: Path, output: dict[str, Output], metadata: dict) -> dict: if path.exists(): raise FileExistsError(f"Refusing to overwrite {path}") table = {"__metadata__": metadata} offset = 0 for name, item in sorted(output.items()): size = sum(part[2] for part in item.parts) if size != math.prod(item.shape) * DTYPE_BYTES[item.dtype]: raise ValueError(f"Output byte count mismatch: {name}") table[name] = {"dtype": item.dtype, "shape": item.shape, "data_offsets": [offset, offset + size]} offset += size raw = json.dumps(table, separators=(",", ":"), ensure_ascii=False).encode() raw += b" " * (-len(raw) % 8) digest = hashlib.sha256() tmp = path.with_name(path.name + ".partial") if tmp.exists(): raise FileExistsError(f"Scratch output already exists: {tmp}") path.parent.mkdir(parents=True, exist_ok=True) with tmp.open("xb") as f: def emit(data): f.write(data) digest.update(data) emit(struct.pack("<Q", len(raw))) emit(raw) for name, item in sorted(output.items()): for src, begin, count in item.parts: with src.open("rb") as source: source.seek(begin) while count: block = source.read(min(count, CHUNK)) if not block: raise ValueError(f"Truncated source during output: {name}") emit(block) count -= len(block) tmp.rename(path) return {"file": path.name, "bytes": path.stat().st_size, "sha256": digest.hexdigest(), "tensors": len(output), "tensor_data_bytes": offset}
def metadata_for(c, contract, rank): transformer = {"pdd_steps": c["pdd_steps"], "sigma_shift_video": contract["video_scheduler_shift"], "sigma_shift_audio": contract["audio_scheduler_shift"], "norm_eps": c["norm_eps"], "qk_norm_eps": c["qk_norm_eps"], "final_norm_eps": c["final_norm_eps"]} if rank: transformer["time_embed_dim"] = rank return {"format": "pt", "config": json.dumps({"transformer": transformer}, separators=(",", ":")), "source_repo": SOURCE_REPO, "source_revision": SOURCE_REVISION, "comfyui_commit": COMFY_COMMIT, "comfy_model_tools_commit": TOOLS_COMMIT, "source_inference_contract": json.dumps(contract, separators=(",", ":")), "pdd_head_storage": "head0-full;heads1-31-offset-from-head0;fp32", "adaln_curve_approximation": str(bool(rank)).lower(), "inference_parity": "not-validated;native-Comfy-PDD-uses-unit-grid-source-uses-0.999"}
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--src", type=Path, required=True, help="Canonical transformer_ref component directory") p.add_argument("--output", type=Path, required=True) p.add_argument("--contract", type=Path, help="Defaults to SRC/../fastvideo_inference.json") p.add_argument("--scratch", type=Path, required=True) p.add_argument("--adaln-curve-rank", type=int, default=0, help="0 retains full dense AdaLN;8 mirrors V2 technique") p.add_argument("--curve-grid", type=int, default=1025) p.add_argument("--threads", type=int, default=4) p.add_argument("--inspect-only", action="store_true", help="Validate headers and print plan without conversion") args = p.parse_args() c, tensors = load_source(args.src) expected = expected_shapes(c) if set(expected) != set(tensors) or any(tensors[k].shape != v for k, v in expected.items()): raise ValueError("Source geometry does not match the canonical native H3 mapping") if args.inspect_only: print(json.dumps({"source_tensors": len(tensors), "source_tensor_bytes": sum(t.size for t in tensors.values()), "pdd_steps": c["pdd_steps"], "curve_rank": args.adaln_curve_rank, "output_tensors": len(tensors) - 2 * (c["num_layers"] + c["num_refiner_layers"]) + 1 - (3 if args.adaln_curve_rank else 0)}, indent=2)) return import torch torch.set_num_threads(args.threads) args.scratch.mkdir(parents=True, exist_ok=False) contract_path = args.contract or args.src.parent / "fastvideo_inference.json" contract = json.loads(contract_path.read_text()) if contract.get("pdd_steps") != c["pdd_steps"] or contract.get("grid_max_t") != 0.999: raise ValueError("Unexpected source inference contract") output, curve = make_plan(c, tensors, args.scratch, args.adaln_curve_rank, args.curve_grid) receipt = write_file(args.output, output, metadata_for(c, contract, args.adaln_curve_rank)) receipt.update({"source_repo": SOURCE_REPO, "source_revision": SOURCE_REVISION, "source_index_sha256": hashlib.sha256((args.src / "diffusion_pytorch_model.safetensors.index.json").read_bytes()).hexdigest(), "source_config": c, "source_contract": contract, "source_tensors": len(tensors), "source_tensor_bytes": sum(t.size for t in tensors.values()), "skipped_source_tensors": [], "conversion": ["concatenateQKV", "swapSwiGLUhalves", "PDDfullheadsToFP32offsetheads", "deriveRoPE"], "curve": curve, "comfyui_commit": COMFY_COMMIT, "comfy_model_tools_commit": TOOLS_COMMIT, "gpu_inference_validated": False}) receipt_path = args.output.with_suffix(args.output.suffix + ".receipt.json") receipt_path.write_text(json.dumps(receipt, indent=2) + "\n") print(json.dumps(receipt, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""CPU regression checks against the pinned native ComfyUI consumer."""import astfrom contextlib import contextmanagerimport importlib.utilimport jsonimport mathfrom pathlib import Pathimport sysimport tempfilefrom types import SimpleNamespaceimport unittest
import torchfrom safetensors import safe_openfrom safetensors.torch import load_file, save_file
HERE = Path(__file__).parentspec = importlib.util.spec_from_file_location("omniref_converter", HERE / "convert_omniref_comfy.py")conv = importlib.util.module_from_spec(spec)sys.modules[spec.name] = convspec.loader.exec_module(conv)
def native_namespace(): # Execute the actual pinned architecture, with ordinary CPU Linear/RMSNorm # and an explicit activation implementation in place of CUDA kitchen ops. @contextmanager def cast_weights(head, h, offloadable=True): yield head.weight.to(h), head.bias.to(h)
def swiglu(linear, packed, activation): assert activation == "swiglu" gate, value = packed.chunk(2, dim=-1) return linear(torch.nn.functional.silu(gate) * value)
namespace = {"torch": torch, "nn": torch.nn, "math": math, "ComfyAttention": lambda: None, "comfy": SimpleNamespace(ops=SimpleNamespace( CastBiasWeightContext=cast_weights, linear_input_act=swiglu))} tree = ast.parse((HERE / "upstream/comfy_model.py").read_text()) body = [node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.ClassDef))] exec(compile(ast.Module(body=body, type_ignores=[]), "pinned-ComfyUI-model", "exec"), namespace) detection = ast.parse((HERE / "upstream/comfy_model_detection.py").read_text()) funcs = [n for n in detection.body if isinstance(n, ast.FunctionDef) and n.name in {"count_blocks", "detect_unet_config", "any_suffix_in"}] namespace["json"] = json exec(compile(ast.Module(body=funcs, type_ignores=[]), "pinned-ComfyUI-detection", "exec"), namespace) return namespace
def fixture(path): config = {"hidden_size": 4, "num_attention_heads": 2, "attention_head_dim": 2, "ffn_dim": 6, "time_embed_dim": 3, "pdd_steps": 4, "in_channels": 2, "audio_in_channels": 2, "patch_size": [1, 2, 2], "text_dim": 5, "time_embed_hidden_dim": 4, "freq_dim": 4, "num_layers": 2, "num_refiner_layers": 1, "rope_theta": 10000.0, "rope_freq_dim": 2, "norm_eps": 1e-5, "qk_norm_eps": 1e-5, "final_norm_eps": 1e-5} g = torch.Generator().manual_seed(24) tensors = {k: (torch.randn(shape, generator=g) * 0.1).bfloat16() for k, shape in conv.expected_shapes(config).items()} names = sorted(tensors) mapping = {} for j in range(2): selected = {k: tensors[k] for k in names[j::2]} filename = f"part-{j}.safetensors" save_file(selected, str(path / filename)) mapping.update({k: filename for k in selected}) (path / "config.json").write_text(json.dumps(config)) (path / "diffusion_pytorch_model.safetensors.index.json").write_text(json.dumps({"weight_map": mapping})) return config, tensors
class ConversionTests(unittest.TestCase): @classmethod def setUpClass(cls): torch.set_num_threads(2) cls.native = native_namespace()
def convert(self, path, rank=0): c, original = fixture(path) _, source = conv.load_source(path) scratch = path / "scratch" scratch.mkdir() output, curve = conv.make_plan(c, source, scratch, rank=rank, grid=1025) contract = {"pdd_steps": 4, "grid_max_t": 0.999, "video_scheduler_shift": 12.0, "audio_scheduler_shift": 3.0} metadata = conv.metadata_for(c, contract, rank) target = path / "export.safetensors" receipt = conv.write_file(target, output, metadata) return c, original, load_file(str(target)), metadata, curve, receipt
def test_native_detection_and_strict_dense_state_dict_load(self): with tempfile.TemporaryDirectory() as d: c, source, target, metadata, _, _ = self.convert(Path(d)) detected = self.native["detect_unet_config"](target, "", metadata=metadata) self.assertEqual(detected["pdd_steps"], 4) self.assertTrue(detected["gate_compress"]) self.assertEqual(detected["latents_dim"], 2) model = self.native["MiniMaxH3Model"](**detected, device="cpu", dtype=torch.float32, operations=torch.nn) model.load_state_dict(target, strict=True) qkv = model.blocks[0].attn.qkv_proj.weight expected = torch.cat([source[f"transformer_blocks.0.attn.to_{p}.weight"].float() for p in ("q", "k", "v")]) self.assertTrue(torch.equal(qkv, expected))
def test_swiglu_native_forward_matches_diffusers_value_first(self): with tempfile.TemporaryDirectory() as d: c, source, target, _, _, _ = self.convert(Path(d)) mlp = self.native["MLP"](c["hidden_size"], c["ffn_dim"], operations=torch.nn, dtype=torch.float32) mlp.load_state_dict({"fc1.weight": target["blocks.0.mlp.fc1.weight"], "fc2.weight": target["blocks.0.mlp.fc2.weight"]}, strict=True) x = torch.randn(7, c["hidden_size"]) value, gate = torch.nn.functional.linear(x, source["transformer_blocks.0.ff.net.0.proj.weight"].float()).chunk(2, dim=-1) expected = torch.nn.functional.linear(value * torch.nn.functional.silu(gate), source["transformer_blocks.0.ff.net.2.weight"].float()) torch.testing.assert_close(mlp(x), expected, rtol=0, atol=0)
def test_pdd_native_consumer_recovers_weighted_full_heads(self): with tempfile.TemporaryDirectory() as d: c, source, target, _, _, _ = self.convert(Path(d)) h = torch.randn(3, c["hidden_size"]) for stream, key in [("video", "proj_out"), ("audio", "audio_proj_out")]: weight = target[f"final_layer.{stream}_out.weight"] bias = target[f"final_layer.{stream}_out.bias"] head = SimpleNamespace(weight=weight, bias=bias) original_w = source[key + ".weight"].float().reshape(4, -1, c["hidden_size"]) original_b = source[key + ".bias"].float().reshape(4, -1) for start, stop in [(0, 1), (0, 2), (1, 3), (3, 4)]: for shift in [3.0, 12.0]: grid = torch.linspace(1.0, 0.0, 5, dtype=torch.float64) dt = (1 - shift * grid / (1 + (shift - 1) * grid)).diff()[start:stop] normalized = (dt / dt.sum()).float() expected = torch.nn.functional.linear(h, torch.einsum("n,noi->oi", normalized, original_w[start:stop]), torch.einsum("n,no->o", normalized, original_b[start:stop])) actual = self.native["_pdd_head"](head, h, 4, start, stop, shift) torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6)
def test_curve_export_native_strict_load_and_holdout_error(self): with tempfile.TemporaryDirectory() as d: c, source, target, metadata, curve, _ = self.convert(Path(d), rank=3) detected = self.native["detect_unet_config"](target, "", metadata=metadata) self.assertEqual(detected["adaln_curve_grid"], 1025) self.assertEqual(detected["time_embed_dim"], 3) model = self.native["MiniMaxH3Model"](**detected, device="cpu", dtype=torch.float32, operations=torch.nn) model.load_state_dict(target, strict=True) self.assertFalse(any(k.startswith("time_embedder.") for k in target)) self.assertTrue(curve["approximation"]) self.assertLess(max(e["relative_l2"] for e in curve["holdout_modulation_samples"]), 1e-5)
def test_reject_unexpected_tensor_before_writing(self): with tempfile.TemporaryDirectory() as d: path = Path(d) fixture(path) c, source = conv.load_source(path) source["optimizer.unknown"] = source["proj_in.weight"] with self.assertRaisesRegex(ValueError, "Unexpected source keys"): conv.make_plan(c, source, path)
def test_output_hash_and_refuse_overwrite(self): import hashlib with tempfile.TemporaryDirectory() as d: path = Path(d) _, _, _, _, _, receipt = self.convert(path) self.assertEqual(receipt["sha256"], hashlib.sha256((path / "export.safetensors").read_bytes()).hexdigest()) with self.assertRaises(FileExistsError): conv.write_file(path / "export.safetensors", {}, {})
if __name__ == "__main__": unittest.main(verbosity=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<https://www.gnu.org/licenses/why-not-lgpl.html>.1234567891011121314151617181920212223242526272829303132[ { "file": "comfy_model.py", "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c/comfy/ldm/minimax/model.py", "sha256": "bdf1c2121a94ae8ef3da72dba6caf120eb6255457cecf569af32ff91d34c5fda", "bytes": 41140 }, { "file": "comfy_model_detection.py", "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c/comfy/model_detection.py", "sha256": "b0f615387a1808eb01edf92bc301bb79e02c42112b566cf6826b67c45e7d71ed", "bytes": 93877 }, { "file": "quant_int8_convrot.py", "url": "https://raw.githubusercontent.com/Comfy-Org/comfy-model-tools/d6797787e6bdb1a1fb0094d588a26f8e71a1c757/quant_int8_convrot.py", "sha256": "dd85ca376b985222719f052acbe47081c6fdf54742791ac1b44209923828146a", "bytes": 24249 }, { "file": "COMFY_LICENSE", "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c/LICENSE", "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", "bytes": 35149 }, { "file": "TOOLS_LICENSE", "url": "https://raw.githubusercontent.com/Comfy-Org/comfy-model-tools/d6797787e6bdb1a1fb0094d588a26f8e71a1c757/LICENSE", "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", "bytes": 35149 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<https://www.gnu.org/licenses/why-not-lgpl.html>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792"""MiniMax H3 audio-video DiT.
Single-stream packed-token transformer denoising video (24ch, patch 1x2x2) andstereo audio (32ch, 40 Hz) latents jointly, conditioned on Qwen3-VL layer-50 hidden states.The packed sequence is:[text | cond rows | audio | video] for t2va/fl2va[text | reference blocks | audio | video] for ref2va
Timestep domain: the model receives the *video* sigma from the sampler andderives per-token timesteps t = 1 - sigma internally; the audio stream runs onits own shifted schedule (sigma_shift video 12.0 / audio 3.0), mapped from thevideo sigma in closed form. The sampler carries the audio latent scaled onto thevideo schedule (ModelSamplingAV); forward() undoes that scale and converts thevelocity back, so _forward only ever sees the stream's own latent."""
import math
import torchimport torch.nn as nn
import comfy.ldm.common_ditimport comfy.model_managementimport comfy.model_prefetchimport comfy.opsimport comfy.patcher_extensionimport comfy.quant_opsfrom comfy.ldm.modules.attention import ComfyAttention, AttentionTensorContainer, optimized_attention
FRAME_PER_TOKEN = (1, 4, 4, 4, 4)FRAME_RESCALE = 5.0 / 3.0VISUAL_COND_TIMESTEP = 0.999AUDIO_COND_TIMESTEP = 1.0
def time_shift_sigma(sigma, from_shift, to_shift): # invert sigma = s*b/(1+(s-1)*b) to the base grid, re-apply the other shift base = sigma / (from_shift + sigma * (1.0 - from_shift)) return to_shift * base / (1.0 + (to_shift - 1.0) * base)
def patchify_video(latent, patch_size=(1, 2, 2)): # [B, C, T, H, W] -> [B*t*h*w, C*pt*ph*pw] b, c, t_full, h_full, w_full = latent.shape pt, ph, pw = patch_size t, h, w = t_full // pt, h_full // ph, w_full // pw x = latent.reshape(b, c, t, pt, h, ph, w, pw) x = torch.einsum("nctrhpwq->nthwcrpq", x) return x.reshape(b * t * h * w, c * pt * ph * pw)
def unpatchify_video(rows, t, h, w, c=24, patch_size=(1, 2, 2)): pt, ph, pw = patch_size x = rows.reshape(-1, t, h, w, c, pt, ph, pw) x = torch.einsum("nthwcrpq->nctrhpwq", x) return x.reshape(-1, c, t * pt, h * ph, w * pw)
def pack_audio(latent): # [B, C=32, ch=2, T] -> [ch*T, 32] channel-major (ch0 t0..T-1, ch1 t0..T-1) b, c, ch, t = latent.shape return latent[0].permute(1, 2, 0).reshape(ch * t, c)
def unpack_audio(rows, ch=2): t = rows.shape[0] // ch return rows.reshape(ch, t, rows.shape[-1]).permute(2, 0, 1).unsqueeze(0)
def _axis_from_sqrt_area(dim, patch, sqrt_area): # linspace((1 - ratio) / 2, (1 + ratio) / 2, dim // patch, endpoint=False) * 32 ratio = dim / sqrt_area n = dim // patch return (torch.arange(n, dtype=torch.float64) * (ratio / n) + (1.0 - ratio) / 2.0) * 32.0
def mask_row_values(mask, latent_t, lat_h, lat_w): # [T, H, W] denoise mask (1 = generate) -> per-2x2-patch-row float in [0, 1], # None when every row fully generates m = torch.nn.functional.pad(mask, (0, lat_w - mask.shape[-1], 0, lat_h - mask.shape[-2]), mode="replicate") m = m.reshape(latent_t, lat_h // 2, 2, lat_w // 2, 2).amax(dim=(2, 4)) values = m.reshape(-1) if bool((values >= 1.0 - 1e-3).all()): return None return values
def _frame_grid(h, w): # area-normalized (h, w) coordinates of one latent frame's 2x2-patch rows area = math.sqrt(h * w) hh, ww = torch.meshgrid(_axis_from_sqrt_area(h, 2, area), _axis_from_sqrt_area(w, 2, area), indexing="ij") return torch.stack([hh.reshape(-1), ww.reshape(-1)], dim=-1), _axis_from_sqrt_area(w, 2, area)
def _video_t_spans(n): return [FRAME_RESCALE * FRAME_PER_TOKEN[k % 5] for k in range(n)]
def _video_t_grid(n, origin): # origin + exclusive cumsum spans = torch.tensor(_video_t_spans(n), dtype=torch.float64) return float(origin) + torch.cat([torch.zeros(1, dtype=torch.float64), spans[:-1].cumsum(0)])
def _ref_t_span(blk): # time-axis span a reference block occupies ahead of the target streams kind = blk["kind"] if kind == "image": return 1.0 if kind == "audio": return float(blk["ref_audio_t"]) if kind in ("video", "video_audio"): return max(float(blk["ref_audio_t"]), sum(_video_t_spans(blk["latent_t"]))) return 0.0
def _audio_grid(cursor, t, w_low, w_high): # channel-major stereo rows: t advances per latent frame, w pinned to the grid extremes per stereo channel, h stays 0 g = torch.zeros(t * 2, 3, dtype=torch.float64) g[:, 0] = (cursor + torch.arange(t, dtype=torch.float64)).repeat(2) g[:t, 2] = w_low g[t:, 2] = w_high return g
def _video_grid(vt, frame, cursor): g = torch.empty(vt, frame.shape[0], 3, dtype=torch.float64) g[:, :, 0] = _video_t_grid(vt, cursor)[:, None] g[:, :, 1:] = frame[None] return g.reshape(-1, 3)
class TimeEmbedder(nn.Module): def __init__(self, freq_dim, hidden, out, dtype=None, device=None, operations=None): super().__init__() self.freq_dim = freq_dim self.proj_in = operations.Linear(freq_dim, hidden, bias=True, dtype=dtype, device=device) self.proj_out = operations.Linear(hidden, out, bias=True, dtype=dtype, device=device)
def forward(self, t): # t: [M] in [0, 1]; fp32 throughout, cos before sin half = self.freq_dim // 2 freqs = torch.exp(-math.log(10000.0) * torch.arange(half, dtype=torch.float32, device=t.device) / half) args = t.to(torch.float32)[:, None] * freqs[None] emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) return self.proj_out(nn.functional.silu(self.proj_in(emb)))
def rope_rotation_table(angles, dtype): """[S, rot_dim] pair angles -> [1, S, 1, rot_dim/2, 2, 2] rotation matrices.""" half = angles.shape[-1] // 2 ang = angles[:, :half] # duplicated halves: [:, :half] == [:, half:] c, s = torch.cos(ang), torch.sin(ang) table = torch.stack([c, -s, s, c], dim=-1).reshape(1, angles.shape[0], 1, half, 2, 2) return table.to(dtype)
class Attention(nn.Module): def __init__(self, hidden, heads, head_dim, eps, gate_compress=False, dtype=None, device=None, operations=None): super().__init__() self.comfy_attention = ComfyAttention() self.heads = heads self.head_dim = head_dim inner = heads * head_dim self.qkv_proj = operations.Linear(hidden, inner * 3, bias=False, dtype=dtype, device=device) self.q_norm = operations.RMSNorm(head_dim, eps=eps, dtype=dtype, device=device) self.k_norm = operations.RMSNorm(head_dim, eps=eps, dtype=dtype, device=device) self.out_proj = operations.Linear(inner, hidden, bias=False, dtype=dtype, device=device) self.to_gate_compress = None if gate_compress: # VSA gate, unused by the dense forward; consumed by sparse attention patches self.to_gate_compress = operations.Linear(hidden, inner, bias=False, dtype=dtype, device=device)
def forward(self, x, rope_freqs=None, transformer_options={}): s = x.shape[0] q, k, v = self.qkv_proj(x).split(self.heads * self.head_dim, dim=-1) v = v.view(s, self.heads, self.head_dim) if rope_freqs is not None: # fused per-head RMSNorm + partial split-half rope, in place on the qkv buffer q = q.view(1, s, self.heads, self.head_dim) k = k.view(1, s, self.heads, self.head_dim) qw = comfy.model_management.cast_to(self.q_norm.weight, device=x.device) kw = comfy.model_management.cast_to(self.k_norm.weight, device=x.device) rot = rope_freqs.shape[-3] * 2 if comfy.model_management.in_training: q, k = comfy.quant_ops.ck.rms_rope_split_half( q, k, rope_freqs, qw, kw, epsilon=self.q_norm.eps, rot_dim=rot) else: comfy.quant_ops.ck.rms_rope_split_half_( q, k, rope_freqs, qw, kw, epsilon=self.q_norm.eps, rot_dim=rot) q = q[0] k = k[0] else: q = self.q_norm(q.view(s, self.heads, self.head_dim)) k = self.k_norm(k.view(s, self.heads, self.head_dim))
q = AttentionTensorContainer(q.transpose(0, 1).unsqueeze(0)) k = AttentionTensorContainer(k.transpose(0, 1).unsqueeze(0)) v = AttentionTensorContainer(v.transpose(0, 1).unsqueeze(0)) out = optimized_attention(q, k, v, self.heads, preferred_attention=self.comfy_attention, mask=None, skip_reshape=True, transformer_options=transformer_options) return self.out_proj(out.squeeze(0))
class MLP(nn.Module): def __init__(self, hidden, ffn, dtype=None, device=None, operations=None): super().__init__() self.fc1 = operations.Linear(hidden, ffn * 2, bias=False, dtype=dtype, device=device) self.fc2 = operations.Linear(ffn, hidden, bias=False, dtype=dtype, device=device)
def forward(self, x): return comfy.ops.linear_input_act(self.fc2, self.fc1(x), "swiglu")
class AdalnProj(nn.Module): def __init__(self, t_dim, hidden, expand, modalities, apply_silu=True, dtype=None, device=None, operations=None): super().__init__() self.expand = expand self.modalities = modalities self.hidden = hidden self.apply_silu = apply_silu self.linear = operations.Linear(t_dim, expand * hidden * modalities, bias=True, dtype=dtype, device=device)
def forward(self, t_emb): # [M, t_dim] -> expand tensors of [M*modalities, hidden] x = self.linear(nn.functional.silu(t_emb) if self.apply_silu else t_emb) x = x.view(x.shape[0] * self.modalities, self.expand * self.hidden) return x.chunk(self.expand, dim=-1)
def _mod_row(vecs, row, dtype): # row is a mod-row index, or a per-token LongTensor of mod-row indices return vecs[row].to(dtype)
def _mod_scale_shift(h, shift, scale, segments): # segments: [(start, stop, mod_row)] covering h contiguously. for a, b, row in segments: h[a:b].mul_(1.0 + _mod_row(scale, row, h.dtype)).add_(_mod_row(shift, row, h.dtype)) return h
def _mod_gate(x, gate, other, segments): # other is the fresh attn/mlp output: accumulate the gated residual into the stream in place, one fused kernel per segment for a, b, row in segments: x[a:b].addcmul_(other[a:b], _mod_row(gate, row, x.dtype)) return x
class RefinerBlock(nn.Module): def __init__(self, hidden, heads, head_dim, ffn, eps, qk_eps, dtype=None, device=None, operations=None): super().__init__() self.norm1 = operations.RMSNorm(hidden, eps=eps, dtype=dtype, device=device) self.norm2 = operations.RMSNorm(hidden, eps=eps, dtype=dtype, device=device) self.attn = Attention(hidden, heads, head_dim, qk_eps, dtype=dtype, device=device, operations=operations) self.mlp = MLP(hidden, ffn, dtype=dtype, device=device, operations=operations)
def forward(self, x, transformer_options={}): # attn/mlp outputs are fresh: accumulate residuals in place x = self.attn(self.norm1(x), transformer_options=transformer_options).add_(x) return self.mlp(self.norm2(x)).add_(x)
class TokenRefiner(nn.Module): def __init__(self, num_layers, hidden, heads, head_dim, ffn, eps, qk_eps, final_eps, dtype=None, device=None, operations=None): super().__init__() self.blocks = nn.ModuleList([ RefinerBlock(hidden, heads, head_dim, ffn, eps, qk_eps, dtype=dtype, device=device, operations=operations) for _ in range(num_layers)]) self.final_norm = operations.RMSNorm(hidden, eps=final_eps, dtype=dtype, device=device)
def forward(self, x, transformer_options={}): for block in self.blocks: x = block(x, transformer_options=transformer_options) return self.final_norm(x)
class DiTBlock(nn.Module): def __init__(self, hidden, heads, head_dim, ffn, t_dim, eps, qk_eps, apply_silu=True, adaln_dtype=None, gate_compress=False, dtype=None, device=None, operations=None): super().__init__() self.norm1 = operations.RMSNorm(hidden, eps=eps, dtype=dtype, device=device) self.norm2 = operations.RMSNorm(hidden, eps=eps, dtype=dtype, device=device) self.attn = Attention(hidden, heads, head_dim, qk_eps, gate_compress=gate_compress, dtype=dtype, device=device, operations=operations) self.mlp = MLP(hidden, ffn, dtype=dtype, device=device, operations=operations) self.adaln_proj = AdalnProj(t_dim, hidden, 6, 3, apply_silu=apply_silu, dtype=adaln_dtype if adaln_dtype is not None else dtype, device=device, operations=operations)
def forward(self, x, t_emb, mod_segments, rope_freqs, transformer_options={}, attention=None): attention = self.attn if attention is None else attention shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaln_proj(t_emb) h = _mod_scale_shift(self.norm1(x), shift_msa, scale_msa, mod_segments) x = _mod_gate(x, gate_msa, attention(h, rope_freqs=rope_freqs, transformer_options=transformer_options), mod_segments) h = _mod_scale_shift(self.norm2(x), shift_mlp, scale_mlp, mod_segments) return _mod_gate(x, gate_mlp, self.mlp(h), mod_segments)
class FinalLayer(nn.Module): def __init__(self, hidden, t_dim, video_dim, audio_dim, eps, apply_silu=True, adaln_dtype=None, pdd_steps=1, dtype=None, device=None, operations=None): super().__init__() self.video_dim = video_dim self.norm = operations.RMSNorm(hidden, eps=eps, dtype=dtype, device=device) self.adaln_proj = AdalnProj(t_dim, hidden, 2, 1, apply_silu=apply_silu, dtype=adaln_dtype if adaln_dtype is not None else dtype, device=device, operations=operations) # output heads are the checkpoint's fp32 island; norm/adaln are stored at model dtype. # a PDD checkpoint ships pdd_steps stacked heads per stream (a PDD LoRA grows plain heads to the same layout) self.video_out = operations.Linear(hidden, video_dim * pdd_steps, bias=True, dtype=torch.float32, device=device) self.audio_out = operations.Linear(hidden, audio_dim * pdd_steps, bias=True, dtype=torch.float32, device=device)
def forward(self, x, t_emb, video_seg, audio_seg, sigma, sample_sigmas, shifts): # video_seg / audio_seg: (start, stop, row) of the target streams, where row # is a mod-row index or a per-token blend (see _mod_row) shift, scale = self.adaln_proj(t_emb)
def mod(seg): a, b, row = seg return (self.norm(x[a:b]) * (1.0 + _mod_row(scale, row, scale.dtype)) + _mod_row(shift, row, shift.dtype)).to(torch.float32)
n = self.video_out.weight.shape[0] // self.video_dim if n == 1: return self.video_out(mod(video_seg)), self.audio_out(mod(audio_seg))
# PDD head bank: row block 0 is a full head, later blocks are offsets from it; # a step consumes the dt-weighted mean of the heads it spans. if sample_sigmas is None: raise ValueError("MiniMax H3 PDD heads need the sampler's sigma schedule") i = int((sample_sigmas - sigma).abs().argmin()) sigma_next = sample_sigmas[min(i + 1, sample_sigmas.shape[0] - 1)] start, stop = (round(float(1.0 - time_shift_sigma(s, shifts[0], 1.0)) * n) for s in (sigma, sigma_next)) start = min(start, n - 1) stop = max(stop, start + 1) return (_pdd_head(self.video_out, mod(video_seg), n, start, stop, shifts[0]), _pdd_head(self.audio_out, mod(audio_seg), n, start, stop, shifts[1]))
def _pdd_head(head, h, n, start, stop, flow_shift): grid = torch.linspace(1.0, 0.0, n + 1, dtype=torch.float64) dt = (1.0 - flow_shift * grid / (1.0 + (flow_shift - 1.0) * grid)).diff()[start:stop] w = (dt / dt.sum()).to(h) with comfy.ops.CastBiasWeightContext(head, h, offloadable=True) as (weight, bias): rows = weight.reshape(n, -1, weight.shape[1]) brows = bias.reshape(n, -1) first = max(start, 1) return nn.functional.linear(h, rows[0] + torch.einsum("n,noi->oi", w[first - start:], rows[first:stop]), brows[0] + torch.einsum("n,no->o", w[first - start:], brows[first:stop]))
class PackedLayout: """Static packed-sequence structure for one shape/conditioning signature."""
def __init__(self, text_len, latent_t, latent_h, latent_w, audio_t, keyframes=None, refs=None): frame, w_grid = _frame_grid(latent_h, latent_w) frame_rows = frame.shape[0]
segments = [("text", text_len)] # (kind, n_rows) g = torch.zeros(text_len, 3, dtype=torch.float64) g[:, 0] = torch.arange(text_len, dtype=torch.float64) pos = [g] # per segment: [n, 3] float64 (t, h, w)
img_pos, img_update = [], [] audio_pos, audio_update = [], [] row = text_len
target_audio_w = (float(w_grid[0]), float(w_grid[-1])) # refs pack between text and the targets, so the target timeline starts after their spans cursor = float(text_len) for blk in refs or (): cursor += _ref_t_span(blk)
if keyframes: # fl2va: keyframe cond rows right after text, sharing the target spatial grid; # anchors count from the target timeline origin, FRAME_RESCALE per pixel frame, 1.0 per audio latent frame for kf in keyframes: cond_t = cursor + FRAME_RESCALE * kf["resolved_frame_index"] video_latent = kf.get("latent") if video_latent is not None: vt = video_latent.shape[2] n = vt * frame_rows segments.append(("cond", n)) pos.append(_video_grid(vt, frame, cond_t)) img_pos.append(torch.arange(row, row + n)) img_update.append(torch.zeros(n, dtype=torch.bool)) row += n audio_latent = kf.get("audio_latent") if audio_latent is not None: rt = audio_latent.shape[-1] segments.append(("cond_audio", rt * 2)) pos.append(_audio_grid(cond_t, rt, *target_audio_w)) audio_pos.append(torch.arange(row, row + rt * 2)) audio_update.append(torch.zeros(rt * 2, dtype=torch.bool)) row += rt * 2
if refs: cursor = float(text_len) for blk in refs: kind = blk["kind"] if kind == "image": r_frame, _ = _frame_grid(blk["latent_h"], blk["latent_w"]) n = r_frame.shape[0] g = torch.empty(n, 3, dtype=torch.float64) g[:, 0] = cursor g[:, 1:] = r_frame segments.append(("ref_img", n)) pos.append(g) img_pos.append(torch.arange(row, row + n)) img_update.append(torch.zeros(n, dtype=torch.bool)) row += n cursor += 1.0 elif kind == "audio": rt = blk["ref_audio_t"] if rt > 0: segments.append(("ref_audio", rt * 2)) pos.append(_audio_grid(cursor, rt, *target_audio_w)) audio_pos.append(torch.arange(row, row + rt * 2)) audio_update.append(torch.zeros(rt * 2, dtype=torch.bool)) row += rt * 2 cursor += float(rt) elif kind in ("video", "video_audio"): # the block's audio rows pack immediately before its video # rows, both sharing the cursor origin rt = blk["ref_audio_t"] vt = blk["latent_t"] r_frame, r_w_grid = _frame_grid(blk["latent_h"], blk["latent_w"]) if rt > 0: segments.append(("ref_audio", rt * 2)) pos.append(_audio_grid(cursor, rt, float(r_w_grid[0]), float(r_w_grid[-1]))) audio_pos.append(torch.arange(row, row + rt * 2)) audio_update.append(torch.zeros(rt * 2, dtype=torch.bool)) row += rt * 2 n = vt * r_frame.shape[0] segments.append(("ref_img", n)) pos.append(_video_grid(vt, r_frame, cursor)) img_pos.append(torch.arange(row, row + n)) img_update.append(torch.zeros(n, dtype=torch.bool)) row += n cursor += max(float(rt), sum(_video_t_spans(vt)))
# target audio then target video, always the last two segments segments.append(("audio", audio_t * 2)) pos.append(_audio_grid(cursor, audio_t, *target_audio_w)) audio_pos.append(torch.arange(row, row + audio_t * 2)) audio_update.append(torch.ones(audio_t * 2, dtype=torch.bool)) row += audio_t * 2
n_video = latent_t * frame_rows segments.append(("video", n_video)) pos.append(_video_grid(latent_t, frame, cursor)) img_pos.append(torch.arange(row, row + n_video)) img_update.append(torch.ones(n_video, dtype=torch.bool)) row += n_video
self.seq_len = row self.position_ids = torch.cat(pos) # [S, 3] float64 self.img_pos = torch.cat(img_pos) self.img_update = torch.cat(img_update) self.audio_pos = torch.cat(audio_pos) self.audio_update = torch.cat(audio_update) self.signature = (text_len, latent_t, latent_h, latent_w, audio_t) # contiguous segment table (start, stop, kind) # kinds: text / cond / cond_audio / ref_img / ref_audio / audio / video # the packed sequence is uniform per segment in (modality tag, timestep class), # except the text span (tag runs resolved at forward time from the presentation tags) seg_abs = [] off = 0 for kind, n in segments: seg_abs.append((off, off + n, kind)) off += n self.segments = seg_abs
class MiniMaxH3Model(nn.Module): def __init__(self, hidden_size=5376, num_layers=50, token_refiner_num_layers=2, num_attention_heads=56, attention_head_dim=128, ffn_hidden_size=14336, latents_dim=24, audio_latents_dim=32, patch_size=(1, 2, 2), text_dim=5120, timestep_input_dim=256, time_embed_hidden_size=5376, time_embed_dim=2688, rope_inv_freq_len=16, norm_eps=1e-5, qk_norm_eps=1e-5, final_norm_eps=1e-5, sigma_shift_video=12.0, sigma_shift_audio=3.0, adaln_curve_grid=None, gate_compress=False, pdd_steps=1, image_model=None, dtype=None, device=None, operations=None, **kwargs): super().__init__() self.dtype = dtype self.hidden_size = hidden_size self.patch_size = tuple(patch_size) self.latents_dim = latents_dim self.audio_latents_dim = audio_latents_dim self.sigma_shift_video = sigma_shift_video self.sigma_shift_audio = sigma_shift_audio self.use_adaln_curves = adaln_curve_grid is not None # curve-form checkpoints replace the time embedder and full-width adaln weights with a small shared basis of the time-embedding curve curve = {"apply_silu": not self.use_adaln_curves, "adaln_dtype": torch.float32 if self.use_adaln_curves else dtype} video_patch_dim = latents_dim * self.patch_size[0] * self.patch_size[1] * self.patch_size[2]
self.video_patch_proj = operations.Linear(video_patch_dim, hidden_size, bias=True, dtype=torch.float32, device=device) self.audio_patch_proj = operations.Linear(audio_latents_dim, hidden_size, bias=True, dtype=torch.float32, device=device) self.condition_proj = operations.Linear(text_dim, hidden_size, bias=True, dtype=dtype, device=device) if self.use_adaln_curves: self.register_buffer("adaln_t_table", torch.empty(adaln_curve_grid, time_embed_dim, dtype=torch.float32)) else: self.time_embedder = TimeEmbedder(timestep_input_dim, time_embed_hidden_size, time_embed_dim, dtype=torch.float32, device=device, operations=operations) self.rope = nn.Module() self.rope.register_buffer("inv_freq", torch.empty(rope_inv_freq_len, dtype=torch.float32)) self.token_refiner = TokenRefiner(token_refiner_num_layers, hidden_size, num_attention_heads, attention_head_dim, ffn_hidden_size, norm_eps, qk_norm_eps, final_norm_eps, dtype=dtype, device=device, operations=operations) self.blocks = nn.ModuleList([ DiTBlock(hidden_size, num_attention_heads, attention_head_dim, ffn_hidden_size, time_embed_dim, norm_eps, qk_norm_eps, **curve, gate_compress=gate_compress, dtype=dtype, device=device, operations=operations) for _ in range(num_layers)]) self.final_layer = FinalLayer(hidden_size, time_embed_dim, video_patch_dim, audio_latents_dim, final_norm_eps, **curve, pdd_steps=pdd_steps, dtype=dtype, device=device, operations=operations)
def preprocess_text_embeds(self, text_states): """[B, L, text_dim] Qwen states -> [B, L, hidden] refined text embeds.""" if text_states.shape[-1] == self.hidden_size: return text_states return self.token_refiner(self.condition_proj(text_states[0])).unsqueeze(0)
def rope_freqs(self, position_ids, device): # [S, 3] float64 -> [S, 96] fp32 pos = position_ids.to(torch.float32).to(device) inv = comfy.model_management.cast_to(self.rope.inv_freq, device=device) per_axis = pos.unsqueeze(-1) * inv.view(1, 1, -1) # [S, 3, 16] t_f, h_f, w_f = per_axis.unbind(dim=1) half = torch.cat((t_f, h_f, w_f), dim=-1) # [S, 48] return torch.cat((half, half), dim=-1) # [S, 96]
def _cond_video_rows(self, payload, device): """Concatenated visual condition rows (normalized latents -> patchified), with condition noise augmentation.""" rows = [] aug = payload.get("visual_cond_noise_aug", VISUAL_COND_TIMESTEP) seed = int(payload.get("seed", 0)) # every condition intentionally restarts the same RNG stream for z in payload.get("cond_video_latents", []): r = patchify_video(z.to(torch.float32), self.patch_size) if aug < 1.0: gen = torch.Generator("cpu").manual_seed(seed) noise = torch.randn(r.shape, generator=gen, dtype=torch.float32) r = aug * r + (1.0 - aug) * noise.to(r.device) rows.append(r.to(device)) return torch.cat(rows, dim=0) if rows else None
def _cond_audio_rows(self, payload, device): rows = [] aug = payload.get("audio_cond_noise_aug", AUDIO_COND_TIMESTEP) seed = int(payload.get("seed", 0)) + 1 for z in payload.get("cond_audio_latents", []): r = pack_audio(z.to(torch.float32)) if aug < 1.0: gen = torch.Generator("cpu").manual_seed(seed) noise = torch.randn(r.shape, generator=gen, dtype=torch.float32) r = aug * r + (1.0 - aug) * noise.to(r.device) rows.append(r.to(device)) return torch.cat(rows, dim=0) if rows else None
def _embed_and_pack(self, video_x, audio_x, context, layout, payload, transformer_options): device = video_x.device dtype = context.dtype img_update = layout.img_update.to(device) audio_update = layout.audio_update.to(device) video_rows = patchify_video(video_x.to(torch.float32), self.patch_size) audio_rows = pack_audio(audio_x.to(torch.float32)) cond_video_rows = self._cond_video_rows(payload, device) cond_audio_rows = self._cond_audio_rows(payload, device)
all_video_rows = video_rows if cond_video_rows is not None: all_video_rows = torch.empty(img_update.shape[0], video_rows.shape[1], dtype=torch.float32, device=device) all_video_rows[~img_update] = cond_video_rows all_video_rows[img_update] = video_rows all_audio_rows = audio_rows if cond_audio_rows is not None: all_audio_rows = torch.empty(audio_update.shape[0], audio_rows.shape[1], dtype=torch.float32, device=device) all_audio_rows[~audio_update] = cond_audio_rows all_audio_rows[audio_update] = audio_rows
video_embed = self.video_patch_proj(all_video_rows).to(dtype) audio_embed = self.audio_patch_proj(all_audio_rows).to(dtype) text_states = context[0] if text_states.shape[-1] != self.hidden_size: text_states = self.token_refiner(self.condition_proj(text_states), transformer_options=transformer_options)
# segments are contiguous: assemble by slices, embed rows follow segment order h = torch.empty(layout.seq_len, self.hidden_size, dtype=dtype, device=device) voff = aoff = 0 for a, b, kind in layout.segments: n = b - a if kind == "text": h[a:b] = text_states elif kind in ("cond", "ref_img", "video"): h[a:b] = video_embed[voff:voff + n] voff += n else: # ref_audio / audio h[a:b] = audio_embed[aoff:aoff + n] aoff += n return h
def forward(self, x, timestep, context, transformer_options={}, minimax_payload=None, denoise_mask=None, audio_denoise_mask=None, **kwargs): # the sampler carries the audio as (sigma_v / sigma_a) * x_audio; undo it outside # the wrappers so they and the network see the stream's own latent and velocity scale = float((minimax_payload or {}).get("audio_scale", 1.0)) audio_src = x[1] if scale != 1.0: shift_v = float(transformer_options.get("minimax_h3_sigma_shift_video", self.sigma_shift_video)) shift_a = float(transformer_options.get("minimax_h3_sigma_shift_audio", self.sigma_shift_audio)) sigma_v = (timestep.flatten()[0] / 1000.0).float().clamp(min=1e-6) sigma_a = time_shift_sigma(sigma_v, shift_v, shift_a) carry = (sigma_a / sigma_v).to(audio_src.dtype) x = [x[0], audio_src * carry]
compile_allocations = comfy.model_prefetch.malloc_graph_enabled(x[0].device) if compile_allocations: out = [torch.empty_like(x[0]), torch.empty_like(x[1])] comfy.model_prefetch.malloc_graph_begin(x[0].device) graph_out = comfy.patcher_extension.WrapperExecutor.new_class_executor( self._forward, self, comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL, transformer_options) ).execute(x, timestep, context, transformer_options, minimax_payload=minimax_payload, denoise_mask=denoise_mask, audio_denoise_mask=audio_denoise_mask, **kwargs) if compile_allocations: out[0].copy_(graph_out[0]) out[1].copy_(graph_out[1]) del graph_out comfy.model_prefetch.malloc_graph_end() else: out = graph_out
# Masked rows predict at mask * sigma; scale their velocity to match the outer x0 conversion. if denoise_mask is not None: out[0] = out[0] * denoise_mask if audio_denoise_mask is not None: out[1] = out[1] * audio_denoise_mask
if scale != 1.0: # d/d(sigma_v) of the carried variable out[1] = ((1.0 - scale) * (audio_src * carry) + (1.0 + (scale - 1.0) * sigma_a).to(out[1].dtype) * out[1]) return out
def _forward(self, x, timestep, context, transformer_options={}, minimax_payload=None, denoise_mask=None, audio_denoise_mask=None, **kwargs): video_x, audio_x = x[0], x[1] orig_t, orig_h, orig_w = video_x.shape[2], video_x.shape[3], video_x.shape[4] video_x = comfy.ldm.common_dit.pad_to_patch_size(video_x, self.patch_size) if video_x.shape[0] != 1: raise ValueError("MiniMax H3 supports batch size 1") payload = minimax_payload or {} device = video_x.device dtype = context.dtype # compute dtype
latent_t, lat_h, lat_w = video_x.shape[2], video_x.shape[3], video_x.shape[4] audio_t = audio_x.shape[-1] text_len = context.shape[1] # extra_conds prebuilds the layout once per sampling run layout = payload.get("layout") if layout is None or layout.signature != (text_len, latent_t, lat_h, lat_w, audio_t): layout = PackedLayout(text_len, latent_t, lat_h, lat_w, audio_t, keyframes=payload.get("keyframes"), refs=payload.get("refs"))
transformer_options["minimax_h3_layout"] = layout # segment spans for attention patches
# model_base passes model_sampling.timestep(sigma) = sigma * 1000 shift_v = float(transformer_options.get("minimax_h3_sigma_shift_video", self.sigma_shift_video)) shift_a = float(transformer_options.get("minimax_h3_sigma_shift_audio", self.sigma_shift_audio)) sigma_v = (timestep.flatten()[0] / 1000.0).float().clamp(min=1e-6) t_v = float(1.0 - sigma_v) t_a = float(1.0 - time_shift_sigma(sigma_v, shift_v, shift_a))
# distinct timesteps are known analytically: text/pad follow video, cond rows pin near 1 vis_aug = float(payload.get("visual_cond_noise_aug", VISUAL_COND_TIMESTEP)) aud_aug = float(payload.get("audio_cond_noise_aug", AUDIO_COND_TIMESTEP)) seg_t = {"text": t_v, "video": t_v, "audio": t_a, "cond": max(t_v, vis_aug), "ref_img": max(t_v, vis_aug), "cond_audio": max(t_a, aud_aug), "ref_audio": max(t_a, aud_aug)}
# masked rows run at their own strength: mask value m puts a row at sigma = m * sigma_stream, # so its label is 1 - m * sigma, clamped at the cond timestep for fully preserved rows t_pin_v = max(t_v, VISUAL_COND_TIMESTEP) t_pin_a = max(t_a, AUDIO_COND_TIMESTEP) video_rows_t = None audio_rows_t = None if denoise_mask is not None: m = mask_row_values(denoise_mask[0, 0].to(torch.float32), latent_t, lat_h, lat_w) if m is not None: rows_t = (1.0 - m * sigma_v.to(m.device)).clamp(max=t_pin_v) if rows_t.unique().numel() == 1: seg_t["video"] = float(rows_t[0]) else: video_rows_t = rows_t if audio_denoise_mask is not None: m = audio_denoise_mask[0, 0].to(torch.float32).reshape(-1) if not bool((m >= 1.0 - 1e-3).all()): sigma_a = 1.0 - t_a rows_t = (1.0 - m * sigma_a).clamp(max=t_pin_a) if rows_t.unique().numel() == 1: seg_t["audio"] = float(rows_t[0]) else: audio_rows_t = rows_t
unique_t = sorted({t_v, t_a} | {seg_t[k] for _, _, k in layout.segments} | (set(video_rows_t.unique().tolist()) if video_rows_t is not None else set()) | (set(audio_rows_t.unique().tolist()) if audio_rows_t is not None else set())) t_row = {t: i for i, t in enumerate(unique_t)} seg_tag = {"text": 1, "video": 0, "audio": 2, "cond": 0, "ref_img": 0, "cond_audio": 2, "ref_audio": 2}
def rows_to_mod_index(rows_t, tag): # per-row timestep values -> per-row mod-row indices into the t_emb table levels = rows_t.unique() base = torch.tensor([t_row[v] * 3 + tag for v in levels.tolist()], dtype=torch.long, device=rows_t.device) return base[torch.searchsorted(levels, rows_t)]
text_tags = payload.get("text_token_tags") mod_segments = [] for a, b, kind in layout.segments: row_base = t_row[seg_t[kind]] * 3 if kind == "text" and text_tags is not None: # the presentation text span mixes tags (vision pads carry the video modality) split into tag runs tags = text_tags.view(-1).tolist() run_start = 0 for i in range(1, b - a + 1): if i == b - a or tags[i] != tags[run_start]: mod_segments.append((a + run_start, a + i, row_base + int(tags[run_start]))) run_start = i elif kind == "video" and video_rows_t is not None: mod_segments.append((a, b, rows_to_mod_index(video_rows_t, seg_tag[kind]))) elif kind == "audio" and audio_rows_t is not None: mod_segments.append((a, b, rows_to_mod_index(audio_rows_t, seg_tag[kind]))) else: mod_segments.append((a, b, row_base + seg_tag[kind]))
h = self._embed_and_pack(video_x, audio_x, context, layout, payload, transformer_options)
t_vals = torch.tensor(unique_t, dtype=torch.float32, device=device) if self.use_adaln_curves: # adaln projections consume interpolated coordinates of the time-embedding curve table = comfy.model_management.cast_to(self.adaln_t_table, device=device) pos = t_vals.clamp(0.0, 1.0) * (table.shape[0] - 1) # t in [0,1] -> fractional grid index, out-of-range t clamps to the curve ends i0 = pos.floor().long().clamp(max=table.shape[0] - 2) # lower grid row, max-clamp keeps t=1.0 on the last interval instead of reading past the table t_emb = torch.lerp(table[i0], table[i0 + 1], (pos - i0).unsqueeze(1)) # blend the two rows by the fractional part else: t_emb = self.time_embedder(t_vals).to(dtype)
# rotation table computed once per forward, consumed by the kitchen split-half rope rope_freqs = rope_rotation_table(self.rope_freqs(layout.position_ids, device), dtype)
# blocks patches_replace = transformer_options.get("patches_replace", {}) blocks_replace = patches_replace.get("dit", {}) prefetch_queue = comfy.model_prefetch.make_prefetch_queue(list(self.blocks), device, transformer_options) for i, block in enumerate(self.blocks): comfy.model_prefetch.prefetch_queue_pop(prefetch_queue, device, block, malloc_scope="block") transformer_options["block_index"] = i if ("double_block", i) in blocks_replace: def block_wrap(args): return {"img": block(args["img"], args["t_emb"], args["mod_segments"], args["rope_freqs"], transformer_options=args["transformer_options"], attention=args.get("attention"))} h = blocks_replace[("double_block", i)]( {"img": h, "t_emb": t_emb, "mod_segments": mod_segments, "rope_freqs": rope_freqs, "layout": layout, "transformer_options": transformer_options}, {"original_block": block_wrap})["img"] else: h = block(h, t_emb, mod_segments, rope_freqs, transformer_options=transformer_options) comfy.model_prefetch.prefetch_queue_pop(prefetch_queue, device, None, malloc_scope="block")
# target streams are single contiguous segments (audio then video, last two) va, vb, _ = next(s for s in layout.segments if s[2] == "video") aa, ab, _ = next(s for s in layout.segments if s[2] == "audio") if video_rows_t is not None: video_seg = (va, vb, rows_to_mod_index(video_rows_t, 0) // 3) else: video_seg = (va, vb, t_row[seg_t["video"]]) if audio_rows_t is not None: audio_seg = (aa, ab, rows_to_mod_index(audio_rows_t, 0) // 3) else: audio_seg = (aa, ab, t_row[seg_t["audio"]]) v, a = self.final_layer(h, t_emb, video_seg, audio_seg, sigma_v, transformer_options.get("sample_sigmas"), (shift_v, shift_a))
video_out = unpatchify_video(v, latent_t, lat_h // 2, lat_w // 2, self.latents_dim, self.patch_size) video_out = video_out[:, :, :orig_t, :orig_h, :orig_w] audio_out = unpack_audio(a)
return [-video_out.to(video_x.dtype), -audio_out.to(audio_x.dtype)]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664import jsonimport comfy.memory_managementimport comfy.supported_modelsimport comfy.supported_models_baseimport comfy.utilsimport mathimport loggingimport torch
def count_blocks(state_dict_keys, prefix_string): count = 0 while True: c = False for k in state_dict_keys: if k.startswith(prefix_string.format(count)): c = True break if c == False: break count += 1 return count
def any_suffix_in(keys, prefix, main, suffix_list=[]): for x in suffix_list: if "{}{}{}".format(prefix, main, x) in keys: return True return False
def calculate_transformer_depth(prefix, state_dict_keys, state_dict): context_dim = None use_linear_in_transformer = False
transformer_prefix = prefix + "1.transformer_blocks." transformer_keys = sorted(list(filter(lambda a: a.startswith(transformer_prefix), state_dict_keys))) if len(transformer_keys) > 0: last_transformer_depth = count_blocks(state_dict_keys, transformer_prefix + '{}') context_dim = state_dict['{}0.attn2.to_k.weight'.format(transformer_prefix)].shape[1] use_linear_in_transformer = len(state_dict['{}1.proj_in.weight'.format(prefix)].shape) == 2 time_stack = '{}1.time_stack.0.attn1.to_q.weight'.format(prefix) in state_dict or '{}1.time_mix_blocks.0.attn1.to_q.weight'.format(prefix) in state_dict time_stack_cross = '{}1.time_stack.0.attn2.to_q.weight'.format(prefix) in state_dict or '{}1.time_mix_blocks.0.attn2.to_q.weight'.format(prefix) in state_dict return last_transformer_depth, context_dim, use_linear_in_transformer, time_stack, time_stack_cross return None
def detect_unet_config(state_dict, key_prefix, metadata=None): state_dict_keys = list(state_dict.keys())
if ( '{}cond_layer_logits'.format(key_prefix) in state_dict_keys and '{}latent_conditioners.0.weight'.format(key_prefix) in state_dict_keys and '{}diffusion_transformer.transformer.layers.0.self_attn.to_qkv.weight'.format(key_prefix) in state_dict_keys ): return {"audio_model": "minimax_music3"}
if '{}joint_blocks.0.context_block.attn.qkv.weight'.format(key_prefix) in state_dict_keys: #mmdit model unet_config = {} unet_config["in_channels"] = state_dict['{}x_embedder.proj.weight'.format(key_prefix)].shape[1] patch_size = state_dict['{}x_embedder.proj.weight'.format(key_prefix)].shape[2] unet_config["patch_size"] = patch_size final_layer = '{}final_layer.linear.weight'.format(key_prefix) if final_layer in state_dict: unet_config["out_channels"] = state_dict[final_layer].shape[0] // (patch_size * patch_size)
unet_config["depth"] = state_dict['{}x_embedder.proj.weight'.format(key_prefix)].shape[0] // 64 unet_config["input_size"] = None y_key = '{}y_embedder.mlp.0.weight'.format(key_prefix) if y_key in state_dict_keys: unet_config["adm_in_channels"] = state_dict[y_key].shape[1]
context_key = '{}context_embedder.weight'.format(key_prefix) if context_key in state_dict_keys: in_features = state_dict[context_key].shape[1] out_features = state_dict[context_key].shape[0] unet_config["context_embedder_config"] = {"target": "torch.nn.Linear", "params": {"in_features": in_features, "out_features": out_features}} num_patches_key = '{}pos_embed'.format(key_prefix) if num_patches_key in state_dict_keys: num_patches = state_dict[num_patches_key].shape[1] unet_config["num_patches"] = num_patches unet_config["pos_embed_max_size"] = round(math.sqrt(num_patches))
rms_qk = '{}joint_blocks.0.context_block.attn.ln_q.weight'.format(key_prefix) if rms_qk in state_dict_keys: unet_config["qk_norm"] = "rms"
unet_config["pos_embed_scaling_factor"] = None #unused for inference context_processor = '{}context_processor.layers.0.attn.qkv.weight'.format(key_prefix) if context_processor in state_dict_keys: unet_config["context_processor_layers"] = count_blocks(state_dict_keys, '{}context_processor.layers.'.format(key_prefix) + '{}.') unet_config["x_block_self_attn_layers"] = [] for key in state_dict_keys: if key.startswith('{}joint_blocks.'.format(key_prefix)) and key.endswith('.x_block.attn2.qkv.weight'): layer = key[len('{}joint_blocks.'.format(key_prefix)):-len('.x_block.attn2.qkv.weight')] unet_config["x_block_self_attn_layers"].append(int(layer)) return unet_config
if '{}clf.1.weight'.format(key_prefix) in state_dict_keys: #stable cascade unet_config = {} text_mapper_name = '{}clip_txt_mapper.weight'.format(key_prefix) if text_mapper_name in state_dict_keys: unet_config['stable_cascade_stage'] = 'c' w = state_dict[text_mapper_name] if w.shape[0] == 1536: #stage c lite unet_config['c_cond'] = 1536 unet_config['c_hidden'] = [1536, 1536] unet_config['nhead'] = [24, 24] unet_config['blocks'] = [[4, 12], [12, 4]] elif w.shape[0] == 2048: #stage c full unet_config['c_cond'] = 2048 elif '{}clip_mapper.weight'.format(key_prefix) in state_dict_keys: unet_config['stable_cascade_stage'] = 'b' w = state_dict['{}down_blocks.1.0.channelwise.0.weight'.format(key_prefix)] if w.shape[-1] == 640: unet_config['c_hidden'] = [320, 640, 1280, 1280] unet_config['nhead'] = [-1, -1, 20, 20] unet_config['blocks'] = [[2, 6, 28, 6], [6, 28, 6, 2]] unet_config['block_repeat'] = [[1, 1, 1, 1], [3, 3, 2, 2]] elif w.shape[-1] == 576: #stage b lite unet_config['c_hidden'] = [320, 576, 1152, 1152] unet_config['nhead'] = [-1, 9, 18, 18] unet_config['blocks'] = [[2, 4, 14, 4], [4, 14, 4, 2]] unet_config['block_repeat'] = [[1, 1, 1, 1], [2, 2, 2, 2]] return unet_config
shape_key = '{}img2shape.t_embedder.mlp.0.weight'.format(key_prefix) tex_key = '{}shape2txt.t_embedder.mlp.0.weight'.format(key_prefix) if shape_key in state_dict_keys or tex_key in state_dict_keys: # trellis2 / pixal3d has_shape = shape_key in state_dict_keys has_tex = tex_key in state_dict_keys unet_config = { "image_model": "trellis2", "resolution": 32 if (metadata or {}).get("is_512") else 64, "init_txt_model": has_tex, "txt_only": has_tex and not has_shape, } # Per-submodel projection head (Pixal3D adds `proj_linear`; Trellis2 doesn't). for sub, name, proj_in_channels in (("img2shape", "shape", 2048), ("shape2txt", "texture", 2048), ("structure_model", "structure", 1024)): key = '{}{}.blocks.0.cross_attn.proj_linear.weight'.format(key_prefix, sub) if key in state_dict_keys: unet_config["image_attn_mode_{}".format(name)] = "proj" unet_config["proj_in_channels_{}".format(name)] = proj_in_channels return unet_config
if '{}transformer.rotary_pos_emb.inv_freq'.format(key_prefix) in state_dict_keys: #stable audio dit unet_config = {} unet_config["audio_model"] = "dit1.0" unet_config["global_cond_dim"] = state_dict['{}to_global_embed.0.weight'.format(key_prefix)].shape[1] cond_embed = state_dict['{}to_cond_embed.0.weight'.format(key_prefix)] unet_config["project_cond_tokens"] = cond_embed.shape[0] != cond_embed.shape[1] unet_config["embed_dim"] = state_dict['{}to_timestep_embed.0.weight'.format(key_prefix)].shape[0] mem_tokens = state_dict.get('{}transformer.memory_tokens'.format(key_prefix), None) to_qkv = state_dict.get('{}transformer.layers.0.self_attn.to_qkv.weight'.format(key_prefix), None) differential = False if to_qkv is not None: if to_qkv.shape[0] == to_qkv.shape[1] * 5: differential = True if mem_tokens is not None: unet_config["num_memory_tokens"] = mem_tokens.shape[0] if '{}transformer.layers.0.self_attn.q_norm.weight'.format(key_prefix) in state_dict: unet_config["attn_kwargs"] = {"qk_norm": "ln", "feat_scale": True} rms_norm = state_dict.get('{}transformer.layers.0.self_attn.q_norm.gamma'.format(key_prefix), None) if rms_norm is not None: unet_config["attn_kwargs"] = {"qk_norm": "rms", "differential": differential} unet_config["norm_type"] = "rms_norm" unet_config["num_heads"] = unet_config["embed_dim"] // rms_norm.shape[0]
if '{}timestep_features.weight'.format(key_prefix) in state_dict: unet_config["timestep_features_type"] = "learned" else: unet_config["timestep_features_type"] = "expo"
io_channels = state_dict['{}postprocess_conv.weight'.format(key_prefix)].shape[0] unet_config["io_channels"] = io_channels unet_config["input_concat_dim"] = state_dict['{}transformer.project_in.weight'.format(key_prefix)].shape[1] - io_channels
local_add_cond = state_dict.get('{}transformer.layers.0.to_local_embed.0.weight'.format(key_prefix), None) if local_add_cond is not None: unet_config["local_add_cond_dim"] = local_add_cond.shape[1]
global_cond_embed = state_dict.get('{}transformer.global_cond_embedder.0.weight'.format(key_prefix), None) if global_cond_embed is not None: unet_config["global_cond_shared_embed"] = True unet_config["global_cond_type"] = "adaLN"
unet_config["depth"] = count_blocks(state_dict_keys, '{}transformer.layers.'.format(key_prefix) + '{}.') return unet_config
if '{}double_layers.0.attn.w1q.weight'.format(key_prefix) in state_dict_keys: #aura flow dit unet_config = {} unet_config["max_seq"] = state_dict['{}positional_encoding'.format(key_prefix)].shape[1] unet_config["cond_seq_dim"] = state_dict['{}cond_seq_linear.weight'.format(key_prefix)].shape[1] double_layers = count_blocks(state_dict_keys, '{}double_layers.'.format(key_prefix) + '{}.') single_layers = count_blocks(state_dict_keys, '{}single_layers.'.format(key_prefix) + '{}.') unet_config["n_double_layers"] = double_layers unet_config["n_layers"] = double_layers + single_layers return unet_config
if '{}mlp_t5.0.weight'.format(key_prefix) in state_dict_keys: #Hunyuan DiT unet_config = {} unet_config["image_model"] = "hydit" unet_config["depth"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.') unet_config["hidden_size"] = state_dict['{}x_embedder.proj.weight'.format(key_prefix)].shape[0] if unet_config["hidden_size"] == 1408 and unet_config["depth"] == 40: #DiT-g/2 unet_config["mlp_ratio"] = 4.3637 if state_dict['{}extra_embedder.0.weight'.format(key_prefix)].shape[1] == 3968: unet_config["size_cond"] = True unet_config["use_style_cond"] = True unet_config["image_model"] = "hydit1" return unet_config
if '{}txt_in.individual_token_refiner.blocks.0.norm1.weight'.format(key_prefix) in state_dict_keys: #Hunyuan Video dit_config = {} in_w = state_dict['{}img_in.proj.weight'.format(key_prefix)] out_w = state_dict['{}final_layer.linear.weight'.format(key_prefix)] dit_config["image_model"] = "hunyuan_video" dit_config["in_channels"] = in_w.shape[1] #SkyReels img2video has 32 input channels dit_config["patch_size"] = list(in_w.shape[2:]) dit_config["out_channels"] = out_w.shape[0] // math.prod(dit_config["patch_size"]) if any(s.startswith('{}vector_in.'.format(key_prefix)) for s in state_dict_keys): dit_config["vec_in_dim"] = 768 else: dit_config["vec_in_dim"] = None
if len(dit_config["patch_size"]) == 2: dit_config["axes_dim"] = [64, 64] else: dit_config["axes_dim"] = [16, 56, 56]
if any(s.startswith('{}time_r_in.'.format(key_prefix)) for s in state_dict_keys): dit_config["meanflow"] = True else: dit_config["meanflow"] = False
dit_config["context_in_dim"] = state_dict['{}txt_in.input_embedder.weight'.format(key_prefix)].shape[1] dit_config["hidden_size"] = in_w.shape[0] dit_config["mlp_ratio"] = 4.0 dit_config["num_heads"] = in_w.shape[0] // 128 dit_config["depth"] = count_blocks(state_dict_keys, '{}double_blocks.'.format(key_prefix) + '{}.') dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, '{}single_blocks.'.format(key_prefix) + '{}.') dit_config["theta"] = 256 dit_config["qkv_bias"] = True if '{}byt5_in.fc1.weight'.format(key_prefix) in state_dict: dit_config["byt5"] = True else: dit_config["byt5"] = False
guidance_keys = list(filter(lambda a: a.startswith("{}guidance_in.".format(key_prefix)), state_dict_keys)) dit_config["guidance_embed"] = len(guidance_keys) > 0
# HunyuanVideo 1.5 if '{}cond_type_embedding.weight'.format(key_prefix) in state_dict_keys: dit_config["use_cond_type_embedding"] = True else: dit_config["use_cond_type_embedding"] = False if '{}vision_in.proj.0.weight'.format(key_prefix) in state_dict_keys: dit_config["vision_in_dim"] = state_dict['{}vision_in.proj.0.weight'.format(key_prefix)].shape[0] dit_config["meanflow_sum"] = True else: dit_config["vision_in_dim"] = None dit_config["meanflow_sum"] = False return dit_config
if '{}content_mode_blocks.image.0.attn_out.weight'.format(key_prefix) in state_dict_keys and '{}single_stream_modulations.txt.lin.weight'.format(key_prefix) in state_dict_keys: # FLUX.3 dit_config = {} dit_config["image_model"] = "flux3" dit_config["hidden_size"] = state_dict['{}content_mode_blocks.image.0.attn_out.weight'.format(key_prefix)].shape[0] dit_config["num_heads"] = dit_config["hidden_size"] // 128 dit_config["fused_qkv"] = '{}single_blocks.0.qkv.weight'.format(key_prefix) in state_dict_keys dit_config["flow_map"] = '{}ref_time_in.in_layer.weight'.format(key_prefix) in state_dict_keys dit_config["depth"] = count_blocks(state_dict_keys, '{}txt_mode_blocks.'.format(key_prefix) + '{}.') dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, '{}single_blocks.'.format(key_prefix) + '{}.') return dit_config
if any_suffix_in(state_dict_keys, key_prefix, 'double_blocks.0.img_attn.norm.key_norm.', ["weight", "scale"]) and ('{}img_in.weight'.format(key_prefix) in state_dict_keys or any_suffix_in(state_dict_keys, key_prefix, 'distilled_guidance_layer.norms.0.', ["weight", "scale"])): #Flux, Chroma or Chroma Radiance (has no img_in.weight) dit_config = {} if '{}double_stream_modulation_img.lin.weight'.format(key_prefix) in state_dict_keys: dit_config["image_model"] = "flux2" dit_config["axes_dim"] = [32, 32, 32, 32] dit_config["num_heads"] = 48 dit_config["mlp_ratio"] = 3.0 dit_config["theta"] = 2000 dit_config["out_channels"] = 128 dit_config["global_modulation"] = True dit_config["mlp_silu_act"] = True dit_config["qkv_bias"] = False dit_config["ops_bias"] = False dit_config["default_ref_method"] = "index" dit_config["ref_index_scale"] = 10.0 dit_config["txt_ids_dims"] = [3] patch_size = 1 else: dit_config["image_model"] = "flux" dit_config["axes_dim"] = [16, 56, 56] dit_config["num_heads"] = 24 dit_config["mlp_ratio"] = 4.0 dit_config["theta"] = 10000 dit_config["out_channels"] = 16 dit_config["qkv_bias"] = True dit_config["txt_ids_dims"] = [] patch_size = 2
dit_config["in_channels"] = 16 dit_config["hidden_size"] = 3072 dit_config["context_in_dim"] = 4096
dit_config["patch_size"] = patch_size in_key = "{}img_in.weight".format(key_prefix) if in_key in state_dict_keys: w = state_dict[in_key] dit_config["in_channels"] = w.shape[1] // (patch_size * patch_size) dit_config["hidden_size"] = w.shape[0]
txt_in_key = "{}txt_in.weight".format(key_prefix) if txt_in_key in state_dict_keys: w = state_dict[txt_in_key] dit_config["context_in_dim"] = w.shape[1] dit_config["hidden_size"] = w.shape[0]
vec_in_key = '{}vector_in.in_layer.weight'.format(key_prefix) if vec_in_key in state_dict_keys: dit_config["vec_in_dim"] = state_dict[vec_in_key].shape[1] else: dit_config["vec_in_dim"] = None
dit_config["num_heads"] = dit_config["hidden_size"] // sum(dit_config["axes_dim"])
dit_config["depth"] = count_blocks(state_dict_keys, '{}double_blocks.'.format(key_prefix) + '{}.') dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, '{}single_blocks.'.format(key_prefix) + '{}.')
if any_suffix_in(state_dict_keys, key_prefix, 'distilled_guidance_layer.0.norms.0.', ["weight", "scale"]) or any_suffix_in(state_dict_keys, key_prefix, 'distilled_guidance_layer.norms.0.', ["weight", "scale"]): #Chroma dit_config["image_model"] = "chroma" dit_config["in_channels"] = 64 dit_config["out_channels"] = 64 dit_config["in_dim"] = 64 dit_config["out_dim"] = 3072 dit_config["hidden_dim"] = 5120 dit_config["n_layers"] = 5
if any_suffix_in(state_dict_keys, key_prefix, 'nerf_blocks.0.norm.', ["weight", "scale"]): #Chroma Radiance dit_config["image_model"] = "chroma_radiance" dit_config["in_channels"] = 3 dit_config["out_channels"] = 3 dit_config["patch_size"] = state_dict.get('{}img_in_patch.weight'.format(key_prefix)).size(dim=-1) dit_config["nerf_hidden_size"] = 64 dit_config["nerf_mlp_ratio"] = 4 dit_config["nerf_depth"] = 4 dit_config["nerf_max_freqs"] = 8 dit_config["nerf_tile_size"] = 512 dit_config["nerf_final_head_type"] = "conv" if any_suffix_in(state_dict_keys, key_prefix, 'nerf_final_layer_conv.norm.', ["weight", "scale"]) else "linear" dit_config["nerf_embedder_dtype"] = torch.float32 if "{}__x0__".format(key_prefix) in state_dict_keys: # x0 pred dit_config["use_x0"] = True else: dit_config["use_x0"] = False if "{}__sequential__".format(key_prefix) in state_dict_keys: # sequential txt_ids dit_config["use_sequential_txt_ids"] = True else: dit_config["use_sequential_txt_ids"] = False else: dit_config["guidance_embed"] = "{}guidance_in.in_layer.weight".format(key_prefix) in state_dict_keys dit_config["yak_mlp"] = '{}double_blocks.0.img_mlp.gate_proj.weight'.format(key_prefix) in state_dict_keys dit_config["txt_norm"] = any_suffix_in(state_dict_keys, key_prefix, 'txt_norm.', ["weight", "scale"]) if dit_config["yak_mlp"] and dit_config["txt_norm"]: # Ovis model dit_config["txt_ids_dims"] = [1, 2] if dit_config.get("context_in_dim") == 3584 and dit_config["vec_in_dim"] is None: # LongCat-Image dit_config["txt_ids_dims"] = [1, 2]
return dit_config
if '{}t5_yproj.weight'.format(key_prefix) in state_dict_keys: #Genmo mochi preview dit_config = {} dit_config["image_model"] = "mochi_preview" dit_config["depth"] = 48 dit_config["patch_size"] = 2 dit_config["num_heads"] = 24 dit_config["hidden_size_x"] = 3072 dit_config["hidden_size_y"] = 1536 dit_config["mlp_ratio_x"] = 4.0 dit_config["mlp_ratio_y"] = 4.0 dit_config["learn_sigma"] = False dit_config["in_channels"] = 12 dit_config["qk_norm"] = True dit_config["qkv_bias"] = False dit_config["out_bias"] = True dit_config["attn_drop"] = 0.0 dit_config["patch_embed_bias"] = True dit_config["posenc_preserve_area"] = True dit_config["timestep_mlp_bias"] = True dit_config["attend_to_padding"] = False dit_config["timestep_scale"] = 1000.0 dit_config["use_t5"] = True dit_config["t5_feat_dim"] = 4096 dit_config["t5_token_length"] = 256 dit_config["rope_theta"] = 10000.0 return dit_config
if '{}adaln_single.emb.timestep_embedder.linear_1.bias'.format(key_prefix) in state_dict_keys and '{}pos_embed.proj.bias'.format(key_prefix) in state_dict_keys: # PixArt diffusers return None
if '{}video_patch_proj.weight'.format(key_prefix) in state_dict_keys and '{}audio_patch_proj.weight'.format(key_prefix) in state_dict_keys: # MiniMax H3 dit_config = {} dit_config["image_model"] = "minimax_h3" dit_config["num_layers"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.') dit_config["token_refiner_num_layers"] = count_blocks(state_dict_keys, '{}token_refiner.blocks.'.format(key_prefix) + '{}.') dit_config["hidden_size"] = state_dict['{}video_patch_proj.weight'.format(key_prefix)].shape[0] # a PDD checkpoint stacks pdd_steps output heads per stream (declared in its config metadata) pdd_steps = 1 if metadata is not None and "config" in metadata: pdd_steps = json.loads(metadata["config"]).get("transformer", {}).get("pdd_steps", 1) dit_config["latents_dim"] = state_dict['{}final_layer.video_out.weight'.format(key_prefix)].shape[0] // (4 * pdd_steps) # patch 1x2x2 dit_config["audio_latents_dim"] = state_dict['{}final_layer.audio_out.weight'.format(key_prefix)].shape[0] // pdd_steps dit_config["attention_head_dim"] = state_dict['{}blocks.0.attn.q_norm.weight'.format(key_prefix)].shape[0] qkv = state_dict['{}blocks.0.attn.qkv_proj.weight'.format(key_prefix)] dit_config["num_attention_heads"] = qkv.shape[0] // (3 * dit_config["attention_head_dim"]) dit_config["ffn_hidden_size"] = state_dict['{}blocks.0.mlp.fc1.weight'.format(key_prefix)].shape[0] // 2 dit_config["text_dim"] = state_dict['{}condition_proj.weight'.format(key_prefix)].shape[1] table_key = '{}adaln_t_table'.format(key_prefix) if table_key in state_dict_keys: # adaln shipped over a precomputed curve basis: the adaln linears span a small shared basis of the time-embedding curve (no time embedder) table = state_dict[table_key].shape # [grid, k] dit_config["adaln_curve_grid"] = table[0] dit_config["time_embed_dim"] = table[1] else: te = state_dict['{}time_embedder.proj_in.weight'.format(key_prefix)] dit_config["timestep_input_dim"] = te.shape[1] dit_config["time_embed_hidden_size"] = te.shape[0] dit_config["time_embed_dim"] = state_dict['{}time_embedder.proj_out.weight'.format(key_prefix)].shape[0] dit_config["rope_inv_freq_len"] = state_dict['{}rope.inv_freq'.format(key_prefix)].shape[0] dit_config["gate_compress"] = '{}blocks.0.attn.to_gate_compress.weight'.format(key_prefix) in state_dict_keys # VSA-trained if metadata is not None and "config" in metadata: dit_config.update(json.loads(metadata["config"]).get("transformer", {})) return dit_config
if '{}adaln_single.emb.timestep_embedder.linear_1.bias'.format(key_prefix) in state_dict_keys: #Lightricks ltxv dit_config = {} dit_config["image_model"] = "ltxav" if f'{key_prefix}audio_adaln_single.linear.weight' in state_dict_keys else "ltxv" dit_config["num_layers"] = count_blocks(state_dict_keys, '{}transformer_blocks.'.format(key_prefix) + '{}.') shape = state_dict['{}transformer_blocks.0.attn2.to_k.weight'.format(key_prefix)].shape dit_config["attention_head_dim"] = shape[0] // 32 dit_config["cross_attention_dim"] = shape[1] if metadata is not None and "config" in metadata: dit_config.update(json.loads(metadata["config"]).get("transformer", {})) dit_config["use_keyframes_abs_pos_embedding"] = '{}keyframes_abs_pos_embedding'.format(key_prefix) in state_dict_keys return dit_config
if '{}genre_embedder.weight'.format(key_prefix) in state_dict_keys: #ACE-Step model dit_config = {} dit_config["audio_model"] = "ace" dit_config["attention_head_dim"] = 128 dit_config["in_channels"] = 8 dit_config["inner_dim"] = 2560 dit_config["max_height"] = 16 dit_config["max_position"] = 32768 dit_config["max_width"] = 32768 dit_config["mlp_ratio"] = 2.5 dit_config["num_attention_heads"] = 20 dit_config["num_layers"] = 24 dit_config["out_channels"] = 8 dit_config["patch_size"] = [16, 1] dit_config["rope_theta"] = 1000000.0 dit_config["speaker_embedding_dim"] = 512 dit_config["text_embedding_dim"] = 768
dit_config["ssl_encoder_depths"] = [8, 8] dit_config["ssl_latent_dims"] = [1024, 768] dit_config["ssl_names"] = ["mert", "m-hubert"] dit_config["lyric_encoder_vocab_size"] = 6693 dit_config["lyric_hidden_size"] = 1024 return dit_config
if '{}t_block.1.weight'.format(key_prefix) in state_dict_keys: # PixArt patch_size = 2 dit_config = {} dit_config["num_heads"] = 16 dit_config["patch_size"] = patch_size dit_config["hidden_size"] = 1152 dit_config["in_channels"] = 4 dit_config["depth"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.')
y_key = "{}y_embedder.y_embedding".format(key_prefix) if y_key in state_dict_keys: dit_config["model_max_length"] = state_dict[y_key].shape[0]
pe_key = "{}pos_embed".format(key_prefix) if pe_key in state_dict_keys: dit_config["input_size"] = int(math.sqrt(state_dict[pe_key].shape[1])) * patch_size dit_config["pe_interpolation"] = dit_config["input_size"] // (512//8) # guess
ar_key = "{}ar_embedder.mlp.0.weight".format(key_prefix) if ar_key in state_dict_keys: dit_config["image_model"] = "pixart_alpha" dit_config["micro_condition"] = True else: dit_config["image_model"] = "pixart_sigma" dit_config["micro_condition"] = False return dit_config
if '{}blocks.block0.blocks.0.block.attn.to_q.0.weight'.format(key_prefix) in state_dict_keys: # Cosmos dit_config = {} dit_config["image_model"] = "cosmos" dit_config["max_img_h"] = 240 dit_config["max_img_w"] = 240 dit_config["max_frames"] = 128 concat_padding_mask = True dit_config["in_channels"] = (state_dict['{}x_embedder.proj.1.weight'.format(key_prefix)].shape[1] // 4) - int(concat_padding_mask) dit_config["out_channels"] = 16 dit_config["patch_spatial"] = 2 dit_config["patch_temporal"] = 1 dit_config["model_channels"] = state_dict['{}blocks.block0.blocks.0.block.attn.to_q.0.weight'.format(key_prefix)].shape[0] dit_config["block_config"] = "FA-CA-MLP" dit_config["concat_padding_mask"] = concat_padding_mask dit_config["pos_emb_cls"] = "rope3d" dit_config["pos_emb_learnable"] = False dit_config["pos_emb_interpolation"] = "crop" dit_config["block_x_format"] = "THWBD" dit_config["affline_emb_norm"] = True dit_config["use_adaln_lora"] = True dit_config["adaln_lora_dim"] = 256
if dit_config["model_channels"] == 4096: # 7B dit_config["num_blocks"] = 28 dit_config["num_heads"] = 32 dit_config["extra_per_block_abs_pos_emb"] = True dit_config["rope_h_extrapolation_ratio"] = 1.0 dit_config["rope_w_extrapolation_ratio"] = 1.0 dit_config["rope_t_extrapolation_ratio"] = 2.0 dit_config["extra_per_block_abs_pos_emb_type"] = "learnable" else: # 5120 # 14B dit_config["num_blocks"] = 36 dit_config["num_heads"] = 40 dit_config["extra_per_block_abs_pos_emb"] = True dit_config["rope_h_extrapolation_ratio"] = 2.0 dit_config["rope_w_extrapolation_ratio"] = 2.0 dit_config["rope_t_extrapolation_ratio"] = 2.0 dit_config["extra_h_extrapolation_ratio"] = 2.0 dit_config["extra_w_extrapolation_ratio"] = 2.0 dit_config["extra_t_extrapolation_ratio"] = 2.0 dit_config["extra_per_block_abs_pos_emb_type"] = "learnable" return dit_config
# PiD (Pixel Diffusion Decoder). Must check BEFORE plain PixelDiT_T2I. _lq_w_key = '{}lq_proj.latent_proj.0.weight'.format(key_prefix) if _lq_w_key in state_dict_keys: latent_proj_in_channels = int(state_dict[_lq_w_key].shape[1]) hidden_dim = int(state_dict[_lq_w_key].shape[0]) _gate_prefix = '{}lq_proj.gate_modules.'.format(key_prefix) num_gates = len({k[len(_gate_prefix):].split('.')[0] for k in state_dict_keys if k.startswith(_gate_prefix)}) pid_v1_5 = '{}lq_proj.pit_head.weight'.format(key_prefix) in state_dict_keys dit_config = {"image_model": "pid", "lq_hidden_dim": hidden_dim} if num_gates > 0: dit_config["lq_interval"] = (14 + num_gates - 1) // num_gates if pid_v1_5: pid_v1_5_variants = { 16: { # Flux and QwenImage "lq_latent_channels": 16, "latent_spatial_down_factor": 8, "lq_latent_unpatchify_factor": 1, }, 32: { # Flux2 after 2x latent unpatchify "lq_latent_channels": 128, "latent_spatial_down_factor": 16, "lq_latent_unpatchify_factor": 2, }, } variant = pid_v1_5_variants.get(latent_proj_in_channels) if variant is None: raise ValueError(f"Unsupported PiD v1.5 latent projection with {latent_proj_in_channels} input channels") gate_weight = state_dict['{}lq_proj.gate_modules.0.content_proj.weight'.format(key_prefix)] dit_config.update(variant) dit_config.update({ "lq_conv_padding_mode": "replicate", "lq_gate_per_token": gate_weight.shape[0] == 1, "pit_lq_inject": True, "rope_ref_h": 2048, "rope_ref_w": 2048, }) else: dit_config.update({ "lq_latent_channels": latent_proj_in_channels, "latent_spatial_down_factor": 16 if latent_proj_in_channels >= 64 else 8, }) return dit_config
if '{}core.pixel_embedder.proj.weight'.format(key_prefix) in state_dict_keys: # PixelDiT T2I return {"image_model": "pixeldit_t2i"}
if '{}cap_embedder.1.weight'.format(key_prefix) in state_dict_keys and '{}noise_refiner.0.attention.k_norm.weight'.format(key_prefix) in state_dict_keys: # Lumina 2 dit_config = {} dit_config["image_model"] = "lumina2" dit_config["patch_size"] = 2 dit_config["in_channels"] = 16 w = state_dict['{}cap_embedder.1.weight'.format(key_prefix)] dit_config["dim"] = w.shape[0] dit_config["cap_feat_dim"] = w.shape[1] dit_config["n_layers"] = count_blocks(state_dict_keys, '{}layers.'.format(key_prefix) + '{}.') dit_config["qk_norm"] = True
if dit_config["dim"] == 2304: # Original Lumina 2 dit_config["n_heads"] = 24 dit_config["n_kv_heads"] = 8 dit_config["axes_dims"] = [32, 32, 32] dit_config["axes_lens"] = [300, 512, 512] dit_config["rope_theta"] = 10000.0 dit_config["ffn_dim_multiplier"] = 4.0 ctd_weight = state_dict.get('{}clip_text_pooled_proj.0.weight'.format(key_prefix), None) if ctd_weight is not None: # NewBie dit_config["clip_text_dim"] = ctd_weight.shape[0] # NewBie also sets axes_lens = [1024, 512, 512] but it's not used in ComfyUI elif dit_config["dim"] == 3840: # Z image dit_config["n_heads"] = 30 dit_config["n_kv_heads"] = 30 dit_config["axes_dims"] = [32, 48, 48] dit_config["axes_lens"] = [1536, 512, 512] dit_config["rope_theta"] = 256.0 dit_config["ffn_dim_multiplier"] = (8.0 / 3.0) dit_config["z_image_modulation"] = True dit_config["time_scale"] = 1000.0 try: dit_config["allow_fp16"] = torch.std(state_dict['{}layers.{}.ffn_norm1.weight'.format(key_prefix, dit_config["n_layers"] - 2)], unbiased=False).item() < 0.42 except Exception: pass dec_cond_key = '{}dec_net.cond_embed.weight'.format(key_prefix) if '{}cap_pad_token'.format(key_prefix) in state_dict_keys: dit_config["pad_tokens_multiple"] = 32 # Ming-Image Design has no learned pad tokens; Layer needs a saved marker or repack metadata. ming_metadata = metadata is not None and "config" in metadata and json.loads(metadata["config"]).get("transformer", {}).get("image_model") == "ming_image" if '{}__ming_image__'.format(key_prefix) in state_dict_keys or ming_metadata or ("pad_tokens_multiple" not in dit_config and dec_cond_key not in state_dict_keys): dit_config["image_model"] = "ming_image" if "pad_tokens_multiple" not in dit_config: dit_config["masked_pad_multiple"] = 32 sig_weight = state_dict.get('{}siglip_embedder.0.weight'.format(key_prefix), None) if sig_weight is not None: dit_config["siglip_feat_dim"] = sig_weight.shape[0]
if dec_cond_key in state_dict_keys: # pixel-space variant dit_config["image_model"] = "zimage_pixel" # patch_size and in_channels are derived from x_embedder: # x_embedder: Linear(patch_size * patch_size * in_channels, dim) # The decoder also receives the full flat patch, so decoder_in_channels = x_embedder input dim. x_emb_in = state_dict['{}x_embedder.weight'.format(key_prefix)].shape[1] dec_out = state_dict['{}dec_net.final_layer.linear.weight'.format(key_prefix)].shape[0] # patch_size: infer from decoder final layer output matching x_embedder input # in_channels: infer from dec_net input_embedder (in_features = dec_in_ch + max_freqs^2) embedder_w = state_dict['{}dec_net.input_embedder.embedder.0.weight'.format(key_prefix)] dec_in_ch = dec_out # decoder in == decoder out (same pixel space) dit_config["patch_size"] = round((x_emb_in / 3) ** 0.5) # assume RGB (in_channels=3) dit_config["in_channels"] = 3 dit_config["decoder_in_channels"] = dec_in_ch dit_config["decoder_hidden_size"] = state_dict[dec_cond_key].shape[0] dit_config["decoder_num_res_blocks"] = count_blocks( state_dict_keys, '{}dec_net.res_blocks.'.format(key_prefix) + '{}.' ) dit_config["decoder_max_freqs"] = int((embedder_w.shape[1] - dec_in_ch) ** 0.5) if '{}__x0__'.format(key_prefix) in state_dict_keys: dit_config["use_x0"] = True
return dit_config
if '{}blocks.0.norm1.linear.weight'.format(key_prefix) in state_dict_keys: # CogVideoX dit_config = {} dit_config["image_model"] = "cogvideox"
# Extract config from weight shapes norm1_weight = state_dict['{}blocks.0.norm1.linear.weight'.format(key_prefix)] time_embed_dim = norm1_weight.shape[1] dim = norm1_weight.shape[0] // 6
dit_config["num_attention_heads"] = dim // 64 dit_config["attention_head_dim"] = 64 dit_config["time_embed_dim"] = time_embed_dim dit_config["num_layers"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.')
# Detect in_channels from patch_embed patch_proj_key = '{}patch_embed.proj.weight'.format(key_prefix) if patch_proj_key in state_dict_keys: w = state_dict[patch_proj_key] if w.ndim == 4: # Conv2d: [out, in, kh, kw] — CogVideoX 1.0 dit_config["in_channels"] = w.shape[1] dit_config["patch_size"] = w.shape[2] elif w.ndim == 2: # Linear: [out, in_channels * patch_size * patch_size * patch_size_t] — CogVideoX 1.5 dit_config["patch_size"] = 2 dit_config["patch_size_t"] = 2 dit_config["in_channels"] = w.shape[1] // (2 * 2 * 2) # 256 // 8 = 32
text_proj_key = '{}patch_embed.text_proj.weight'.format(key_prefix) if text_proj_key in state_dict_keys: dit_config["text_embed_dim"] = state_dict[text_proj_key].shape[1]
# Detect OFS embedding ofs_key = '{}ofs_embedding_linear_1.weight'.format(key_prefix) if ofs_key in state_dict_keys: dit_config["ofs_embed_dim"] = state_dict[ofs_key].shape[1]
# Detect positional embedding type pos_key = '{}patch_embed.pos_embedding'.format(key_prefix) if pos_key in state_dict_keys: dit_config["use_learned_positional_embeddings"] = True dit_config["use_rotary_positional_embeddings"] = False else: dit_config["use_learned_positional_embeddings"] = False dit_config["use_rotary_positional_embeddings"] = True
return dit_config
seedvr2_7b_separate_key = "{}blocks.35.mlp.vid.proj_out.weight".format(key_prefix) if seedvr2_7b_separate_key in state_dict_keys and state_dict[seedvr2_7b_separate_key].shape[0] == 3072: # seedvr2 7b dit_config = {} dit_config["image_model"] = "seedvr2" dit_config["vid_dim"] = 3072 dit_config["heads"] = 24 dit_config["num_layers"] = 36 # This checkpoint uses separate vid/txt MMModule keys in every block. dit_config["mm_layers"] = 36 dit_config["norm_eps"] = 1e-5 dit_config["rope_type"] = "rope3d" dit_config["rope_dim"] = 64 dit_config["mlp_type"] = "normal" return dit_config if "{}blocks.35.mlp.all.proj_in_gate.weight".format(key_prefix) in state_dict_keys: # seedvr2 7b dit_config = {} dit_config["image_model"] = "seedvr2" dit_config["vid_dim"] = 3072 dit_config["heads"] = 24 dit_config["num_layers"] = 36 # This checkpoint uses shared all.* MMModule keys after the initial blocks. dit_config["mm_layers"] = 10 dit_config["norm_eps"] = 1e-5 dit_config["rope_type"] = "rope3d" dit_config["rope_dim"] = 64 dit_config["mlp_type"] = "swiglu" return dit_config if "{}blocks.31.mlp.all.proj_in_gate.weight".format(key_prefix) in state_dict_keys: # seedvr2 3b dit_config = {} dit_config["image_model"] = "seedvr2" dit_config["vid_dim"] = 2560 dit_config["heads"] = 20 dit_config["num_layers"] = 32 dit_config["norm_eps"] = 1.0e-05 dit_config["mlp_type"] = "swiglu" dit_config["vid_out_norm"] = True return dit_config
if '{}head.modulation'.format(key_prefix) in state_dict_keys: # Wan 2.1 dit_config = {} dit_config["image_model"] = "wan2.1" dim = state_dict['{}head.modulation'.format(key_prefix)].shape[-1] out_dim = state_dict['{}head.head.weight'.format(key_prefix)].shape[0] // 4 dit_config["dim"] = dim dit_config["out_dim"] = out_dim dit_config["num_heads"] = dim // 128 dit_config["ffn_dim"] = state_dict['{}blocks.0.ffn.0.weight'.format(key_prefix)].shape[0] dit_config["num_layers"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.') dit_config["patch_size"] = (1, 2, 2) dit_config["freq_dim"] = 256 dit_config["window_size"] = (-1, -1) dit_config["qk_norm"] = True dit_config["cross_attn_norm"] = True dit_config["eps"] = 1e-6 dit_config["in_dim"] = state_dict['{}patch_embedding.weight'.format(key_prefix)].shape[1] if '{}vace_patch_embedding.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "vace" dit_config["vace_in_dim"] = state_dict['{}vace_patch_embedding.weight'.format(key_prefix)].shape[1] dit_config["vace_layers"] = count_blocks(state_dict_keys, '{}vace_blocks.'.format(key_prefix) + '{}.') if '{}img_emb.proj.0.bias'.format(key_prefix) in state_dict_keys: # ID-V2V, vace on an i2v model dit_config["vace_image_input"] = True elif '{}control_adapter.conv.weight'.format(key_prefix) in state_dict_keys: if '{}img_emb.proj.0.bias'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "camera" else: dit_config["model_type"] = "camera_2.2" elif '{}casual_audio_encoder.encoder.final_linear.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "s2v" elif '{}audio_proj.audio_proj_glob_1.layer.bias'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "humo" elif '{}face_adapter.fuser_blocks.0.k_norm.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "animate" elif '{}patch_embedding_mask.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "scail2" elif '{}patch_embedding_pose.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "scail" elif '{}patch_embedding_global.weight'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "wandancer" else: if '{}img_emb.proj.0.bias'.format(key_prefix) in state_dict_keys: dit_config["model_type"] = "i2v" else: dit_config["model_type"] = "t2v" flf_weight = state_dict.get('{}img_emb.emb_pos'.format(key_prefix)) if flf_weight is not None: dit_config["flf_pos_embed_token_number"] = flf_weight.shape[1]
ref_conv_weight = state_dict.get('{}ref_conv.weight'.format(key_prefix)) if ref_conv_weight is not None: dit_config["in_dim_ref_conv"] = ref_conv_weight.shape[1]
if metadata is not None and "config" in metadata: dit_config.update(json.loads(metadata["config"]).get("transformer", {}))
return dit_config
if '{}latent_in.weight'.format(key_prefix) in state_dict_keys: # Hunyuan 3D in_shape = state_dict['{}latent_in.weight'.format(key_prefix)].shape dit_config = {} dit_config["image_model"] = "hunyuan3d2" dit_config["in_channels"] = in_shape[1] dit_config["context_in_dim"] = state_dict['{}cond_in.weight'.format(key_prefix)].shape[1] dit_config["hidden_size"] = in_shape[0] dit_config["mlp_ratio"] = 4.0 dit_config["num_heads"] = 16 dit_config["depth"] = count_blocks(state_dict_keys, '{}double_blocks.'.format(key_prefix) + '{}.') dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, '{}single_blocks.'.format(key_prefix) + '{}.') dit_config["qkv_bias"] = True dit_config["guidance_embed"] = "{}guidance_in.in_layer.weight".format(key_prefix) in state_dict_keys return dit_config
if f"{key_prefix}t_embedder.mlp.2.weight" in state_dict_keys and f"{key_prefix}blocks.0.attn1.k_norm.weight" in state_dict_keys: # Hunyuan 3D 2.1 dit_config = {} dit_config["image_model"] = "hunyuan3d2_1" dit_config["in_channels"] = state_dict[f"{key_prefix}x_embedder.weight"].shape[1] dit_config["context_dim"] = 1024 dit_config["hidden_size"] = state_dict[f"{key_prefix}x_embedder.weight"].shape[0] dit_config["mlp_ratio"] = 4.0 dit_config["num_heads"] = 16 dit_config["depth"] = count_blocks(state_dict_keys, f"{key_prefix}blocks.{{}}") dit_config["qkv_bias"] = False dit_config["guidance_cond_proj_dim"] = None#f"{key_prefix}t_embedder.cond_proj.weight" in state_dict_keys return dit_config
if '{}cam_out_layer.weight'.format(key_prefix) in state_dict_keys and '{}repo_layers.0.final_map.weight'.format(key_prefix) in state_dict_keys: # TripoSplat return {"image_model": "triposplat"}
if '{}t_embedder1.mlp.0.weight'.format(key_prefix) in state_dict_keys and '{}x_embedder.proj1.weight'.format(key_prefix) in state_dict_keys: # HiDream-O1 return {"image_model": "hidream_o1"}
vision_key = f"{key_prefix}fm_modules.vision_model_mot_gen.embeddings.patch_embedding.weight" query_key = f"{key_prefix}language_model.model.layers.0.self_attn.q_proj_mot_gen.weight" if ( vision_key in state_dict and query_key in state_dict and state_dict[vision_key].shape[0] == 1024 and state_dict[query_key].shape[0] == 4096 ): # SenseNova U1.5 return {"image_model": "sensenova_u15"}
if '{}caption_projection.0.linear.weight'.format(key_prefix) in state_dict_keys: # HiDream dit_config = {} dit_config["image_model"] = "hidream" dit_config["attention_head_dim"] = 128 dit_config["axes_dims_rope"] = [64, 32, 32] dit_config["caption_channels"] = [4096, 4096] dit_config["max_resolution"] = [128, 128] dit_config["in_channels"] = 16 dit_config["llama_layers"] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31] dit_config["num_attention_heads"] = 20 dit_config["num_routed_experts"] = 4 dit_config["num_activated_experts"] = 2 dit_config["num_layers"] = 16 dit_config["num_single_layers"] = 32 dit_config["out_channels"] = 16 dit_config["patch_size"] = 2 dit_config["text_emb_dim"] = 2048 return dit_config
if '{}blocks.0.mlp.layer1.weight'.format(key_prefix) in state_dict_keys: # Cosmos predict2 dit_config = {} dit_config["image_model"] = "cosmos_predict2" if "{}llm_adapter.blocks.0.cross_attn.q_proj.weight".format(key_prefix) in state_dict_keys: dit_config["image_model"] = "anima" dit_config["max_img_h"] = 240 dit_config["max_img_w"] = 240 dit_config["max_frames"] = 128 concat_padding_mask = True dit_config["in_channels"] = (state_dict['{}x_embedder.proj.1.weight'.format(key_prefix)].shape[1] // 4) - int(concat_padding_mask) dit_config["out_channels"] = 16 dit_config["patch_spatial"] = 2 dit_config["patch_temporal"] = 1 dit_config["model_channels"] = state_dict['{}x_embedder.proj.1.weight'.format(key_prefix)].shape[0] dit_config["concat_padding_mask"] = concat_padding_mask dit_config["crossattn_emb_channels"] = 1024 dit_config["pos_emb_cls"] = "rope3d" dit_config["pos_emb_learnable"] = True dit_config["pos_emb_interpolation"] = "crop" dit_config["min_fps"] = 1 dit_config["max_fps"] = 30
dit_config["use_adaln_lora"] = True dit_config["adaln_lora_dim"] = 256 dit_config["num_blocks"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.') if dit_config["model_channels"] == 2048: dit_config["num_heads"] = 16 elif dit_config["model_channels"] == 5120: dit_config["num_heads"] = 40
if dit_config["in_channels"] == 16: dit_config["extra_per_block_abs_pos_emb"] = False dit_config["rope_h_extrapolation_ratio"] = 4.0 dit_config["rope_w_extrapolation_ratio"] = 4.0 dit_config["rope_t_extrapolation_ratio"] = 1.0 elif dit_config["in_channels"] == 17: # img to video if dit_config["model_channels"] == 2048: dit_config["extra_per_block_abs_pos_emb"] = False dit_config["rope_h_extrapolation_ratio"] = 3.0 dit_config["rope_w_extrapolation_ratio"] = 3.0 dit_config["rope_t_extrapolation_ratio"] = 1.0 elif dit_config["model_channels"] == 5120: dit_config["rope_h_extrapolation_ratio"] = 2.0 dit_config["rope_w_extrapolation_ratio"] = 2.0 dit_config["rope_t_extrapolation_ratio"] = 0.8333333333333334
dit_config["extra_h_extrapolation_ratio"] = 1.0 dit_config["extra_w_extrapolation_ratio"] = 1.0 dit_config["extra_t_extrapolation_ratio"] = 1.0 dit_config["rope_enable_fps_modulation"] = False
return dit_config
if '{}double_stream_layers.0.img_instruct_attn.processor.img_to_q.weight'.format(key_prefix) in state_dict_keys: # Boogu-Image (OmniGen2 derivative + dual-stream stage) dit_config = {} dit_config["image_model"] = "boogu" dit_config["hidden_size"] = state_dict['{}x_embedder.weight'.format(key_prefix)].shape[0] dit_config["num_layers"] = count_blocks(state_dict_keys, '{}single_stream_layers.'.format(key_prefix) + '{}.') dit_config["num_double_stream_layers"] = count_blocks(state_dict_keys, '{}double_stream_layers.'.format(key_prefix) + '{}.') dit_config["num_refiner_layers"] = count_blocks(state_dict_keys, '{}noise_refiner.'.format(key_prefix) + '{}.') dit_config["instruction_feat_dim"] = state_dict['{}time_caption_embed.caption_embedder.0.weight'.format(key_prefix)].shape[0] return dit_config
if '{}time_caption_embed.timestep_embedder.linear_1.bias'.format(key_prefix) in state_dict_keys: # Omnigen2 dit_config = {} dit_config["image_model"] = "omnigen2" dit_config["axes_dim_rope"] = [40, 40, 40] dit_config["axes_lens"] = [1024, 1664, 1664] dit_config["ffn_dim_multiplier"] = None dit_config["hidden_size"] = 2520 dit_config["in_channels"] = 16 dit_config["multiple_of"] = 256 dit_config["norm_eps"] = 1e-05 dit_config["num_attention_heads"] = 21 dit_config["num_kv_heads"] = 7 dit_config["num_layers"] = 32 dit_config["num_refiner_layers"] = 2 dit_config["out_channels"] = None dit_config["patch_size"] = 2 dit_config["text_feat_dim"] = 2048 dit_config["timestep_scale"] = 1000.0 return dit_config
if '{}transformer_blocks.0.attn.norm_added_q.weight'.format(key_prefix) in state_dict_keys \ and '{}transformer_blocks.0.img_mlp.w1.weight'.format(key_prefix) in state_dict_keys: # Lens img_in_w = state_dict['{}img_in.weight'.format(key_prefix)] proj_out_w = state_dict['{}proj_out.weight'.format(key_prefix)] multi_layer = '{}txt_norm.0.weight'.format(key_prefix) in state_dict_keys if multi_layer: enc_hidden_dim = state_dict['{}txt_norm.0.weight'.format(key_prefix)].shape[0] # Indices are TE-side; the DiT just consumes L layers in order. selected_layer_index = tuple(range(count_blocks(state_dict_keys, '{}txt_norm.'.format(key_prefix) + '{}.'))) else: enc_hidden_dim = state_dict['{}txt_norm.weight'.format(key_prefix)].shape[0] selected_layer_index = (0,)
return { "image_model": "lens", "in_channels": img_in_w.shape[1], "out_channels": proj_out_w.shape[0] // 4, # patch_size ** 2 (=2² default) "num_layers": count_blocks(state_dict_keys, '{}transformer_blocks.'.format(key_prefix) + '{}.'), "num_attention_heads": img_in_w.shape[0] // 64, # // attention_head_dim default "enc_hidden_dim": enc_hidden_dim, "multi_layer_encoder_feature": multi_layer, "selected_layer_index": selected_layer_index, }
if '{}txt_norm.weight'.format(key_prefix) in state_dict_keys and '{}proj_out.weight'.format(key_prefix) in state_dict_keys and state_dict['{}txt_norm.weight'.format(key_prefix)].shape[0] == 2560 and state_dict['{}proj_out.weight'.format(key_prefix)].shape[0] == 128: # Mage-Flow (Qwen Image txt_norm/proj_out are 3584/64) dit_config = {} dit_config["image_model"] = "mage_flow" dit_config["in_channels"] = 128 dit_config["num_layers"] = count_blocks(state_dict_keys, '{}transformer_blocks.'.format(key_prefix) + '{}.') return dit_config
qwen_image21_keys = ['txt_in.text_norm.weight', 'modulation.1.weight', 'transformer_blocks.0.attn.norm_q.weight', 'img_in.weight', 'proj_out.weight'] if all('{}{}'.format(key_prefix, k) in state_dict_keys for k in qwen_image21_keys) and any('{}transformer_blocks.0.img_mlp.{}.weight'.format(key_prefix, k) in state_dict_keys for k in ('gate_up', 'proj')): # Qwen Image 2.1 dit_config = {} dit_config["image_model"] = "qwen_image21" head_dim = state_dict['{}transformer_blocks.0.attn.norm_q.weight'.format(key_prefix)].shape[0] inner_dim = state_dict['{}img_in.weight'.format(key_prefix)].shape[0] dit_config["in_channels"] = state_dict['{}img_in.weight'.format(key_prefix)].shape[1] dit_config["out_channels"] = state_dict['{}proj_out.weight'.format(key_prefix)].shape[0] dit_config["num_layers"] = count_blocks(state_dict_keys, '{}transformer_blocks.'.format(key_prefix) + '{}.') dit_config["attention_head_dim"] = head_dim dit_config["num_attention_heads"] = inner_dim // head_dim dit_config["context_in_dim"] = state_dict['{}txt_in.text_norm.weight'.format(key_prefix)].shape[0] # gate and up projections fuse into one GEMM when their rows can be concatenated: plain weights or per-row scales; a comfy-saved file is already fused gate_up = state_dict.get('{}transformer_blocks.0.img_mlp.gate_up.weight'.format(key_prefix), None) if gate_up is not None: dit_config["mlp_ratio"] = gate_up.shape[0] // 2 // inner_dim else: dit_config["mlp_ratio"] = state_dict['{}transformer_blocks.0.img_mlp.proj.weight'.format(key_prefix)].shape[0] // inner_dim dit_config["fused_mlp"] = gate_up is not None return dit_config
if '{}txt_norm.weight'.format(key_prefix) in state_dict_keys: # Qwen Image dit_config = {} dit_config["image_model"] = "qwen_image" dit_config["in_channels"] = state_dict['{}img_in.weight'.format(key_prefix)].shape[1] dit_config["num_layers"] = count_blocks(state_dict_keys, '{}transformer_blocks.'.format(key_prefix) + '{}.') if "{}__index_timestep_zero__".format(key_prefix) in state_dict_keys: # 2511 dit_config["default_ref_method"] = "index_timestep_zero" if "{}time_text_embed.addition_t_embedding.weight".format(key_prefix) in state_dict_keys: # Layered dit_config["use_additional_t_cond"] = True dit_config["default_ref_method"] = "negative_index" return dit_config
if '{}embed_image_indicator.weight'.format(key_prefix) in state_dict_keys: # Ideogram 4 dit_config = {} dit_config["image_model"] = "ideogram4" dit_config["in_channels"] = state_dict['{}input_proj.weight'.format(key_prefix)].shape[1] dit_config["num_layers"] = count_blocks(state_dict_keys, '{}layers.'.format(key_prefix) + '{}.') return dit_config
if '{}shared_block_modulation.weight'.format(key_prefix) in state_dict_keys and '{}layers.0.proj.ffn_up_gate.weight'.format(key_prefix) in state_dict_keys: # MOSS-Image dit_config = {} dit_config["image_model"] = "moss_image" dit_config["dim"] = state_dict['{}shared_block_modulation.weight'.format(key_prefix)].shape[0] // 6 dit_config["ffn_dim"] = state_dict['{}layers.0.proj.ffn_up_gate.weight'.format(key_prefix)].shape[0] // 2 dit_config["num_heads"] = dit_config["dim"] // 128 dit_config["num_layers"] = count_blocks(state_dict_keys, '{}layers.'.format(key_prefix) + '{}.') dit_config["fused_qkv"] = '{}layers.0.proj.qkv.weight'.format(key_prefix) in state_dict_keys return dit_config
if '{}txtfusion.projector.weight'.format(key_prefix) in state_dict_keys: # Krea 2 (K2) dit_config = {} dit_config["image_model"] = "krea2" head_dim = 128 first_w = state_dict['{}first.weight'.format(key_prefix)] # (features, channels*patch^2) dit_config["features"] = first_w.shape[0] dit_config["channels"] = first_w.shape[1] // (2 * 2) # patch=2 dit_config["patch"] = 2 dit_config["layers"] = count_blocks(state_dict_keys, '{}blocks.'.format(key_prefix) + '{}.') dit_config["heads"] = state_dict['{}blocks.0.attn.wq.weight'.format(key_prefix)].shape[0] // head_dim dit_config["kvheads"] = state_dict['{}blocks.0.attn.wk.weight'.format(key_prefix)].shape[0] // head_dim dit_config["txtlayers"] = state_dict['{}txtfusion.projector.weight'.format(key_prefix)].shape[1] dit_config["txtdim"] = state_dict['{}txtfusion.layerwise_blocks.0.prenorm.scale'.format(key_prefix)].shape[0] return dit_config
if '{}visual_transformer_blocks.0.cross_attention.key_norm.weight'.format(key_prefix) in state_dict_keys: # Kandinsky 5 dit_config = {} model_dim = state_dict['{}visual_embeddings.in_layer.bias'.format(key_prefix)].shape[0] dit_config["model_dim"] = model_dim if model_dim in [4096, 2560]: # pro video and lite image dit_config["axes_dims"] = (32, 48, 48) if model_dim == 2560: # lite image dit_config["rope_scale_factor"] = (1.0, 1.0, 1.0) elif model_dim == 1792: # lite video dit_config["axes_dims"] = (16, 24, 24) dit_config["time_dim"] = state_dict['{}time_embeddings.in_layer.bias'.format(key_prefix)].shape[0] dit_config["image_model"] = "kandinsky5" dit_config["ff_dim"] = state_dict['{}visual_transformer_blocks.0.feed_forward.in_layer.weight'.format(key_prefix)].shape[0] dit_config["visual_embed_dim"] = state_dict['{}visual_embeddings.in_layer.weight'.format(key_prefix)].shape[1] dit_config["num_text_blocks"] = count_blocks(state_dict_keys, '{}text_transformer_blocks.'.format(key_prefix) + '{}.') dit_config["num_visual_blocks"] = count_blocks(state_dict_keys, '{}visual_transformer_blocks.'.format(key_prefix) + '{}.') return dit_config
if '{}encoder.lyric_encoder.layers.0.input_layernorm.weight'.format(key_prefix) in state_dict_keys: dit_config = {} dit_config["audio_model"] = "ace1.5" head_dim = 128 dit_config["hidden_size"] = state_dict['{}decoder.layers.0.self_attn_norm.weight'.format(key_prefix)].shape[0] dit_config["intermediate_size"] = state_dict['{}decoder.layers.0.mlp.gate_proj.weight'.format(key_prefix)].shape[0] dit_config["num_heads"] = state_dict['{}decoder.layers.0.self_attn.q_proj.weight'.format(key_prefix)].shape[0] // head_dim
dit_config["encoder_hidden_size"] = state_dict['{}encoder.lyric_encoder.layers.0.input_layernorm.weight'.format(key_prefix)].shape[0] dit_config["encoder_num_heads"] = state_dict['{}encoder.lyric_encoder.layers.0.self_attn.q_proj.weight'.format(key_prefix)].shape[0] // head_dim dit_config["encoder_intermediate_size"] = state_dict['{}encoder.lyric_encoder.layers.0.mlp.gate_proj.weight'.format(key_prefix)].shape[0] dit_config["num_dit_layers"] = count_blocks(state_dict_keys, '{}decoder.layers.'.format(key_prefix) + '{}.') return dit_config
if '{}encoder.pan_blocks.1.cv4.conv.weight'.format(key_prefix) in state_dict_keys: # RT-DETR_v4 dit_config = {} dit_config["image_model"] = "RT_DETR_v4" dit_config["enc_h"] = state_dict['{}encoder.pan_blocks.1.cv4.conv.weight'.format(key_prefix)].shape[0] return dit_config
# Depth Anything 3 (repackaged to ComfyUI's native Dinov2Model layout via scripts/convert_da3.py) if '{}backbone.embeddings.patch_embeddings.projection.weight'.format(key_prefix) in state_dict_keys: dit_config = {} dit_config["image_model"] = "DepthAnything3"
patch_w = state_dict['{}backbone.embeddings.patch_embeddings.projection.weight'.format(key_prefix)] embed_dim = patch_w.shape[0] depth = count_blocks(state_dict_keys, '{}backbone.encoder.layer.'.format(key_prefix) + '{}.')
# Backbone preset is determined by embed_dim (matches vits/vitb/vitl/vitg). backbone_name = {384: "vits", 768: "vitb", 1024: "vitl", 1536: "vitg"}.get(embed_dim) if backbone_name is None: return None dit_config["backbone_name"] = backbone_name
# Detect DA3 extensions on top of vanilla DINOv2. has_camera_token = '{}backbone.embeddings.camera_token'.format(key_prefix) in state_dict_keys # qk-norm shows up as `attention.q_norm.weight` on enabled blocks. qknorm_indices = [ i for i in range(depth) if '{}backbone.encoder.layer.{}.attention.q_norm.weight'.format(key_prefix, i) in state_dict_keys ] qknorm_start = qknorm_indices[0] if qknorm_indices else -1
# The DA3 main-series configs always set alt_start == qknorm_start == rope_start. # cat_token=True is implied by the presence of camera_token. if has_camera_token: dit_config["alt_start"] = qknorm_start dit_config["rope_start"] = qknorm_start dit_config["qknorm_start"] = qknorm_start dit_config["cat_token"] = True else: dit_config["alt_start"] = -1 dit_config["rope_start"] = -1 dit_config["qknorm_start"] = -1 dit_config["cat_token"] = False
# Detect head type and config. has_aux = '{}head.scratch.refinenet1_aux.out_conv.weight'.format(key_prefix) in state_dict_keys dit_config["head_dim_in"] = state_dict['{}head.projects.0.weight'.format(key_prefix)].shape[1] dit_config["head_features"] = state_dict['{}head.scratch.refinenet1.out_conv.weight'.format(key_prefix)].shape[0] dit_config["head_out_channels"] = [ state_dict['{}head.projects.{}.weight'.format(key_prefix, i)].shape[0] for i in range(4) ] if has_aux: # DualDPT: dim_in = 2 * embed_dim (because cat_token doubles token width). dit_config["head_type"] = "dualdpt" dit_config["head_output_dim"] = 2 dit_config["head_use_sky_head"] = False else: dit_config["head_type"] = "dpt" dit_config["head_output_dim"] = state_dict[ '{}head.scratch.output_conv2.2.weight'.format(key_prefix) ].shape[0] dit_config["head_use_sky_head"] = ( '{}head.scratch.sky_output_conv2.0.weight'.format(key_prefix) in state_dict_keys )
# out_layers: hard-coded per upstream YAML config (depth-aware default). if depth >= 24: # vitl: depths used vary between DA3-Large (DualDPT) and Mono/Metric (DPT). if has_aux: dit_config["out_layers"] = [11, 15, 19, 23] else: dit_config["out_layers"] = [4, 11, 17, 23] else: # vits/vitb: 12 blocks dit_config["out_layers"] = [5, 7, 9, 11]
# Camera encoder/decoder presence (multi-view + pose path). has_cam_enc = '{}cam_enc.token_norm.weight'.format(key_prefix) in state_dict_keys has_cam_dec = '{}cam_dec.fc_t.weight'.format(key_prefix) in state_dict_keys dit_config["has_cam_enc"] = has_cam_enc dit_config["has_cam_dec"] = has_cam_dec if has_cam_enc: cam_enc_w = state_dict.get( '{}cam_enc.pose_branch.fc2.weight'.format(key_prefix) ) if cam_enc_w is not None: dit_config["cam_dim_out"] = cam_enc_w.shape[0] if has_cam_dec: cam_dec_w = state_dict.get( '{}cam_dec.fc_t.weight'.format(key_prefix) ) if cam_dec_w is not None: dit_config["cam_dec_dim_in"] = cam_dec_w.shape[1] return dit_config
if '{}layers.0.mlp.linear_fc2.weight'.format(key_prefix) in state_dict_keys: # Ernie Image dit_config = {} dit_config["image_model"] = "ernie" return dit_config
if 'detector.backbone.vision_backbone.trunk.blocks.0.attn.qkv.weight' in state_dict_keys: # SAM3 / SAM3.1 if 'detector.transformer.decoder.query_embed.weight' in state_dict_keys: dit_config = {} dit_config["image_model"] = "SAM3" if 'detector.backbone.vision_backbone.propagation_convs.0.conv_1x1.weight' in state_dict_keys: dit_config["image_model"] = "SAM31" return dit_config
if ( '{}double_blocks.0.attn.img_attn_qkv.weight'.format(key_prefix) in state_dict_keys and '{}double_blocks.0.attn.img_attn_q_norm.weight'.format(key_prefix) in state_dict_keys and '{}condition_embedder.time_embedder.linear_1.weight'.format(key_prefix) in state_dict_keys and '{}img_in.weight'.format(key_prefix) in state_dict_keys and len(state_dict['{}img_in.weight'.format(key_prefix)].shape) == 5 ): img_in = state_dict['{}img_in.weight'.format(key_prefix)] head_dim = state_dict['{}double_blocks.0.attn.img_attn_q_norm.weight'.format(key_prefix)].shape[0] return { "image_model": "joyimage", "in_channels": img_in.shape[1], "hidden_size": img_in.shape[0], "patch_size": list(img_in.shape[2:]), "num_layers": count_blocks(state_dict_keys, '{}double_blocks.'.format(key_prefix) + '{}.'), "num_attention_heads": img_in.shape[0] // head_dim, "text_dim": 4096, }
if all(key_prefix + key in state_dict for key in ( "vae2llm.weight", "llm2vae.weight", "latent_pos_embed.pe", "model.layers.0.self_attn.qkv_proj.weight", "time_embedder.mlp.0.weight", )): return {"audio_model": "yue2"}
if '{}input_blocks.0.0.weight'.format(key_prefix) not in state_dict_keys: return None
unet_config = { "use_checkpoint": False, "image_size": 32, "use_spatial_transformer": True, "legacy": False }
y_input = '{}label_emb.0.0.weight'.format(key_prefix) if y_input in state_dict_keys: unet_config["num_classes"] = "sequential" unet_config["adm_in_channels"] = state_dict[y_input].shape[1] else: unet_config["adm_in_channels"] = None
model_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[0] in_channels = state_dict['{}input_blocks.0.0.weight'.format(key_prefix)].shape[1]
out_key = '{}out.2.weight'.format(key_prefix) if out_key in state_dict: out_channels = state_dict[out_key].shape[0] else: out_channels = 4
num_res_blocks = [] channel_mult = [] transformer_depth = [] transformer_depth_output = [] context_dim = None use_linear_in_transformer = False
video_model = False video_model_cross = False
current_res = 1 count = 0
last_res_blocks = 0 last_channel_mult = 0
input_block_count = count_blocks(state_dict_keys, '{}input_blocks'.format(key_prefix) + '.{}.') for count in range(input_block_count): prefix = '{}input_blocks.{}.'.format(key_prefix, count) prefix_output = '{}output_blocks.{}.'.format(key_prefix, input_block_count - count - 1)
block_keys = sorted(list(filter(lambda a: a.startswith(prefix), state_dict_keys))) if len(block_keys) == 0: break
block_keys_output = sorted(list(filter(lambda a: a.startswith(prefix_output), state_dict_keys)))
if "{}0.op.weight".format(prefix) in block_keys: #new layer num_res_blocks.append(last_res_blocks) channel_mult.append(last_channel_mult)
current_res *= 2 last_res_blocks = 0 last_channel_mult = 0 out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict) if out is not None: transformer_depth_output.append(out[0]) else: transformer_depth_output.append(0) else: res_block_prefix = "{}0.in_layers.0.weight".format(prefix) if res_block_prefix in block_keys: last_res_blocks += 1 last_channel_mult = state_dict["{}0.out_layers.3.weight".format(prefix)].shape[0] // model_channels
out = calculate_transformer_depth(prefix, state_dict_keys, state_dict) if out is not None: transformer_depth.append(out[0]) if context_dim is None: context_dim = out[1] use_linear_in_transformer = out[2] video_model = out[3] video_model_cross = out[4] else: transformer_depth.append(0)
res_block_prefix = "{}0.in_layers.0.weight".format(prefix_output) if res_block_prefix in block_keys_output: out = calculate_transformer_depth(prefix_output, state_dict_keys, state_dict) if out is not None: transformer_depth_output.append(out[0]) else: transformer_depth_output.append(0)
num_res_blocks.append(last_res_blocks) channel_mult.append(last_channel_mult) if "{}middle_block.1.proj_in.weight".format(key_prefix) in state_dict_keys: transformer_depth_middle = count_blocks(state_dict_keys, '{}middle_block.1.transformer_blocks.'.format(key_prefix) + '{}') elif "{}middle_block.0.in_layers.0.weight".format(key_prefix) in state_dict_keys: transformer_depth_middle = -1 else: transformer_depth_middle = -2
unet_config["in_channels"] = in_channels unet_config["out_channels"] = out_channels unet_config["model_channels"] = model_channels unet_config["num_res_blocks"] = num_res_blocks unet_config["transformer_depth"] = transformer_depth unet_config["transformer_depth_output"] = transformer_depth_output unet_config["channel_mult"] = channel_mult unet_config["transformer_depth_middle"] = transformer_depth_middle unet_config['use_linear_in_transformer'] = use_linear_in_transformer unet_config["context_dim"] = context_dim
if video_model: unet_config["extra_ff_mix_layer"] = True unet_config["use_spatial_context"] = True unet_config["merge_strategy"] = "learned_with_images" unet_config["merge_factor"] = 0.0 unet_config["video_kernel_size"] = [3, 1, 1] unet_config["use_temporal_resblock"] = True unet_config["use_temporal_attention"] = True unet_config["disable_temporal_crossattention"] = not video_model_cross else: unet_config["use_temporal_resblock"] = False unet_config["use_temporal_attention"] = False
heatmap_key = '{}heatmap_head.conv_layers.0.weight'.format(key_prefix) if heatmap_key in state_dict_keys: unet_config["heatmap_head"] = True
return unet_config
def model_config_from_unet_config(unet_config, state_dict=None, unet_key_prefix=""): for model_config in comfy.supported_models.models: if model_config.matches(unet_config, state_dict, unet_key_prefix=unet_key_prefix): return model_config(unet_config)
logging.error("no match {}".format(unet_config)) return None
def model_config_from_unet(state_dict, unet_key_prefix, use_base_if_no_match=False, metadata=None): unet_config = detect_unet_config(state_dict, unet_key_prefix, metadata=metadata) if unet_config is None: return None model_config = model_config_from_unet_config(unet_config, state_dict, unet_key_prefix) if model_config is None and use_base_if_no_match: model_config = comfy.supported_models_base.BASE(unet_config)
# Detect per-layer quantization (mixed precision) quant_config = comfy.utils.detect_layer_quantization(state_dict, unet_key_prefix) if quant_config: model_config.quant_config = quant_config logging.info("Detected mixed precision quantization")
return model_config
def unet_prefix_from_state_dict(state_dict): # SAM3: detector.* and tracker.* at top level, no common prefix if any(k.startswith("detector.") for k in state_dict) and any(k.startswith("tracker.") for k in state_dict): return ""
# SenseNova checkpoints store the diffusion and language backbones at top level. if ( "fm_modules.vision_model_mot_gen.embeddings.patch_embedding.weight" in state_dict and "language_model.model.layers.0.self_attn.q_proj_mot_gen.weight" in state_dict ): return ""
candidates = ["model.diffusion_model.", #ldm/sgm models "model.model.", #audio models "net.", #cosmos ] counts = {k: 0 for k in candidates} for k in state_dict: for c in candidates: if k.startswith(c): counts[c] += 1 break
top = max(counts, key=counts.get) if counts[top] > 5: return top else: return "model." #aura flow and others
def convert_config(unet_config): new_config = unet_config.copy() num_res_blocks = new_config.get("num_res_blocks", None) channel_mult = new_config.get("channel_mult", None)
if isinstance(num_res_blocks, int): num_res_blocks = len(channel_mult) * [num_res_blocks]
if "attention_resolutions" in new_config: attention_resolutions = new_config.pop("attention_resolutions") transformer_depth = new_config.get("transformer_depth", None) transformer_depth_middle = new_config.get("transformer_depth_middle", None)
if isinstance(transformer_depth, int): transformer_depth = len(channel_mult) * [transformer_depth] if transformer_depth_middle is None: transformer_depth_middle = transformer_depth[-1] t_in = [] t_out = [] s = 1 for i in range(len(num_res_blocks)): res = num_res_blocks[i] d = 0 if s in attention_resolutions: d = transformer_depth[i]
t_in += [d] * res t_out += [d] * (res + 1) s *= 2 transformer_depth = t_in new_config["transformer_depth"] = t_in new_config["transformer_depth_output"] = t_out new_config["transformer_depth_middle"] = transformer_depth_middle
new_config["num_res_blocks"] = num_res_blocks return new_config
def unet_config_from_diffusers_unet(state_dict, dtype=None): if "conv_in.weight" not in state_dict: return None
match = {} transformer_depth = []
attn_res = 1 down_blocks = count_blocks(state_dict, "down_blocks.{}") for i in range(down_blocks): attn_blocks = count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}') res_blocks = count_blocks(state_dict, "down_blocks.{}.resnets.".format(i) + '{}') for ab in range(attn_blocks): transformer_count = count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}') transformer_depth.append(transformer_count) if transformer_count > 0: match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
attn_res *= 2 if attn_blocks == 0: for i in range(res_blocks): transformer_depth.append(0)
match["transformer_depth"] = transformer_depth
match["model_channels"] = state_dict["conv_in.weight"].shape[0] match["in_channels"] = state_dict["conv_in.weight"].shape[1] match["adm_in_channels"] = None if "class_embedding.linear_1.weight" in state_dict: match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1] elif "add_embedding.linear_1.weight" in state_dict: match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SDXL_refiner = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2560, 'dtype': dtype, 'in_channels': 4, 'model_channels': 384, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [0, 0, 4, 4, 4, 4, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 4, 'use_linear_in_transformer': True, 'context_dim': 1280, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD21 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD21_uncliph = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2048, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD21_unclipl = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 1536, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD15 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 1, 1, 1], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 0, 0, 0, 0], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 0, 'use_linear_in_transformer': True, 'num_head_channels': 64, 'context_dim': 1, 'transformer_depth_output': [0, 0, 0, 0, 0, 0, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SDXL_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SDXL_diffusers_ip2p = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 8, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 10, 10], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 10, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 0, 2, 2, 2, 10, 10, 10], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SSD_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 2, 2, 4, 4], 'transformer_depth_output': [0, 0, 0, 1, 1, 2, 10, 4, 4], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'use_temporal_attention': False, 'use_temporal_resblock': False}
Segmind_Vega = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2], 'transformer_depth': [0, 0, 1, 1, 2, 2], 'transformer_depth_output': [0, 0, 0, 1, 1, 1, 2, 2, 2], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -1, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'use_temporal_attention': False, 'use_temporal_resblock': False}
KOALA_700M = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [1, 1, 1], 'transformer_depth': [0, 2, 5], 'transformer_depth_output': [0, 0, 2, 2, 5, 5], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -2, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'use_temporal_attention': False, 'use_temporal_resblock': False}
KOALA_1B = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'num_classes': 'sequential', 'adm_in_channels': 2816, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [1, 1, 1], 'transformer_depth': [0, 2, 6], 'transformer_depth_output': [0, 0, 2, 2, 6, 6], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': 6, 'use_linear_in_transformer': True, 'context_dim': 2048, 'num_head_channels': 64, 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD09_XS = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [1, 1, 1], 'transformer_depth': [1, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -2, 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1], 'use_temporal_attention': False, 'use_temporal_resblock': False, 'disable_self_attentions': [True, False, False]}
SD_XS = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [1, 1, 1], 'transformer_depth': [0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -2, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 1, 1, 1, 1], 'use_temporal_attention': False, 'use_temporal_resblock': False}
SD15_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None, 'dtype': dtype, 'in_channels': 9, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
LotusD = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': 4, 'dtype': dtype, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0], 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, 'num_head_channels': 64, 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 'use_temporal_attention': False, 'use_temporal_resblock': False}
supported_models = [LotusD, SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B, Segmind_Vega, KOALA_700M, KOALA_1B, SD09_XS, SD_XS, SDXL_diffusers_ip2p, SD15_diffusers_inpaint]
for unet_config in supported_models: matches = True for k in match: if match[k] != unet_config[k]: matches = False break if matches: return convert_config(unet_config) return None
def model_config_from_diffusers_unet(state_dict): unet_config = unet_config_from_diffusers_unet(state_dict) if unet_config is not None: return model_config_from_unet_config(unet_config) return None
def convert_diffusers_mmdit(state_dict, output_prefix=""): out_sd = {}
if 'joint_transformer_blocks.0.attn.add_k_proj.weight' in state_dict: #AuraFlow num_joint = count_blocks(state_dict, 'joint_transformer_blocks.{}.') num_single = count_blocks(state_dict, 'single_transformer_blocks.{}.') sd_map = comfy.utils.auraflow_to_diffusers({"n_double_layers": num_joint, "n_layers": num_joint + num_single}, output_prefix=output_prefix) elif 'adaln_single.emb.timestep_embedder.linear_1.bias' in state_dict and 'pos_embed.proj.bias' in state_dict: # PixArt num_blocks = count_blocks(state_dict, 'transformer_blocks.{}.') sd_map = comfy.utils.pixart_to_diffusers({"depth": num_blocks}, output_prefix=output_prefix) elif 'noise_refiner.0.attention.norm_k.weight' in state_dict: n_layers = count_blocks(state_dict, 'layers.{}.') dim = state_dict['noise_refiner.0.attention.to_k.weight'].shape[0] sd_map = comfy.utils.z_image_to_diffusers({"n_layers": n_layers, "dim": dim}, output_prefix=output_prefix) for k in state_dict: # For zeta chroma if k not in sd_map: sd_map[k] = k elif 'x_embedder.weight' in state_dict: #Flux depth = count_blocks(state_dict, 'transformer_blocks.{}.') depth_single_blocks = count_blocks(state_dict, 'single_transformer_blocks.{}.') hidden_size = state_dict["x_embedder.bias"].shape[0] sd_map = comfy.utils.flux_to_diffusers({"depth": depth, "depth_single_blocks": depth_single_blocks, "hidden_size": hidden_size}, output_prefix=output_prefix) elif 'transformer_blocks.0.attn.add_q_proj.weight' in state_dict and 'pos_embed.proj.weight' in state_dict: #SD3 num_blocks = count_blocks(state_dict, 'transformer_blocks.{}.') depth = state_dict["pos_embed.proj.weight"].shape[0] // 64 sd_map = comfy.utils.mmdit_to_diffusers({"depth": depth, "num_blocks": num_blocks}, output_prefix=output_prefix) else: return None
for k in sd_map: weight = state_dict.get(k, None) if weight is not None: t = sd_map[k]
if not isinstance(t, str): if len(t) > 2: fun = t[2] else: fun = lambda a: a offset = t[1] if offset is not None: old_weight = out_sd.get(t[0], None) if old_weight is None: old_weight = torch.empty_like(weight) if old_weight.shape[offset[0]] < offset[1] + offset[2]: exp = list(weight.shape) exp[offset[0]] = offset[1] + offset[2] new = torch.empty(exp, device=weight.device, dtype=weight.dtype) new[:old_weight.shape[0]] = old_weight old_weight = new
if old_weight is out_sd.get(t[0], None) and comfy.memory_management.aimdo_enabled: old_weight = old_weight.clone()
w = old_weight.narrow(offset[0], offset[1], offset[2]) else: if comfy.memory_management.aimdo_enabled: weight = weight.clone() old_weight = weight w = weight w[:] = fun(weight) t = t[0] out_sd[t] = old_weight else: out_sd[t] = weight state_dict.pop(k)
return out_sd123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441"""INT8 + ConvRot quantizer for comfy-kitchen — auto layer detection (no per-model recipe).
Quantizes the per-token block linears (attention + FFN), passes everything else through.Recipe: fp32 upcast, block-Hadamard rotation at the per-layer best power-of-4 groupsize,per-channel absmax scale, embedded `<layer>.comfy_quant` config.
python quant_int8_auto.py SRC [DST.safetensors] [--dry-run] [options]
SRC: .safetensors (lazy) or torch pickle .pth/.pt/.ckpt (safe weights_only load, held in RAM).DST optional: defaults to SRC with bf16/fp16/fp32 -> int8_convrot (or _int8_convrot appended).Auto-detect can't see token count M (small-M/windowed/audio layers get quantized anyway — sizewin, maybe not speed) or loader quirks (manual_cast/key-remap loaders -> loads but outputs garbage).So run --dry-run on an unfamiliar arch and use --min-gemm / --exclude as needed."""# ruff: noqa: T201 (print() is this CLI's output)import argparseimport jsonimport osimport reimport timeimport collectionsimport torchfrom safetensors import safe_openfrom safetensors.torch import save_filetry: from comfy_kitchen.tensor.int8 import _build_hadamard, _rotate_weightexcept ImportError: from comfy_kitchen.tensor.int8_utils import _build_hadamard, _rotate_weight
VALID_GS = (256, 64, 16) # convrot Hadamard sizes; power-of-4, prefer largestCLIP_GRID = torch.linspace(0.55, 1.0, 80)FP8 = (getattr(torch, "float8_e4m3fn", None), getattr(torch, "float8_e5m2", None))
def best_gs(k): return next((g for g in VALID_GS if k % g == 0), None)
# Token-embedding lookup tables -> per-row int8 (+rotation). Match real token tables# (embed_tokens / embed_tokens_per_layer / wte / ...), not an `*.embedding_projection`.EMBED_SEG = re.compile(r"^(embed_tokens(_per_layer)?|token_embedding|word_embeddings|tok_embeddings|wte|shared)$")
def is_token_embedding(key, shape): if len(shape) != 2: return False n, k = shape if n < 4096 or n <= k: # vocab-sized table (rows >> cols) return False return any(EMBED_SEG.match(s) for s in key.split("."))
# safe_open-compatible reader for torch pickle checkpoints (weights_only=True -> safe load, no code# execution; whole file into RAM since pickle has no lazy access)._DTYPE_CODE = {torch.float16: "F16", torch.bfloat16: "BF16", torch.float32: "F32", torch.float64: "F64", torch.int8: "I8", torch.uint8: "U8", getattr(torch, "float8_e4m3fn", None): "F8_E4M3", getattr(torch, "float8_e5m2", None): "F8_E5M2"}
class _TorchSlice: # mimics safetensors get_slice() def __init__(self, t): self._t = t def get_shape(self): return list(self._t.shape) def get_dtype(self): return _DTYPE_CODE.get(self._t.dtype, str(self._t.dtype))
class _TorchReader: def __init__(self, path): obj = torch.load(path, map_location="cpu", weights_only=True) sd = self._find_state_dict(obj) if sd is None: raise ValueError(f"no tensor state-dict found in {path}") self._sd = sd @staticmethod def _find_state_dict(obj): if isinstance(obj, dict): tensors = {k: v for k, v in obj.items() if isinstance(v, torch.Tensor)} if tensors: return tensors # this level holds the weights for key in ("state_dict", "model_state_dict", "model", "module", "net", "ema", "params"): if isinstance(obj.get(key), dict): found = _TorchReader._find_state_dict(obj[key]) if found: return found return None def __enter__(self): return self def __exit__(self, *a): return False def metadata(self): return {} def keys(self): return list(self._sd.keys()) def get_slice(self, k): return _TorchSlice(self._sd[k]) def get_tensor(self, k): return self._sd[k]
def open_model(path): """safe_open for .safetensors; safe (weights_only) torch.load for .pth/.pt/.ckpt/.bin.""" if path.lower().endswith(".safetensors"): return safe_open(path, framework="pt", device="cpu") return _TorchReader(path)
# Detection = quantize every eligible 2-D block linear, minus a name denylist. No projection-name# allowlist (fragile: every arch invents new names like to_qkv/add_q_proj/single_blocks.linear1).# adaLN MODULATION *is* quantized (it's a big M=batch GEMM that quantizes cleanly ~0.9%, and on# Qwen/Flux it's 18-33% of the model — no reason to leave it bf16). We only exclude what's genuinely# not a per-token GEMM worth quantizing: scale_shift buffers, rope/pos_embed, input embedders,# gate/router logits, M=1 timestep MLPs, output head/final. 1-D norms are dropped by not-2d already.# Careful bits: `embedder` (not `embed`) keeps `*_embeddings_connector` in; bare `gate` stays# (SwiGLU) — only gate_logits/router drop; `timestep`/`time` catch the M=1 embed but not the modulator.EXCLUDE_SEG = re.compile( r"scale_shift|rope|rotary|rel_pos|pos_?embed|embedder|" r"gate_logits|router|routing|logit|temperature|" r"(?:^|_)time|temb|t_emb|guidance|register|refiner_blocks|adapter|" r"(?:^|_)(?:final|head|proj_out|out_layer)(?:_|$)")# `refiner_blocks` = short-M text side-path (Krea txtfusion.refiner_blocks); main-stream refiners are# `*_refiner` (Boogu/Z-Image), kept. `adapter` = conditioning injection modules (Wan-Animate# face_adapter, ip/control adapters): tiny, identity/quality-critical, quantize worst -> leave bf16.
def classify(key, shape): """Quantize every eligible 2-D block linear except the name denylist. Returns (bool, reason).""" if len(shape) != 2: return (False, "not-2d") n, k = shape if n < 8: return (False, "small-N") gs = best_gs(k) if gs is None: return (False, "ineligible-K") segs = key.split(".") # in a block = an integer segment with named structure after it (blocks.5.attn.q). A trailing # integer is a Sequential index on a top-level MLP (tmlp.0, img_emb.proj.1) -> not a block. if not any(segs[i].isdigit() for i in range(len(segs) - 1)): return (False, "not-in-indexed-block") if any(EXCLUDE_SEG.search(s) for s in segs): return (False, "denylist(scale_shift/embed/gate/time/head/refiner_blocks/adapter)") return (True, f"gs{gs}")
# ---------------------------------------------------------------------------# Quantization (fp32 upcast + block-Hadamard rotation + MSE-optimal per-channel clip)# ---------------------------------------------------------------------------@torch.no_grad()def quantize_convrot(w, gs, mseclip=True, device="cuda"): wf = w.to(device, torch.float32) h = _build_hadamard(gs, device=wf.device, dtype=torch.float32) wr = _rotate_weight(wf, h, gs) absmax = wr.abs().amax(dim=1, keepdim=True).clamp(min=1e-30) if not mseclip: scale = (absmax / 127.0).clamp(min=1e-30) q = (wr / scale).round().clamp(-127, 127) return q.to(torch.int8), scale.to(torch.float32) best_mse = torch.full_like(absmax, float("inf")) best_scale = absmax / 127.0 best_q = None for a in CLIP_GRID.tolist(): scale = (absmax * a / 127.0).clamp(min=1e-30) q = (wr / scale).round().clamp(-127, 127) mse = ((q * scale - wr) ** 2).mean(dim=1, keepdim=True) better = mse < best_mse best_mse = torch.where(better, mse, best_mse) best_scale = torch.where(better, scale, best_scale) best_q = q.clone() if best_q is None else torch.where(better.expand_as(q), q, best_q) return best_q.to(torch.int8), best_scale.to(torch.float32)
@torch.no_grad()def recon_metrics(qd, scale, w_ref, gs, device="cuda"): """Reconstruct (dequant + un-rotate) and return (cosine, relative_error_%).""" deq = qd.to(device).float() * scale.to(device) h = _build_hadamard(gs, device=device, dtype=torch.float32) deq = _rotate_weight(deq, h, gs) wf = w_ref.to(device).float() cos = torch.nn.functional.cosine_similarity(deq.flatten(), wf.flatten(), dim=0).item() relerr = ((deq - wf).norm() / wf.norm().clamp(min=1e-30)).item() * 100.0 return cos, relerr
def cq_tensor(gs): cfg = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": gs} return torch.tensor(list(json.dumps(cfg).encode("utf-8")), dtype=torch.uint8)
@torch.no_grad()def quantize_w4a8(w, bits=4, group_size=None, device="cuda"): """W4A8: ConvRot-rotated int4 weight with a Lloyd-Max codebook + fp8 group scales, or with bits=6 W6A8: uniform int6, no codebook, ~3x lower weight error for 1.5x the bytes. Activations quantize to int8 at runtime. Needs K divisible by 256 and N>=64. Returns (out-tensor dict, comfy_quant cfg, relerr%).""" from comfy_kitchen.tensor import AsymW4A8Int8Layout, QuantizedTensor group_size = group_size or (32 if bits == 6 else 16) wf = w.to(device, torch.bfloat16) q, p = AsymW4A8Int8Layout.quantize( wf, group_size=group_size, convrot_groupsize=256, scale_dtype=torch.float8_e4m3fn, codebook=True, stochastic_rounding=0, bits=bits) deq = QuantizedTensor(q, "AsymW4A8Int8Layout", p).dequantize() tensors = {"weight": q.cpu(), "weight_s_rel": p.scale.cpu(), "weight_s_channel": p.s_channel.cpu()} if p.codebook is not None: tensors["weight_codebook"] = p.codebook.cpu() cfg = {"format": "w6a8_int8" if bits == 6 else "asym_w4a8_int8", "group_size": group_size, "convrot": True, "convrot_groupsize": 256} relerr = ((deq.float() - wf.float()).norm() / wf.float().norm().clamp(min=1e-30)).item() * 100.0 return tensors, cfg, relerr
@torch.no_grad()def quantize_embedding(w, gs, device="cuda", chunk=32768): """Rotated per-row int8 for token-embedding tables. Rotation Gaussianizes each row, tightening its absmax (~half the error for free). The runtime un-rotates after the lookup, since a lookup has no GEMM to fold the inverse into. gs=None -> plain absmax per-row int8 (no rotation). Chunked over rows so a ~1B-element vocab table never lands fully on the GPU.""" h = _build_hadamard(gs, device=device, dtype=torch.float32) if gs else None qs, ss = [], [] for i in range(0, w.shape[0], chunk): wf = w[i:i + chunk].to(device, torch.float32) wr = _rotate_weight(wf, h, gs) if h is not None else wf scale = (wr.abs().amax(dim=1, keepdim=True) / 127.0).clamp(min=1e-30) q = (wr / scale).round().clamp(-127, 127) qs.append(q.to(torch.int8).cpu()) ss.append(scale.to(torch.float32).cpu()) del wf, wr, q, scale torch.cuda.empty_cache() return torch.cat(qs), torch.cat(ss)
# ---------------------------------------------------------------------------def main(): ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("dst", nargs="?", help="output .safetensors; if omitted, derived from SRC by " "replacing bf16/fp16/fp32 with int8_convrot (or appending _int8_convrot)") ap.add_argument("--dry-run", action="store_true", help="report the plan, write nothing") fmt = ap.add_mutually_exclusive_group() fmt.add_argument("--w4a8", action="store_true", help="quantize eligible block linears as W4A8 (int4 weight + codebook " "+ fp8 scales, int8 activations) instead of int8. Layers with K not divisible by " "256 or N<64 fall back to int8; embeddings stay int8.") fmt.add_argument("--w6a8", action="store_true", help="like --w4a8 but uniform 6-bit weights: ~3x lower weight error than " "W4A8 at 0.78 vs 0.56 bytes/weight, same speed") ap.add_argument("--group-size", type=int, default=None, help="columns per fp8 group scale for --w4a8/--w6a8 (default 16 for W4A8, 32 for W6A8)") ap.add_argument("--exclude", default=None, help="regex; matching layers are FORCED to passthrough") ap.add_argument("--include", default=None, help="regex; matching eligible layers are FORCED to quantize") ap.add_argument("--min-gemm", type=int, default=256, help="skip a layer if min(N,K) < this (default 256: a GEMM whose small side is " "under ~256 never beats bf16 at any M, so int8 is pure overhead). --min-gemm 0 disables.") ap.add_argument("--quant-embeddings", action=argparse.BooleanOptionalAction, default=True, help="quantize token-embedding tables (embed_tokens, embed_tokens_per_layer, ...) " "per-ROW int8 (+rotation); ON by default (often the biggest size win). " "--no-quant-embeddings keeps them bf16.") ap.add_argument("--mseclip", action="store_true", help="MSE-optimal clip instead of absmax for the CONVROT linears only (embeddings always absmax) (~2-3%% lower weight error, but a proxy — validate output before trusting it)") ap.add_argument("--downcast-fp32", action="store_true", help="downcast stray fp32 passthrough linears to compute dtype") ap.add_argument("--warn-thresh", type=float, default=None, help="warn on any quantized layer whose relerr%% exceeds this (default 2.0 for int8, " "4.0 for W6A8, 10.0 for W4A8: their normal weight error is ~2.4%% / ~7%%)") ap.add_argument("--verify-report", default=None, help="write the full per-layer (relerr, cos, gs) table to this path") args = ap.parse_args() bits = 6 if args.w6a8 else 4 args.w4a8 = args.w4a8 or args.w6a8 # one grouped-int path below, parametrized by bits if args.warn_thresh is None: args.warn_thresh = {4: 10.0, 6: 4.0}[bits] if args.w4a8 else 2.0 if not args.dst and not args.dry_run: # derive dst from src: swap dtype token for int8_convrot (else append), always .safetensors base = os.path.splitext(os.path.basename(args.src))[0] tag = f"w{bits}a8_convrot" if args.w4a8 else "int8_convrot" new = re.sub(r"(?i)(bf16|fp16|fp32)", tag, base) if new == base: new = base + "_" + tag args.dst = os.path.join(os.path.dirname(args.src), new + ".safetensors") print(f"auto dst -> {args.dst}") exc = re.compile(args.exclude) if args.exclude else None inc = re.compile(args.include) if args.include else None
with open_model(args.src) as st: # .safetensors (lazy) or .pth/.pt/.ckpt (safe load) src_meta = st.metadata() or {} keys = list(st.keys()) scaled = {k[:-len(".weight_scale")] for k in keys if k.endswith(".weight_scale")} # fp8 sources # compute/passthrough dtype = dominant non-fp8 float weight dtype dtc = collections.Counter(st.get_slice(k).get_dtype() for k in keys if k.endswith(".weight")) target = torch.float16 if dtc.get("F16", 0) >= dtc.get("BF16", 0) and dtc.get("F16", 0) else torch.bfloat16
# ---- plan ---- plan = [] # (base, shape, gs) block linears -> int8+convrot eplan = [] # (base, shape) token embeddings -> per-row int8 skip = collections.Counter() for key in keys: if not key.endswith(".weight"): continue base = key[:-len(".weight")] shape = tuple(st.get_slice(key).get_shape()) if is_token_embedding(base, shape): if args.quant_embeddings and not (exc and exc.search(base)): eplan.append((base, shape)) else: skip["embedding(--no-quant-embeddings/excluded)"] += 1 continue q, reason = classify(base, shape) if exc and exc.search(base): q, reason = False, "excluded(flag)" if inc and inc.search(base) and len(shape) == 2 and best_gs(shape[1]) and shape[0] >= 8: q, reason = True, f"gs{best_gs(shape[1])}(incl-flag)" if q and args.min_gemm and min(shape) < args.min_gemm: q, reason = False, f"below-min-gemm({min(shape)})" if q: plan.append((base, shape, best_gs(shape[1]))) else: skip[reason] += 1
# ---- report ---- by_pat = collections.defaultdict(lambda: [0, None, None]) qparams = 0 for base, shape, gs in plan: pat = re.sub(r"\d+", "N", base) by_pat[pat][0] += 1 by_pat[pat][1] = shape by_pat[pat][2] = gs qparams += shape[0] * shape[1] print(f"SRC {args.src}") print(f"compute/passthrough dtype: {target}") fmt_label = (f"W{bits}A8+convrot (int8 fallback for K%256!=0 or N<64)" if args.w4a8 else f"int8+convrot, {'MSE-clip' if args.mseclip else 'absmax'}") print(f"\nQUANTIZE {len(plan)} layers ({fmt_label}):") for pat in sorted(by_pat): c, shape, gs = by_pat[pat] print(f" x{c:<4d} gs{gs:<3d} {str(shape):16s} {pat}") gsdist = collections.Counter(gs for _, _, gs in plan) print(f" groupsizes: {dict(gsdist)} quantized params: {qparams/1e9:.2f}B (~{qparams/1e9:.1f} GB int8)") if eplan: ep = sum(s[0] * s[1] for _, s in eplan) print(f"\nEMBEDDINGS {len(eplan)} table(s) per-row int8 (+rotation):") for b, s in eplan: print(f" {str(s):20s} {b}") print(f" embedding params: {ep/1e9:.2f}B (~{ep/1e9:.1f} GB int8, saves ~{ep/1e9:.1f} GB vs bf16)") print(f"\nLEAVE AS-IS ({sum(skip.values())} weights):") for reason, c in skip.most_common(): print(f" x{c:<4d} {reason}") if args.dry_run: print("\n[dry-run] nothing written.") return
# ---- execute ---- quant_set = {b for b, _, _ in plan} embed_set = {b for b, _ in eplan} out = {} nq = 0 t0 = time.time() errs = [] # (relerr%, cos, gs, base) per quantized layer for key in keys: if key.endswith(".weight_scale"): continue # fp8 source scale: consumed by dequant t = st.get_tensor(key) if not key.endswith(".weight"): out[key] = t continue base = key[:-len(".weight")] # materialize source weight (dequant fp8 rowwise if needed) if t.dtype in FP8 and base in scaled: sc = st.get_tensor(base + ".weight_scale").float() w = t.float() * sc.view(-1, 1) elif t.dtype in FP8: w = t.float() else: w = t if base in embed_set: egs = best_gs(w.shape[1]) # rotate if the row dim allows it qd, scale = quantize_embedding(w, egs) # relerr, chunked with f64 accumulation (a single fp32 .norm() over a ~1B-element # vocab table accumulates enough error to misreport by >0.1pp) h_e = _build_hadamard(egs, device="cuda", dtype=torch.float32) if egs else None se = sw = 0.0 for i in range(0, w.shape[0], 32768): wf = w[i:i + 32768].to("cuda", torch.float32) dq = qd[i:i + 32768].to("cuda").float() * scale[i:i + 32768].to("cuda") if h_e is not None: dq = _rotate_weight(dq, h_e, egs) # un-rotate to compare against source se += ((dq - wf) ** 2).sum().double().item() sw += (wf ** 2).sum().double().item() del wf, dq torch.cuda.empty_cache() relerr = (se / sw) ** 0.5 * 100.0 rot = f"rotated gs{egs} + " if egs else "" print(f" embedding {base} {tuple(w.shape)} {rot}per-row int8 relerr={relerr:.3f}%", flush=True) ecfg = {"format": "int8_tensorwise"} if egs is not None: ecfg["convrot"] = True ecfg["convrot_groupsize"] = egs out[key] = qd out[f"{base}.weight_scale"] = scale out[f"{base}.comfy_quant"] = torch.tensor(list(json.dumps(ecfg).encode("utf-8")), dtype=torch.uint8) torch.cuda.empty_cache() continue if base in quant_set and args.w4a8 and best_gs(w.shape[1]) == 256 and w.shape[0] >= 64: tensors, cfg, relerr = quantize_w4a8(w, bits, args.group_size) if relerr > args.warn_thresh: print(f" WARN high error: {base} W{bits}A8 relerr={relerr:.2f}%", flush=True) errs.append((relerr, 1.0, 256, base)) for suf, val in tensors.items(): out[f"{base}.{suf}"] = val out[f"{base}.comfy_quant"] = torch.tensor(list(json.dumps(cfg).encode("utf-8")), dtype=torch.uint8) nq += 1 if nq % 100 == 0: print(f" {nq}/{len(plan)} ... {base} W{bits}A8 relerr={relerr:.2f}%", flush=True) elif base in quant_set: gs = best_gs(w.shape[1]) qd, scale = quantize_convrot(w, gs, mseclip=args.mseclip) cos, relerr = recon_metrics(qd, scale, w, gs) assert cos > 0.99, f"BROKEN quant (rotation/format?) {base} cos={cos:.5f} relerr={relerr:.2f}%" if relerr > args.warn_thresh: print(f" WARN high error: {base} gs={gs} relerr={relerr:.2f}% cos={cos:.5f}", flush=True) errs.append((relerr, cos, gs, base)) out[key] = qd.cpu() out[f"{base}.weight_scale"] = scale.cpu() out[f"{base}.comfy_quant"] = cq_tensor(gs) nq += 1 if nq % 100 == 0: print(f" {nq}/{len(plan)} ... {base} gs={gs} relerr={relerr:.2f}% cos={cos:.5f}", flush=True) else: # passthrough: fp8 must be de-fp8'd; fp32 optionally downcast; else keep source dtype if t.dtype in FP8: out[key] = w.to(target) elif t.dtype == torch.float32 and args.downcast_fp32 \ and not (base.endswith(".scale") or EXCLUDE_SEG.search(base.split(".")[-1])): out[key] = w.to(target) else: out[key] = t torch.cuda.empty_cache() save_file(out, args.dst, metadata=dict(src_meta)) print(f"DONE: quantized {nq} layers, {len(out)} tensors, {time.time()-t0:.1f}s -> {args.dst}")
# ---- per-layer error report ---- if errs: errs.sort(reverse=True) # worst relerr first rvals = [e[0] for e in errs] mean = sum(rvals) / len(rvals) over = [e for e in errs if e[0] > args.warn_thresh] per_gs = collections.defaultdict(list) for r, c, gs, b in errs: per_gs[gs].append(r) print("\n=== quant error (relerr = ||dequant-source|| / ||source||) ===") print(f" mean {mean:.3f}% min {min(rvals):.3f}% max {max(rvals):.3f}% layers {len(errs)}") print(" per groupsize: " + " ".join( f"gs{gs}: mean {sum(v)/len(v):.3f}% max {max(v):.3f}% (x{len(v)})" for gs, v in sorted(per_gs.items()))) print(" worst 8 layers:") for r, c, gs, b in errs[:8]: print(f" {r:6.3f}% cos {c:.5f} gs{gs:<3d} {b}") if over: print(f" !! {len(over)} layer(s) over --warn-thresh ({args.warn_thresh}%) — review above") if args.verify_report and errs: with open(args.verify_report, "w") as f: f.write("relerr_pct\tcosine\tgroupsize\tlayer\n") for r, c, gs, b in errs: f.write(f"{r:.4f}\t{c:.6f}\t{gs}\t{b}\n") print(f" full per-layer table -> {args.verify_report}")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:c0fac98c0317eb85215bd186b250be9b113675baab1323add40f26262f552ed9size 44240780704123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403{ "file": "fasth3_omniref_8step_pruned_bf16.safetensors", "bytes": 44240780704, "sha256": "c0fac98c0317eb85215bd186b250be9b113675baab1323add40f26262f552ed9", "tensors": 582, "tensor_data_bytes": 44240717408, "source_repo": "FastVideo/FastVideo-FastH3-Omni-8-Step-V1", "source_revision": "88d512c5e7cc38dda499fbb65688ce58611f9c80", "source_index_sha256": "40979168a4c9f720953f5af95552603a5273f4eee3e58d3615514a6267cc3d46", "source_config": { "_class_name": "MiniMaxH3Transformer3DModel", "_diffusers_version": "0.36.0.dev0", "attention_head_dim": 128, "audio_in_channels": 32, "ffn_dim": 14336, "final_norm_eps": 1e-05, "freq_dim": 256, "hidden_size": 5376, "in_channels": 24, "norm_eps": 1e-05, "num_attention_heads": 56, "num_layers": 50, "num_refiner_layers": 2, "patch_size": [ 1, 2, 2 ], "pdd_steps": 32, "qk_norm_eps": 1e-05, "rope_freq_dim": 16, "rope_theta": 10000.0, "text_dim": 5120, "time_embed_dim": 2688, "time_embed_hidden_dim": 5376 }, "source_contract": { "attention_backend": "VIDEO_SPARSE_ATTN_H3", "audio_scheduler_shift": 3.0, "base_model_revision": "hf://MiniMaxAI/MiniMax-H3@9bfb6693f2cf6de171db46d1aa586f67d773a1da", "conditioning": "fixed_ordered_references_target_only_flow", "grid_max_t": 0.999, "guidance_scale": 1.0, "model_type": "ref2va", "num_inference_steps": 8, "pdd_step_indices": [ 0, 4, 8, 12, 16, 20, 24, 28, 32 ], "pdd_steps": 32, "schema": "fasth3-inference-contract-v1", "schema_version": "fasth3-inference-contract-v1", "transformer_component": "transformer_ref", "transformer_forwards": 8, "video_scheduler_shift": 12.0, "vsa_ref_keep_rate": 0.1, "vsa_ref_policy": "p2_multi_region", "vsa_sparsity": 0.9, "vsa_tile_size": 128 }, "source_tensors": 688, "source_tensor_bytes": 70142174464, "skipped_source_tensors": [], "conversion": [ "concatenateQKV", "swapSwiGLUhalves", "PDDfullheadsToFP32offsetheads", "deriveRoPE" ], "curve": { "kind": "time-embedding-curve-svd-and-linear-interpolation", "rank": 8, "grid": 1025, "table_dtype": "F32", "projected_weight_dtype": "F32", "fit_domain": [ 0.0, 1.0 ], "fit_relative_residual": 0.00010133369976634108, "holdout_timesteps": 129, "holdout_modulation_samples": [ { "tensor": "norm_out.linear.weight", "sampled_rows": 64, "relative_l2": 0.00028652334645744016, "max_abs": 0.0006642544918664672 }, { "tensor": "transformer_blocks.0.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00028220971342392075, "max_abs": 0.000655848104541612 }, { "tensor": "transformer_blocks.1.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00025000190949607483, "max_abs": 0.0005601141953750499 }, { "tensor": "transformer_blocks.10.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024165512132966627, "max_abs": 0.0005127902298566189 }, { "tensor": "transformer_blocks.11.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00025566255176297833, "max_abs": 0.0006970543184968703 }, { "tensor": "transformer_blocks.12.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00028037809688809246, "max_abs": 0.0005343511257966393 }, { "tensor": "transformer_blocks.13.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002584695908441508, "max_abs": 0.0004739712926107309 }, { "tensor": "transformer_blocks.14.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002910532788419239, "max_abs": 0.0006167935081640152 }, { "tensor": "transformer_blocks.15.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002469427830971346, "max_abs": 0.00035769183356748613 }, { "tensor": "transformer_blocks.16.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002839179058677464, "max_abs": 0.0004724660988124074 }, { "tensor": "transformer_blocks.17.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002869634349253955, "max_abs": 0.0007902806770643256 }, { "tensor": "transformer_blocks.18.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024857720949707007, "max_abs": 0.0006660115750544149 }, { "tensor": "transformer_blocks.19.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022820637810836962, "max_abs": 0.00045495876933077106 }, { "tensor": "transformer_blocks.2.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002765542707480162, "max_abs": 0.0009016942397260808 }, { "tensor": "transformer_blocks.20.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0003072557756611611, "max_abs": 0.0008379473900060885 }, { "tensor": "transformer_blocks.21.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023061350160197104, "max_abs": 0.0011666881189658085 }, { "tensor": "transformer_blocks.22.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023835166467097032, "max_abs": 0.0007218851744514865 }, { "tensor": "transformer_blocks.23.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00025335585065625044, "max_abs": 0.0007599189025755404 }, { "tensor": "transformer_blocks.24.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002543436177268904, "max_abs": 0.0006184998097028549 }, { "tensor": "transformer_blocks.25.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00028032874780389735, "max_abs": 0.0008424069119216115 }, { "tensor": "transformer_blocks.26.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024270972262677103, "max_abs": 0.0005747431665026337 }, { "tensor": "transformer_blocks.27.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00026108749794962453, "max_abs": 0.0011547877335886803 }, { "tensor": "transformer_blocks.28.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00025688772628385296, "max_abs": 0.0007070723287413427 }, { "tensor": "transformer_blocks.29.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002688396088180777, "max_abs": 0.0008599025781306224 }, { "tensor": "transformer_blocks.3.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023685782473934324, "max_abs": 0.0009200827465116745 }, { "tensor": "transformer_blocks.30.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.000248550779309443, "max_abs": 0.0013539101566315548 }, { "tensor": "transformer_blocks.31.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024847496205974057, "max_abs": 0.0012859274503889129 }, { "tensor": "transformer_blocks.32.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002428254709366286, "max_abs": 0.0014554129821482409 }, { "tensor": "transformer_blocks.33.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002359841793607532, "max_abs": 0.0018375454871271124 }, { "tensor": "transformer_blocks.34.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002501798711765042, "max_abs": 0.002109945793156154 }, { "tensor": "transformer_blocks.35.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024255838227987025, "max_abs": 0.0020201156612551507 }, { "tensor": "transformer_blocks.36.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023483459604000967, "max_abs": 0.0017876969071384252 }, { "tensor": "transformer_blocks.37.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.000231343583464432, "max_abs": 0.0017698832170349732 }, { "tensor": "transformer_blocks.38.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022657149892788835, "max_abs": 0.0019057241907227684 }, { "tensor": "transformer_blocks.39.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022759120835297926, "max_abs": 0.0022020056775180485 }, { "tensor": "transformer_blocks.4.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00025953029913786607, "max_abs": 0.0008776936584852235 }, { "tensor": "transformer_blocks.40.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023133925679162136, "max_abs": 0.002374266907371414 }, { "tensor": "transformer_blocks.41.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022581828148541302, "max_abs": 0.0024674527611909802 }, { "tensor": "transformer_blocks.42.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022962368103622346, "max_abs": 0.0026009713186581074 }, { "tensor": "transformer_blocks.43.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022464286675264464, "max_abs": 0.0023927730378185963 }, { "tensor": "transformer_blocks.44.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022718124717153738, "max_abs": 0.002239463950176823 }, { "tensor": "transformer_blocks.45.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023251823784488883, "max_abs": 0.0023542710586714755 }, { "tensor": "transformer_blocks.46.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00023286344384668394, "max_abs": 0.0031324041617377674 }, { "tensor": "transformer_blocks.47.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00022930350045823733, "max_abs": 0.003507691650752154 }, { "tensor": "transformer_blocks.48.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024681796230691246, "max_abs": 0.002922120861851951 }, { "tensor": "transformer_blocks.49.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00028150893929038915, "max_abs": 0.005873630323455004 }, { "tensor": "transformer_blocks.5.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.00024675880824156143, "max_abs": 0.0008948593859613441 }, { "tensor": "transformer_blocks.6.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002949506234050563, "max_abs": 0.0006582339453933272 }, { "tensor": "transformer_blocks.7.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002824122047870788, "max_abs": 0.0006037143577198867 }, { "tensor": "transformer_blocks.8.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002680551951240265, "max_abs": 0.0004946770126524891 }, { "tensor": "transformer_blocks.9.adaln_proj.linear.weight", "sampled_rows": 64, "relative_l2": 0.0002718576327394142, "max_abs": 0.0005833224778662993 } ], "approximation": true, "end_to_end_quality_validated": false }, "comfyui_commit": "b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c", "comfy_model_tools_commit": "d6797787e6bdb1a1fb0094d588a26f8e71a1c757", "gpu_inference_validated": false}123version https://git-lfs.github.com/spec/v1oid sha256:851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80size 2221372306412345678910111213{ "status": "verified_byte_preserving_copy", "source_repository": "nuva-omniref-preview/FastH3-OmniRef-v5-DMPDD8-w03-cfg2-step3500", "source_revision": "2d04fd2e79c633f514c3a14310bdf5cdf67f9147", "source_path": "diffusion_models/fastvideo_fasth3_omniref_v5_dmpdd8_step3500_ref2va_pruned_int8_convrot.safetensors", "target_path": "diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors", "bytes": 22213723064, "sha256": "851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80", "canonical_source_match_receipt": "PREVIEW_SOURCE_MATCH.json", "pdd_sample_validation": "conversion/PREVIEW_PDD_SAMPLE_VALIDATION.json", "modifications": "filename only; safetensors content and metadata unchanged", "gpu_inference_validated_here": false}12345678910111213141516171819202122232425262728{ "version": "0.2.39", "tag": "v0.2.39", "commit": "e40e76d9c544b3f74c3b9ea923f7bc3d45a96372", "files": [ { "file": "comfy_kitchen/tensor/fp8.py", "installed_sha256": "9ee88f3f7ae3aa7c54e96a767719dc3a10aba61cf83a56e572bf4eb6f415e410", "tagged_sha256": "9ee88f3f7ae3aa7c54e96a767719dc3a10aba61cf83a56e572bf4eb6f415e410", "match": true, "url": "https://github.com/Comfy-Org/comfy-kitchen/blob/e40e76d9c544b3f74c3b9ea923f7bc3d45a96372/comfy_kitchen/tensor/fp8.py" }, { "file": "comfy_kitchen/scaled_mm_v2.py", "installed_sha256": "05d79ac082a51fb6624f94f878dfa8a1499f678b9b81274e54ce812cecde1262", "tagged_sha256": "05d79ac082a51fb6624f94f878dfa8a1499f678b9b81274e54ce812cecde1262", "match": true, "url": "https://github.com/Comfy-Org/comfy-kitchen/blob/e40e76d9c544b3f74c3b9ea923f7bc3d45a96372/comfy_kitchen/scaled_mm_v2.py" }, { "file": "comfy_kitchen/backends/cuda/__init__.py", "installed_sha256": "c5b1c3bc70869e418728114e8c27a889cf5b56ccb31ccf82a001386aef12ee8e", "tagged_sha256": "c5b1c3bc70869e418728114e8c27a889cf5b56ccb31ccf82a001386aef12ee8e", "match": true, "url": "https://github.com/Comfy-Org/comfy-kitchen/blob/e40e76d9c544b3f74c3b9ea923f7bc3d45a96372/comfy_kitchen/backends/cuda/__init__.py" } ]}12345678910111213141516171819202122232425262728293031323334{ "repo": "FastVideo/FastH3-OmniRef-FP8", "revision": "58c4d2ac52f366ac268149334da282341c747003", "sample": [ { "shard": "diffusion_pytorch_model-00001-of-00014.safetensors", "header_bytes": 9872, "tensors": { "transformer_blocks.0.attn.to_q.weight": { "dtype": "F8_E4M3", "shape": [ 7168, 5376 ], "data_offsets": [ 3601620736, 3640155904 ] }, "transformer_blocks.0.attn.to_q.weight_scale": { "dtype": "F32", "shape": [ 7168, 1 ], "data_offsets": [ 50176, 78848 ] } } } ]}12345678910111213141516171819202122232425262728293031323334{ "status": "passed", "scope": "Full pinned ComfyUI detector and real operations/classes on meta device, strict loading of actual exported file header; no GPU inference", "file": "fasth3_omniref_8step_pruned_bf16.safetensors", "bytes": 44240780704, "header_sha256": "3624e2aedac173fd25884af0cf2f5a288bd4b80c5f0927b85d09b8373d7886d7", "tensor_count": 582, "detected_config": { "image_model": "minimax_h3", "num_layers": 50, "token_refiner_num_layers": 2, "hidden_size": 5376, "latents_dim": 24, "audio_latents_dim": 32, "attention_head_dim": 128, "num_attention_heads": 56, "ffn_hidden_size": 14336, "text_dim": 5120, "adaln_curve_grid": 1025, "time_embed_dim": 8, "rope_inv_freq_len": 16, "gate_compress": true, "pdd_steps": 32, "sigma_shift_video": 12.0, "sigma_shift_audio": 3.0, "norm_eps": 1e-05, "qk_norm_eps": 1e-05, "final_norm_eps": 1e-05 }, "missing_keys": [], "unexpected_keys": [], "torch": "2.13.0+cu130", "comfyui_commit": "b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c"}123456789101112131415161718192021222324252627282930313233{ "repo": "FastVideo/FastH3-OmniRef-NVFP4-QAD", "revision": "33349824181060ffc0f736e33dcead1b21dd24c8", "file": "transformer_ref/nvfp4_weights.safetensors", "header_bytes": 174440, "scalars": [ { "key": "transformer_blocks.0.attn.to_gate_compress::_nvfp4_alpha", "value": 9.763808748175506e-07, "raw_hex": "310c8335" }, { "key": "transformer_blocks.0.attn.to_k::_nvfp4_alpha", "value": 0.0013427734375, "raw_hex": "0000b03a" }, { "key": "transformer_blocks.0.attn.to_out::_nvfp4_alpha", "value": 0.0006859189015813172, "raw_hex": "3dcf333a" }, { "key": "transformer_blocks.0.attn.to_q::_nvfp4_alpha", "value": 0.0009068080107681453, "raw_hex": "dbb66d3a" }, { "key": "transformer_blocks.0.attn.to_v::_nvfp4_alpha", "value": 0.0006626674439758062, "raw_hex": "dcb62d3a" } ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980{ "source_revision": "88d512c5e7cc38dda499fbb65688ce58611f9c80", "preview_revision": "2d04fd2e79c633f514c3a14310bdf5cdf67f9147", "sampling_only": true, "results": [ { "tensor": "final_layer.video_out.weight", "head": 0, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 36513000-36534503/22213723064" }, { "tensor": "final_layer.video_out.weight", "head": 1, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 38577384-38598887/22213723064" }, { "tensor": "final_layer.video_out.weight", "head": 7, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 50963688-50985191/22213723064" }, { "tensor": "final_layer.video_out.weight", "head": 31, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 100508904-100530407/22213723064" }, { "tensor": "final_layer.audio_out.weight", "head": 0, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 14480616-14502119/22213723064" }, { "tensor": "final_layer.audio_out.weight", "head": 1, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 15168744-15190247/22213723064" }, { "tensor": "final_layer.audio_out.weight", "head": 7, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 19297512-19319015/22213723064" }, { "tensor": "final_layer.audio_out.weight", "head": 31, "sampled_row": 0, "elements": 5376, "equal": true, "max_abs": 0.0, "content_range": "bytes 35812584-35834087/22213723064" } ], "all_equal": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121{ "source_revision": "88d512c5e7cc38dda499fbb65688ce58611f9c80", "preview_revision": "2d04fd2e79c633f514c3a14310bdf5cdf67f9147", "sampling_only": true, "reference": "pinned official Comfy quant_int8_convrot.quantize_convrot(mseclip=False,device=cpu)", "samples": [ { "projection": "blocks.0.attn.qkv_proj", "target_row": 0, "canonical_source_key": "transformer_blocks.0.attn.to_q.weight", "source_row": 0, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.00849036406725645 }, { "projection": "blocks.0.attn.qkv_proj", "target_row": 7168, "canonical_source_key": "transformer_blocks.0.attn.to_k.weight", "source_row": 0, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.0085593955591321 }, { "projection": "blocks.0.attn.qkv_proj", "target_row": 14336, "canonical_source_key": "transformer_blocks.0.attn.to_v.weight", "source_row": 0, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.009172344580292702 }, { "projection": "blocks.0.mlp.fc1", "target_row": 0, "canonical_source_key": "transformer_blocks.0.ff.net.0.proj.weight", "source_row": 14336, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.008960394188761711 }, { "projection": "blocks.0.mlp.fc1", "target_row": 14336, "canonical_source_key": "transformer_blocks.0.ff.net.0.proj.weight", "source_row": 0, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.00857174675911665 }, { "projection": "blocks.49.attn.qkv_proj", "target_row": 0, "canonical_source_key": "transformer_blocks.49.attn.to_q.weight", "source_row": 0, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.008440399542450905 }, { "projection": "blocks.49.mlp.fc1", "target_row": 0, "canonical_source_key": "transformer_blocks.49.ff.net.0.proj.weight", "source_row": 14336, "marker": { "format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256 }, "elements": 5376, "quantized_bytes_equal": true, "scale_equal": true, "max_quantized_difference": 0, "reconstruction_relative_l2": 0.01006264053285122 } ], "all_quantized_bytes_and_scales_equal": true}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788{ "status": "passed", "canonical_repository": "FastVideo/FastVideo-FastH3-Omni-8-Step-V1", "canonical_revision": "88d512c5e7cc38dda499fbb65688ce58611f9c80", "preview_repository": "nuva-omniref-preview/FastH3-OmniRef-v5-DMPDD8-w03-cfg2-step3500", "preview_revision": "2d04fd2e79c633f514c3a14310bdf5cdf67f9147", "matched_shards": [ { "path": "transformer_ref/diffusion_pytorch_model-00001-of-00014.safetensors", "sha256": "36df5817c34db966434469af1b53fc68c3b4d5b7db0434d0a98727f5b4ea8dc5", "bytes": 5296609992 }, { "path": "transformer_ref/diffusion_pytorch_model-00002-of-00014.safetensors", "sha256": "5b03b1e63f6529b3f3cabbd958c0f0b8c44a275c83da7b49bd9283907dc95821", "bytes": 5318721248 }, { "path": "transformer_ref/diffusion_pytorch_model-00003-of-00014.safetensors", "sha256": "1f47768be5808ec6351538591fd9a65b4a213c74fa90541cfbf3c7c6290a5dfb", "bytes": 5318721240 }, { "path": "transformer_ref/diffusion_pytorch_model-00004-of-00014.safetensors", "sha256": "3d0edd0b16019c757a6de3e3e697ba56c196de35085171b16cb43d0eec739641", "bytes": 4952636512 }, { "path": "transformer_ref/diffusion_pytorch_model-00005-of-00014.safetensors", "sha256": "399fd4263e60b789f422caebf5d0890cd5ea0cbfbc0d96224d0bead51654da06", "bytes": 5318505992 }, { "path": "transformer_ref/diffusion_pytorch_model-00006-of-00014.safetensors", "sha256": "8265285c22ca044b650bd3d7663d54cc258cc0ca7c7546c311eb1c2fc615647e", "bytes": 5164580688 }, { "path": "transformer_ref/diffusion_pytorch_model-00007-of-00014.safetensors", "sha256": "9b1245c4fb2a1b11ef69679af694bd754f19bb14ab70e9b7683fceb115a25cbb", "bytes": 5318721240 }, { "path": "transformer_ref/diffusion_pytorch_model-00008-of-00014.safetensors", "sha256": "5f3426834896191887487bc61e6e0f59168b2fb66bcef743a8065ec9cd9c669c", "bytes": 5318721248 }, { "path": "transformer_ref/diffusion_pytorch_model-00009-of-00014.safetensors", "sha256": "9930b2c02e86349d0b68d3d6efa13e5f78fe35d9d15668380cd4df0ca7fe3270", "bytes": 4875566056 }, { "path": "transformer_ref/diffusion_pytorch_model-00010-of-00014.safetensors", "sha256": "555452c8155c5c80267e076e74d5c40d0ac71f46029308c3405037bdc91e2568", "bytes": 5318505984 }, { "path": "transformer_ref/diffusion_pytorch_model-00011-of-00014.safetensors", "sha256": "e62326f89abd31d18409a98ef63c24544cf50e1ba1b4e08dbeb28bde64c25b2c", "bytes": 5164580688 }, { "path": "transformer_ref/diffusion_pytorch_model-00012-of-00014.safetensors", "sha256": "aaea3c6b97ca936032bf760ccb07450f37422337ec303d43a2dbc55e87490c76", "bytes": 5318721256 }, { "path": "transformer_ref/diffusion_pytorch_model-00013-of-00014.safetensors", "sha256": "647210d8604bd6f1dc033c95fcc9aa9050a1cc187f5ce22d70320e49a6bbb42a", "bytes": 5318721208 }, { "path": "transformer_ref/diffusion_pytorch_model-00014-of-00014.safetensors", "sha256": "6ba131b48a36a4d0c15f076fab9923850fa4dcbc2d7ed4f64bc8681795803696", "bytes": 2138941296 } ], "matching_small_files": [ "transformer_ref/config.json", "fastvideo_inference.json", "transformer_ref/diffusion_pytorch_model.safetensors.index.json" ], "comfy_file": "diffusion_models/fastvideo_fasth3_omniref_v5_dmpdd8_step3500_ref2va_pruned_int8_convrot.safetensors", "comfy_sha256": "851b2dc9670ed864b7f1e951ac9da047d83b1c04ded9bfcc1a9e5bba0ee33f80", "comfy_bytes": 22213723064, "header_sha256": "82a1df3c9956beb675b2e58afba915f78311bd008f68eb10df5ffd3ff49c64b7"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778{ "status": "passed", "source_repository": "FastVideo/FastVideo-FastH3-Omni-8-Step-V1", "source_revision": "88d512c5e7cc38dda499fbb65688ce58611f9c80", "files": [ { "path": "transformer_ref/diffusion_pytorch_model-00001-of-00014.safetensors", "bytes": 5296609992, "sha256": "36df5817c34db966434469af1b53fc68c3b4d5b7db0434d0a98727f5b4ea8dc5" }, { "path": "transformer_ref/diffusion_pytorch_model-00002-of-00014.safetensors", "bytes": 5318721248, "sha256": "5b03b1e63f6529b3f3cabbd958c0f0b8c44a275c83da7b49bd9283907dc95821" }, { "path": "transformer_ref/diffusion_pytorch_model-00003-of-00014.safetensors", "bytes": 5318721240, "sha256": "1f47768be5808ec6351538591fd9a65b4a213c74fa90541cfbf3c7c6290a5dfb" }, { "path": "transformer_ref/diffusion_pytorch_model-00004-of-00014.safetensors", "bytes": 4952636512, "sha256": "3d0edd0b16019c757a6de3e3e697ba56c196de35085171b16cb43d0eec739641" }, { "path": "transformer_ref/diffusion_pytorch_model-00005-of-00014.safetensors", "bytes": 5318505992, "sha256": "399fd4263e60b789f422caebf5d0890cd5ea0cbfbc0d96224d0bead51654da06" }, { "path": "transformer_ref/diffusion_pytorch_model-00006-of-00014.safetensors", "bytes": 5164580688, "sha256": "8265285c22ca044b650bd3d7663d54cc258cc0ca7c7546c311eb1c2fc615647e" }, { "path": "transformer_ref/diffusion_pytorch_model-00007-of-00014.safetensors", "bytes": 5318721240, "sha256": "9b1245c4fb2a1b11ef69679af694bd754f19bb14ab70e9b7683fceb115a25cbb" }, { "path": "transformer_ref/diffusion_pytorch_model-00008-of-00014.safetensors", "bytes": 5318721248, "sha256": "5f3426834896191887487bc61e6e0f59168b2fb66bcef743a8065ec9cd9c669c" }, { "path": "transformer_ref/diffusion_pytorch_model-00009-of-00014.safetensors", "bytes": 4875566056, "sha256": "9930b2c02e86349d0b68d3d6efa13e5f78fe35d9d15668380cd4df0ca7fe3270" }, { "path": "transformer_ref/diffusion_pytorch_model-00010-of-00014.safetensors", "bytes": 5318505984, "sha256": "555452c8155c5c80267e076e74d5c40d0ac71f46029308c3405037bdc91e2568" }, { "path": "transformer_ref/diffusion_pytorch_model-00011-of-00014.safetensors", "bytes": 5164580688, "sha256": "e62326f89abd31d18409a98ef63c24544cf50e1ba1b4e08dbeb28bde64c25b2c" }, { "path": "transformer_ref/diffusion_pytorch_model-00012-of-00014.safetensors", "bytes": 5318721256, "sha256": "aaea3c6b97ca936032bf760ccb07450f37422337ec303d43a2dbc55e87490c76" }, { "path": "transformer_ref/diffusion_pytorch_model-00013-of-00014.safetensors", "bytes": 5318721208, "sha256": "647210d8604bd6f1dc033c95fcc9aa9050a1cc187f5ce22d70320e49a6bbb42a" }, { "path": "transformer_ref/diffusion_pytorch_model-00014-of-00014.safetensors", "bytes": 2138941296, "sha256": "6ba131b48a36a4d0c15f076fab9923850fa4dcbc2d7ed4f64bc8681795803696" } ], "elapsed_seconds": 76.25929117202759}123456789101112131415161718192021222324252627282930313233343536373839404142434445{ "timestamp_utc": "2026-10-20T04:42:18.019751+00:00", "cpu_tests": { "command": "python test_conversion.py", "tests": 6, "result": "passed", "seconds": 2.362 }, "canonical_source_geometry": { "source_tensors": 688, "source_tensor_bytes": 70142174464, "pdd_steps": 32, "native_strict_meta_load": [ { "curve_rank": 0, "target_tensors": 585, "result": "passed" }, { "curve_rank": 8, "target_tensors": 582, "result": "passed" } ] }, "python_compile": "passed", "gpu_inference": "not_run", "full_conversion": "not_run_by_subagent", "comfyui_commit": "b1a247c9cf9dbfda4b2c0a0c1d50950667eeaa0c", "comfy_model_tools_commit": "d6797787e6bdb1a1fb0094d588a26f8e71a1c757", "files": [ { "file": "audit_native_geometry.py", "sha256": "d084a5a4c461208453133f65c57000b49e18b7ccf6dba50f69ff0a4e502c51d4" }, { "file": "convert_omniref_comfy.py", "sha256": "96b745f3fae81450eac777d60c7f3452d24d61384f18877fe4f1fc4e930320a3" }, { "file": "test_conversion.py", "sha256": "704386dc881cb6ae50fecd8d95783949e84b36b1f2549509730cf1cceb83e8a7" } ]}12345678910111213141516171819202122232425262728293031{ "attention_backend": "VIDEO_SPARSE_ATTN_H3", "audio_scheduler_shift": 3.0, "base_model_revision": "hf://MiniMaxAI/MiniMax-H3@9bfb6693f2cf6de171db46d1aa586f67d773a1da", "conditioning": "fixed_ordered_references_target_only_flow", "grid_max_t": 0.999, "guidance_scale": 1.0, "model_type": "ref2va", "num_inference_steps": 8, "pdd_step_indices": [ 0, 4, 8, 12, 16, 20, 24, 28, 32 ], "pdd_steps": 32, "schema": "fasth3-inference-contract-v1", "schema_version": "fasth3-inference-contract-v1", "transformer_component": "transformer_ref", "transformer_forwards": 8, "video_scheduler_shift": 12.0, "vsa_ref_keep_rate": 0.1, "vsa_ref_policy": "p2_multi_region", "vsa_sparsity": 0.9, "vsa_tile_size": 128}12345678910111213141516171819202122232425262728293031323334353637383940{ "target_repository": "FastVideo/FastH3-OmniRef-Comfy", "target_private": true, "collection_slug": "FastVideo/fasth3-omniref-6ad501acfccdebd3c3b7445b", "shared_source_repository": "FastVideo/FastVideo-FastH3-Comfy", "shared_source_revision": "ec1e3aa374a91c57b0b94a1623b7e657c0498cf2", "files": [ { "path": "text_encoders/qwen3vl_32b_minimax_h3_bf16.safetensors", "bytes": 51506295256, "sha256": "600d567f6a9629c8574e8e7041b199bdd9c59a986afa7906910a81919610607d" }, { "path": "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors", "bytes": 27141342152, "sha256": "bc2ced0fbea64757fa9acddccfc0b3f4819d1dcf1da6c124d690d368be283923" }, { "path": "text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors", "bytes": 15687142551, "sha256": "35a88d51044231fe332301d7a62aa81e3f2cba62febeb446e2c1e3e0ef76f2c6" }, { "path": "vae/minimax_h3_audio_vae_fp32.safetensors", "bytes": 605254808, "sha256": "8e505d95dd1561d47abd43d4238fd40d9bb1ae9e147ed0a4cba778d76ae4db48" }, { "path": "vae/minimax_h3_video_vae_fp16.safetensors", "bytes": 5207808496, "sha256": "7c1f131492e7eddacaac9069a61b81bdd39de5cc96561e677c5eab1cdce5e522" }, { "path": "vae/minimax_h3_video_vae_int8_convrot.safetensors", "bytes": 2811065184, "sha256": "52a2c8c73583c86e4f41cdcce3a6ad0ea562987bc0bf3d60a0cef5f5c8e60c0e" } ], "method": "Hugging Face CommitOperationCopy with src_repo_id and frozen src_revision; verify target LFS hashes match source after commit"}123version https://git-lfs.github.com/spec/v1oid sha256:600d567f6a9629c8574e8e7041b199bdd9c59a986afa7906910a81919610607dsize 51506295256123version https://git-lfs.github.com/spec/v1oid sha256:bc2ced0fbea64757fa9acddccfc0b3f4819d1dcf1da6c124d690d368be283923size 27141342152123version https://git-lfs.github.com/spec/v1oid sha256:35a88d51044231fe332301d7a62aa81e3f2cba62febeb446e2c1e3e0ef76f2c6size 15687142551123version https://git-lfs.github.com/spec/v1oid sha256:8e505d95dd1561d47abd43d4238fd40d9bb1ae9e147ed0a4cba778d76ae4db48size 605254808123version https://git-lfs.github.com/spec/v1oid sha256:7c1f131492e7eddacaac9069a61b81bdd39de5cc96561e677c5eab1cdce5e522size 5207808496123version https://git-lfs.github.com/spec/v1oid sha256:52a2c8c73583c86e4f41cdcce3a6ad0ea562987bc0bf3d60a0cef5f5c8e60c0esize 2811065184MANIFEST.jsonAdded+188
README.mdAdded+136
conversion/CONVERSION.mdAdded+139
conversion/QUANTIZATION_COMPATIBILITY.mdAdded+89
conversion/audit_native_geometry.pyAdded+54
conversion/convert_omniref_comfy.pyAdded+367
conversion/test_conversion.pyAdded+170
conversion/upstream/COMFY_LICENSEAdded+674
conversion/upstream/SOURCE_PINS.jsonAdded+32
conversion/upstream/TOOLS_LICENSEAdded+674
conversion/upstream/comfy_model.pyAdded+792
conversion/upstream/comfy_model_detection.pyAdded+1664
conversion/upstream/quant_int8_convrot.pyAdded+441
diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensorsAdded+3
diffusion_models/fasth3_omniref_8step_pruned_bf16.safetensors.receipt.jsonAdded+403
diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensorsAdded+3
diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors.receipt.jsonAdded+13
provenance/COMFY_KITCHEN_SOURCE_AUDIT.jsonAdded+28
provenance/FP8_SOURCE_SAMPLE_HEADER.jsonAdded+34
provenance/FULL_NATIVE_BF16_SCHEMA.jsonAdded+34
provenance/NVFP4_QKV_SCALAR_AUDIT.jsonAdded+33
provenance/NVFP4_SOURCE_HEADER.jsonAdded
provenance/PREVIEW_HEADER.jsonAdded
provenance/PREVIEW_PDD_SAMPLE_VALIDATION.jsonAdded+80
provenance/PREVIEW_QUANTIZED_SAMPLE_VALIDATION.jsonAdded+121
provenance/PREVIEW_SOURCE_MATCH.jsonAdded+88
provenance/SOURCE_VERIFICATION.jsonAdded+78
provenance/VALIDATION.jsonAdded+45
provenance/fastvideo_inference.jsonAdded+31
provenance/shared-copy-plan.jsonAdded+40
text_encoders/qwen3vl_32b_minimax_h3_bf16.safetensorsAdded+3
text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensorsAdded+3
text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensorsAdded+3
vae/minimax_h3_audio_vae_fp32.safetensorsAdded+3
vae/minimax_h3_video_vae_fp16.safetensorsAdded+3
vae/minimax_h3_video_vae_int8_convrot.safetensorsAdded+3