Instructions to use aina-tech/Anima-Lightning with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use aina-tech/Anima-Lightning with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("aina-tech/Anima-Lightning", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Cosmos
How to use aina-tech/Anima-Lightning with Cosmos:
# 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
- Local Apps Settings
- Draw Things
- DiffusionBee
Download anima_lightning_transformer.py from aina-tech/Anima-Lightning: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/aina-tech/Anima-Lightning/resolve/main/anima_lightning_transformer.py
- Command line
-
hf download hf://aina-tech/Anima-Lightning/anima_lightning_transformer.py
-
curl -L -o anima_lightning_transformer.py https://huggingface.co/aina-tech/Anima-Lightning/resolve/main/anima_lightning_transformer.py
13 kB
| from __future__ import annotations | |
| from contextlib import contextmanager | |
| from typing import Any, Iterator | |
| import torch | |
| from torch import nn | |
| from diffusers.models.transformers.transformer_cosmos import ( | |
| CosmosEmbedding, | |
| CosmosTransformer3DModel, | |
| ) | |
| TDM_NUM_STEPS_ARGUMENT = "tdm_num_steps" | |
| def shifted_reciprocal_condition( | |
| num_steps: int | torch.Tensor, | |
| *, | |
| shift: float, | |
| device: torch.device | str | None = None, | |
| ) -> torch.Tensor: | |
| """Map a sampling-step count to its shifted final nonterminal sigma. | |
| For a raw FlowMatch schedule, the final nonterminal boundary is ``1 / K``. | |
| Applying the scheduler's rational shift gives | |
| shift * (1 / K) / (1 + (shift - 1) * (1 / K)) | |
| = shift / (K + shift - 1). | |
| The returned tensor is float32 because ``CosmosEmbedding.time_proj`` builds | |
| its sinusoidal features in float32 before casting them to the model input. | |
| """ | |
| if not isinstance(shift, (int, float)) or not torch.isfinite( | |
| torch.tensor(float(shift)) | |
| ): | |
| raise ValueError("shift must be finite") | |
| if float(shift) <= 0.0: | |
| raise ValueError("shift must be positive") | |
| steps = torch.as_tensor(num_steps, device=device) | |
| if steps.dtype == torch.bool or steps.is_complex(): | |
| raise ValueError("num_steps must contain positive integers") | |
| steps_float = steps.to(dtype=torch.float32) | |
| if not torch.isfinite(steps_float).all(): | |
| raise ValueError("num_steps must be finite") | |
| if (steps_float <= 0).any() or not torch.equal( | |
| steps_float, steps_float.round() | |
| ): | |
| raise ValueError("num_steps must contain positive integers") | |
| shift_tensor = torch.as_tensor( | |
| float(shift), device=steps_float.device, dtype=torch.float32 | |
| ) | |
| return shift_tensor / (steps_float + shift_tensor - 1.0) | |
| class CosmosTDMUnifyEmbedding(nn.Module): | |
| """Cosmos time embedding with an additive, sampling-step-aware branch. | |
| The original ``CosmosEmbedding`` children remain registered under | |
| ``time_proj``, ``t_embedder``, and ``norm``. Consequently, converting a | |
| model does not rename any pretrained ``time_embed.*`` state-dict keys. | |
| The new full ``CosmosEmbedding`` branch is registered as ``k_embed``. | |
| """ | |
| def __init__( | |
| self, | |
| original: CosmosEmbedding, | |
| *, | |
| shift: float, | |
| initial_scale: float = 0.01, | |
| ) -> None: | |
| super().__init__() | |
| if not isinstance(original, CosmosEmbedding): | |
| raise TypeError("original must be a CosmosEmbedding") | |
| if not torch.isfinite(torch.tensor(float(initial_scale))): | |
| raise ValueError("initial_scale must be finite") | |
| # Preserve the original module hierarchy and parameter names exactly. | |
| self.time_proj = original.time_proj | |
| self.t_embedder = original.t_embedder | |
| self.norm = original.norm | |
| embedding_dim = self.t_embedder.linear_1.in_features | |
| condition_dim = self.t_embedder.linear_1.out_features | |
| self.k_embed = CosmosEmbedding(embedding_dim, condition_dim) | |
| self.k_scale = nn.Parameter(torch.tensor(float(initial_scale))) | |
| self.shift = float(shift) | |
| if self.shift <= 0.0 or not torch.isfinite(torch.tensor(self.shift)): | |
| raise ValueError("shift must be finite and positive") | |
| # Runtime-only condition. It deliberately is not persistent model state. | |
| self._active_num_steps: int | torch.Tensor | None = None | |
| def use_num_steps(self, num_steps: int | torch.Tensor) -> Iterator[None]: | |
| previous = self._active_num_steps | |
| self._active_num_steps = num_steps | |
| try: | |
| yield | |
| finally: | |
| self._active_num_steps = previous | |
| def forward( | |
| self, hidden_states: torch.Tensor, timestep: torch.Tensor | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| if self._active_num_steps is None: | |
| raise RuntimeError( | |
| "TDM-Unify sampling steps are unset; pass " | |
| f"{TDM_NUM_STEPS_ARGUMENT} to the project Cosmos model" | |
| ) | |
| timesteps_proj = self.time_proj(timestep).type_as(hidden_states) | |
| temb = self.t_embedder(timesteps_proj) | |
| embedded_timestep = self.norm(timesteps_proj) | |
| k_condition = self._condition_for_timestep( | |
| self._active_num_steps, timestep=timestep | |
| ) | |
| k_temb, k_embedded_timestep = self.k_embed(hidden_states, k_condition) | |
| scale = self.k_scale.to(device=temb.device, dtype=temb.dtype) | |
| return ( | |
| temb + scale * k_temb, | |
| embedded_timestep + scale * k_embedded_timestep, | |
| ) | |
| def _condition_for_timestep( | |
| self, num_steps: int | torch.Tensor, *, timestep: torch.Tensor | |
| ) -> torch.Tensor: | |
| condition = shifted_reciprocal_condition( | |
| num_steps, shift=self.shift, device=timestep.device | |
| ) | |
| if condition.ndim == 0: | |
| return condition.expand(timestep.shape) | |
| if condition.shape == timestep.shape: | |
| return condition | |
| if condition.numel() == timestep.numel(): | |
| return condition.reshape(timestep.shape) | |
| if condition.ndim == 1 and timestep.ndim == 1: | |
| if timestep.numel() % condition.numel() == 0: | |
| repeats = timestep.numel() // condition.numel() | |
| return condition.repeat_interleave(repeats) | |
| raise ValueError( | |
| "num_steps must be scalar, match timestep, or provide one value per " | |
| "batch item that evenly expands across flattened video frames" | |
| ) | |
| def enable_cosmos_tdm_unify( | |
| transformer: CosmosTransformer3DModel, | |
| *, | |
| shift: float, | |
| initial_scale: float = 0.01, | |
| ) -> CosmosTDMUnifyEmbedding: | |
| """Install K conditioning without changing pretrained time-embedding keys.""" | |
| if not isinstance(transformer, CosmosTransformer3DModel): | |
| raise TypeError("transformer must be a CosmosTransformer3DModel") | |
| if isinstance(transformer.time_embed, CosmosTDMUnifyEmbedding): | |
| if transformer.time_embed.shift != float(shift): | |
| raise ValueError( | |
| "TDM-Unify conditioning is already enabled with another shift" | |
| ) | |
| return transformer.time_embed | |
| transformer.time_embed = CosmosTDMUnifyEmbedding( | |
| transformer.time_embed, | |
| shift=shift, | |
| initial_scale=initial_scale, | |
| ) | |
| return transformer.time_embed | |
| def use_cosmos_tdm_unify_steps( | |
| transformer: CosmosTransformer3DModel, num_steps: int | torch.Tensor | |
| ) -> Iterator[None]: | |
| """Apply a K condition to an already converted Cosmos model for one call.""" | |
| if not isinstance(transformer.time_embed, CosmosTDMUnifyEmbedding): | |
| raise RuntimeError("TDM-Unify conditioning has not been enabled") | |
| with transformer.time_embed.use_num_steps(num_steps): | |
| yield | |
| class CosmosTDMUnifyTransformer3DModel(CosmosTransformer3DModel): | |
| """Save/load-compatible Cosmos model with explicit TDM-Unify K input. | |
| Use this class for the trainable student and fake-score transformers only. | |
| The frozen teacher remains the unmodified Diffusers class. | |
| """ | |
| def from_pretrained( | |
| cls, | |
| pretrained_model_name_or_path: str | None, | |
| *model_args: Any, | |
| **kwargs: Any, | |
| ) -> CosmosTDMUnifyTransformer3DModel: | |
| # A base Cosmos checkpoint has no K-branch tensors. Diffusers' meta-device | |
| # loader leaves such newly introduced parameters on ``meta``. Cosmos also | |
| # requires its normal low-memory loader for selected FP32 modules, so | |
| # materialize only the missing project branch after base weights load. | |
| output_loading_info = bool(kwargs.pop("output_loading_info", False)) | |
| model, loading_info = super().from_pretrained( | |
| pretrained_model_name_or_path, | |
| *model_args, | |
| output_loading_info=True, | |
| **kwargs, | |
| ) | |
| model._tdm_unify_loading_info = { | |
| key: tuple(value) if isinstance(value, list) else value | |
| for key, value in loading_info.items() | |
| } | |
| model._materialize_missing_k_branch() | |
| if output_loading_info: | |
| return model, loading_info | |
| return model | |
| def __init__( | |
| self, | |
| in_channels: int = 16, | |
| out_channels: int = 16, | |
| num_attention_heads: int = 32, | |
| attention_head_dim: int = 128, | |
| num_layers: int = 28, | |
| mlp_ratio: float = 4.0, | |
| text_embed_dim: int = 1024, | |
| adaln_lora_dim: int = 256, | |
| max_size: tuple[int, int, int] = (128, 240, 240), | |
| patch_size: tuple[int, int, int] = (1, 2, 2), | |
| rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0), | |
| concat_padding_mask: bool = True, | |
| extra_pos_embed_type: str | None = "learnable", | |
| use_crossattn_projection: bool = False, | |
| crossattn_proj_in_channels: int = 1024, | |
| encoder_hidden_states_channels: int = 1024, | |
| controlnet_block_every_n: int | None = None, | |
| img_context_dim_in: int | None = None, | |
| img_context_num_tokens: int = 256, | |
| img_context_dim_out: int = 2048, | |
| tdm_unify_shift: float = 3.0, | |
| tdm_unify_initial_scale: float = 0.01, | |
| ) -> None: | |
| # Keep this signature aligned with Diffusers 0.39.0 so ConfigMixin can | |
| # reconstruct the project subclass from either a base or Unify config. | |
| super().__init__( | |
| in_channels=in_channels, | |
| out_channels=out_channels, | |
| num_attention_heads=num_attention_heads, | |
| attention_head_dim=attention_head_dim, | |
| num_layers=num_layers, | |
| mlp_ratio=mlp_ratio, | |
| text_embed_dim=text_embed_dim, | |
| adaln_lora_dim=adaln_lora_dim, | |
| max_size=max_size, | |
| patch_size=patch_size, | |
| rope_scale=rope_scale, | |
| concat_padding_mask=concat_padding_mask, | |
| extra_pos_embed_type=extra_pos_embed_type, | |
| use_crossattn_projection=use_crossattn_projection, | |
| crossattn_proj_in_channels=crossattn_proj_in_channels, | |
| encoder_hidden_states_channels=encoder_hidden_states_channels, | |
| controlnet_block_every_n=controlnet_block_every_n, | |
| img_context_dim_in=img_context_dim_in, | |
| img_context_num_tokens=img_context_num_tokens, | |
| img_context_dim_out=img_context_dim_out, | |
| ) | |
| enable_cosmos_tdm_unify( | |
| self, | |
| shift=tdm_unify_shift, | |
| initial_scale=tdm_unify_initial_scale, | |
| ) | |
| self.register_to_config( | |
| tdm_unify_shift=float(tdm_unify_shift), | |
| tdm_unify_initial_scale=float(tdm_unify_initial_scale), | |
| ) | |
| def _materialize_missing_k_branch(self) -> None: | |
| if not any( | |
| parameter.is_meta for parameter in self.time_embed.k_embed.parameters() | |
| ): | |
| if not self.time_embed.k_scale.is_meta: | |
| return | |
| reference = self.time_embed.t_embedder.linear_1.weight | |
| if reference.is_meta: | |
| raise RuntimeError("Base Cosmos time embedding was not materialized") | |
| embedding_dim = self.time_embed.t_embedder.linear_1.in_features | |
| condition_dim = self.time_embed.t_embedder.linear_1.out_features | |
| if any( | |
| parameter.is_meta for parameter in self.time_embed.k_embed.parameters() | |
| ): | |
| self.time_embed.k_embed = CosmosEmbedding( | |
| embedding_dim, condition_dim | |
| ).to(device=reference.device, dtype=reference.dtype) | |
| if self.time_embed.k_scale.is_meta: | |
| initial_scale = float(self.config.tdm_unify_initial_scale) | |
| self.time_embed.k_scale = nn.Parameter( | |
| torch.tensor( | |
| initial_scale, device=reference.device, dtype=reference.dtype | |
| ) | |
| ) | |
| def forward( | |
| self, | |
| hidden_states: torch.Tensor, | |
| timestep: torch.Tensor, | |
| encoder_hidden_states: torch.Tensor, | |
| block_controlnet_hidden_states: list[torch.Tensor] | None = None, | |
| attention_mask: torch.Tensor | None = None, | |
| fps: int | None = None, | |
| condition_mask: torch.Tensor | None = None, | |
| padding_mask: torch.Tensor | None = None, | |
| return_dict: bool = True, | |
| *, | |
| tdm_num_steps: int | torch.Tensor = 4, | |
| ) -> Any: | |
| with use_cosmos_tdm_unify_steps(self, tdm_num_steps): | |
| return super().forward( | |
| hidden_states=hidden_states, | |
| timestep=timestep, | |
| encoder_hidden_states=encoder_hidden_states, | |
| block_controlnet_hidden_states=block_controlnet_hidden_states, | |
| attention_mask=attention_mask, | |
| fps=fps, | |
| condition_mask=condition_mask, | |
| padding_mask=padding_mask, | |
| return_dict=return_dict, | |
| ) | |