Skip to content

Add MAGI-1: Autoregressive Video Generation at Scale #11713

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 49 commits into
base: main
Choose a base branch
from

Conversation

tolgacangoz
Copy link
Contributor

@tolgacangoz tolgacangoz commented Jun 14, 2025

Thanks for the opportunity to fix #11519!

Original repo: https://github.com/SandAI-org/MAGI-1

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag members/contributors who may be interested in your PR.

…te attention mechanism accordingly. Updated initialization parameters and reshaping logic.
…tering and equal split ratio. Add utility functions for resizing and cropping images while preserving aspect ratio.

Enhance 3D rotary positional embeddings

Adds `center_grid_hw_indices` and `equal_split_ratio` parameters to the 3D rotary positional embedding function for more flexible configuration.

The `center_grid_hw_indices` option centers the spatial grid indices around zero. The `equal_split_ratio` parameter provides an alternative way to divide the embedding dimension equally among the temporal and spatial axes.

Updates the Magi1 VAE to utilize these new embedding features, introducing helper functions to prepare the embeddings dynamically based on input tensor dimensions.
Replaces the initial causal 3D convolution in the encoder with a standard `Conv3d` patch embedding layer. This simplifies the model and makes its input processing more consistent with Diffusion Transformer (DiT) architectures.

Additionally, this change:
- Removes the unused `Magi1CausalConv3d` class.
- Updates the attention mechanism to use the standard `scaled_dot_product_attention`.
- Sets the default for `sample_posterior` to `True` in the forward pass.
Removes the feature caching logic (`feat_cache`, `feat_idx`) from the encoder, decoder, and their sub-modules. This change significantly simplifies the forward pass implementation by removing stateful cache management.

Additionally, this commit replaces the custom `Magi1RMS_norm` with a standard `nn.LayerNorm` and updates several custom causal convolution layers to use standard `nn.Linear` or `nn.Conv3d` layers.
Moves the positional embedding and dropout layers from the main autoencoder class into the decoder module. This improves encapsulation as the embedding is only used within the decoder.

The decoder's forward pass is updated to apply the positional embedding and to remove the class token before the final output convolution.

Additionally, `quant_conv` is renamed to `quant_linear` to accurately reflect the layer type.
Updates the `Magi1Decoder3d` from a convolutional design to a Transformer-like structure that operates on patches.

This change replaces the initial convolutional and middle blocks with a linear projection layer, positional embeddings, and a class token. The logic for these components is moved from the parent `AutoencoderKLMagi1` model into the decoder for better encapsulation.
Removes several custom modules, including `Magi1ResidualBlock`, `Magi1Resample`, and `Magi1UpBlock`.

Replaces the previous `Magi1MidBlock` with a more standard transformer-style `Magi1Block`. This change simplifies the overall VAE architecture by consolidating complex, specialized blocks into a more conventional design.
Replaces the custom `Magi1AttentionBlock` with the more generic `diffusers.Attention` module, combined with a new (?) `Magi1AttnProcessor2_0`.

This change aligns the implementation with standard library patterns and leverages PyTorch 2.0's `scaled_dot_product_attention` for improved efficiency. The `Magi1Block` is also refactored into a more conventional transformer block structure using `Attention` and `FeedForward` modules.
Refactors the Magi1 VAE decoder to use a more standard transformer-based architecture.

This change replaces the previous U-Net-like upsampling blocks with a series of standard transformer blocks, each containing self-attention and a feed-forward network.

The custom rotary positional embedding logic and its helper functions have been removed, and the attention processor is simplified to work with the standard `Attention` module. This simplifies the overall model implementation.
Replaces the previous convolutional U-Net style encoder with a Vision Transformer (ViT) based implementation.

This new architecture processes the input by dividing it into patches, adding positional embeddings, and then passing the sequence through a series of transformer blocks.

The attention processor is also updated to support attention masks, and the model's configuration is adjusted to accommodate the new transformer-specific parameters.
Removes complex and unused parameters from the Magi1 VAE, encoder, and decoder modules.

This change refactors the model to use a more standard Transformer architecture, eliminating the previous U-Net-like structure with dimension multipliers and residual blocks.

