---
title: hunyuanvideo15
---

<div class="python-reference">
<a id="fastvideo.models.dits.hunyuanvideo15-classes"></a>
<a id="fastvideo.models.dits.hunyuanvideo15-functions"></a>
<a id="fastvideo.models.dits.hunyuanvideo15.HunyuanRMSNorm-functions"></a>
<a id="fastvideo.models.dits.hunyuanvideo15"></a>

<h2 id="fastvideo.models.dits.hunyuanvideo15.DistributedAttention"><code>fastvideo.models.dits.hunyuanvideo15.DistributedAttention</code></h2>
<pre class="doc-signature"><code>DistributedAttention(num_heads: int, head_size: int, num_kv_heads: int | None = None, softmax_scale: float | None = None, causal: bool = False, supported_attention_backends: tuple&#91;AttentionBackendEnum, ...&#93; | None = None, prefix: str = &#x27;&#x27;, **extra_impl_args)</code></pre>
<p>Distributed attention layer.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.DistributedAttention.forward"><code>fastvideo.models.dits.hunyuanvideo15.DistributedAttention.forward</code></h3>
<pre class="doc-signature"><code>forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, original_seq_len: int | None = None, replicated_q: torch.Tensor | None = None, replicated_k: torch.Tensor | None = None, replicated_v: torch.Tensor | None = None, freqs_cis: tuple&#91;torch.Tensor, torch.Tensor&#93; | None = None, attn_metadata: AttentionMetadata | None = None) -&gt; tuple&#91;torch.Tensor, torch.Tensor | None&#93;</code></pre>
<p>Forward pass for distributed attention.</p>
<h4>Parameters</h4>
<dl>
<dt><code>q: torch.Tensor</code></dt><dd><p>Query tensor [batch_size, seq_len, num_heads, head_dim]</p></dd>
<dt><code>k: torch.Tensor</code></dt><dd><p>Key tensor [batch_size, seq_len, num_heads, head_dim]</p></dd>
<dt><code>v: torch.Tensor</code></dt><dd><p>Value tensor [batch_size, seq_len, num_heads, head_dim]</p></dd>
<dt><code>original_seq_len: int</code></dt><dd><p>Original (unpadded) full sequence length</p></dd>
<dt><code>replicated_q: Optional[torch.Tensor]</code></dt><dd><p>Replicated query tensor, typically for text tokens</p></dd>
<dt><code>replicated_k: Optional[torch.Tensor]</code></dt><dd><p>Replicated key tensor</p></dd>
<dt><code>replicated_v: Optional[torch.Tensor]</code></dt><dd><p>Replicated value tensor</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>tuple[torch.Tensor, torch.Tensor | None]</code></dt><dd><p>Tuple[torch.Tensor, Optional[torch.Tensor]]: A tuple containing:
- o (torch.Tensor): Output tensor after attention for the main sequence
- replicated_o (Optional[torch.Tensor]): Output tensor for replicated tokens, if provided</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.LocalAttention"><code>fastvideo.models.dits.hunyuanvideo15.LocalAttention</code></h2>
<pre class="doc-signature"><code>LocalAttention(num_heads: int, head_size: int, num_kv_heads: int | None = None, softmax_scale: float | None = None, causal: bool = False, supported_attention_backends: tuple&#91;AttentionBackendEnum, ...&#93; | None = None, default_backend: AttentionBackendEnum | None = None, **extra_impl_args)</code></pre>
<p>Attention layer.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.LocalAttention.forward"><code>fastvideo.models.dits.hunyuanvideo15.LocalAttention.forward</code></h3>
<pre class="doc-signature"><code>forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, freqs_cis: tuple&#91;torch.Tensor, torch.Tensor&#93; | None = None) -&gt; torch.Tensor</code></pre>
<p>Apply local attention between query, key and value tensors.</p>
<h4>Parameters</h4>
<dl>
<dt><code>q: torch.Tensor</code></dt><dd><p>Query tensor of shape [batch_size, seq_len, num_heads, head_dim]</p></dd>
<dt><code>k: torch.Tensor</code></dt><dd><p>Key tensor of shape [batch_size, seq_len, num_heads, head_dim] </p></dd>
<dt><code>v: torch.Tensor</code></dt><dd><p>Value tensor of shape [batch_size, seq_len, num_heads, head_dim]</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code>torch.Tensor</code></dt><dd><p>torch.Tensor: Output tensor after local attention</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.set_forward_context"><code>fastvideo.models.dits.hunyuanvideo15.set_forward_context</code></h2>
<pre class="doc-signature"><code>set_forward_context(current_timestep, attn_metadata, forward_batch: Optional&#91;ForwardBatch&#93; = None)</code></pre>
<p>A context manager that stores the current forward context,
can be attention metadata, etc.
Here we can inject common logic for every model forward pass.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.sequence_model_parallel_all_gather_with_unpad"><code>fastvideo.models.dits.hunyuanvideo15.sequence_model_parallel_all_gather_with_unpad</code></h2>
<pre class="doc-signature"><code>sequence_model_parallel_all_gather_with_unpad(input_: torch.Tensor, original_seq_len: int, dim: int = -1) -&gt; torch.Tensor</code></pre>
<p>All-gather the input tensor and remove padding.</p>
<h3>Parameters</h3>
<dl>
<dt><code>input_: torch.Tensor</code></dt><dd><p>Sharded (and possibly padded) tensor to gather</p></dd>
<dt><code>original_seq_len: int</code></dt><dd><p>Original sequence length before padding</p></dd>
<dt><code>dim: int</code></dt><dd><p>Dimension to gather along (default: -1)</p></dd>
</dl>
<h3>Returns</h3>
<dl>
<dt><code>Tensor: torch.Tensor</code></dt><dd><p>Gathered and unpadded tensor</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.sequence_model_parallel_shard"><code>fastvideo.models.dits.hunyuanvideo15.sequence_model_parallel_shard</code></h2>
<pre class="doc-signature"><code>sequence_model_parallel_shard(input_: torch.Tensor, dim: int = 1) -&gt; tuple&#91;torch.Tensor, int&#93;</code></pre>
<p>Shard the input tensor across model parallel group with optional padding.</p>
<h3>Parameters</h3>
<dl>
<dt><code>input_: torch.Tensor</code></dt><dd><p>Input tensor to shard</p></dd>
<dt><code>dim: int</code></dt><dd><p>Dimension to shard along (default: 1)</p></dd>
</dl>
<h3>Returns</h3>
<dl>
<dt><code>tuple: tuple[torch.Tensor, int]</code></dt><dd><p>(sharded_tensor, original_seq_len)
- sharded_tensor: The sharded (and possibly padded) tensor
- original_seq_len: Original sequence length before padding</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Config"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Config</code></h2>
<pre class="doc-signature"><code>HunyuanVideo15Config(arch_config: DiTArchConfig = HunyuanVideo15ArchConfig(), prefix: str = &#x27;Hunyuan15&#x27;, quant_config: QuantizationConfig | None = None, *, _resolved_attention_backend: AttentionBackendEnum | None = None)</code></pre>


<h2 id="fastvideo.models.dits.hunyuanvideo15.LayerNormScaleShift"><code>fastvideo.models.dits.hunyuanvideo15.LayerNormScaleShift</code></h2>
<pre class="doc-signature"><code>LayerNormScaleShift(hidden_size: int, norm_type: str = &#x27;rms&#x27;, eps: float = 1e-06, elementwise_affine: bool = False, dtype: torch.dtype = torch.float32, compute_dtype: torch.dtype | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Fused operation that combines LayerNorm with scale and shift operations.
This reduces memory bandwidth by combining memory-bound operations.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.LayerNormScaleShift.forward"><code>fastvideo.models.dits.hunyuanvideo15.LayerNormScaleShift.forward</code></h3>
<pre class="doc-signature"><code>forward(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor, convert_modulation_dtype: bool = False) -&gt; torch.Tensor</code></pre>
<p>Apply ln followed by scale and shift in a single fused operation.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.ScaleResidual"><code>fastvideo.models.dits.hunyuanvideo15.ScaleResidual</code></h2>
<pre class="doc-signature"><code>ScaleResidual(prefix: str = &#x27;&#x27;)</code></pre>
<p>Applies gated residual connection.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ScaleResidual.forward"><code>fastvideo.models.dits.hunyuanvideo15.ScaleResidual.forward</code></h3>
<pre class="doc-signature"><code>forward(residual: torch.Tensor, x: torch.Tensor, gate: torch.Tensor) -&gt; torch.Tensor</code></pre>
<p>Apply gated residual connection.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.ScaleResidualLayerNormScaleShift"><code>fastvideo.models.dits.hunyuanvideo15.ScaleResidualLayerNormScaleShift</code></h2>
<pre class="doc-signature"><code>ScaleResidualLayerNormScaleShift(hidden_size: int, norm_type: str = &#x27;rms&#x27;, eps: float = 1e-06, elementwise_affine: bool = False, dtype: torch.dtype = torch.float32, compute_dtype: torch.dtype | None = None, prefix: str = &#x27;&#x27;, fuse_inference: bool = False)</code></pre>
<p>Fused operation that combines:
1. Gated residual connection
2. LayerNorm
3. Scale and shift operations</p>
<p>This reduces memory bandwidth by combining memory-bound operations.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ScaleResidualLayerNormScaleShift.forward"><code>fastvideo.models.dits.hunyuanvideo15.ScaleResidualLayerNormScaleShift.forward</code></h3>
<pre class="doc-signature"><code>forward(residual: torch.Tensor, x: torch.Tensor, gate: torch.Tensor | int, shift: torch.Tensor | None, scale: torch.Tensor | None, convert_modulation_dtype: bool = False) -&gt; tuple&#91;torch.Tensor, torch.Tensor&#93;</code></pre>
<p>Apply gated residual connection, followed by layernorm and
scale/shift in a single fused operation.</p>
<p>Pass <code>shift=None, scale=None</code> (both, not just one) to skip the
modulation entirely and return the normalized tensor as-is. Callers
that need norm-only behavior (e.g. Wan's post-self-attn site) would
otherwise pay two full-tensor elementwise passes computing
<code>normalized * (1.0 + 0) + 0</code>.</p>
<h4>Returns</h4>
<dl>
<dt><code>torch.Tensor</code></dt><dd><p>Tuple containing:</p></dd>
<dt><code>torch.Tensor</code></dt><dd><ul>
<li>normalized and modulated output</li>
</ul></dd>
<dt><code>tuple[torch.Tensor, torch.Tensor]</code></dt><dd><ul>
<li>residual value (value after residual connection
but before normalization)</li>
</ul></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear</code></h2>
<pre class="doc-signature"><code>ReplicatedLinear(input_size: int, output_size: int, bias: bool = True, skip_bias_add: bool = False, params_dtype: torch.dtype | None = None, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Replicated linear layer.</p>
<h3>Parameters</h3>
<dl>
<dt><code>input_size: int</code></dt><dd><p>input dimension of the linear layer.</p></dd>
<dt><code>output_size: int</code></dt><dd><p>output dimension of the linear layer.</p></dd>
<dt><code>bias: bool</code></dt><dd><p>If true, add bias.</p></dd>
<dt><code>skip_bias_add: bool</code></dt><dd><p>If true, skip adding bias but instead return it.</p></dd>
<dt><code>params_dtype: torch.dtype | None</code></dt><dd><p>Data type for the parameters.</p></dd>
<dt><code>quant_config: QuantizationConfig | None</code></dt><dd><p>Quantization configure.</p></dd>
<dt><code>prefix: str</code></dt><dd><p>The name of the layer in the state dict, including all parents
            (e.g. model.layers.0.qkv_proj)</p></dd>
</dl>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.weight_loader"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.weight_loader</code></h3>
<pre class="doc-signature"><code>weight_loader(param: Parameter, loaded_weight: torch.Tensor) -&gt; None</code></pre>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.forward"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.forward</code></h3>
<pre class="doc-signature"><code>forward(x: torch.Tensor) -&gt; tuple&#91;torch.Tensor, Parameter | None&#93;</code></pre>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.extra_repr"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.extra_repr</code></h3>
<pre class="doc-signature"><code>extra_repr() -&gt; str</code></pre>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.get_shape_mapping"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.get_shape_mapping</code></h3>
<pre class="doc-signature"><code>get_shape_mapping() -&gt; dict</code></pre>
<p>Get the mapping from (input_shape, output_shape) to layer types.</p>
<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.reset_shape_tracking"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.reset_shape_tracking</code></h3>
<pre class="doc-signature"><code>reset_shape_tracking() -&gt; None</code></pre>
<p>Clear tracked shapes and layer type mappings.</p>
<h3 id="fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.print_shape_summary"><code>fastvideo.models.dits.hunyuanvideo15.ReplicatedLinear.print_shape_summary</code></h3>
<pre class="doc-signature"><code>print_shape_summary() -&gt; None</code></pre>
<p>Log a summary of all unique shapes and their layer types.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.MLP"><code>fastvideo.models.dits.hunyuanvideo15.MLP</code></h2>
<pre class="doc-signature"><code>MLP(input_dim: int, mlp_hidden_dim: int, output_dim: int | None = None, bias: bool = True, act_type: str = &#x27;gelu_pytorch_tanh&#x27;, dtype: torch.dtype | None = None, prefix: str = &#x27;&#x27;, quant_config: QuantizationConfig | None = None)</code></pre>
<p>MLP for DiT blocks, NO gated linear units</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.MLP.forward"><code>fastvideo.models.dits.hunyuanvideo15.MLP.forward</code></h3>
<pre class="doc-signature"><code>forward(x: torch.Tensor) -&gt; torch.Tensor</code></pre>

<h2 id="fastvideo.models.dits.hunyuanvideo15.get_rotary_pos_embed"><code>fastvideo.models.dits.hunyuanvideo15.get_rotary_pos_embed</code></h2>
<pre class="doc-signature"><code>get_rotary_pos_embed(rope_sizes, hidden_size, heads_num, rope_dim_list, rope_theta, theta_rescale_factor = 1.0, interpolation_factor = 1.0, shard_dim: int = 0, do_sp_sharding: bool = False, dtype: torch.dtype = torch.float32, start_frame: int = 0, use_real: bool = True) -&gt; tuple&#91;torch.Tensor, torch.Tensor&#93;</code></pre>
<p>Generate rotary positional embeddings for the given sizes.</p>
<h3>Parameters</h3>
<dl>
<dt><code>rope_sizes</code></dt><dd><p>Tuple of dimensions (t, h, w)</p></dd>
<dt><code>hidden_size</code></dt><dd><p>Hidden dimension size</p></dd>
<dt><code>heads_num</code></dt><dd><p>Number of attention heads</p></dd>
<dt><code>rope_dim_list</code></dt><dd><p>List of dimensions for each axis, or None</p></dd>
<dt><code>rope_theta</code></dt><dd><p>Base for frequency calculations</p></dd>
<dt><code>theta_rescale_factor</code></dt><dd><p>Rescale factor for theta. Defaults to 1.0</p></dd>
<dt><code>interpolation_factor</code></dt><dd><p>Factor to scale positions. Defaults to 1.0</p></dd>
<dt><code>shard_dim: int</code></dt><dd><p>Which dimension to shard for sequence parallelism. Defaults to 0.</p></dd>
<dt><code>do_sp_sharding: bool</code></dt><dd><p>Whether to shard the positional embeddings for sequence parallelism. Defaults to False.</p></dd>
<dt><code>use_real: bool</code></dt><dd><p>If True, output full head_dim for rotate_half style RoPE. Defaults to True.</p></dd>
</dl>
<h3>Returns</h3>
<dl>
<dt><code>tuple[torch.Tensor, torch.Tensor]</code></dt><dd><p>Tuple of (cos, sin) tensors for rotary embeddings. Shape [S, D] if use_real, [S, D/2] otherwise.</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.ModulateProjection"><code>fastvideo.models.dits.hunyuanvideo15.ModulateProjection</code></h2>
<pre class="doc-signature"><code>ModulateProjection(hidden_size: int, factor: int = 2, act_layer: str = &#x27;silu&#x27;, dtype: torch.dtype | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Modulation layer for DiT blocks.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.ModulateProjection.forward"><code>fastvideo.models.dits.hunyuanvideo15.ModulateProjection.forward</code></h3>
<pre class="doc-signature"><code>forward(x: torch.Tensor) -&gt; torch.Tensor</code></pre>

<h2 id="fastvideo.models.dits.hunyuanvideo15.PatchEmbed"><code>fastvideo.models.dits.hunyuanvideo15.PatchEmbed</code></h2>
<pre class="doc-signature"><code>PatchEmbed(patch_size = 16, in_chans = 3, embed_dim = 768, norm_layer = None, flatten = True, bias = True, dtype = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>2D Image to Patch Embedding</p>
<p>Image to Patch Embedding using Conv2d</p>
<p>A convolution based approach to patchifying a 2D image w/ embedding projection.</p>
<p>Based on the impl in https://github.com/google-research/vision_transformer</p>
<p>Hacked together by / Copyright 2020 Ross Wightman</p>
<p>Remove the _assert function in forward function to be compatible with multi-resolution images.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.PatchEmbed.forward"><code>fastvideo.models.dits.hunyuanvideo15.PatchEmbed.forward</code></h3>
<pre class="doc-signature"><code>forward(x)</code></pre>

<h2 id="fastvideo.models.dits.hunyuanvideo15.TimestepEmbedder"><code>fastvideo.models.dits.hunyuanvideo15.TimestepEmbedder</code></h2>
<pre class="doc-signature"><code>TimestepEmbedder(hidden_size, act_layer = &#x27;silu&#x27;, frequency_embedding_size = 256, max_period = 10000, dtype = None, freq_dtype = torch.float32, prefix: str = &#x27;&#x27;)</code></pre>
<p>Embeds scalar timesteps into vector representations.</p>

<h3 id="fastvideo.models.dits.hunyuanvideo15.TimestepEmbedder.forward"><code>fastvideo.models.dits.hunyuanvideo15.TimestepEmbedder.forward</code></h3>
<pre class="doc-signature"><code>forward(t: torch.Tensor, timestep_seq_len: int | None = None) -&gt; torch.Tensor</code></pre>

<h2 id="fastvideo.models.dits.hunyuanvideo15.unpatchify"><code>fastvideo.models.dits.hunyuanvideo15.unpatchify</code></h2>
<pre class="doc-signature"><code>unpatchify(x, t, h, w, patch_size, channels) -&gt; torch.Tensor</code></pre>
<p>Convert patched representation back to image space.</p>
<h3>Parameters</h3>
<dl>
<dt><code>x</code></dt><dd><p>Tensor of shape [B, T<em>H</em>W, C<em>P_t</em>P_h*P_w]</p></dd>
<dt><code>t, h, w</code></dt><dd><p>Temporal and spatial dimensions</p></dd>
</dl>
<h3>Returns</h3>
<dl>
<dt><code>torch.Tensor</code></dt><dd><p>Unpatchified tensor of shape [B, C, T<em>P_t, H</em>P_h, W*P_w]</p></dd>
</dl>
<h2 id="fastvideo.models.dits.hunyuanvideo15.BaseDiT"><code>fastvideo.models.dits.hunyuanvideo15.BaseDiT</code></h2>
<pre class="doc-signature"><code>BaseDiT(config: DiTConfig, hf_config: dict&#91;str, Any&#93;, **kwargs)</code></pre>


<h3 id="fastvideo.models.dits.hunyuanvideo15.BaseDiT.forward"><code>fastvideo.models.dits.hunyuanvideo15.BaseDiT.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor | list&#91;torch.Tensor&#93;, timestep: torch.LongTensor, encoder_hidden_states_image: torch.Tensor | list&#91;torch.Tensor&#93; | None = None, guidance = None, **kwargs) -&gt; torch.Tensor</code></pre>

<h3 id="fastvideo.models.dits.hunyuanvideo15.BaseDiT.preprocess_loaded_weight"><code>fastvideo.models.dits.hunyuanvideo15.BaseDiT.preprocess_loaded_weight</code></h3>
<pre class="doc-signature"><code>preprocess_loaded_weight(name: str, tensor: torch.Tensor) -&gt; torch.Tensor</code></pre>
<p>Adapt a checkpoint tensor before sharding; default models are unchanged.</p>
<h3 id="fastvideo.models.dits.hunyuanvideo15.BaseDiT.inference_config_overrides"><code>fastvideo.models.dits.hunyuanvideo15.BaseDiT.inference_config_overrides</code></h3>
<pre class="doc-signature"><code>inference_config_overrides() -&gt; dict&#91;str, Any&#93;</code></pre>
<p>Extra <code>config.json</code> keys a deployable checkpoint of this model needs.</p>
<h3 id="fastvideo.models.dits.hunyuanvideo15.BaseDiT.inference_export_expected_shape"><code>fastvideo.models.dits.hunyuanvideo15.BaseDiT.inference_export_expected_shape</code></h3>
<pre class="doc-signature"><code>inference_export_expected_shape(output_key: str, base_shape: tuple&#91;int, ...&#93;) -&gt; tuple&#91;int, ...&#93;</code></pre>
<p>The exported shape of <em>output_key</em> given the base checkpoint's shape.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.AttentionBackendEnum"><code>fastvideo.models.dits.hunyuanvideo15.AttentionBackendEnum</code></h2>
<pre class="doc-signature"><code>AttentionBackendEnum()</code></pre>

<h2 id="fastvideo.models.dits.hunyuanvideo15.init_logger"><code>fastvideo.models.dits.hunyuanvideo15.init_logger</code></h2>
<pre class="doc-signature"><code>init_logger(name: str) -&gt; _FastvideoLogger</code></pre>
<p>The main purpose of this function is to ensure that loggers are
retrieved in such a way that we can be sure the root fastvideo logger has
already been configured.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.get_sp_world_size"><code>fastvideo.models.dits.hunyuanvideo15.get_sp_world_size</code></h2>
<pre class="doc-signature"><code>get_sp_world_size() -&gt; int</code></pre>
<p>Return world size for the sequence model parallel group.</p>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanRMSNorm"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanRMSNorm</code></h2>
<pre class="doc-signature"><code>HunyuanRMSNorm(dim: int, elementwise_affine = True, eps: float = 1e-06, device = None, dtype = None)</code></pre>

<p>Initialize the RMSNorm normalization layer.</p>
<h3>Parameters</h3>
<dl>
<dt><code>dim: int</code></dt><dd><p>The dimension of the input tensor.</p></dd>
<dt><code>eps: float</code></dt><dd><p>A small value added to the denominator for numerical stability. Default is 1e-6.</p></dd>
</dl>
<h3>Attributes</h3>
<dl>
<dt><code>eps: float</code></dt><dd><p>A small value added to the denominator for numerical stability.</p></dd>
<dt><code>weight: nn.Parameter</code></dt><dd><p>Learnable scaling parameter.</p></dd>
</dl>
<details><summary>Source</summary><pre><code>class HunyuanRMSNorm(nn.Module):

    def __init__(
        self,
        dim: int,
        elementwise_affine=True,
        eps: float = 1e-6,
        device=None,
        dtype=None,
    ):
        &quot;&quot;&quot;
        Initialize the RMSNorm normalization layer.

        Args:
            dim (int): The dimension of the input tensor.
            eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.

        Attributes:
            eps (float): A small value added to the denominator for numerical stability.
            weight (nn.Parameter): Learnable scaling parameter.

        &quot;&quot;&quot;
        factory_kwargs = &#123;&quot;device&quot;: device, &quot;dtype&quot;: dtype&#125;
        super().__init__()
        self.eps = eps
        if elementwise_affine:
            self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))

    def _norm(self, x) -&gt; torch.Tensor:
        &quot;&quot;&quot;
        Apply the RMSNorm normalization to the input tensor.

        Args:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The normalized tensor.

        &quot;&quot;&quot;
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        &quot;&quot;&quot;
        Forward pass through the RMSNorm layer.

        Args:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The output tensor after applying RMSNorm.

        &quot;&quot;&quot;
        output = self._norm(x.float()).type_as(x)
        if hasattr(self, &quot;weight&quot;):
            output = output * self.weight
        return output</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.HunyuanRMSNorm.forward"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanRMSNorm.forward</code></h3>
<pre class="doc-signature"><code>forward(x)</code></pre>
<p>Forward pass through the RMSNorm layer.</p>
<h4>Parameters</h4>
<dl>
<dt><code>x: torch.Tensor</code></dt><dd><p>The input tensor.</p></dd>
</dl>
<h4>Returns</h4>
<dl>
<dt><code></code></dt><dd><p>torch.Tensor: The output tensor after applying RMSNorm.</p></dd>
</dl>
<details><summary>Source</summary><pre><code>def forward(self, x):
    &quot;&quot;&quot;
    Forward pass through the RMSNorm layer.

    Args:
        x (torch.Tensor): The input tensor.

    Returns:
        torch.Tensor: The output tensor after applying RMSNorm.

    &quot;&quot;&quot;
    output = self._norm(x.float()).type_as(x)
    if hasattr(self, &quot;weight&quot;):
        output = output * self.weight
    return output</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15TimeEmbedding"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15TimeEmbedding</code></h2>
<pre class="doc-signature"><code>HunyuanVideo15TimeEmbedding(embedding_dim: int, use_meanflow: bool = False)</code></pre>
<p>Time embedding for HunyuanVideo 1.5.</p>
<p>Supports standard timestep embedding and optional reference timestep embedding for MeanFlow-based super-resolution
models.</p>
<h3>Parameters</h3>
<dl>
<dt><code>embedding_dim: `int`</code></dt><dd><p>The dimension of the output embedding.</p></dd>
</dl>

<details><summary>Source</summary><pre><code>class HunyuanVideo15TimeEmbedding(nn.Module):
    r&quot;&quot;&quot;
    Time embedding for HunyuanVideo 1.5.

    Supports standard timestep embedding and optional reference timestep embedding for MeanFlow-based super-resolution
    models.

    Args:
        embedding_dim (`int`):
            The dimension of the output embedding.
    &quot;&quot;&quot;

    def __init__(self, embedding_dim: int, use_meanflow: bool = False):
        super().__init__()

        self.timestep_embedder = TimestepEmbedder(hidden_size=embedding_dim)

        self.use_meanflow = use_meanflow
        self.time_proj_r = None
        self.timestep_embedder_r = None
        if use_meanflow:
            self.timestep_embedder_r = TimestepEmbedder(hidden_size=embedding_dim)

    def forward(
        self,
        timestep: torch.Tensor,
        timestep_r: Optional&#91;torch.Tensor&#93; = None,
    ) -&gt; torch.Tensor:
        timesteps_emb = self.timestep_embedder(timestep)

        if timestep_r is not None:
            timesteps_emb_r = self.timestep_embedder_r(timestep_r)
            timesteps_emb = timesteps_emb + timesteps_emb_r

        return timesteps_emb</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15TimeEmbedding.forward"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15TimeEmbedding.forward</code></h3>
<pre class="doc-signature"><code>forward(timestep: torch.Tensor, timestep_r: Optional&#91;torch.Tensor&#93; = None) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    timestep: torch.Tensor,
    timestep_r: Optional&#91;torch.Tensor&#93; = None,
) -&gt; torch.Tensor:
    timesteps_emb = self.timestep_embedder(timestep)

    if timestep_r is not None:
        timesteps_emb_r = self.timestep_embedder_r(timestep_r)
        timesteps_emb = timesteps_emb + timesteps_emb_r

    return timesteps_emb</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ByT5TextProjection"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ByT5TextProjection</code></h2>
<pre class="doc-signature"><code>HunyuanVideo15ByT5TextProjection(in_features: int, hidden_size: int, out_features: int)</code></pre>


<details><summary>Source</summary><pre><code>class HunyuanVideo15ByT5TextProjection(nn.Module):

    def __init__(self, in_features: int, hidden_size: int, out_features: int):
        super().__init__()
        self.norm = nn.LayerNorm(in_features)
        self.linear_1 = nn.Linear(in_features, hidden_size)
        self.linear_2 = nn.Linear(hidden_size, hidden_size)
        self.linear_3 = nn.Linear(hidden_size, out_features)
        self.act_fn = nn.GELU()

    def forward(self, encoder_hidden_states: torch.Tensor) -&gt; torch.Tensor:
        hidden_states = self.norm(encoder_hidden_states)
        hidden_states = self.linear_1(hidden_states)
        hidden_states = self.act_fn(hidden_states)
        hidden_states = self.linear_2(hidden_states)
        hidden_states = self.act_fn(hidden_states)
        hidden_states = self.linear_3(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ByT5TextProjection.forward"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ByT5TextProjection.forward</code></h3>
<pre class="doc-signature"><code>forward(encoder_hidden_states: torch.Tensor) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, encoder_hidden_states: torch.Tensor) -&gt; torch.Tensor:
    hidden_states = self.norm(encoder_hidden_states)
    hidden_states = self.linear_1(hidden_states)
    hidden_states = self.act_fn(hidden_states)
    hidden_states = self.linear_2(hidden_states)
    hidden_states = self.act_fn(hidden_states)
    hidden_states = self.linear_3(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ImageProjection"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ImageProjection</code></h2>
<pre class="doc-signature"><code>HunyuanVideo15ImageProjection(in_channels: int, hidden_size: int)</code></pre>


<details><summary>Source</summary><pre><code>class HunyuanVideo15ImageProjection(nn.Module):

    def __init__(self, in_channels: int, hidden_size: int):
        super().__init__()
        self.norm_in = nn.LayerNorm(in_channels)
        self.linear_1 = nn.Linear(in_channels, in_channels)
        self.act_fn = nn.GELU()
        self.linear_2 = nn.Linear(in_channels, hidden_size)
        self.norm_out = nn.LayerNorm(hidden_size)

    def forward(self, image_embeds: torch.Tensor) -&gt; torch.Tensor:
        hidden_states = self.norm_in(image_embeds)
        hidden_states = self.linear_1(hidden_states)
        hidden_states = self.act_fn(hidden_states)
        hidden_states = self.linear_2(hidden_states)
        hidden_states = self.norm_out(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ImageProjection.forward"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15ImageProjection.forward</code></h3>
<pre class="doc-signature"><code>forward(image_embeds: torch.Tensor) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, image_embeds: torch.Tensor) -&gt; torch.Tensor:
    hidden_states = self.norm_in(image_embeds)
    hidden_states = self.linear_1(hidden_states)
    hidden_states = self.act_fn(hidden_states)
    hidden_states = self.linear_2(hidden_states)
    hidden_states = self.norm_out(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.MMDoubleStreamBlock"><code>fastvideo.models.dits.hunyuanvideo15.MMDoubleStreamBlock</code></h2>
<pre class="doc-signature"><code>MMDoubleStreamBlock(hidden_size: int, num_attention_heads: int, mlp_ratio: float, dtype: torch.dtype | None = None, supported_attention_backends: tuple&#91;AttentionBackendEnum, ...&#93; | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>A multimodal DiT block with separate modulation for text and image/video,
using distributed attention and linear layers.</p>

<details><summary>Source</summary><pre><code>class MMDoubleStreamBlock(nn.Module):
    &quot;&quot;&quot;
    A multimodal DiT block with separate modulation for text and image/video,
    using distributed attention and linear layers.
    &quot;&quot;&quot;

    def __init__(
        self,
        hidden_size: int,
        num_attention_heads: int,
        mlp_ratio: float,
        dtype: torch.dtype | None = None,
        supported_attention_backends: tuple&#91;AttentionBackendEnum, ...&#93;
        | None = None,
        prefix: str = &quot;&quot;,
    ):
        super().__init__()

        self.deterministic = False
        self.num_attention_heads = num_attention_heads
        head_dim = hidden_size // num_attention_heads
        mlp_hidden_dim = int(hidden_size * mlp_ratio)

        # Image modulation components
        self.img_mod = ModulateProjection(
            hidden_size,
            factor=6,
            act_layer=&quot;silu&quot;,
            dtype=dtype,
            prefix=f&quot;&#123;prefix&#125;.img_mod&quot;,
        )

        # Fused operations for image stream
        self.img_attn_norm = LayerNormScaleShift(hidden_size, norm_type=&quot;layer&quot;, elementwise_affine=False, dtype=dtype)
        self.img_attn_residual_mlp_norm = ScaleResidualLayerNormScaleShift(hidden_size,
                                                                           norm_type=&quot;layer&quot;,
                                                                           elementwise_affine=False,
                                                                           dtype=dtype)
        self.img_mlp_residual = ScaleResidual()

        # Image attention components
        self.img_attn_qkv = ReplicatedLinear(hidden_size,
                                             hidden_size * 3,
                                             bias=True,
                                             params_dtype=dtype,
                                             prefix=f&quot;&#123;prefix&#125;.img_attn_qkv&quot;)

        self.img_attn_q_norm = HunyuanRMSNorm(head_dim, eps=1e-6, dtype=dtype)
        self.img_attn_k_norm = HunyuanRMSNorm(head_dim, eps=1e-6, dtype=dtype)

        self.img_attn_proj = ReplicatedLinear(hidden_size,
                                              hidden_size,
                                              bias=True,
                                              params_dtype=dtype,
                                              prefix=f&quot;&#123;prefix&#125;.img_attn_proj&quot;)

        self.img_mlp = MLP(hidden_size, mlp_hidden_dim, bias=True, dtype=dtype, prefix=f&quot;&#123;prefix&#125;.img_mlp&quot;)

        # Text modulation components
        self.txt_mod = ModulateProjection(
            hidden_size,
            factor=6,
            act_layer=&quot;silu&quot;,
            dtype=dtype,
            prefix=f&quot;&#123;prefix&#125;.txt_mod&quot;,
        )

        # Fused operations for text stream
        self.txt_attn_norm = LayerNormScaleShift(hidden_size, norm_type=&quot;layer&quot;, elementwise_affine=False, dtype=dtype)
        self.txt_attn_residual_mlp_norm = ScaleResidualLayerNormScaleShift(hidden_size,
                                                                           norm_type=&quot;layer&quot;,
                                                                           elementwise_affine=False,
                                                                           dtype=dtype)
        self.txt_mlp_residual = ScaleResidual()

        # Text attention components
        self.txt_attn_qkv = ReplicatedLinear(hidden_size, hidden_size * 3, bias=True, params_dtype=dtype)

        # QK norm layers for text
        self.txt_attn_q_norm = HunyuanRMSNorm(head_dim, eps=1e-6, dtype=dtype)
        self.txt_attn_k_norm = HunyuanRMSNorm(head_dim, eps=1e-6, dtype=dtype)

        self.txt_attn_proj = ReplicatedLinear(hidden_size, hidden_size, bias=True, params_dtype=dtype)

        self.txt_mlp = MLP(hidden_size, mlp_hidden_dim, bias=True, dtype=dtype)

        # Distributed attention
        self.attn = DistributedAttention(num_heads=num_attention_heads,
                                         head_size=head_dim,
                                         causal=False,
                                         supported_attention_backends=supported_attention_backends,
                                         prefix=f&quot;&#123;prefix&#125;.attn&quot;)

    def forward(
        self,
        img: torch.Tensor,
        txt: torch.Tensor,
        vec: torch.Tensor,
        freqs_cis: tuple,
        original_seq_len: int,
    ) -&gt; tuple&#91;torch.Tensor, torch.Tensor&#93;:
        # Broadcast per-example conditioning over tokens, not over the batch.
        img_mod_outputs = self.img_mod(vec).unsqueeze(1)
        (
            img_attn_shift,
            img_attn_scale,
            img_attn_gate,
            img_mlp_shift,
            img_mlp_scale,
            img_mlp_gate,
        ) = torch.chunk(img_mod_outputs, 6, dim=-1)

        txt_mod_outputs = self.txt_mod(vec).unsqueeze(1)
        (
            txt_attn_shift,
            txt_attn_scale,
            txt_attn_gate,
            txt_mlp_shift,
            txt_mlp_scale,
            txt_mlp_gate,
        ) = torch.chunk(txt_mod_outputs, 6, dim=-1)

        # Prepare image for attention using fused operation
        img_attn_input = self.img_attn_norm(img, img_attn_shift, img_attn_scale)
        # Get QKV for image
        img_qkv, _ = self.img_attn_qkv(img_attn_input)
        batch_size, image_seq_len = img_qkv.shape&#91;0&#93;, img_qkv.shape&#91;1&#93;

        # Split QKV
        img_qkv = img_qkv.view(batch_size, image_seq_len, 3, self.num_attention_heads, -1)
        img_q, img_k, img_v = img_qkv&#91;:, :, 0&#93;, img_qkv&#91;:, :, 1&#93;, img_qkv&#91;:, :, 2&#93;

        # Apply QK-Norm if needed
        img_q = self.img_attn_q_norm(img_q).to(img_v)
        img_k = self.img_attn_k_norm(img_k).to(img_v)

        # Prepare text for attention using fused operation
        txt_attn_input = self.txt_attn_norm(txt, txt_attn_shift, txt_attn_scale)

        # Get QKV for text
        txt_qkv, _ = self.txt_attn_qkv(txt_attn_input)
        batch_size, text_seq_len = txt_qkv.shape&#91;0&#93;, txt_qkv.shape&#91;1&#93;

        # Split QKV
        txt_qkv = txt_qkv.view(batch_size, text_seq_len, 3, self.num_attention_heads, -1)
        txt_q, txt_k, txt_v = txt_qkv&#91;:, :, 0&#93;, txt_qkv&#91;:, :, 1&#93;, txt_qkv&#91;:, :, 2&#93;
        # Apply QK-Norm if needed
        txt_q = self.txt_attn_q_norm(txt_q).to(txt_q.dtype)
        txt_k = self.txt_attn_k_norm(txt_k).to(txt_k.dtype)

        img_attn, txt_attn = self.attn(img_q, img_k, img_v, original_seq_len, txt_q, txt_k, txt_v, freqs_cis=freqs_cis)

        img_attn_out, _ = self.img_attn_proj(img_attn.reshape(batch_size, image_seq_len, -1))
        # Use fused operation for residual connection, normalization, and modulation
        img_mlp_input, img_residual = self.img_attn_residual_mlp_norm(img, img_attn_out, img_attn_gate, img_mlp_shift,
                                                                      img_mlp_scale)

        # Process image MLP
        img_mlp_out = self.img_mlp(img_mlp_input)
        img = self.img_mlp_residual(img_residual, img_mlp_out, img_mlp_gate)

        # Process text attention output
        txt_attn_out, _ = self.txt_attn_proj(txt_attn.reshape(batch_size, text_seq_len, -1))

        # Use fused operation for residual connection, normalization, and modulation
        txt_mlp_input, txt_residual = self.txt_attn_residual_mlp_norm(txt, txt_attn_out, txt_attn_gate, txt_mlp_shift,
                                                                      txt_mlp_scale)

        # Process text MLP
        txt_mlp_out = self.txt_mlp(txt_mlp_input)
        txt = self.txt_mlp_residual(txt_residual, txt_mlp_out, txt_mlp_gate)

        return img, txt</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.MMDoubleStreamBlock.forward"><code>fastvideo.models.dits.hunyuanvideo15.MMDoubleStreamBlock.forward</code></h3>
<pre class="doc-signature"><code>forward(img: torch.Tensor, txt: torch.Tensor, vec: torch.Tensor, freqs_cis: tuple, original_seq_len: int) -&gt; tuple&#91;torch.Tensor, torch.Tensor&#93;</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    img: torch.Tensor,
    txt: torch.Tensor,
    vec: torch.Tensor,
    freqs_cis: tuple,
    original_seq_len: int,
) -&gt; tuple&#91;torch.Tensor, torch.Tensor&#93;:
    # Broadcast per-example conditioning over tokens, not over the batch.
    img_mod_outputs = self.img_mod(vec).unsqueeze(1)
    (
        img_attn_shift,
        img_attn_scale,
        img_attn_gate,
        img_mlp_shift,
        img_mlp_scale,
        img_mlp_gate,
    ) = torch.chunk(img_mod_outputs, 6, dim=-1)

    txt_mod_outputs = self.txt_mod(vec).unsqueeze(1)
    (
        txt_attn_shift,
        txt_attn_scale,
        txt_attn_gate,
        txt_mlp_shift,
        txt_mlp_scale,
        txt_mlp_gate,
    ) = torch.chunk(txt_mod_outputs, 6, dim=-1)

    # Prepare image for attention using fused operation
    img_attn_input = self.img_attn_norm(img, img_attn_shift, img_attn_scale)
    # Get QKV for image
    img_qkv, _ = self.img_attn_qkv(img_attn_input)
    batch_size, image_seq_len = img_qkv.shape&#91;0&#93;, img_qkv.shape&#91;1&#93;

    # Split QKV
    img_qkv = img_qkv.view(batch_size, image_seq_len, 3, self.num_attention_heads, -1)
    img_q, img_k, img_v = img_qkv&#91;:, :, 0&#93;, img_qkv&#91;:, :, 1&#93;, img_qkv&#91;:, :, 2&#93;

    # Apply QK-Norm if needed
    img_q = self.img_attn_q_norm(img_q).to(img_v)
    img_k = self.img_attn_k_norm(img_k).to(img_v)

    # Prepare text for attention using fused operation
    txt_attn_input = self.txt_attn_norm(txt, txt_attn_shift, txt_attn_scale)

    # Get QKV for text
    txt_qkv, _ = self.txt_attn_qkv(txt_attn_input)
    batch_size, text_seq_len = txt_qkv.shape&#91;0&#93;, txt_qkv.shape&#91;1&#93;

    # Split QKV
    txt_qkv = txt_qkv.view(batch_size, text_seq_len, 3, self.num_attention_heads, -1)
    txt_q, txt_k, txt_v = txt_qkv&#91;:, :, 0&#93;, txt_qkv&#91;:, :, 1&#93;, txt_qkv&#91;:, :, 2&#93;
    # Apply QK-Norm if needed
    txt_q = self.txt_attn_q_norm(txt_q).to(txt_q.dtype)
    txt_k = self.txt_attn_k_norm(txt_k).to(txt_k.dtype)

    img_attn, txt_attn = self.attn(img_q, img_k, img_v, original_seq_len, txt_q, txt_k, txt_v, freqs_cis=freqs_cis)

    img_attn_out, _ = self.img_attn_proj(img_attn.reshape(batch_size, image_seq_len, -1))
    # Use fused operation for residual connection, normalization, and modulation
    img_mlp_input, img_residual = self.img_attn_residual_mlp_norm(img, img_attn_out, img_attn_gate, img_mlp_shift,
                                                                  img_mlp_scale)

    # Process image MLP
    img_mlp_out = self.img_mlp(img_mlp_input)
    img = self.img_mlp_residual(img_residual, img_mlp_out, img_mlp_gate)

    # Process text attention output
    txt_attn_out, _ = self.txt_attn_proj(txt_attn.reshape(batch_size, text_seq_len, -1))

    # Use fused operation for residual connection, normalization, and modulation
    txt_mlp_input, txt_residual = self.txt_attn_residual_mlp_norm(txt, txt_attn_out, txt_attn_gate, txt_mlp_shift,
                                                                  txt_mlp_scale)

    # Process text MLP
    txt_mlp_out = self.txt_mlp(txt_mlp_input)
    txt = self.txt_mlp_residual(txt_residual, txt_mlp_out, txt_mlp_gate)

    return img, txt</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Transformer3DModel"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Transformer3DModel</code></h2>
<pre class="doc-signature"><code>HunyuanVideo15Transformer3DModel(config: HunyuanVideo15Config, hf_config: dict&#91;str, Any&#93;)</code></pre>
<p>A Transformer model for video-like data used in <a href="https://huggingface.co/tencent/HunyuanVideo1.5">HunyuanVideo1.5</a>.</p>

<details><summary>Source</summary><pre><code>class HunyuanVideo15Transformer3DModel(BaseDiT):
    r&quot;&quot;&quot;
    A Transformer model for video-like data used in &#91;HunyuanVideo1.5&#93;(https://huggingface.co/tencent/HunyuanVideo1.5).
    &quot;&quot;&quot;

    # shard single stream, double stream blocks, and refiner_blocks
    _fsdp_shard_conditions = HunyuanVideo15Config()._fsdp_shard_conditions
    _compile_conditions = HunyuanVideo15Config()._compile_conditions
    _supported_attention_backends = HunyuanVideo15Config()._supported_attention_backends
    param_names_mapping = HunyuanVideo15Config().param_names_mapping
    reverse_param_names_mapping = HunyuanVideo15Config().reverse_param_names_mapping
    lora_param_names_mapping = HunyuanVideo15Config().lora_param_names_mapping

    def __init__(
        self,
        config: HunyuanVideo15Config,
        hf_config: dict&#91;str, Any&#93;,
    ) -&gt; None:
        super().__init__(config=config, hf_config=hf_config)

        self.hidden_size = config.hidden_size
        self.num_attention_heads = config.num_attention_heads
        self.num_channels_latents = config.num_channels_latents
        self.out_channels = config.out_channels or config.in_channels
        self.patch_size = (config.patch_size_t, config.patch_size, config.patch_size)

        # 1. Latent and condition embedders
        self.img_in = PatchEmbed(self.patch_size,
                                 config.in_channels,
                                 self.hidden_size,
                                 prefix=f&quot;&#123;config.prefix&#125;.img_in&quot;)
        self.image_embedder = HunyuanVideo15ImageProjection(config.image_embed_dim, self.hidden_size)

        self.txt_in = SingleTokenRefiner(config.text_embed_dim,
                                         self.hidden_size,
                                         config.num_attention_heads,
                                         depth=config.num_refiner_layers,
                                         dtype=None,
                                         prefix=f&quot;&#123;config.prefix&#125;.txt_in&quot;)

        self.txt_in_2 = HunyuanVideo15ByT5TextProjection(config.text_embed_2_dim, 2048, self.hidden_size)

        self.time_in = HunyuanVideo15TimeEmbedding(self.hidden_size, use_meanflow=config.use_meanflow)

        self.cond_type_embed = nn.Embedding(3, self.hidden_size)

        # 3. Dual stream transformer blocks

        self.double_blocks = nn.ModuleList(&#91;
            MMDoubleStreamBlock(hidden_size=self.hidden_size,
                                num_attention_heads=config.num_attention_heads,
                                mlp_ratio=config.mlp_ratio,
                                dtype=None,
                                supported_attention_backends=self._supported_attention_backends,
                                prefix=f&quot;&#123;config.prefix&#125;.double_blocks.&#123;i&#125;&quot;) for i in range(config.num_layers)
        &#93;)

        # 5. Output projection
        self.final_layer = FinalLayer(self.hidden_size,
                                      self.patch_size,
                                      self.out_channels,
                                      prefix=f&quot;&#123;config.prefix&#125;.final_layer&quot;)

        self.gradient_checkpointing = False

        self.__post_init__()

    def forward(
        self,
        hidden_states: torch.Tensor,
        encoder_hidden_states: List&#91;torch.Tensor&#93;,
        timestep: torch.LongTensor,
        encoder_hidden_states_image: List&#91;torch.Tensor&#93;,
        guidance: Optional&#91;torch.Tensor&#93; = None,
        timestep_r: Optional&#91;torch.LongTensor&#93; = None,
        attention_kwargs: Optional&#91;Dict&#91;str, Any&#93;&#93; = None,
    ):
        encoder_hidden_states_image = encoder_hidden_states_image&#91;0&#93;
        encoder_hidden_states, encoder_hidden_states_2 = encoder_hidden_states
        batch_size, num_channels, num_frames, height, width = hidden_states.shape
        p_t, p_h, p_w = self.config.patch_size_t, self.config.patch_size, self.config.patch_size
        post_patch_num_frames = num_frames // p_t
        post_patch_height = height // p_h
        post_patch_width = width // p_w

        # 1. RoPE
        # Get rotary embeddings
        freqs_cos, freqs_sin = get_rotary_pos_embed((post_patch_num_frames, post_patch_height, post_patch_width),
                                                    self.hidden_size, self.num_attention_heads,
                                                    self.config.rope_axes_dim, self.config.rope_theta)
        freqs_cos = freqs_cos.to(hidden_states.device)
        freqs_sin = freqs_sin.to(hidden_states.device)
        freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None

        # 2. Conditional embeddings
        temb = self.time_in(timestep, timestep_r=timestep_r)

        hidden_states = self.img_in(hidden_states)
        hidden_states, original_seq_len = sequence_model_parallel_shard(hidden_states, dim=1)

        current_seq_len = hidden_states.shape&#91;1&#93;
        sp_world_size = get_sp_world_size()
        padded_seq_len = current_seq_len * sp_world_size

        encoder_hidden_states = self.txt_in(encoder_hidden_states, timestep)

        encoder_hidden_states_cond_emb = self.cond_type_embed(
            torch.zeros_like(encoder_hidden_states&#91;:, :, 0&#93;, dtype=torch.long))
        encoder_hidden_states = encoder_hidden_states + encoder_hidden_states_cond_emb

        # byt5 text embedding
        encoder_hidden_states_2 = self.txt_in_2(encoder_hidden_states_2)

        encoder_hidden_states_2_cond_emb = self.cond_type_embed(
            torch.ones_like(encoder_hidden_states_2&#91;:, :, 0&#93;, dtype=torch.long))
        encoder_hidden_states_2 = encoder_hidden_states_2 + encoder_hidden_states_2_cond_emb

        # image embed
        encoder_hidden_states_3 = self.image_embedder(encoder_hidden_states_image)
        is_t2v = torch.all(encoder_hidden_states_image == 0)
        encoder_hidden_states_3_cond_emb = self.cond_type_embed(2 * torch.ones_like(
            encoder_hidden_states_3&#91;:, :, 0&#93;,
            dtype=torch.long,
        ))
        encoder_hidden_states_3 = encoder_hidden_states_3 + encoder_hidden_states_3_cond_emb

        encoder_hidden_states = torch.cat(
            &#91;encoder_hidden_states_2, encoder_hidden_states&#93;, dim=1) if is_t2v else torch.cat(
                &#91;encoder_hidden_states_3, encoder_hidden_states_2, encoder_hidden_states&#93;, dim=1)

        # 4. Transformer blocks
        if torch.is_grad_enabled() and self.gradient_checkpointing:
            for block in self.double_blocks:
                hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
                    block, hidden_states, encoder_hidden_states, temb, freqs_cis, original_seq_len)

        else:
            for block in self.double_blocks:
                hidden_states, encoder_hidden_states = block(hidden_states, encoder_hidden_states, temb, freqs_cis,
                                                             original_seq_len)

        # Final layer processing
        if get_sp_world_size() &gt; 1:
            hidden_states = hidden_states.contiguous()
        hidden_states = sequence_model_parallel_all_gather_with_unpad(hidden_states, original_seq_len, dim=1)
        hidden_states = self.final_layer(hidden_states, temb)
        # Unpatchify to get original shape
        hidden_states = unpatchify(hidden_states, post_patch_num_frames, post_patch_height, post_patch_width,
                                   self.patch_size, self.out_channels)

        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Transformer3DModel.forward"><code>fastvideo.models.dits.hunyuanvideo15.HunyuanVideo15Transformer3DModel.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, encoder_hidden_states: List&#91;torch.Tensor&#93;, timestep: torch.LongTensor, encoder_hidden_states_image: List&#91;torch.Tensor&#93;, guidance: Optional&#91;torch.Tensor&#93; = None, timestep_r: Optional&#91;torch.LongTensor&#93; = None, attention_kwargs: Optional&#91;Dict&#91;str, Any&#93;&#93; = None)</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    hidden_states: torch.Tensor,
    encoder_hidden_states: List&#91;torch.Tensor&#93;,
    timestep: torch.LongTensor,
    encoder_hidden_states_image: List&#91;torch.Tensor&#93;,
    guidance: Optional&#91;torch.Tensor&#93; = None,
    timestep_r: Optional&#91;torch.LongTensor&#93; = None,
    attention_kwargs: Optional&#91;Dict&#91;str, Any&#93;&#93; = None,
):
    encoder_hidden_states_image = encoder_hidden_states_image&#91;0&#93;
    encoder_hidden_states, encoder_hidden_states_2 = encoder_hidden_states
    batch_size, num_channels, num_frames, height, width = hidden_states.shape
    p_t, p_h, p_w = self.config.patch_size_t, self.config.patch_size, self.config.patch_size
    post_patch_num_frames = num_frames // p_t
    post_patch_height = height // p_h
    post_patch_width = width // p_w

    # 1. RoPE
    # Get rotary embeddings
    freqs_cos, freqs_sin = get_rotary_pos_embed((post_patch_num_frames, post_patch_height, post_patch_width),
                                                self.hidden_size, self.num_attention_heads,
                                                self.config.rope_axes_dim, self.config.rope_theta)
    freqs_cos = freqs_cos.to(hidden_states.device)
    freqs_sin = freqs_sin.to(hidden_states.device)
    freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None

    # 2. Conditional embeddings
    temb = self.time_in(timestep, timestep_r=timestep_r)

    hidden_states = self.img_in(hidden_states)
    hidden_states, original_seq_len = sequence_model_parallel_shard(hidden_states, dim=1)

    current_seq_len = hidden_states.shape&#91;1&#93;
    sp_world_size = get_sp_world_size()
    padded_seq_len = current_seq_len * sp_world_size

    encoder_hidden_states = self.txt_in(encoder_hidden_states, timestep)

    encoder_hidden_states_cond_emb = self.cond_type_embed(
        torch.zeros_like(encoder_hidden_states&#91;:, :, 0&#93;, dtype=torch.long))
    encoder_hidden_states = encoder_hidden_states + encoder_hidden_states_cond_emb

    # byt5 text embedding
    encoder_hidden_states_2 = self.txt_in_2(encoder_hidden_states_2)

    encoder_hidden_states_2_cond_emb = self.cond_type_embed(
        torch.ones_like(encoder_hidden_states_2&#91;:, :, 0&#93;, dtype=torch.long))
    encoder_hidden_states_2 = encoder_hidden_states_2 + encoder_hidden_states_2_cond_emb

    # image embed
    encoder_hidden_states_3 = self.image_embedder(encoder_hidden_states_image)
    is_t2v = torch.all(encoder_hidden_states_image == 0)
    encoder_hidden_states_3_cond_emb = self.cond_type_embed(2 * torch.ones_like(
        encoder_hidden_states_3&#91;:, :, 0&#93;,
        dtype=torch.long,
    ))
    encoder_hidden_states_3 = encoder_hidden_states_3 + encoder_hidden_states_3_cond_emb

    encoder_hidden_states = torch.cat(
        &#91;encoder_hidden_states_2, encoder_hidden_states&#93;, dim=1) if is_t2v else torch.cat(
            &#91;encoder_hidden_states_3, encoder_hidden_states_2, encoder_hidden_states&#93;, dim=1)

    # 4. Transformer blocks
    if torch.is_grad_enabled() and self.gradient_checkpointing:
        for block in self.double_blocks:
            hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
                block, hidden_states, encoder_hidden_states, temb, freqs_cis, original_seq_len)

    else:
        for block in self.double_blocks:
            hidden_states, encoder_hidden_states = block(hidden_states, encoder_hidden_states, temb, freqs_cis,
                                                         original_seq_len)

    # Final layer processing
    if get_sp_world_size() &gt; 1:
        hidden_states = hidden_states.contiguous()
    hidden_states = sequence_model_parallel_all_gather_with_unpad(hidden_states, original_seq_len, dim=1)
    hidden_states = self.final_layer(hidden_states, temb)
    # Unpatchify to get original shape
    hidden_states = unpatchify(hidden_states, post_patch_num_frames, post_patch_height, post_patch_width,
                               self.patch_size, self.out_channels)

    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.SingleTokenRefiner"><code>fastvideo.models.dits.hunyuanvideo15.SingleTokenRefiner</code></h2>
<pre class="doc-signature"><code>SingleTokenRefiner(in_channels, hidden_size, num_attention_heads, depth = 2, qkv_bias = True, dtype = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>A token refiner that processes text embeddings with attention to improve
their representation for cross-attention with image features.</p>

<details><summary>Source</summary><pre><code>class SingleTokenRefiner(nn.Module):
    &quot;&quot;&quot;
    A token refiner that processes text embeddings with attention to improve
    their representation for cross-attention with image features.
    &quot;&quot;&quot;

    def __init__(
        self,
        in_channels,
        hidden_size,
        num_attention_heads,
        depth=2,
        qkv_bias=True,
        dtype=None,
        prefix: str = &quot;&quot;,
    ) -&gt; None:
        super().__init__()

        # Input projection
        # self.input_embedder = ReplicatedLinear(
        #     in_channels,
        #     hidden_size,
        #     bias=True,
        #     params_dtype=dtype,
        #     prefix=f&quot;&#123;prefix&#125;.input_embedder&quot;)
        self.input_embedder = nn.Linear(in_channels, hidden_size, bias=True)

        # Timestep embedding
        self.t_embedder = TimestepEmbedder(hidden_size, act_layer=&quot;silu&quot;, dtype=dtype, prefix=f&quot;&#123;prefix&#125;.t_embedder&quot;)

        # Context embedding
        self.c_embedder = MLP(in_channels,
                              hidden_size,
                              hidden_size,
                              act_type=&quot;silu&quot;,
                              dtype=dtype,
                              prefix=f&quot;&#123;prefix&#125;.c_embedder&quot;)

        # Refiner blocks
        self.refiner_blocks = nn.ModuleList(&#91;
            IndividualTokenRefinerBlock(
                hidden_size,
                num_attention_heads,
                qkv_bias=qkv_bias,
                dtype=dtype,
                prefix=f&quot;&#123;prefix&#125;.refiner_blocks.&#123;i&#125;&quot;,
            ) for i in range(depth)
        &#93;)

    def forward(self, x, t, mask=None):
        # Get timestep embeddings
        timestep_aware_representations = self.t_embedder(t)

        original_dtype = x.dtype
        if mask is None:
            context_aware_representations = x.mean(dim=1)
        else:
            mask_float = mask.float().unsqueeze(-1)  # &#91;B, L, 1&#93;
            context_aware_representations = (x * mask_float).sum(dim=1) / mask_float.sum(dim=1)

        context_aware_representations = self.c_embedder(context_aware_representations)
        c = timestep_aware_representations + context_aware_representations
        # Project input
        x = self.input_embedder(x)
        # Process through refiner blocks
        for block in self.refiner_blocks:
            x = block(x, c, mask=mask)
        return x</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.SingleTokenRefiner.forward"><code>fastvideo.models.dits.hunyuanvideo15.SingleTokenRefiner.forward</code></h3>
<pre class="doc-signature"><code>forward(x, t, mask = None)</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, x, t, mask=None):
    # Get timestep embeddings
    timestep_aware_representations = self.t_embedder(t)

    original_dtype = x.dtype
    if mask is None:
        context_aware_representations = x.mean(dim=1)
    else:
        mask_float = mask.float().unsqueeze(-1)  # &#91;B, L, 1&#93;
        context_aware_representations = (x * mask_float).sum(dim=1) / mask_float.sum(dim=1)

    context_aware_representations = self.c_embedder(context_aware_representations)
    c = timestep_aware_representations + context_aware_representations
    # Project input
    x = self.input_embedder(x)
    # Process through refiner blocks
    for block in self.refiner_blocks:
        x = block(x, c, mask=mask)
    return x</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.IndividualTokenRefinerBlock"><code>fastvideo.models.dits.hunyuanvideo15.IndividualTokenRefinerBlock</code></h2>
<pre class="doc-signature"><code>IndividualTokenRefinerBlock(hidden_size, num_attention_heads, mlp_ratio = 4.0, qkv_bias = True, dtype = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>A transformer block for refining individual tokens with self-attention.</p>

<details><summary>Source</summary><pre><code>class IndividualTokenRefinerBlock(nn.Module):
    &quot;&quot;&quot;
    A transformer block for refining individual tokens with self-attention.
    &quot;&quot;&quot;

    def __init__(
        self,
        hidden_size,
        num_attention_heads,
        mlp_ratio=4.0,
        qkv_bias=True,
        dtype=None,
        prefix: str = &quot;&quot;,
    ) -&gt; None:
        super().__init__()
        self.num_attention_heads = num_attention_heads
        mlp_hidden_dim = int(hidden_size * mlp_ratio)

        # Normalization and attention
        self.norm1 = nn.LayerNorm(hidden_size, eps=1e-6, elementwise_affine=True, dtype=dtype)

        self.self_attn_qkv = ReplicatedLinear(hidden_size,
                                              hidden_size * 3,
                                              bias=qkv_bias,
                                              params_dtype=dtype,
                                              prefix=f&quot;&#123;prefix&#125;.self_attn_qkv&quot;)

        self.self_attn_proj = ReplicatedLinear(hidden_size,
                                               hidden_size,
                                               bias=qkv_bias,
                                               params_dtype=dtype,
                                               prefix=f&quot;&#123;prefix&#125;.self_attn_proj&quot;)

        # MLP
        self.norm2 = nn.LayerNorm(hidden_size, eps=1e-6, elementwise_affine=True, dtype=dtype)
        self.mlp = MLP(hidden_size, mlp_hidden_dim, bias=True, act_type=&quot;silu&quot;, dtype=dtype, prefix=f&quot;&#123;prefix&#125;.mlp&quot;)

        # Modulation
        self.adaLN_modulation = ModulateProjection(hidden_size,
                                                   factor=2,
                                                   act_layer=&quot;silu&quot;,
                                                   dtype=dtype,
                                                   prefix=f&quot;&#123;prefix&#125;.adaLN_modulation&quot;)

        # Scaled dot product attention
        self.attn = LocalAttention(
            num_heads=num_attention_heads,
            head_size=hidden_size // num_attention_heads,
            # TODO: remove hardcode
            supported_attention_backends=(AttentionBackendEnum.FLASH_ATTN, AttentionBackendEnum.TORCH_SDPA),
        )

    def forward(self, x, c, mask=None):

        # Get modulation parameters
        gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=-1)
        # Self-attention
        norm_x = self.norm1(x)
        qkv, _ = self.self_attn_qkv(norm_x)

        batch_size, seq_len = qkv.shape&#91;0&#93;, qkv.shape&#91;1&#93;
        qkv = qkv.view(batch_size, seq_len, 3, self.num_attention_heads, -1)
        q, k, v = qkv&#91;:, :, 0&#93;, qkv&#91;:, :, 1&#93;, qkv&#91;:, :, 2&#93;
        if mask is None:
            attn_output = self.attn(q, k, v)
        else:
            from fastvideo.attention.backends.sdpa import SDPAMetadataBuilder
            attn_metadata = SDPAMetadataBuilder().build(
                current_timestep=0,
                attn_mask=mask,
            )
            # Run distributed attention
            with set_forward_context(current_timestep=0, attn_metadata=attn_metadata):
                attn_output = self.attn(q, k, v)  # &#91;B, L, H, D&#93;
        attn_output = attn_output.reshape(batch_size, seq_len, -1)

        # Project and apply residual connection with gating
        attn_out, _ = self.self_attn_proj(attn_output)
        x = x + attn_out * gate_msa.unsqueeze(1)

        # MLP
        mlp_out = self.mlp(self.norm2(x))
        x = x + mlp_out * gate_mlp.unsqueeze(1)

        return x</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.IndividualTokenRefinerBlock.forward"><code>fastvideo.models.dits.hunyuanvideo15.IndividualTokenRefinerBlock.forward</code></h3>
<pre class="doc-signature"><code>forward(x, c, mask = None)</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, x, c, mask=None):

    # Get modulation parameters
    gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=-1)
    # Self-attention
    norm_x = self.norm1(x)
    qkv, _ = self.self_attn_qkv(norm_x)

    batch_size, seq_len = qkv.shape&#91;0&#93;, qkv.shape&#91;1&#93;
    qkv = qkv.view(batch_size, seq_len, 3, self.num_attention_heads, -1)
    q, k, v = qkv&#91;:, :, 0&#93;, qkv&#91;:, :, 1&#93;, qkv&#91;:, :, 2&#93;
    if mask is None:
        attn_output = self.attn(q, k, v)
    else:
        from fastvideo.attention.backends.sdpa import SDPAMetadataBuilder
        attn_metadata = SDPAMetadataBuilder().build(
            current_timestep=0,
            attn_mask=mask,
        )
        # Run distributed attention
        with set_forward_context(current_timestep=0, attn_metadata=attn_metadata):
            attn_output = self.attn(q, k, v)  # &#91;B, L, H, D&#93;
    attn_output = attn_output.reshape(batch_size, seq_len, -1)

    # Project and apply residual connection with gating
    attn_out, _ = self.self_attn_proj(attn_output)
    x = x + attn_out * gate_msa.unsqueeze(1)

    # MLP
    mlp_out = self.mlp(self.norm2(x))
    x = x + mlp_out * gate_mlp.unsqueeze(1)

    return x</code></pre></details>
<h2 id="fastvideo.models.dits.hunyuanvideo15.FinalLayer"><code>fastvideo.models.dits.hunyuanvideo15.FinalLayer</code></h2>
<pre class="doc-signature"><code>FinalLayer(hidden_size, patch_size, out_channels, dtype = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>The final layer of DiT that projects features to pixel space.</p>

<details><summary>Source</summary><pre><code>class FinalLayer(nn.Module):
    &quot;&quot;&quot;
    The final layer of DiT that projects features to pixel space.
    &quot;&quot;&quot;

    def __init__(self, hidden_size, patch_size, out_channels, dtype=None, prefix: str = &quot;&quot;) -&gt; None:
        super().__init__()

        # Normalization
        self.norm_final = nn.LayerNorm(hidden_size, eps=1e-6, elementwise_affine=False, dtype=dtype)

        output_dim = patch_size&#91;0&#93; * patch_size&#91;1&#93; * patch_size&#91;2&#93; * out_channels

        self.linear = ReplicatedLinear(hidden_size,
                                       output_dim,
                                       bias=True,
                                       params_dtype=dtype,
                                       prefix=f&quot;&#123;prefix&#125;.linear&quot;)

        # Modulation
        self.adaLN_modulation = ModulateProjection(hidden_size,
                                                   factor=2,
                                                   act_layer=&quot;silu&quot;,
                                                   dtype=dtype,
                                                   prefix=f&quot;&#123;prefix&#125;.adaLN_modulation&quot;)

    def forward(self, x, c):
        # What the heck HF? Why you change the scale and shift order here???
        scale, shift = self.adaLN_modulation(c).chunk(2, dim=-1)
        x = self.norm_final(x) * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
        x, _ = self.linear(x)
        return x</code></pre></details>
<h3 id="fastvideo.models.dits.hunyuanvideo15.FinalLayer.forward"><code>fastvideo.models.dits.hunyuanvideo15.FinalLayer.forward</code></h3>
<pre class="doc-signature"><code>forward(x, c)</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, x, c):
    # What the heck HF? Why you change the scale and shift order here???
    scale, shift = self.adaLN_modulation(c).chunk(2, dim=-1)
    x = self.norm_final(x) * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
    x, _ = self.linear(x)
    return x</code></pre></details>
</div>
