---
title: t5
---

<div class="python-reference">
<a id="fastvideo.models.encoders.t5-classes"></a>
<a id="fastvideo.models.encoders.t5-functions"></a>
<a id="fastvideo.models.encoders.t5.T5Attention-functions"></a>
<a id="fastvideo.models.encoders.t5"></a>
<p>PyTorch T5 &amp; UMT5 model.</p>
<h2 id="fastvideo.models.encoders.t5.BaseEncoderOutput"><code>fastvideo.models.encoders.t5.BaseEncoderOutput</code></h2>
<pre class="doc-signature"><code>BaseEncoderOutput(last_hidden_state: torch.FloatTensor | None = None, pooler_output: torch.FloatTensor | None = None, hidden_states: tuple&#91;torch.FloatTensor, ...&#93; | None = None, attentions: tuple&#91;torch.FloatTensor, ...&#93; | None = None, attention_mask: torch.Tensor | None = None)</code></pre>


<h2 id="fastvideo.models.encoders.t5.T5Config"><code>fastvideo.models.encoders.t5.T5Config</code></h2>
<pre class="doc-signature"><code>T5Config(arch_config: TextEncoderArchConfig = T5ArchConfig(), prefix: str = &#x27;t5&#x27;, quant_config: QuantizationConfig | None = None, lora_config: Any | None = None, is_chat_model: bool = False, treat_empty_as_dot: bool = False, *, _resolved_attention_backend: AttentionBackendEnum | None = None, chat_template_enable_thinking: bool = False)</code></pre>


<h2 id="fastvideo.models.encoders.t5.get_tp_rank"><code>fastvideo.models.encoders.t5.get_tp_rank</code></h2>
<pre class="doc-signature"><code>get_tp_rank() -&gt; int</code></pre>
<p>Return my rank for the tensor model parallel group.</p>
<h2 id="fastvideo.models.encoders.t5.get_tp_world_size"><code>fastvideo.models.encoders.t5.get_tp_world_size</code></h2>
<pre class="doc-signature"><code>get_tp_world_size() -&gt; int</code></pre>
<p>Return world size for the tensor model parallel group.</p>
<h2 id="fastvideo.models.encoders.t5.get_act_fn"><code>fastvideo.models.encoders.t5.get_act_fn</code></h2>
<pre class="doc-signature"><code>get_act_fn(act_fn_name: str) -&gt; nn.Module</code></pre>
<p>Get an activation function by name.</p>
<h2 id="fastvideo.models.encoders.t5.RMSNorm"><code>fastvideo.models.encoders.t5.RMSNorm</code></h2>
<pre class="doc-signature"><code>RMSNorm(hidden_size: int, eps: float = 1e-06, dtype: torch.dtype = torch.float32, var_hidden_size: int | None = None, has_weight: bool = True)</code></pre>
<p>Root mean square normalization.</p>
<p>Computes x -&gt; w * x / sqrt(E[x^2] + eps) where w is the learned weight.
Refer to https://arxiv.org/abs/1910.07467</p>

<h3 id="fastvideo.models.encoders.t5.RMSNorm.forward_native"><code>fastvideo.models.encoders.t5.RMSNorm.forward_native</code></h3>
<pre class="doc-signature"><code>forward_native(x: torch.Tensor, residual: torch.Tensor | None = None) -&gt; torch.Tensor | tuple&#91;torch.Tensor, torch.Tensor&#93;</code></pre>
<p>PyTorch-native implementation equivalent to forward().</p>
<h3 id="fastvideo.models.encoders.t5.RMSNorm.extra_repr"><code>fastvideo.models.encoders.t5.RMSNorm.extra_repr</code></h3>
<pre class="doc-signature"><code>extra_repr() -&gt; str</code></pre>

<h2 id="fastvideo.models.encoders.t5.MergedColumnParallelLinear"><code>fastvideo.models.encoders.t5.MergedColumnParallelLinear</code></h2>
<pre class="doc-signature"><code>MergedColumnParallelLinear(input_size: int, output_sizes: list&#91;int&#93;, bias: bool = True, gather_output: bool = False, skip_bias_add: bool = False, params_dtype: torch.dtype | None = None, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Packed linear layers with column parallelism.</p>
<p>Similar to ColumnParallelLinear, but the weight matrix is concatenated
along the output dimension. When the weight matrix is loaded, the
different partitions are sharded separately.</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_sizes: list[int]</code></dt><dd><p>list of output dimensions of the linear layer.</p></dd>
<dt><code>bias: bool</code></dt><dd><p>If true, add bias.</p></dd>
<dt><code>gather_output: bool</code></dt><dd><p>If true, call all-gather on output and make the output
           available to all GPUs, otherwise, every GPU will have
           its own output.</p></dd>
<dt><code>skip_bias_add: bool</code></dt><dd><p>This was added to enable performance optimizations where
           bias can be fused with other element-wise operations. we
           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.encoders.t5.MergedColumnParallelLinear.weight_loader"><code>fastvideo.models.encoders.t5.MergedColumnParallelLinear.weight_loader</code></h3>
<pre class="doc-signature"><code>weight_loader(param: Parameter, loaded_weight: torch.Tensor, loaded_shard_id: int | None = None) -&gt; None</code></pre>

<h3 id="fastvideo.models.encoders.t5.MergedColumnParallelLinear.weight_loader_v2"><code>fastvideo.models.encoders.t5.MergedColumnParallelLinear.weight_loader_v2</code></h3>
<pre class="doc-signature"><code>weight_loader_v2(param: BasevLLMParameter, loaded_weight: torch.Tensor, loaded_shard_id: int | None = None) -&gt; None</code></pre>

<h2 id="fastvideo.models.encoders.t5.QKVParallelLinear"><code>fastvideo.models.encoders.t5.QKVParallelLinear</code></h2>
<pre class="doc-signature"><code>QKVParallelLinear(hidden_size: int, head_size: int, total_num_heads: int, total_num_kv_heads: int | None = None, 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>Linear layers for the attention's QKV transformation.</p>
<p>Linear layers for the linear transformation of the query, key, and value
vectors in the attention layer. The weight matrix is concatenated along
the output dimension. The layer is parallelized along the head dimension.
When the number of key/value heads is smaller than the number of query
heads (e.g., multi-query/grouped-query attention), the key/value head may
be replicated while the query heads are partitioned.</p>
<h3>Parameters</h3>
<dl>
<dt><code>hidden_size: int</code></dt><dd><p>input hidden state size of the transformer.</p></dd>
<dt><code>head_size: int</code></dt><dd><p>size of each attention head.</p></dd>
<dt><code>total_num_heads: int</code></dt><dd><p>total number of attention query heads.</p></dd>
<dt><code>total_num_kv_heads: int | None</code></dt><dd><p>total number of attention key/value heads. If
                None, assume total_num_kv_heads = total_num_heads.</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>This was added to enable performance optimizations where
           bias can be fused with other element-wise operations. we
           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.encoders.t5.QKVParallelLinear.weight_loader_v2"><code>fastvideo.models.encoders.t5.QKVParallelLinear.weight_loader_v2</code></h3>
<pre class="doc-signature"><code>weight_loader_v2(param: BasevLLMParameter, loaded_weight: torch.Tensor, loaded_shard_id: str | None = None)</code></pre>

<h3 id="fastvideo.models.encoders.t5.QKVParallelLinear.weight_loader"><code>fastvideo.models.encoders.t5.QKVParallelLinear.weight_loader</code></h3>
<pre class="doc-signature"><code>weight_loader(param: Parameter, loaded_weight: torch.Tensor, loaded_shard_id: str | None = None)</code></pre>

<h2 id="fastvideo.models.encoders.t5.RowParallelLinear"><code>fastvideo.models.encoders.t5.RowParallelLinear</code></h2>
<pre class="doc-signature"><code>RowParallelLinear(input_size: int, output_size: int, bias: bool = True, input_is_parallel: bool = True, skip_bias_add: bool = False, params_dtype: torch.dtype | None = None, reduce_results: bool = True, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Linear layer with row parallelism.</p>
<p>The linear layer is defined as Y = XA + b. A is parallelized along
its first dimension and X along its second dimension as:
           -   -
          | A_1 |
          | .   |
      A = | .   |        X = [X_1, ..., X_p]
          | .   |
          | A_p |
           -   -
Arguments:
    input_size: first dimension of matrix A.
    output_size: second dimension of matrix A.
    bias: If true, add bias. Note that bias is not parallelized.
    input_is_parallel: If true, we assume that the input is already
                       split across the GPUs and we do not split
                       again.
    skip_bias_add: This was added to enable performance optimization where
                   bias can be fused with other element-wise operations.
                   We skip adding bias but instead return it.
    params_dtype: Data type for the parameters.
    quant_config: Quantization configure.</p>

<h3 id="fastvideo.models.encoders.t5.RowParallelLinear.weight_loader"><code>fastvideo.models.encoders.t5.RowParallelLinear.weight_loader</code></h3>
<pre class="doc-signature"><code>weight_loader(param: Parameter, loaded_weight: torch.Tensor)</code></pre>

<h3 id="fastvideo.models.encoders.t5.RowParallelLinear.weight_loader_v2"><code>fastvideo.models.encoders.t5.RowParallelLinear.weight_loader_v2</code></h3>
<pre class="doc-signature"><code>weight_loader_v2(param: BasevLLMParameter, loaded_weight: torch.Tensor)</code></pre>

<h3 id="fastvideo.models.encoders.t5.RowParallelLinear.forward"><code>fastvideo.models.encoders.t5.RowParallelLinear.forward</code></h3>
<pre class="doc-signature"><code>forward(input_) -&gt; tuple&#91;torch.Tensor, Parameter | None&#93;</code></pre>

<h3 id="fastvideo.models.encoders.t5.RowParallelLinear.extra_repr"><code>fastvideo.models.encoders.t5.RowParallelLinear.extra_repr</code></h3>
<pre class="doc-signature"><code>extra_repr() -&gt; str</code></pre>

<h2 id="fastvideo.models.encoders.t5.QuantizationConfig"><code>fastvideo.models.encoders.t5.QuantizationConfig</code></h2>
<pre class="doc-signature"><code>QuantizationConfig()</code></pre>
<p>Base class for quantization configs.</p>

<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_name"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_name</code></h3>
<pre class="doc-signature"><code>get_name() -&gt; QuantizationMethods</code></pre>
<p>Name of the quantization method.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_supported_act_dtypes"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_supported_act_dtypes</code></h3>
<pre class="doc-signature"><code>get_supported_act_dtypes() -&gt; list&#91;torch.dtype&#93;</code></pre>
<p>List of supported activation dtypes.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_min_capability"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_min_capability</code></h3>
<pre class="doc-signature"><code>get_min_capability() -&gt; int</code></pre>
<p>Minimum GPU capability to support the quantization method.</p>
<p>E.g., 70 for Volta, 75 for Turing, 80 for Ampere.
This requirement is due to the custom CUDA kernels used by the
quantization method.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_config_filenames"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_config_filenames</code></h3>
<pre class="doc-signature"><code>get_config_filenames() -&gt; list&#91;str&#93;</code></pre>
<p>List of filenames to search for in the model directory.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.from_config"><code>fastvideo.models.encoders.t5.QuantizationConfig.from_config</code></h3>
<pre class="doc-signature"><code>from_config(config: dict&#91;str, Any&#93;) -&gt; QuantizationConfig</code></pre>
<p>Create a config class from the model's quantization config.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.override_quantization_method"><code>fastvideo.models.encoders.t5.QuantizationConfig.override_quantization_method</code></h3>
<pre class="doc-signature"><code>override_quantization_method(hf_quant_cfg, user_quant) -&gt; QuantizationMethods | None</code></pre>
<p>Detects if this quantization method can support a given checkpoint
format by overriding the user specified quantization method -- 
this method should only be overwritten by subclasses in exceptional 
circumstances</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_from_keys"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_from_keys</code></h3>
<pre class="doc-signature"><code>get_from_keys(config: dict&#91;str, Any&#93;, keys: list&#91;str&#93;) -&gt; Any</code></pre>
<p>Get a value from the model's quantization config.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_from_keys_or"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_from_keys_or</code></h3>
<pre class="doc-signature"><code>get_from_keys_or(config: dict&#91;str, Any&#93;, keys: list&#91;str&#93;, default: Any) -&gt; Any</code></pre>
<p>Get a optional value from the model's quantization config.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_quant_method"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_quant_method</code></h3>
<pre class="doc-signature"><code>get_quant_method(layer: torch.nn.Module, prefix: str) -&gt; QuantizeMethodBase | None</code></pre>
<p>Get the quantize method to use for the quantized layer.</p>
<h4>Parameters</h4>
<dl>
<dt><code>layer: torch.nn.Module</code></dt><dd><p>The layer for the quant method.</p></dd>
<dt><code>prefix: str</code></dt><dd><p>The full name of the layer in the state dict</p></dd>
</dl>
<p>Returns:
    The quantize method. None if the given layer doesn't support quant
    method.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.validate_runtime"><code>fastvideo.models.encoders.t5.QuantizationConfig.validate_runtime</code></h3>
<pre class="doc-signature"><code>validate_runtime(device: torch.device) -&gt; None</code></pre>
<p>Fail fast on a device the scheme cannot execute on.</p>
<p>Called once by loaders that select a serialized checkpoint scheme,
before any weight is read. The default accepts every device; schemes
with kernel or capability requirements override it.</p>
<h3 id="fastvideo.models.encoders.t5.QuantizationConfig.get_cache_scale"><code>fastvideo.models.encoders.t5.QuantizationConfig.get_cache_scale</code></h3>
<pre class="doc-signature"><code>get_cache_scale(name: str) -&gt; str | None</code></pre>

<h2 id="fastvideo.models.encoders.t5.VocabParallelEmbedding"><code>fastvideo.models.encoders.t5.VocabParallelEmbedding</code></h2>
<pre class="doc-signature"><code>VocabParallelEmbedding(num_embeddings: int, embedding_dim: int, params_dtype: torch.dtype | None = None, org_num_embeddings: int | None = None, padding_size: int = DEFAULT_VOCAB_PADDING_SIZE, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>
<p>Embedding parallelized in the vocabulary dimension.</p>
<p>Adapted from torch.nn.Embedding, note that we pad the vocabulary size to
make sure it is divisible by the number of model parallel GPUs.</p>
<p>In order to support various loading methods, we ensure that LoRA-added
embeddings are always at the end of TP-sharded tensors. In other words,
we shard base embeddings and LoRA embeddings separately (both padded),
and place them in the same tensor.
In this example, we will have the original vocab size = 1010,
added vocab size = 16 and padding to 64. Therefore, the total
vocab size with padding will be 1088 (because we first pad 1010 to
1024, add 16, and then pad to 1088).
Therefore, the tensor format looks like the following:
TP1, rank 0 (no sharding):
                        |&lt; --------BASE-------- &gt;|&lt; -BASE PADDING-- &gt;|&lt; -----LORA------ &gt;|&lt; -LORA PADDING-- &gt;|
corresponding token_id: |  0  |  1  | ... | 1009 |  -1  | ... |  -1  | 1010 | ... | 1015 |  -1  | ... |  -1  |
                 index: |  0  |  1  | ... | 1009 | 1010 | ... | 1023 | 1024 | ... | 1039 | 1040 | ... | 1087 |</p>
<p>TP2, rank 0:
                        |&lt; --------------------BASE--------------------- &gt;|&lt; -----LORA------ &gt;|&lt; -LORA PADDING- &gt;|
corresponding token_id: |  0  |  1  |  2  | ... | 497  | 498 | ...  | 511 | 1000 | ... | 1015 |  -1  | ... |  -1 |
                 index: |  0  |  1  |  2  | ... | 497  | 498 | ...  | 511 | 512  | ... | 527  |  520 | ... | 543 |
TP2, rank 1:
                        |&lt; -----------BASE----------- &gt;|&lt; -BASE PADDING- &gt;|&lt; -----------LORA PADDING----------- &gt;|
corresponding token_id: | 512 | 513 | 514 | ... | 1009 | -1  | ...  | -1  |  -1  | ... |  -1  | -1  | ... |   -1 |
                 index: |  0  |  1  |  2  | ... | 497  | 498 | ...  | 511 | 512  | ... | 519  | 520 | ... |  543 |</p>
<h3>Parameters</h3>
<dl>
<dt><code>num_embeddings: int</code></dt><dd><p>vocabulary size.</p></dd>
<dt><code>embedding_dim: int</code></dt><dd><p>size of hidden state.</p></dd>
<dt><code>params_dtype: torch.dtype | None</code></dt><dd><p>type of the parameters.</p></dd>
<dt><code>org_num_embeddings: int | None</code></dt><dd><p>original vocabulary size (without LoRA).</p></dd>
<dt><code>padding_size: int</code></dt><dd><p>padding size for the vocabulary.</p></dd>
<dt><code>quant_config: QuantizationConfig | None</code></dt><dd><p>quant config for the layer</p></dd>
<dt><code>prefix: str</code></dt><dd><p>full name of the layer in the state dict</p></dd>
</dl>

<h3 id="fastvideo.models.encoders.t5.VocabParallelEmbedding.get_sharded_to_full_mapping"><code>fastvideo.models.encoders.t5.VocabParallelEmbedding.get_sharded_to_full_mapping</code></h3>
<pre class="doc-signature"><code>get_sharded_to_full_mapping() -&gt; list&#91;int&#93; | None</code></pre>
<p>Get a mapping that can be used to reindex the gathered
logits for sampling.</p>
<p>During sampling, we gather logits from all ranks. The relationship
of index-&gt;token_id will follow the same format as outlined in the class
docstring. However, after the gather, we want to reindex the final
logits tensor to map index-&gt;token_id one-to-one (the index is always
equal the token_id it corresponds to). The indices returned by this
method allow us to do that.</p>
<h3 id="fastvideo.models.encoders.t5.VocabParallelEmbedding.weight_loader"><code>fastvideo.models.encoders.t5.VocabParallelEmbedding.weight_loader</code></h3>
<pre class="doc-signature"><code>weight_loader(param: Parameter, loaded_weight: torch.Tensor)</code></pre>

<h3 id="fastvideo.models.encoders.t5.VocabParallelEmbedding.forward"><code>fastvideo.models.encoders.t5.VocabParallelEmbedding.forward</code></h3>
<pre class="doc-signature"><code>forward(input_)</code></pre>

<h3 id="fastvideo.models.encoders.t5.VocabParallelEmbedding.extra_repr"><code>fastvideo.models.encoders.t5.VocabParallelEmbedding.extra_repr</code></h3>
<pre class="doc-signature"><code>extra_repr() -&gt; str</code></pre>

<h2 id="fastvideo.models.encoders.t5.TextEncoder"><code>fastvideo.models.encoders.t5.TextEncoder</code></h2>
<pre class="doc-signature"><code>TextEncoder(config: TextEncoderConfig)</code></pre>
<p>Base for native encoders with a model-specific forward output contract.</p>

<h3 id="fastvideo.models.encoders.t5.TextEncoder.forward"><code>fastvideo.models.encoders.t5.TextEncoder.forward</code></h3>
<pre class="doc-signature"><code>forward(*args: Any, **kwargs: Any) -&gt; TextEncoderOutputT</code></pre>

<h2 id="fastvideo.models.encoders.t5.default_weight_loader"><code>fastvideo.models.encoders.t5.default_weight_loader</code></h2>
<pre class="doc-signature"><code>default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -&gt; None</code></pre>
<p>Default weight loader.</p>
<h2 id="fastvideo.models.encoders.t5.AttentionType"><code>fastvideo.models.encoders.t5.AttentionType</code></h2>
<pre class="doc-signature"><code>AttentionType()</code></pre>
<p>Attention type.
Use string to be compatible with <code>torch.compile</code>.</p>
<details><summary>Source</summary><pre><code>class AttentionType:
    &quot;&quot;&quot;
    Attention type.
    Use string to be compatible with `torch.compile`.
    &quot;&quot;&quot;

    # Decoder attention between previous layer Q/K/V
    DECODER = &quot;decoder&quot;
    # Encoder attention between previous layer Q/K/V for encoder-decoder
    ENCODER = &quot;encoder&quot;
    # Encoder attention between previous layer Q/K/V
    ENCODER_ONLY = &quot;encoder_only&quot;
    # Attention between dec. Q and enc. K/V for encoder-decoder
    ENCODER_DECODER = &quot;encoder_decoder&quot;</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.AttentionMetadata"><code>fastvideo.models.encoders.t5.AttentionMetadata</code></h2>
<pre class="doc-signature"><code>AttentionMetadata(attn_bias: torch.Tensor)</code></pre>


<details><summary>Source</summary><pre><code>@dataclass
class AttentionMetadata:
    attn_bias: torch.Tensor</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5DenseActDense"><code>fastvideo.models.encoders.t5.T5DenseActDense</code></h2>
<pre class="doc-signature"><code>T5DenseActDense(config: T5Config, quant_config: QuantizationConfig | None = None)</code></pre>


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

    def __init__(self, config: T5Config, quant_config: QuantizationConfig | None = None):
        super().__init__()
        self.wi = MergedColumnParallelLinear(config.d_model, &#91;config.d_ff&#93;, bias=False)
        self.wo = RowParallelLinear(config.d_ff, config.d_model, bias=False, quant_config=quant_config)
        self.act = get_act_fn(config.dense_act_fn)

    def forward(self, hidden_states) -&gt; torch.Tensor:
        hidden_states, _ = self.wi(hidden_states)
        hidden_states = self.act(hidden_states)
        hidden_states, _ = self.wo(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5DenseActDense.forward"><code>fastvideo.models.encoders.t5.T5DenseActDense.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, hidden_states) -&gt; torch.Tensor:
    hidden_states, _ = self.wi(hidden_states)
    hidden_states = self.act(hidden_states)
    hidden_states, _ = self.wo(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5DenseGatedActDense"><code>fastvideo.models.encoders.t5.T5DenseGatedActDense</code></h2>
<pre class="doc-signature"><code>T5DenseGatedActDense(config: T5Config, quant_config: QuantizationConfig | None = None)</code></pre>


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

    def __init__(self, config: T5Config, quant_config: QuantizationConfig | None = None):
        super().__init__()
        self.wi_0 = MergedColumnParallelLinear(config.d_model, &#91;config.d_ff&#93;, bias=False, quant_config=quant_config)
        self.wi_1 = MergedColumnParallelLinear(config.d_model, &#91;config.d_ff&#93;, bias=False, quant_config=quant_config)
        # Should not run in fp16 unless mixed-precision is used,
        # see https://github.com/huggingface/transformers/issues/20287.
        self.wo = RowParallelLinear(config.d_ff, config.d_model, bias=False, quant_config=quant_config)
        self.act = get_act_fn(config.dense_act_fn)

    def forward(self, hidden_states) -&gt; torch.Tensor:
        hidden_gelu = self.act(self.wi_0(hidden_states)&#91;0&#93;)
        hidden_linear, _ = self.wi_1(hidden_states)
        hidden_states = hidden_gelu * hidden_linear
        hidden_states, _ = self.wo(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5DenseGatedActDense.forward"><code>fastvideo.models.encoders.t5.T5DenseGatedActDense.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, hidden_states) -&gt; torch.Tensor:
    hidden_gelu = self.act(self.wi_0(hidden_states)&#91;0&#93;)
    hidden_linear, _ = self.wi_1(hidden_states)
    hidden_states = hidden_gelu * hidden_linear
    hidden_states, _ = self.wo(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5LayerFF"><code>fastvideo.models.encoders.t5.T5LayerFF</code></h2>
<pre class="doc-signature"><code>T5LayerFF(config: T5Config, quant_config: QuantizationConfig | None = None)</code></pre>


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

    def __init__(self, config: T5Config, quant_config: QuantizationConfig | None = None):
        super().__init__()
        if config.is_gated_act:
            self.DenseReluDense = T5DenseGatedActDense(config, quant_config=quant_config)
        else:
            self.DenseReluDense = T5DenseActDense(config, quant_config=quant_config)

        self.layer_norm = RMSNorm(config.d_model, eps=config.layer_norm_epsilon)

    def forward(self, hidden_states) -&gt; torch.Tensor:
        forwarded_states = self.layer_norm(hidden_states)
        forwarded_states = self.DenseReluDense(forwarded_states)
        hidden_states = hidden_states + forwarded_states
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5LayerFF.forward"><code>fastvideo.models.encoders.t5.T5LayerFF.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, hidden_states) -&gt; torch.Tensor:
    forwarded_states = self.layer_norm(hidden_states)
    forwarded_states = self.DenseReluDense(forwarded_states)
    hidden_states = hidden_states + forwarded_states
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5MultiHeadAttention"><code>fastvideo.models.encoders.t5.T5MultiHeadAttention</code></h2>
<pre class="doc-signature"><code>T5MultiHeadAttention()</code></pre>


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

    def __init__(self) -&gt; None:
        super().__init__()

    def forward(self, q, k, v, attn_bias=None):
        b, _, n, c = q.shape
        attn = torch.einsum(&quot;binc,bjnc-&gt;bnij&quot;, q, k)
        if attn_bias is not None:
            attn += attn_bias

        attn = F.softmax(attn.float(), dim=-1).type_as(attn)
        x = torch.einsum(&quot;bnij,bjnc-&gt;binc&quot;, attn, v)
        x = x.reshape(b, -1, n * c)
        return x</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5MultiHeadAttention.forward"><code>fastvideo.models.encoders.t5.T5MultiHeadAttention.forward</code></h3>
<pre class="doc-signature"><code>forward(q, k, v, attn_bias = None)</code></pre>

<details><summary>Source</summary><pre><code>def forward(self, q, k, v, attn_bias=None):
    b, _, n, c = q.shape
    attn = torch.einsum(&quot;binc,bjnc-&gt;bnij&quot;, q, k)
    if attn_bias is not None:
        attn += attn_bias

    attn = F.softmax(attn.float(), dim=-1).type_as(attn)
    x = torch.einsum(&quot;bnij,bjnc-&gt;binc&quot;, attn, v)
    x = x.reshape(b, -1, n * c)
    return x</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5Attention"><code>fastvideo.models.encoders.t5.T5Attention</code></h2>
<pre class="doc-signature"><code>T5Attention(config: T5Config, attn_type: str, has_relative_attention_bias = False, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>


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

    def __init__(
        self,
        config: T5Config,
        attn_type: str,
        has_relative_attention_bias=False,
        quant_config: QuantizationConfig | None = None,
        prefix: str = &quot;&quot;,
    ):
        super().__init__()
        self.attn_type = attn_type
        # Cross-attention has no relative pos encoding anyway
        self.is_decoder = attn_type == AttentionType.DECODER
        self.has_relative_attention_bias = has_relative_attention_bias
        self.relative_attention_num_buckets = (config.relative_attention_num_buckets)
        self.relative_attention_max_distance = (config.relative_attention_max_distance)
        self.d_model = config.d_model
        self.key_value_proj_dim = config.d_kv
        self.total_num_heads = self.total_num_kv_heads = config.num_heads

        # Partition heads across multiple tensor parallel GPUs.
        tp_world_size = get_tp_world_size()
        assert config.num_heads % tp_world_size == 0
        self.n_heads = config.num_heads // tp_world_size

        self.inner_dim = self.n_heads * self.key_value_proj_dim
        # No GQA in t5.
        # self.n_kv_heads = self.n_heads

        self.qkv_proj = QKVParallelLinear(
            self.d_model,
            self.key_value_proj_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=False,
            quant_config=quant_config,
            prefix=f&quot;&#123;prefix&#125;.qkv_proj&quot;,
        )

        self.attn = T5MultiHeadAttention()

        if self.has_relative_attention_bias:
            self.relative_attention_bias = VocabParallelEmbedding(
                self.relative_attention_num_buckets,
                self.total_num_heads,
                org_num_embeddings=self.relative_attention_num_buckets,
                padding_size=self.relative_attention_num_buckets,
                quant_config=quant_config,
            )
        self.o = RowParallelLinear(
            self.total_num_heads * self.key_value_proj_dim,
            self.d_model,
            bias=False,
            quant_config=quant_config,
            prefix=f&quot;&#123;prefix&#125;.o_proj&quot;,
        )

    @staticmethod
    def _relative_position_bucket(relative_position,
                                  bidirectional=True,
                                  num_buckets=32,
                                  max_distance=128) -&gt; torch.Tensor:
        &quot;&quot;&quot;
        Adapted from Mesh Tensorflow:
        https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
        Translate relative position to a bucket number for relative attention.
        The relative position is defined as memory_position - query_position,
        i.e. the distance in tokens from the attending position to the
        attended-to position. If bidirectional=False, then positive relative
        positions are invalid. We use smaller buckets for small absolute
        relative_position and larger buckets for larger absolute
        relative_positions. All relative positions &gt;=max_distance map to the
        same bucket. All relative positions &lt;=-max_distance map to the same
        bucket. This should allow for more graceful generalization to longer
        sequences than the model has been trained on
        Args:
            relative_position: an int32 Tensor
            bidirectional: a boolean - whether the attention is bidirectional
            num_buckets: an integer
            max_distance: an integer
        Returns:
            a Tensor with the same shape as relative_position, containing int32
            values in the range &#91;0, num_buckets)
        &quot;&quot;&quot;  # noqa: E501
        relative_buckets = 0
        if bidirectional:
            num_buckets //= 2
            relative_buckets += (relative_position &gt; 0).to(torch.long) * num_buckets
            relative_position = torch.abs(relative_position)
        else:
            relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
        # now relative_position is in the range &#91;0, inf)

        # half of the buckets are for exact increments in positions
        max_exact = num_buckets // 2
        is_small = relative_position &lt; max_exact

        # The other half of the buckets are for logarithmically bigger bins
        # in positions up to max_distance
        relative_position_if_large = max_exact + (torch.log(relative_position.float() / max_exact) /
                                                  math.log(max_distance / max_exact) *
                                                  (num_buckets - max_exact)).to(torch.long)
        relative_position_if_large = torch.min(
            relative_position_if_large,
            torch.full_like(relative_position_if_large, num_buckets - 1),
        )

        relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
        return relative_buckets

    def compute_bias(self, query_length, key_length, device=None) -&gt; torch.Tensor:
        &quot;&quot;&quot;Compute binned relative position bias&quot;&quot;&quot;
        if device is None:
            device = self.relative_attention_bias.weight.device
        context_position = torch.arange(query_length, dtype=torch.long, device=device)&#91;:, None&#93;
        memory_position = torch.arange(key_length, dtype=torch.long, device=device)&#91;None, :&#93;
        # max_seq_len, nh
        relative_position = memory_position - context_position
        relative_position_bucket = self._relative_position_bucket(
            relative_position,  # shape (query_length, key_length)
            bidirectional=(not self.is_decoder),
            num_buckets=self.relative_attention_num_buckets,
            max_distance=self.relative_attention_max_distance,
        )
        values = self.relative_attention_bias(relative_position_bucket)  # shape (query_length, key_length, num_heads)
        x = values.permute(&#91;2, 0, 1&#93;).unsqueeze(0)  # shape (1, num_heads, query_length, key_length)
        return x

    def forward(
        self,
        hidden_states: torch.Tensor,  # (num_tokens, d_model)
        attention_mask: torch.Tensor,
        attn_metadata: AttentionMetadata | None = None,
    ) -&gt; torch.Tensor:
        bs, seq_len, _ = hidden_states.shape
        num_seqs = bs
        n, c = self.n_heads, self.key_value_proj_dim
        qkv, _ = self.qkv_proj(hidden_states)
        # Projection of &#x27;own&#x27; hidden state (self-attention). No GQA here.
        q, k, v = qkv.split(self.inner_dim, dim=-1)
        q = q.reshape(bs, seq_len, n, c)
        k = k.reshape(bs, seq_len, n, c)
        v = v.reshape(bs, seq_len, n, c)

        assert attn_metadata is not None
        attn_bias = attn_metadata.attn_bias
        # Not compatible with CP here (as all encoder-decoder models),
        # as it assumes homogeneous batch (prefills or decodes).
        if self.has_relative_attention_bias:
            # Self-attention. Compute T5 relative positional encoding.
            # The bias term is computed on longest sequence in batch. Biases
            # for shorter sequences are slices of the longest.
            assert self.attn_type == AttentionType.ENCODER
            attn_bias = self.compute_bias(seq_len, seq_len).repeat(num_seqs, 1, 1, 1)
            attn_metadata.attn_bias = attn_bias
        else:
            # Encoder/Decoder Self-Attention Layer, attn bias already cached.
            assert attn_bias is not None

        from fastvideo.platforms import current_platform

        if attention_mask is not None:
            attention_mask = (attention_mask.view(bs, 1, 1, -1)
                              if attention_mask.ndim == 2 else attention_mask.unsqueeze(1))
            mask_val = (-1e4 if current_platform.is_mps() else torch.finfo(q.dtype).min)
            attn_bias.masked_fill_(attention_mask == 0, mask_val)

        if get_tp_world_size() &gt; 1:
            rank = get_tp_rank()
            attn_bias = attn_bias&#91;:, rank * self.n_heads:(rank + 1) * self.n_heads, :, :&#93;
        attn_output = self.attn(q, k, v, attn_bias)
        output, _ = self.o(attn_output)
        return output</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5Attention.compute_bias"><code>fastvideo.models.encoders.t5.T5Attention.compute_bias</code></h3>
<pre class="doc-signature"><code>compute_bias(query_length, key_length, device = None) -&gt; torch.Tensor</code></pre>
<p>Compute binned relative position bias</p>
<details><summary>Source</summary><pre><code>def compute_bias(self, query_length, key_length, device=None) -&gt; torch.Tensor:
    &quot;&quot;&quot;Compute binned relative position bias&quot;&quot;&quot;
    if device is None:
        device = self.relative_attention_bias.weight.device
    context_position = torch.arange(query_length, dtype=torch.long, device=device)&#91;:, None&#93;
    memory_position = torch.arange(key_length, dtype=torch.long, device=device)&#91;None, :&#93;
    # max_seq_len, nh
    relative_position = memory_position - context_position
    relative_position_bucket = self._relative_position_bucket(
        relative_position,  # shape (query_length, key_length)
        bidirectional=(not self.is_decoder),
        num_buckets=self.relative_attention_num_buckets,
        max_distance=self.relative_attention_max_distance,
    )
    values = self.relative_attention_bias(relative_position_bucket)  # shape (query_length, key_length, num_heads)
    x = values.permute(&#91;2, 0, 1&#93;).unsqueeze(0)  # shape (1, num_heads, query_length, key_length)
    return x</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5Attention.forward"><code>fastvideo.models.encoders.t5.T5Attention.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, attention_mask: torch.Tensor, attn_metadata: AttentionMetadata | None = None) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    hidden_states: torch.Tensor,  # (num_tokens, d_model)
    attention_mask: torch.Tensor,
    attn_metadata: AttentionMetadata | None = None,
) -&gt; torch.Tensor:
    bs, seq_len, _ = hidden_states.shape
    num_seqs = bs
    n, c = self.n_heads, self.key_value_proj_dim
    qkv, _ = self.qkv_proj(hidden_states)
    # Projection of &#x27;own&#x27; hidden state (self-attention). No GQA here.
    q, k, v = qkv.split(self.inner_dim, dim=-1)
    q = q.reshape(bs, seq_len, n, c)
    k = k.reshape(bs, seq_len, n, c)
    v = v.reshape(bs, seq_len, n, c)

    assert attn_metadata is not None
    attn_bias = attn_metadata.attn_bias
    # Not compatible with CP here (as all encoder-decoder models),
    # as it assumes homogeneous batch (prefills or decodes).
    if self.has_relative_attention_bias:
        # Self-attention. Compute T5 relative positional encoding.
        # The bias term is computed on longest sequence in batch. Biases
        # for shorter sequences are slices of the longest.
        assert self.attn_type == AttentionType.ENCODER
        attn_bias = self.compute_bias(seq_len, seq_len).repeat(num_seqs, 1, 1, 1)
        attn_metadata.attn_bias = attn_bias
    else:
        # Encoder/Decoder Self-Attention Layer, attn bias already cached.
        assert attn_bias is not None

    from fastvideo.platforms import current_platform

    if attention_mask is not None:
        attention_mask = (attention_mask.view(bs, 1, 1, -1)
                          if attention_mask.ndim == 2 else attention_mask.unsqueeze(1))
        mask_val = (-1e4 if current_platform.is_mps() else torch.finfo(q.dtype).min)
        attn_bias.masked_fill_(attention_mask == 0, mask_val)

    if get_tp_world_size() &gt; 1:
        rank = get_tp_rank()
        attn_bias = attn_bias&#91;:, rank * self.n_heads:(rank + 1) * self.n_heads, :, :&#93;
    attn_output = self.attn(q, k, v, attn_bias)
    output, _ = self.o(attn_output)
    return output</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5LayerSelfAttention"><code>fastvideo.models.encoders.t5.T5LayerSelfAttention</code></h2>
<pre class="doc-signature"><code>T5LayerSelfAttention(config, has_relative_attention_bias = False, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>


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

    def __init__(
        self,
        config,
        has_relative_attention_bias=False,
        quant_config: QuantizationConfig | None = None,
        prefix: str = &quot;&quot;,
    ):
        super().__init__()
        self.SelfAttention = T5Attention(
            config,
            AttentionType.DECODER if &quot;decoder&quot; in prefix else AttentionType.ENCODER,
            has_relative_attention_bias=has_relative_attention_bias,
            quant_config=quant_config,
            prefix=f&quot;&#123;prefix&#125;.SelfAttention&quot;,
        )
        self.layer_norm = RMSNorm(config.d_model, eps=config.layer_norm_epsilon)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor,
        attn_metadata: AttentionMetadata | None = None,
    ) -&gt; torch.Tensor:
        normed_hidden_states = self.layer_norm(hidden_states)
        attention_output = self.SelfAttention(
            hidden_states=normed_hidden_states,
            attention_mask=attention_mask,
            attn_metadata=attn_metadata,
        )
        hidden_states = hidden_states + attention_output
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5LayerSelfAttention.forward"><code>fastvideo.models.encoders.t5.T5LayerSelfAttention.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, attention_mask: torch.Tensor, attn_metadata: AttentionMetadata | None = None) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    hidden_states: torch.Tensor,
    attention_mask: torch.Tensor,
    attn_metadata: AttentionMetadata | None = None,
) -&gt; torch.Tensor:
    normed_hidden_states = self.layer_norm(hidden_states)
    attention_output = self.SelfAttention(
        hidden_states=normed_hidden_states,
        attention_mask=attention_mask,
        attn_metadata=attn_metadata,
    )
    hidden_states = hidden_states + attention_output
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5LayerCrossAttention"><code>fastvideo.models.encoders.t5.T5LayerCrossAttention</code></h2>
<pre class="doc-signature"><code>T5LayerCrossAttention(config, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>


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

    def __init__(
        self,
        config,
        quant_config: QuantizationConfig | None = None,
        prefix: str = &quot;&quot;,
    ):
        super().__init__()
        self.EncDecAttention = T5Attention(
            config,
            AttentionType.ENCODER_DECODER,
            has_relative_attention_bias=False,
            quant_config=quant_config,
            prefix=f&quot;&#123;prefix&#125;.EncDecAttention&quot;,
        )
        self.layer_norm = RMSNorm(config.d_model, eps=config.layer_norm_epsilon)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attn_metadata: AttentionMetadata | None = None,
    ) -&gt; torch.Tensor:
        normed_hidden_states = self.layer_norm(hidden_states)
        attention_output = self.EncDecAttention(
            hidden_states=normed_hidden_states,
            attn_metadata=attn_metadata,
        )
        hidden_states = hidden_states + attention_output
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5LayerCrossAttention.forward"><code>fastvideo.models.encoders.t5.T5LayerCrossAttention.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, attn_metadata: AttentionMetadata | None = None) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    hidden_states: torch.Tensor,
    attn_metadata: AttentionMetadata | None = None,
) -&gt; torch.Tensor:
    normed_hidden_states = self.layer_norm(hidden_states)
    attention_output = self.EncDecAttention(
        hidden_states=normed_hidden_states,
        attn_metadata=attn_metadata,
    )
    hidden_states = hidden_states + attention_output
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5Block"><code>fastvideo.models.encoders.t5.T5Block</code></h2>
<pre class="doc-signature"><code>T5Block(config: T5Config, is_decoder: bool, has_relative_attention_bias = False, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;)</code></pre>


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

    def __init__(
        self,
        config: T5Config,
        is_decoder: bool,
        has_relative_attention_bias=False,
        quant_config: QuantizationConfig | None = None,
        prefix: str = &quot;&quot;,
    ):
        super().__init__()
        self.is_decoder = is_decoder
        self.layer = nn.ModuleList()
        self.layer.append(
            T5LayerSelfAttention(
                config,
                has_relative_attention_bias=has_relative_attention_bias,
                quant_config=quant_config,
                prefix=f&quot;&#123;prefix&#125;.self_attn&quot;,
            ))

        if self.is_decoder:
            self.layer.append(T5LayerCrossAttention(
                config,
                quant_config=quant_config,
                prefix=f&quot;&#123;prefix&#125;.cross_attn&quot;,
            ))

        self.layer.append(T5LayerFF(config, quant_config=quant_config))

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor,
        attn_metadata: AttentionMetadata | None = None,
    ) -&gt; torch.Tensor:
        hidden_states = self.layer&#91;0&#93;(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            attn_metadata=attn_metadata,
        )
        if self.is_decoder:
            hidden_states = self.layer&#91;1&#93;(hidden_states=hidden_states, attn_metadata=attn_metadata)

            # Apply Feed Forward layer
            hidden_states = self.layer&#91;2&#93;(hidden_states)
        else:
            hidden_states = self.layer&#91;1&#93;(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5Block.forward"><code>fastvideo.models.encoders.t5.T5Block.forward</code></h3>
<pre class="doc-signature"><code>forward(hidden_states: torch.Tensor, attention_mask: torch.Tensor, attn_metadata: AttentionMetadata | None = None) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    hidden_states: torch.Tensor,
    attention_mask: torch.Tensor,
    attn_metadata: AttentionMetadata | None = None,
) -&gt; torch.Tensor:
    hidden_states = self.layer&#91;0&#93;(
        hidden_states=hidden_states,
        attention_mask=attention_mask,
        attn_metadata=attn_metadata,
    )
    if self.is_decoder:
        hidden_states = self.layer&#91;1&#93;(hidden_states=hidden_states, attn_metadata=attn_metadata)

        # Apply Feed Forward layer
        hidden_states = self.layer&#91;2&#93;(hidden_states)
    else:
        hidden_states = self.layer&#91;1&#93;(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5Stack"><code>fastvideo.models.encoders.t5.T5Stack</code></h2>
<pre class="doc-signature"><code>T5Stack(config: T5Config, is_decoder: bool, n_layers: int, embed_tokens = None, quant_config: QuantizationConfig | None = None, prefix: str = &#x27;&#x27;, is_umt5: bool = False)</code></pre>


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

    def __init__(
        self,
        config: T5Config,
        is_decoder: bool,
        n_layers: int,
        embed_tokens=None,
        quant_config: QuantizationConfig | None = None,
        prefix: str = &quot;&quot;,
        is_umt5: bool = False,
    ):
        super().__init__()
        self.embed_tokens = embed_tokens
        self.is_umt5 = is_umt5
        if is_umt5:
            self.block = nn.ModuleList(&#91;
                T5Block(
                    config,
                    is_decoder=is_decoder,
                    has_relative_attention_bias=True,
                    quant_config=quant_config,
                    prefix=f&quot;&#123;prefix&#125;.blocks.&#123;i&#125;&quot;,
                ) for i in range(n_layers)
            &#93;)
        else:
            # Only the first block has relative positional encoding.
            self.block = nn.ModuleList(&#91;
                T5Block(
                    config,
                    is_decoder=is_decoder,
                    has_relative_attention_bias=i == 0,
                    quant_config=quant_config,
                    prefix=f&quot;&#123;prefix&#125;.blocks.&#123;i&#125;&quot;,
                ) for i in range(n_layers)
            &#93;)
        self.final_layer_norm = RMSNorm(config.d_model, eps=config.layer_norm_epsilon)

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: torch.Tensor,
        attn_metadata: AttentionMetadata,
    ) -&gt; torch.Tensor:
        hidden_states = self.embed_tokens(input_ids)

        for idx, block in enumerate(self.block):
            hidden_states = block(
                hidden_states=hidden_states,
                attention_mask=attention_mask,
                attn_metadata=attn_metadata,
            )
        hidden_states = self.final_layer_norm(hidden_states)
        return hidden_states</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5Stack.forward"><code>fastvideo.models.encoders.t5.T5Stack.forward</code></h3>
<pre class="doc-signature"><code>forward(input_ids: torch.Tensor, attention_mask: torch.Tensor, attn_metadata: AttentionMetadata) -&gt; torch.Tensor</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    input_ids: torch.Tensor,
    attention_mask: torch.Tensor,
    attn_metadata: AttentionMetadata,
) -&gt; torch.Tensor:
    hidden_states = self.embed_tokens(input_ids)

    for idx, block in enumerate(self.block):
        hidden_states = block(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            attn_metadata=attn_metadata,
        )
    hidden_states = self.final_layer_norm(hidden_states)
    return hidden_states</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.T5EncoderModel"><code>fastvideo.models.encoders.t5.T5EncoderModel</code></h2>
<pre class="doc-signature"><code>T5EncoderModel(config: T5Config, prefix: str = &#x27;&#x27;)</code></pre>


<details><summary>Source</summary><pre><code>class T5EncoderModel(TextEncoder):

    def __init__(self, config: T5Config, prefix: str = &quot;&quot;):
        super().__init__(config)

        self.shared = VocabParallelEmbedding(
            config.vocab_size,
            config.d_model,
            org_num_embeddings=config.vocab_size,
        )

        self.encoder = T5Stack(
            config,
            False,
            config.num_layers,
            self.shared,
            quant_config=config.quant_config,
            prefix=f&quot;&#123;prefix&#125;.encoder&quot;,
            is_umt5=False,
        )

    def get_input_embeddings(self):
        return self.shared

    def forward(
        self,
        input_ids: torch.Tensor | None,
        position_ids: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        inputs_embeds: torch.Tensor | None = None,
        output_hidden_states: bool | None = None,
        **kwargs,
    ) -&gt; BaseEncoderOutput:
        attn_metadata = AttentionMetadata(None)
        hidden_states = self.encoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            attn_metadata=attn_metadata,
        )

        return BaseEncoderOutput(
            last_hidden_state=hidden_states,
            attention_mask=attention_mask,
        )

    def load_weights(self, weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;:
        stacked_params_mapping = &#91;
            # (param_name, shard_name, shard_id)
            (&quot;.qkv_proj&quot;, &quot;.q&quot;, &quot;q&quot;),
            (&quot;.qkv_proj&quot;, &quot;.k&quot;, &quot;k&quot;),
            (&quot;.qkv_proj&quot;, &quot;.v&quot;, &quot;v&quot;),
        &#93;
        params_dict = dict(self.named_parameters())
        loaded_params: set&#91;str&#93; = set()
        for name, loaded_weight in weights:
            loaded = False
            if &quot;decoder&quot; in name or &quot;lm_head&quot; in name:
                continue
            for param_name, weight_name, shard_id in stacked_params_mapping:
                if weight_name not in name:
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                    continue

                if name not in params_dict:
                    continue

                param = params_dict&#91;name&#93;
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                loaded = True
                break
            if not loaded:
                # Skip loading extra bias for GPTQ models.
                if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                    continue

                if name not in params_dict:
                    continue

                param = params_dict&#91;name&#93;
                weight_loader = getattr(param, &quot;weight_loader&quot;, default_weight_loader)
                weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5EncoderModel.get_input_embeddings"><code>fastvideo.models.encoders.t5.T5EncoderModel.get_input_embeddings</code></h3>
<pre class="doc-signature"><code>get_input_embeddings()</code></pre>

<details><summary>Source</summary><pre><code>def get_input_embeddings(self):
    return self.shared</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5EncoderModel.forward"><code>fastvideo.models.encoders.t5.T5EncoderModel.forward</code></h3>
<pre class="doc-signature"><code>forward(input_ids: torch.Tensor | None, position_ids: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, inputs_embeds: torch.Tensor | None = None, output_hidden_states: bool | None = None, **kwargs) -&gt; BaseEncoderOutput</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    input_ids: torch.Tensor | None,
    position_ids: torch.Tensor | None = None,
    attention_mask: torch.Tensor | None = None,
    inputs_embeds: torch.Tensor | None = None,
    output_hidden_states: bool | None = None,
    **kwargs,
) -&gt; BaseEncoderOutput:
    attn_metadata = AttentionMetadata(None)
    hidden_states = self.encoder(
        input_ids=input_ids,
        attention_mask=attention_mask,
        attn_metadata=attn_metadata,
    )

    return BaseEncoderOutput(
        last_hidden_state=hidden_states,
        attention_mask=attention_mask,
    )</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.T5EncoderModel.load_weights"><code>fastvideo.models.encoders.t5.T5EncoderModel.load_weights</code></h3>
<pre class="doc-signature"><code>load_weights(weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;</code></pre>

<details><summary>Source</summary><pre><code>def load_weights(self, weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;:
    stacked_params_mapping = &#91;
        # (param_name, shard_name, shard_id)
        (&quot;.qkv_proj&quot;, &quot;.q&quot;, &quot;q&quot;),
        (&quot;.qkv_proj&quot;, &quot;.k&quot;, &quot;k&quot;),
        (&quot;.qkv_proj&quot;, &quot;.v&quot;, &quot;v&quot;),
    &#93;
    params_dict = dict(self.named_parameters())
    loaded_params: set&#91;str&#93; = set()
    for name, loaded_weight in weights:
        loaded = False
        if &quot;decoder&quot; in name or &quot;lm_head&quot; in name:
            continue
        for param_name, weight_name, shard_id in stacked_params_mapping:
            if weight_name not in name:
                continue
            name = name.replace(weight_name, param_name)
            # Skip loading extra bias for GPTQ models.
            if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                continue

            if name not in params_dict:
                continue

            param = params_dict&#91;name&#93;
            weight_loader = param.weight_loader
            weight_loader(param, loaded_weight, shard_id)
            loaded = True
            break
        if not loaded:
            # Skip loading extra bias for GPTQ models.
            if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                continue

            if name not in params_dict:
                continue

            param = params_dict&#91;name&#93;
            weight_loader = getattr(param, &quot;weight_loader&quot;, default_weight_loader)
            weight_loader(param, loaded_weight)
        loaded_params.add(name)
    return loaded_params</code></pre></details>
<h2 id="fastvideo.models.encoders.t5.UMT5EncoderModel"><code>fastvideo.models.encoders.t5.UMT5EncoderModel</code></h2>
<pre class="doc-signature"><code>UMT5EncoderModel(config: T5Config, prefix: str = &#x27;&#x27;)</code></pre>


<details><summary>Source</summary><pre><code>class UMT5EncoderModel(TextEncoder):

    def __init__(self, config: T5Config, prefix: str = &quot;&quot;):
        super().__init__(config)

        self.shared = VocabParallelEmbedding(
            config.vocab_size,
            config.d_model,
            org_num_embeddings=config.vocab_size,
        )

        self.encoder = T5Stack(
            config,
            False,
            config.num_layers,
            self.shared,
            quant_config=config.quant_config,
            prefix=f&quot;&#123;prefix&#125;.encoder&quot;,
            is_umt5=True,
        )

    def get_input_embeddings(self):
        return self.shared

    def forward(
        self,
        input_ids: torch.Tensor | None,
        position_ids: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        inputs_embeds: torch.Tensor | None = None,
        output_hidden_states: bool | None = None,
        **kwargs,
    ) -&gt; BaseEncoderOutput:
        attn_metadata = AttentionMetadata(None)
        hidden_states = self.encoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            attn_metadata=attn_metadata,
        )

        return BaseEncoderOutput(
            last_hidden_state=hidden_states,
            attention_mask=attention_mask,
        )

    def load_weights(self, weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;:
        params_dict = dict(self.named_parameters())
        loaded_params: set&#91;str&#93; = set()
        for name, loaded_weight in weights:
            loaded = False
            if &quot;decoder&quot; in name or &quot;lm_head&quot; in name:
                continue
            for (
                    param_name,
                    weight_name,
                    shard_id,
            ) in self.config.arch_config.stacked_params_mapping:
                if weight_name not in name:
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                    continue

                if name not in params_dict:
                    continue

                param = params_dict&#91;name&#93;
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                loaded = True
                break
            if not loaded:
                # Skip loading extra bias for GPTQ models.
                if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                    continue

                if name not in params_dict:
                    continue

                param = params_dict&#91;name&#93;
                weight_loader = getattr(param, &quot;weight_loader&quot;, default_weight_loader)
                weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.UMT5EncoderModel.get_input_embeddings"><code>fastvideo.models.encoders.t5.UMT5EncoderModel.get_input_embeddings</code></h3>
<pre class="doc-signature"><code>get_input_embeddings()</code></pre>

<details><summary>Source</summary><pre><code>def get_input_embeddings(self):
    return self.shared</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.UMT5EncoderModel.forward"><code>fastvideo.models.encoders.t5.UMT5EncoderModel.forward</code></h3>
<pre class="doc-signature"><code>forward(input_ids: torch.Tensor | None, position_ids: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, inputs_embeds: torch.Tensor | None = None, output_hidden_states: bool | None = None, **kwargs) -&gt; BaseEncoderOutput</code></pre>

<details><summary>Source</summary><pre><code>def forward(
    self,
    input_ids: torch.Tensor | None,
    position_ids: torch.Tensor | None = None,
    attention_mask: torch.Tensor | None = None,
    inputs_embeds: torch.Tensor | None = None,
    output_hidden_states: bool | None = None,
    **kwargs,
) -&gt; BaseEncoderOutput:
    attn_metadata = AttentionMetadata(None)
    hidden_states = self.encoder(
        input_ids=input_ids,
        attention_mask=attention_mask,
        attn_metadata=attn_metadata,
    )

    return BaseEncoderOutput(
        last_hidden_state=hidden_states,
        attention_mask=attention_mask,
    )</code></pre></details>
<h3 id="fastvideo.models.encoders.t5.UMT5EncoderModel.load_weights"><code>fastvideo.models.encoders.t5.UMT5EncoderModel.load_weights</code></h3>
<pre class="doc-signature"><code>load_weights(weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;</code></pre>

<details><summary>Source</summary><pre><code>def load_weights(self, weights: Iterable&#91;tuple&#91;str, torch.Tensor&#93;&#93;) -&gt; set&#91;str&#93;:
    params_dict = dict(self.named_parameters())
    loaded_params: set&#91;str&#93; = set()
    for name, loaded_weight in weights:
        loaded = False
        if &quot;decoder&quot; in name or &quot;lm_head&quot; in name:
            continue
        for (
                param_name,
                weight_name,
                shard_id,
        ) in self.config.arch_config.stacked_params_mapping:
            if weight_name not in name:
                continue
            name = name.replace(weight_name, param_name)
            # Skip loading extra bias for GPTQ models.
            if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                continue

            if name not in params_dict:
                continue

            param = params_dict&#91;name&#93;
            weight_loader = param.weight_loader
            weight_loader(param, loaded_weight, shard_id)
            loaded = True
            break
        if not loaded:
            # Skip loading extra bias for GPTQ models.
            if name.endswith(&quot;.bias&quot;) and name not in params_dict:
                continue

            if name not in params_dict:
                continue

            param = params_dict&#91;name&#93;
            weight_loader = getattr(param, &quot;weight_loader&quot;, default_weight_loader)
            weight_loader(param, loaded_weight)
        loaded_params.add(name)
    return loaded_params</code></pre></details>
</div>