The configuration is now more direct, improving clarity and maintainability.
Simplifies the initialization of the Magi1 VAE, encoder, and decoder.

Reorders constructor parameters for clarity and removes unused arguments. The spatial and temporal compression ratios are now derived directly from the `patch_size` configuration, making the relationship more explicit.

The pipeline is updated to use these new VAE attributes.
Simplifies the model architecture by removing the quantization and post-quantization convolution layers. This streamlines the `encode` and `decode` methods.

The decoder is also updated to process the entire latent tensor at once, removing the previous frame-by-frame processing loop.

Additionally, this change updates an import path for the `timm` library and renames an internal variable for consistency.
Updates the conversion script for the MAGI-1 VAE to correctly handle its Vision Transformer (ViT) based architecture.

The state dictionary mapping is rewritten to align with the ViT structure. This includes adding logic to split the original checkpoint's combined QKV weights into separate query, key, and value tensors for the `diffusers` model.

The model class and its configuration are also updated to reflect the appropriate ViT parameters, ensuring a correct conversion.
Renames the Magi autoencoder class to align with the "MAGI-1" model name. This refactoring improves consistency and clarity throughout the codebase, including documentation and tests.
Aligns the model naming with the source paper, "MAGI-1".

This change refactors the model class, associated files, tests, and documentation to use the `Magi1` prefix for better clarity and consistency.
Improve compatibility by handling various PyTorch checkpoint formats. The loader now correctly extracts the state dictionary when it is nested under common keys like "model" or "state_dict".

Ensure consistent loading of sharded safetensors by sorting the checkpoint files before merging them.
Corrects the shape of the query, key, and value tensors before they are passed to the scaled dot product attention function.

The `chunk` operation introduces an extra dimension of size one. This change removes that dimension to ensure the tensors are transposed correctly for the attention mechanism.
Modifies the `Magi1Encoder3d` to output both the mean and log variance of the latent distribution, aligning it with a standard variational autoencoder architecture.

The initial linear projection layer is replaced with a convolutional patch embedding layer. Additionally, unused convolution index state variables are removed from the tiled encoding and decoding methods, simplifying the logic.
…ponents

- Enhanced the convert_magi1_to_diffusers.py script with improved logging and error handling.
- Updated key mapping dictionaries for transformer weights to ensure consistency with diffusers format.
- Added detailed docstrings to classes and methods in transformer_magi1.py for better clarity.
- Modified the Magi1Transformer3DModel to support new parameters and improved validation.
- Adjusted test cases in test_models_transformer_magi1.py to reflect changes in parameter names.

Refactor MAGI-1 conversion script and transformer model

Improves the MAGI-1 conversion script by adding support for sharded checkpoints, introducing a more systematic key-mapping approach, and enhancing logging.

Refactors the `Magi1Transformer3DModel` to align its architecture and configuration with the original model. This includes updating parameter names, adding input validation, and improving patch embedding and unpatchifying logic.

Adds comprehensive docstrings to the model and component classes for better clarity and maintainability.
Overhauls the MAGI-1 to Diffusers conversion script to ensure correct model loading.

The previous implementation used a generic key-renaming approach which was incomplete. This update replaces it with an explicit, component-by-component conversion process based on a direct analysis of the 4.5B model checkpoint.

Key improvements include:
- Updates the default transformer configuration to match the actual model architecture.
- Rewrites the state dictionary conversion logic to handle specific parameter shapes and splits, such as for the cross-attention K/V projections.
- Restructures key mappings for clarity and correctness.
Replaces the `rearrange` function with equivalent native PyTorch `permute` and `reshape` operations.

This change removes the external `einops` library dependency, simplifying the model's environment.
@tolgacangoz
Copy link
Contributor Author

tolgacangoz commented Jul 2, 2025

Hi @yiyixuxu, @a-r-r-o-w. Is this model supposed to be placed in src or examples? MAGI-1 has more stars than SkyReels-V1 and V2 on GitHub 😮. Or starting as a community pipeline first?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Request support for MAGI-1
1 participant