---
title: minimax_h3_vsa
---

<div class="python-reference">
<a id="fastvideo.mlx_runtime.minimax_h3_vsa-classes"></a>
<a id="fastvideo.mlx_runtime.minimax_h3_vsa-functions"></a>
<a id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAStats-functions"></a>
<a id="fastvideo.mlx_runtime.minimax_h3_vsa"></a>
<p>MiniMax H3 Video Sparse Attention for the native MLX runtime.</p>
<p>Ports the packed-sequence VSA-H3 contract from
<code>fastvideo/attention/backends/video_sparse_attn_h3.py</code>:</p>
<ul>
<li>Tiles are <code>[segment-pure prefix chunks] + [3D video tiles]</code>.</li>
<li>Tile sizes 64 <code>(4, 4, 4)</code>, 128 <code>(4, 4, 8)</code> and 256 <code>(4, 8, 8)</code>.</li>
<li><code>p2_multi_region</code> Ref2VA policy: every reference VIDEO is its own sparse
  region with its own top-k at <code>ref_keep_rate</code> (image/audio/text rows stay
  dense prefix), as in the CUDA backend's <code>_build_block_mask</code>.</li>
<li>Per-head pooled Q/K scoring and top-k routing.</li>
<li>Prefix queries are always dense; prefix keys are <code>exempt</code> (always kept)
  or <code>compete</code> (FLOP-matched top-k).</li>
<li>Optional dense-first steps and per-layer dense overrides.</li>
<li>Trained <code>to_gate_compress</code> pooled-compression branch.</li>
</ul>
<p>Execution backends:</p>
<ul>
<li><strong>reference</strong> — grouped gather plus batched <code>mx.fast.scaled_dot_product_attention</code>.
  Correctness baseline; <code>auto</code> for tiles other than 128 and <code>impl="reference"</code>.</li>
<li><strong>simd</strong> — flash-style SIMD-group 8x8 matrix operations over the reference tile
  map for tile sizes 64 and 128 and head dimension 128. Unsupported shapes and kernel
  failures fall back to the reference backend.</li>
</ul>
<p>Dense fused SDPA remains the default when VSA is disabled, the geometry is
unsupported, or a dense-only checkpoint is loaded.</p>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.init_logger"><code>fastvideo.mlx_runtime.minimax_h3_vsa.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.mlx_runtime.minimax_h3_vsa.validate_ref_policy"><code>fastvideo.mlx_runtime.minimax_h3_vsa.validate_ref_policy</code></h2>
<pre class="doc-signature"><code>validate_ref_policy(ref_policy: str | None, ref_keep_rate: float | None) -&gt; None</code></pre>
<p><code>p2_multi_region</code> needs a keep rate in (0, 1]; no policy takes no keep rate.</p>
<details><summary>Source</summary><pre><code>def validate_ref_policy(ref_policy: str | None, ref_keep_rate: float | None) -&gt; None:
    &quot;&quot;&quot;``p2_multi_region`` needs a keep rate in (0, 1&#93;; no policy takes no keep rate.&quot;&quot;&quot;
    if ref_policy is None:
        if ref_keep_rate is not None:
            raise ValueError(&quot;VSA ref_keep_rate needs ref_policy=&#x27;p2_multi_region&#x27;.&quot;)
        return
    if ref_policy not in VSA_REF_POLICIES:
        raise ValueError(f&quot;VSA ref_policy must be one of &#123;VSA_REF_POLICIES&#125; or None, got &#123;ref_policy!r&#125;.&quot;)
    if (isinstance(ref_keep_rate, bool) or not isinstance(ref_keep_rate, int | float)
            or not math.isfinite(ref_keep_rate) or not 0.0 &lt; float(ref_keep_rate) &lt;= 1.0):
        raise ValueError(f&quot;VSA ref_keep_rate must be in (0, 1&#93; for &#123;ref_policy&#125;, got &#123;ref_keep_rate!r&#125;.&quot;)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.DenseOnlyVSACheckpointError"><code>fastvideo.mlx_runtime.minimax_h3_vsa.DenseOnlyVSACheckpointError</code></h2>
<pre class="doc-signature"><code>DenseOnlyVSACheckpointError()</code></pre>
<p>VSA was requested for a checkpoint that dropped the gate weights.</p>
<details><summary>Source</summary><pre><code>class DenseOnlyVSACheckpointError(ValueError):
    &quot;&quot;&quot;VSA was requested for a checkpoint that dropped the gate weights.&quot;&quot;&quot;</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig</code></h2>
<pre class="doc-signature"><code>MiniMaxH3VSAConfig(enabled: bool = False, sparsity: float = 0.9, tile_size: int = 64, prefix_mode: PrefixMode = &#x27;exempt&#x27;, dense_first_n_steps: int = 0, dense_layers: tuple&#91;int, ...&#93; = (), impl: VSAImpl = &#x27;auto&#x27;, ref_policy: str | None = None, ref_keep_rate: float | None = None)</code></pre>
<p>Runtime VSA knobs. Defaults preserve dense MLX H3 behavior.</p>

<details><summary>Source</summary><pre><code>@dataclass(frozen=True)
class MiniMaxH3VSAConfig:
    &quot;&quot;&quot;Runtime VSA knobs. Defaults preserve dense MLX H3 behavior.&quot;&quot;&quot;

    enabled: bool = False
    sparsity: float = 0.9
    tile_size: int = 64
    prefix_mode: PrefixMode = &quot;exempt&quot;
    dense_first_n_steps: int = 0
    dense_layers: tuple&#91;int, ...&#93; = ()
    impl: VSAImpl = &quot;auto&quot;
    # ``p2_multi_region`` makes each reference video its own sparse region that
    # keeps ``ref_keep_rate`` of its tiles; None keeps references dense prefix.
    ref_policy: str | None = None
    ref_keep_rate: float | None = None

    def __post_init__(self) -&gt; None:
        validate_ref_policy(self.ref_policy, self.ref_keep_rate)
        if not 0.0 &lt;= self.sparsity &lt; 1.0:
            raise ValueError(f&quot;VSA sparsity must be in &#91;0, 1), got &#123;self.sparsity&#125;.&quot;)
        if self.tile_size not in VSA_H3_TILE_SHAPES:
            raise ValueError(f&quot;VSA tile_size must be one of &#123;sorted(VSA_H3_TILE_SHAPES)&#125;, got &#123;self.tile_size&#125;.&quot;)
        if self.prefix_mode not in VSA_PREFIX_MODES:
            raise ValueError(f&quot;VSA prefix_mode must be one of &#123;VSA_PREFIX_MODES&#125;, got &#123;self.prefix_mode!r&#125;.&quot;)
        if self.impl not in VSA_IMPLS:
            raise ValueError(f&quot;VSA impl must be one of &#123;VSA_IMPLS&#125;, got &#123;self.impl!r&#125;.&quot;)
        if self.dense_first_n_steps &lt; 0:
            raise ValueError(f&quot;vsa_dense_first_n_steps must be &gt;= 0, got &#123;self.dense_first_n_steps&#125;.&quot;)
        if isinstance(self.dense_layers, str) or any(
                not isinstance(layer, Integral) or isinstance(layer, bool) or layer &lt; 0 for layer in self.dense_layers):
            raise ValueError(&quot;VSA dense_layers must be a sequence of non-negative integer indices.&quot;)
        object.__setattr__(self, &quot;dense_layers&quot;, tuple(int(layer) for layer in self.dense_layers))

    @property
    def exempt(self) -&gt; bool:
        return self.prefix_mode == &quot;exempt&quot;

    @property
    def effective_ref_keep_rate(self) -&gt; float | None:
        &quot;&quot;&quot;The per-reference-video keep rate, or None when references stay dense.&quot;&quot;&quot;
        return self.ref_keep_rate if self.ref_policy == &quot;p2_multi_region&quot; else None

    def layer_sparsity(self, layer_idx: int, step_index: int) -&gt; float:
        if not self.enabled:
            return 0.0
        if step_index &lt; self.dense_first_n_steps:
            return 0.0
        if layer_idx in self.dense_layers:
            return 0.0
        return self.sparsity</code></pre></details>
<h3 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig.effective_ref_keep_rate"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig.effective_ref_keep_rate</code></h3>
<pre class="doc-signature"><code>effective_ref_keep_rate: float | None</code></pre>
<p>The per-reference-video keep rate, or None when references stay dense.</p>
<details><summary>Source</summary><pre><code>def effective_ref_keep_rate(self) -&gt; float | None:
    &quot;&quot;&quot;The per-reference-video keep rate, or None when references stay dense.&quot;&quot;&quot;
    return self.ref_keep_rate if self.ref_policy == &quot;p2_multi_region&quot; else None</code></pre></details>
<h3 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig.layer_sparsity"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAConfig.layer_sparsity</code></h3>
<pre class="doc-signature"><code>layer_sparsity(layer_idx: int, step_index: int) -&gt; float</code></pre>

<details><summary>Source</summary><pre><code>def layer_sparsity(self, layer_idx: int, step_index: int) -&gt; float:
    if not self.enabled:
        return 0.0
    if step_index &lt; self.dense_first_n_steps:
        return 0.0
    if layer_idx in self.dense_layers:
        return 0.0
    return self.sparsity</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry</code></h2>
<pre class="doc-signature"><code>MiniMaxH3VSAGeometry(prefix_segments: tuple&#91;int, ...&#93;, dit_seq_shape: tuple&#91;int, int, int&#93;, tile_shape: tuple&#91;int, int, int&#93;, tile_elems: int, total_seq_length: int, num_prefix_tiles: int, num_video_tiles: int, variable_block_sizes: np.ndarray, untile_combined_index: np.ndarray, tile_partition_indices: np.ndarray, video_tile_spans: tuple&#91;tuple&#91;int, int&#93;, ...&#93; = (), segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93; = (), reference_regions: tuple&#91;tuple&#91;int, int, int&#93;, ...&#93; = ())</code></pre>
<p>Packed-sequence tile map shared by routing, reference, and Metal paths.</p>

<details><summary>Source</summary><pre><code>@dataclass(frozen=True)
class MiniMaxH3VSAGeometry:
    &quot;&quot;&quot;Packed-sequence tile map shared by routing, reference, and Metal paths.&quot;&quot;&quot;

    prefix_segments: tuple&#91;int, ...&#93;
    dit_seq_shape: tuple&#91;int, int, int&#93;
    tile_shape: tuple&#91;int, int, int&#93;
    tile_elems: int
    total_seq_length: int
    num_prefix_tiles: int
    num_video_tiles: int
    variable_block_sizes: np.ndarray
    untile_combined_index: np.ndarray
    tile_partition_indices: np.ndarray
    # One &#91;start, end) tile range per sparse video region in packed order, the
    # generated video last. Tile numbering includes the dense prefix tiles.
    video_tile_spans: tuple&#91;tuple&#91;int, int&#93;, ...&#93; = ()
    segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93; = ()
    reference_regions: tuple&#91;tuple&#91;int, int, int&#93;, ...&#93; = ()

    def __post_init__(self) -&gt; None:
        if not self.video_tile_spans:
            object.__setattr__(self, &quot;video_tile_spans&quot;,
                               ((self.num_prefix_tiles, self.num_prefix_tiles + self.num_video_tiles), ))

    @property
    def dense_rows(self) -&gt; np.ndarray:
        &quot;&quot;&quot;Packed positions of the dense rows, in prefix-tile order.&quot;&quot;&quot;
        return self.tile_partition_indices&#91;:self.prefix_length&#93;

    @cached_property
    def dense_rows_lead(self) -&gt; bool:
        &quot;&quot;&quot;True when the dense rows are the first packed rows (no interleaved region).&quot;&quot;&quot;
        return bool(np.array_equal(self.dense_rows, np.arange(self.prefix_length)))

    @property
    def num_tiles(self) -&gt; int:
        return int(self.variable_block_sizes.shape&#91;0&#93;)

    @property
    def padded_length(self) -&gt; int:
        return self.num_tiles * self.tile_elems

    @property
    def prefix_length(self) -&gt; int:
        return int(sum(self.prefix_segments))

    @cached_property
    def tile_gather_index(self):
        import mlx.core as mx

        index = np.full(self.padded_length, self.total_seq_length, dtype=np.int32)
        index&#91;self.untile_combined_index&#93; = np.arange(self.total_seq_length, dtype=np.int32)
        return mx.array(index)

    @cached_property
    def prefix_gather_index(self):
        import mlx.core as mx

        index = np.full(self.num_prefix_tiles * self.tile_elems, self.prefix_length, dtype=np.int32)
        index&#91;self.untile_combined_index&#91;self.dense_rows&#93;&#93; = np.arange(self.prefix_length, dtype=np.int32)
        return mx.array(index)

    @cached_property
    def dense_row_index(self):
        import mlx.core as mx

        return mx.array(self.dense_rows.astype(np.int32))

    @cached_property
    def untile_index(self):
        import mlx.core as mx

        return mx.array(self.untile_combined_index, dtype=mx.int32)</code></pre></details>
<h3 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry.dense_rows"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry.dense_rows</code></h3>
<pre class="doc-signature"><code>dense_rows: np.ndarray</code></pre>
<p>Packed positions of the dense rows, in prefix-tile order.</p>
<details><summary>Source</summary><pre><code>def dense_rows(self) -&gt; np.ndarray:
    &quot;&quot;&quot;Packed positions of the dense rows, in prefix-tile order.&quot;&quot;&quot;
    return self.tile_partition_indices&#91;:self.prefix_length&#93;</code></pre></details>
<h3 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry.dense_rows_lead"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAGeometry.dense_rows_lead</code></h3>
<pre class="doc-signature"><code>dense_rows_lead: bool</code></pre>
<p>True when the dense rows are the first packed rows (no interleaved region).</p>
<details><summary>Source</summary><pre><code>def dense_rows_lead(self) -&gt; bool:
    &quot;&quot;&quot;True when the dense rows are the first packed rows (no interleaved region).&quot;&quot;&quot;
    return bool(np.array_equal(self.dense_rows, np.arange(self.prefix_length)))</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAStats"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAStats</code></h2>
<pre class="doc-signature"><code>MiniMaxH3VSAStats(configured_sparsity: float = 0.0, layer_sparsity: float = 0.0, tile_size: int = 64, prefix_mode: str = &#x27;exempt&#x27;, impl: str = &#x27;dense&#x27;, num_prefix_tiles: int = 0, num_video_tiles: int = 0, video_keep: float = 0.0, achieved_sparsity: float = 0.0, dense_fallback_reason: str | None = None, attention_calls: int = 0, sparse_calls: int = 0, impl_counts: dict&#91;str, int&#93; = dict(), fallback_reasons: list&#91;str&#93; = list())</code></pre>
<p>Filled during a sparse forward so the pipeline can report achieved sparsity.</p>

<details><summary>Source</summary><pre><code>@dataclass
class MiniMaxH3VSAStats:
    &quot;&quot;&quot;Filled during a sparse forward so the pipeline can report achieved sparsity.&quot;&quot;&quot;

    configured_sparsity: float = 0.0
    layer_sparsity: float = 0.0
    tile_size: int = 64
    prefix_mode: str = &quot;exempt&quot;
    impl: str = &quot;dense&quot;
    num_prefix_tiles: int = 0
    num_video_tiles: int = 0
    video_keep: float = 0.0
    achieved_sparsity: float = 0.0
    dense_fallback_reason: str | None = None
    attention_calls: int = 0
    sparse_calls: int = 0
    impl_counts: dict&#91;str, int&#93; = field(default_factory=dict)
    fallback_reasons: list&#91;str&#93; = field(default_factory=list)

    def record(self, call: MiniMaxH3VSAStats) -&gt; None:
        &quot;&quot;&quot;Aggregate equally sized video-query tile maps across blocks and steps.&quot;&quot;&quot;
        self.attention_calls += 1
        self.sparse_calls += int(call.layer_sparsity &gt; 0.0)
        self.impl_counts&#91;call.impl&#93; = self.impl_counts.get(call.impl, 0) + 1
        self.impl = next(iter(self.impl_counts)) if len(self.impl_counts) == 1 else &quot;mixed&quot;
        for name in (&quot;layer_sparsity&quot;, &quot;video_keep&quot;, &quot;achieved_sparsity&quot;):
            old = getattr(self, name)
            setattr(self, name, old + (getattr(call, name) - old) / self.attention_calls)
        self.num_prefix_tiles = call.num_prefix_tiles
        self.num_video_tiles = call.num_video_tiles
        if call.dense_fallback_reason and call.dense_fallback_reason not in self.fallback_reasons:
            self.fallback_reasons.append(call.dense_fallback_reason)
        self.dense_fallback_reason = &quot;; &quot;.join(self.fallback_reasons) or None</code></pre></details>
<h3 id="fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAStats.record"><code>fastvideo.mlx_runtime.minimax_h3_vsa.MiniMaxH3VSAStats.record</code></h3>
<pre class="doc-signature"><code>record(call: MiniMaxH3VSAStats) -&gt; None</code></pre>
<p>Aggregate equally sized video-query tile maps across blocks and steps.</p>
<details><summary>Source</summary><pre><code>def record(self, call: MiniMaxH3VSAStats) -&gt; None:
    &quot;&quot;&quot;Aggregate equally sized video-query tile maps across blocks and steps.&quot;&quot;&quot;
    self.attention_calls += 1
    self.sparse_calls += int(call.layer_sparsity &gt; 0.0)
    self.impl_counts&#91;call.impl&#93; = self.impl_counts.get(call.impl, 0) + 1
    self.impl = next(iter(self.impl_counts)) if len(self.impl_counts) == 1 else &quot;mixed&quot;
    for name in (&quot;layer_sparsity&quot;, &quot;video_keep&quot;, &quot;achieved_sparsity&quot;):
        old = getattr(self, name)
        setattr(self, name, old + (getattr(call, name) - old) / self.attention_calls)
    self.num_prefix_tiles = call.num_prefix_tiles
    self.num_video_tiles = call.num_video_tiles
    if call.dense_fallback_reason and call.dense_fallback_reason not in self.fallback_reasons:
        self.fallback_reasons.append(call.dense_fallback_reason)
    self.dense_fallback_reason = &quot;; &quot;.join(self.fallback_reasons) or None</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.vsa_gate_key"><code>fastvideo.mlx_runtime.minimax_h3_vsa.vsa_gate_key</code></h2>
<pre class="doc-signature"><code>vsa_gate_key(block_index: int) -&gt; str</code></pre>

<details><summary>Source</summary><pre><code>def vsa_gate_key(block_index: int) -&gt; str:
    return f&quot;transformer_blocks.&#123;block_index&#125;.&#123;VSA_GATE_KEY_SUFFIX&#125;&quot;</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.expected_vsa_gate_keys"><code>fastvideo.mlx_runtime.minimax_h3_vsa.expected_vsa_gate_keys</code></h2>
<pre class="doc-signature"><code>expected_vsa_gate_keys(num_layers: int) -&gt; tuple&#91;str, ...&#93;</code></pre>

<details><summary>Source</summary><pre><code>def expected_vsa_gate_keys(num_layers: int) -&gt; tuple&#91;str, ...&#93;:
    return tuple(vsa_gate_key(index) for index in range(num_layers))</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.is_vsa_gate_key"><code>fastvideo.mlx_runtime.minimax_h3_vsa.is_vsa_gate_key</code></h2>
<pre class="doc-signature"><code>is_vsa_gate_key(key: str) -&gt; bool</code></pre>

<details><summary>Source</summary><pre><code>def is_vsa_gate_key(key: str) -&gt; bool:
    return key.endswith(VSA_GATE_KEY_SUFFIX)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.dense_only_vsa_error"><code>fastvideo.mlx_runtime.minimax_h3_vsa.dense_only_vsa_error</code></h2>
<pre class="doc-signature"><code>dense_only_vsa_error(checkpoint_dir: str | Any) -&gt; DenseOnlyVSACheckpointError</code></pre>

<details><summary>Source</summary><pre><code>def dense_only_vsa_error(checkpoint_dir: str | Any) -&gt; DenseOnlyVSACheckpointError:
    return DenseOnlyVSACheckpointError(
        f&quot;VSA was requested but &#123;checkpoint_dir&#125; is a dense-only MLX H3 checkpoint &quot;
        f&quot;(no `&#123;VSA_GATE_KEY_SUFFIX&#125;` matrices / manifest vsa.capable). &quot;
        &quot;Reconvert with `--include-vsa`, for example:\n&quot;
        &quot;  python scripts/checkpoint_conversion/convert_minimax_h3_mlx.py \\\n&quot;
        &quot;    --model-root &lt;FastH3 transformer dir&gt; --out &lt;new dir&gt; --formats int6 --include-vsa&quot;)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.compute_topk"><code>fastvideo.mlx_runtime.minimax_h3_vsa.compute_topk</code></h2>
<pre class="doc-signature"><code>compute_topk(sparsity: float, num_blocks: int) -&gt; int</code></pre>
<p>Blocks to keep for a sparsity level, clamped to [1, num_blocks].</p>
<details><summary>Source</summary><pre><code>def compute_topk(sparsity: float, num_blocks: int) -&gt; int:
    &quot;&quot;&quot;Blocks to keep for a sparsity level, clamped to &#91;1, num_blocks&#93;.&quot;&quot;&quot;
    if num_blocks &lt;= 0:
        return 0
    return max(1, min(math.ceil((1.0 - sparsity) * num_blocks), num_blocks))</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.parse_dense_layers"><code>fastvideo.mlx_runtime.minimax_h3_vsa.parse_dense_layers</code></h2>
<pre class="doc-signature"><code>parse_dense_layers(value: str | None) -&gt; tuple&#91;int, ...&#93;</code></pre>

<details><summary>Source</summary><pre><code>def parse_dense_layers(value: str | None) -&gt; tuple&#91;int, ...&#93;:
    if value is None or value.strip() == &quot;&quot;:
        return ()
    layers = tuple(int(part.strip()) for part in value.split(&quot;,&quot;) if part.strip())
    if any(layer &lt; 0 for layer in layers):
        raise ValueError(f&quot;vsa dense layers must be non-negative, got &#123;value!r&#125;.&quot;)
    return layers</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.prefix_segments_from_layout"><code>fastvideo.mlx_runtime.minimax_h3_vsa.prefix_segments_from_layout</code></h2>
<pre class="doc-signature"><code>prefix_segments_from_layout(layout: Any, patch_size: tuple&#91;int, int, int&#93;) -&gt; tuple&#91;int, ...&#93;</code></pre>
<p>Segment sizes preceding the generated-video tail, matching the PyTorch stage.</p>
<p>Prefix tiles are chunked per segment, so a segment boundary must fall where
the packed rows change kind. A Ref2VA layout interleaves a video
reference's audio rows with the references themselves, so it is split per
reference from <code>layout.reference_segments</code>; T2VA/FL2VA keep the single
condition segment they have always had.</p>
<details><summary>Source</summary><pre><code>def prefix_segments_from_layout(layout: Any, patch_size: tuple&#91;int, int, int&#93;) -&gt; tuple&#91;int, ...&#93;:
    &quot;&quot;&quot;Segment sizes preceding the generated-video tail, matching the PyTorch stage.

    Prefix tiles are chunked per segment, so a segment boundary must fall where
    the packed rows change kind. A Ref2VA layout interleaves a video
    reference&#x27;s audio rows with the references themselves, so it is split per
    reference from ``layout.reference_segments``; T2VA/FL2VA keep the single
    condition segment they have always had.
    &quot;&quot;&quot;
    n_text = int(layout.text_indices.shape&#91;0&#93;)
    n_video = ((layout.num_video_latent_frames // patch_size&#91;0&#93;) * (layout.latent_height // patch_size&#91;1&#93;) *
               (layout.latent_width // patch_size&#91;2&#93;))
    reference_segments = getattr(layout, &quot;reference_segments&quot;, ())
    if reference_segments:
        # Packed order is &#91;text | ordered reference segments | target audio |
        # target video&#93;; everything before the video tail is prefix.
        n_target_audio = int(layout.audio_indices.shape&#91;0&#93;) - int(layout.num_condition_audio_rows)
        segments = (n_text, *(int(rows) for _, rows, _ in reference_segments), n_target_audio)
        prefix_length = sum(segments)
    else:
        n_cond = int(layout.num_condition_video_rows)
        n_audio = int(layout.audio_indices.shape&#91;0&#93;)
        segments = (n_text, n_cond, n_audio)
        prefix_length = n_text + n_cond + n_audio
    if prefix_length + n_video != int(layout.sequence_length):
        raise ValueError(&quot;VSA-H3 supports the standard &#91;text|cond|audio|video&#93; packing only; &quot;
                         f&quot;segments &#123;segments&#125; + video &#123;n_video&#125; do not sum to &quot;
                         f&quot;sequence length &#123;layout.sequence_length&#125;.&quot;)
    return tuple(segments)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.ref2va_vsa_segments_from_layout"><code>fastvideo.mlx_runtime.minimax_h3_vsa.ref2va_vsa_segments_from_layout</code></h2>
<pre class="doc-signature"><code>ref2va_vsa_segments_from_layout(layout: Any, patch_size: tuple&#91;int, int, int&#93;) -&gt; tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;</code></pre>
<p>Packed segments with every reference VIDEO as a sparse region (<code>p2_multi_region</code>).</p>
<p>Mirrors <code>_h3_vsa_ref2va_segments</code> in the CUDA denoising stage:
<code>[text | reference spans... | target audio | target video]</code> where each
reference video is a token grid and text, reference audio, image
references and the target audio are dense row counts.</p>
<details><summary>Source</summary><pre><code>def ref2va_vsa_segments_from_layout(
    layout: Any,
    patch_size: tuple&#91;int, int, int&#93;,
) -&gt; tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;:
    &quot;&quot;&quot;Packed segments with every reference VIDEO as a sparse region (``p2_multi_region``).

    Mirrors ``_h3_vsa_ref2va_segments`` in the CUDA denoising stage:
    ``&#91;text | reference spans... | target audio | target video&#93;`` where each
    reference video is a token grid and text, reference audio, image
    references and the target audio are dense row counts.
    &quot;&quot;&quot;
    reference_segments = getattr(layout, &quot;reference_segments&quot;, ())
    if not reference_segments:
        raise ValueError(&quot;Ref2VA VSA sparsification needs per-reference spans on the layout; &quot;
                         &quot;this layout carries none (T2VA/FL2VA packing).&quot;)
    cursor = int(layout.text_indices.shape&#91;0&#93;)
    segments: list&#91;int | tuple&#91;int, int, int&#93;&#93; = &#91;cursor&#93;
    for kind, rows, latent_shape in reference_segments:
        rows = int(rows)
        if kind == &quot;video&quot;:
            if any(int(axis) &lt;= 0 or int(axis) % patch for axis, patch in zip(latent_shape, patch_size, strict=True)):
                raise ValueError(f&quot;Reference video latent shape &#123;tuple(latent_shape)&#125; is not a positive multiple of &quot;
                                 f&quot;patch &#123;tuple(patch_size)&#125;.&quot;)
            grid = tuple(int(axis) // patch for axis, patch in zip(latent_shape, patch_size, strict=True))
            if math.prod(grid) != rows:
                raise ValueError(f&quot;Reference video span of &#123;rows&#125; rows does not match its grid &#123;grid&#125;.&quot;)
            segments.append(grid)  # type: ignore&#91;arg-type&#93;
        else:
            segments.append(rows)
        cursor += rows
    n_target_audio = int(layout.audio_indices.shape&#91;0&#93;) - int(layout.num_condition_audio_rows)
    segments.append(n_target_audio)
    cursor += n_target_audio
    target = dit_seq_shape_from_layout(layout, patch_size)
    segments.append(target)
    if cursor + math.prod(target) != int(layout.sequence_length):
        raise ValueError(f&quot;Ref2VA reference spans &#123;reference_segments&#125; + target segments do not tile the packed &quot;
                         f&quot;sequence: reached row &#123;cursor&#125; + video &#123;math.prod(target)&#125; != &#123;layout.sequence_length&#125;.&quot;)
    return tuple(segments)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.dit_seq_shape_from_layout"><code>fastvideo.mlx_runtime.minimax_h3_vsa.dit_seq_shape_from_layout</code></h2>
<pre class="doc-signature"><code>dit_seq_shape_from_layout(layout: Any, patch_size: tuple&#91;int, int, int&#93;) -&gt; tuple&#91;int, int, int&#93;</code></pre>

<details><summary>Source</summary><pre><code>def dit_seq_shape_from_layout(layout: Any, patch_size: tuple&#91;int, int, int&#93;) -&gt; tuple&#91;int, int, int&#93;:
    return (
        int(layout.num_video_latent_frames // patch_size&#91;0&#93;),
        int(layout.latent_height // patch_size&#91;1&#93;),
        int(layout.latent_width // patch_size&#91;2&#93;),
    )</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.validate_h3_tile_geometry"><code>fastvideo.mlx_runtime.minimax_h3_vsa.validate_h3_tile_geometry</code></h2>
<pre class="doc-signature"><code>validate_h3_tile_geometry(prefix_segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;, dit_seq_shape: tuple&#91;int, int, int&#93; | None, variable_block_sizes: np.ndarray, untile_combined_index: np.ndarray, tile_elems: int) -&gt; None</code></pre>

<details><summary>Source</summary><pre><code>def validate_h3_tile_geometry(
    prefix_segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;,
    dit_seq_shape: tuple&#91;int, int, int&#93; | None,
    variable_block_sizes: np.ndarray,
    untile_combined_index: np.ndarray,
    tile_elems: int,
) -&gt; None:
    total = _segments_total(prefix_segments) + (math.prod(dit_seq_shape) if dit_seq_shape is not None else 0)
    n_pad = int(variable_block_sizes.size) * tile_elems
    sizes_min = int(variable_block_sizes.min()) if variable_block_sizes.size else 0
    sizes_max = int(variable_block_sizes.max()) if variable_block_sizes.size else 0
    sizes_sum = int(variable_block_sizes.sum())
    if sizes_min &lt; 1 or sizes_max &gt; tile_elems or sizes_sum != total:
        raise ValueError(f&quot;VSA-H3 tile sizes out of bounds for prefix=&#123;prefix_segments&#125;, video=&#123;dit_seq_shape&#125;, &quot;
                         f&quot;tile_elems=&#123;tile_elems&#125;: min=&#123;sizes_min&#125;, max=&#123;sizes_max&#125;, sum=&#123;sizes_sum&#125;, &quot;
                         f&quot;expected sum=&#123;total&#125;.&quot;)
    if int(untile_combined_index.size) != total:
        raise ValueError(f&quot;VSA-H3 untile index has &#123;untile_combined_index.size&#125; entries for a packed &quot;
                         f&quot;sequence of &#123;total&#125; rows (prefix=&#123;prefix_segments&#125;, video=&#123;dit_seq_shape&#125;).&quot;)
    idx_min = int(untile_combined_index.min())
    idx_max = int(untile_combined_index.max())
    if idx_min &lt; 0 or idx_max &gt;= n_pad:
        raise ValueError(f&quot;VSA-H3 untile index is not an injective map into non-pad slots: range &quot;
                         f&quot;&#91;&#123;idx_min&#125;, &#123;idx_max&#125;&#93; vs padded length &#123;n_pad&#125; &quot;
                         f&quot;(prefix=&#123;prefix_segments&#125;, video=&#123;dit_seq_shape&#125;).&quot;)
    in_tile_offset = untile_combined_index % tile_elems
    maps_into_pad = bool((in_tile_offset &gt;= variable_block_sizes&#91;untile_combined_index // tile_elems&#93;).any())
    if maps_into_pad or int(np.unique(untile_combined_index).size) != total:
        raise ValueError(f&quot;VSA-H3 untile index is not an injective map into non-pad slots: &quot;
                         f&quot;pad-slot hit=&#123;maps_into_pad&#125; &quot;
                         f&quot;(prefix=&#123;prefix_segments&#125;, video=&#123;dit_seq_shape&#125;).&quot;)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.build_h3_tile_geometry"><code>fastvideo.mlx_runtime.minimax_h3_vsa.build_h3_tile_geometry</code></h2>
<pre class="doc-signature"><code>build_h3_tile_geometry(prefix_segments: tuple&#91;int, ...&#93;, dit_seq_shape: tuple&#91;int, int, int&#93;, tile_size: int = 64) -&gt; MiniMaxH3VSAGeometry</code></pre>
<p>Tile the packed sequence: segment-pure prefix chunks, then video tiles.</p>
<details><summary>Source</summary><pre><code>def build_h3_tile_geometry(
    prefix_segments: tuple&#91;int, ...&#93;,
    dit_seq_shape: tuple&#91;int, int, int&#93;,
    tile_size: int = 64,
) -&gt; MiniMaxH3VSAGeometry:
    &quot;&quot;&quot;Tile the packed sequence: segment-pure prefix chunks, then video tiles.&quot;&quot;&quot;
    return build_h3_segment_geometry((*prefix_segments, _grid(dit_seq_shape)), tile_size)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.build_h3_segment_geometry"><code>fastvideo.mlx_runtime.minimax_h3_vsa.build_h3_segment_geometry</code></h2>
<pre class="doc-signature"><code>build_h3_segment_geometry(segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;, tile_size: int = 64) -&gt; MiniMaxH3VSAGeometry</code></pre>
<p>Tile a packed sequence of interleaved dense segments and video regions.</p>
<p><code>segments</code> lists, in packed order, dense row counts (<code>int</code>) and video
token grids (<code>(t, h, w)</code>). Rows are permuted to <code>[dense chunks][region 0
tiles][region 1 tiles]...</code> exactly as the CUDA <code>_h3_segment_tile_geometry</code>
does; the last region is the generated video.</p>
<details><summary>Source</summary><pre><code>def build_h3_segment_geometry(
    segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;,
    tile_size: int = 64,
) -&gt; MiniMaxH3VSAGeometry:
    &quot;&quot;&quot;Tile a packed sequence of interleaved dense segments and video regions.

    ``segments`` lists, in packed order, dense row counts (``int``) and video
    token grids (``(t, h, w)``). Rows are permuted to ``&#91;dense chunks&#93;&#91;region 0
    tiles&#93;&#91;region 1 tiles&#93;...`` exactly as the CUDA ``_h3_segment_tile_geometry``
    does; the last region is the generated video.
    &quot;&quot;&quot;
    tile_shape = VSA_H3_TILE_SHAPES.get(int(tile_size))
    if tile_shape is None:
        raise ValueError(f&quot;VSA-H3 tile_size must be one of &#123;sorted(VSA_H3_TILE_SHAPES)&#125;, got &#123;tile_size!r&#125;&quot;)
    tile_elems = math.prod(tile_shape)
    dense_sizes: list&#91;int&#93; = &#91;&#93;
    dense_rows: list&#91;np.ndarray&#93; = &#91;&#93;
    regions: list&#91;tuple&#91;int, tuple&#91;int, int, int&#93;&#93;&#93; = &#91;&#93;
    kept: list&#91;int | tuple&#91;int, int, int&#93;&#93; = &#91;&#93;
    cursor = 0
    for segment in segments:
        if isinstance(segment, tuple):
            grid = tuple(int(axis) for axis in segment)
            if len(grid) != 3 or any(axis &lt;= 0 for axis in grid):
                raise ValueError(f&quot;VSA-H3 video axes must be positive, got &#123;segment&#125;.&quot;)
            regions.append((cursor, grid))  # type: ignore&#91;arg-type&#93;
            kept.append(grid)  # type: ignore&#91;arg-type&#93;
            cursor += math.prod(grid)
            continue
        rows = int(segment)
        if rows &lt;= 0:
            continue
        full, rem = divmod(rows, tile_elems)
        dense_sizes.extend(&#91;tile_elems&#93; * full)
        if rem:
            dense_sizes.append(rem)
        dense_rows.append(np.arange(cursor, cursor + rows, dtype=np.int64))
        kept.append(rows)
        cursor += rows
    if not regions:
        raise ValueError(&quot;VSA-H3 needs at least one video region.&quot;)
    num_prefix_tiles = len(dense_sizes)

    index_parts: list&#91;np.ndarray&#93; = &#91;&#93;
    size_parts: list&#91;np.ndarray&#93; = &#91;&#93;
    spans: list&#91;tuple&#91;int, int&#93;&#93; = &#91;&#93;
    tile_cursor = num_prefix_tiles
    for start, grid in regions:
        sizes = _video_tile_sizes(grid, tile_shape)
        index_parts.append(_video_tile_partition_indices(grid, tile_shape) + start)
        size_parts.append(sizes.astype(np.int64))
        spans.append((tile_cursor, tile_cursor + int(sizes.size)))
        tile_cursor += int(sizes.size)
    num_video_tiles = tile_cursor - num_prefix_tiles
    tile_partition_indices = np.concatenate(&#91;*dense_rows, *index_parts&#93;, axis=0)
    variable_block_sizes = np.concatenate(&#91;np.asarray(dense_sizes, dtype=np.int64), *size_parts&#93;, axis=0)
    non_pad_index = _non_pad_index(variable_block_sizes, tile_elems)
    untile_combined_index = non_pad_index&#91;np.argsort(tile_partition_indices, kind=&quot;stable&quot;)&#93;
    validate_h3_tile_geometry(tuple(kept), None, variable_block_sizes, untile_combined_index, tile_elems)
    prefix_segments = tuple(segment for segment in kept if not isinstance(segment, tuple))
    return MiniMaxH3VSAGeometry(
        prefix_segments=prefix_segments,  # type: ignore&#91;arg-type&#93;
        dit_seq_shape=regions&#91;-1&#93;&#91;1&#93;,
        tile_shape=tile_shape,
        tile_elems=tile_elems,
        total_seq_length=cursor,
        num_prefix_tiles=num_prefix_tiles,
        num_video_tiles=num_video_tiles,
        variable_block_sizes=variable_block_sizes,
        untile_combined_index=untile_combined_index,
        tile_partition_indices=tile_partition_indices,
        video_tile_spans=tuple(spans),
        segments=tuple(kept),
        reference_regions=tuple(grid for _, grid in regions&#91;:-1&#93;),
    )</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.token_tile_and_valid"><code>fastvideo.mlx_runtime.minimax_h3_vsa.token_tile_and_valid</code></h2>
<pre class="doc-signature"><code>token_tile_and_valid(variable_block_sizes: np.ndarray, tile_elems: int) -&gt; tuple&#91;np.ndarray, np.ndarray&#93;</code></pre>

<details><summary>Source</summary><pre><code>def token_tile_and_valid(variable_block_sizes: np.ndarray, tile_elems: int) -&gt; tuple&#91;np.ndarray, np.ndarray&#93;:
    token_tile = np.repeat(np.arange(variable_block_sizes.size, dtype=np.int64), tile_elems)
    token_valid = (np.arange(tile_elems, dtype=np.int64)&#91;None, :&#93; &lt; variable_block_sizes&#91;:, None&#93;).reshape(-1)
    return token_tile, token_valid</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.region_sparsities"><code>fastvideo.mlx_runtime.minimax_h3_vsa.region_sparsities</code></h2>
<pre class="doc-signature"><code>region_sparsities(num_regions: int, sparsity: float, ref_keep_rate: float | None) -&gt; tuple&#91;float, ...&#93;</code></pre>
<p>Per-region sparsity: reference videos keep <code>ref_keep_rate</code>, the target follows <code>sparsity</code>.</p>
<p>Mirrors <code>MiniMaxH3VSAMetadataBuilder.build</code>: a dense step (sparsity &lt;= 0)
keeps every region dense, whatever the reference keep rate.</p>
<details><summary>Source</summary><pre><code>def region_sparsities(num_regions: int, sparsity: float, ref_keep_rate: float | None) -&gt; tuple&#91;float, ...&#93;:
    &quot;&quot;&quot;Per-region sparsity: reference videos keep ``ref_keep_rate``, the target follows ``sparsity``.

    Mirrors ``MiniMaxH3VSAMetadataBuilder.build``: a dense step (sparsity &lt;= 0)
    keeps every region dense, whatever the reference keep rate.
    &quot;&quot;&quot;
    if num_regions &lt; 1:
        raise ValueError(&quot;VSA-H3 needs at least one video region.&quot;)
    if sparsity &lt;= 0.0:
        return (0.0, ) * num_regions
    if num_regions == 1:
        return (float(sparsity), )
    if ref_keep_rate is None:
        raise ValueError(f&quot;A VSA-H3 build with &#123;num_regions - 1&#125; reference-video region(s) needs ref_keep_rate.&quot;)
    return (1.0 - float(ref_keep_rate), ) * (num_regions - 1) + (float(sparsity), )</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.build_block_mask"><code>fastvideo.mlx_runtime.minimax_h3_vsa.build_block_mask</code></h2>
<pre class="doc-signature"><code>build_block_mask(scores: np.ndarray, num_prefix_tiles: int, num_video_tiles: int, sparsity: float, exempt: bool, spans: tuple&#91;tuple&#91;int, int&#93;, ...&#93; | None = None, span_sparsities: tuple&#91;float, ...&#93; | None = None) -&gt; np.ndarray</code></pre>
<p>scores: [..., n_tiles, n_tiles] -&gt; bool mask, same shape.</p>
<p>Mirrors <code>_build_block_mask</code> in the PyTorch H3 backend: every video query
keeps its own top-k of EACH video region (<code>spans</code> / <code>span_sparsities</code>).</p>
<details><summary>Source</summary><pre><code>def build_block_mask(
    scores: np.ndarray,
    num_prefix_tiles: int,
    num_video_tiles: int,
    sparsity: float,
    exempt: bool,
    spans: tuple&#91;tuple&#91;int, int&#93;, ...&#93; | None = None,
    span_sparsities: tuple&#91;float, ...&#93; | None = None,
) -&gt; np.ndarray:
    &quot;&quot;&quot;scores: &#91;..., n_tiles, n_tiles&#93; -&gt; bool mask, same shape.

    Mirrors ``_build_block_mask`` in the PyTorch H3 backend: every video query
    keeps its own top-k of EACH video region (``spans`` / ``span_sparsities``).
    &quot;&quot;&quot;
    n_tiles = scores.shape&#91;-1&#93;
    spans, topks = _region_plan(num_prefix_tiles, num_video_tiles, sparsity, exempt, spans, span_sparsities)
    if all(k == end - start for k, (start, end) in zip(topks, spans, strict=True)):
        return np.ones_like(scores, dtype=bool)
    mask = np.zeros_like(scores, dtype=bool)
    if exempt or num_prefix_tiles == 0:
        for (start, end), k_span in zip(spans, topks, strict=True):
            if k_span == end - start:
                mask&#91;..., start:end&#93; = True
                continue
            idx = np.argsort(-scores&#91;..., start:end&#93;, axis=-1, kind=&quot;stable&quot;)&#91;..., :k_span&#93; + start
            np.put_along_axis(mask, idx, True, axis=-1)
        mask&#91;..., :num_prefix_tiles&#93; = True
    else:
        k_total = min(topks&#91;0&#93; + num_prefix_tiles, n_tiles)
        idx = np.argsort(-scores, axis=-1, kind=&quot;stable&quot;)&#91;..., :k_total&#93;
        np.put_along_axis(mask, idx, True, axis=-1)
    mask&#91;..., :num_prefix_tiles, :&#93; = True
    return mask</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.resolve_impl"><code>fastvideo.mlx_runtime.minimax_h3_vsa.resolve_impl</code></h2>
<pre class="doc-signature"><code>resolve_impl(requested: VSAImpl, head_dim: int, tile_elems: int) -&gt; str</code></pre>

<details><summary>Source</summary><pre><code>def resolve_impl(requested: VSAImpl, head_dim: int, tile_elems: int) -&gt; str:
    if requested == &quot;reference&quot; or (requested == &quot;auto&quot; and tile_elems not in _AUTO_SIMD_TILES):
        return &quot;reference&quot;

    from fastvideo.mlx_runtime.minimax_h3_vsa_simd import (SIMD_HEAD_DIM, SIMD_TILE_SIZES, simd_kernel_available,
                                                           simd_kernel_error)

    if tile_elems not in SIMD_TILE_SIZES or head_dim != SIMD_HEAD_DIM:
        if requested == &quot;simd&quot;:
            logger.warning_once(
                f&quot;SIMD VSA requires tile &#123;&#x27; or &#x27;.join(map(str, SIMD_TILE_SIZES))&#125; and head dim &#123;SIMD_HEAD_DIM&#125; &quot;
                f&quot;(got tile=&#123;tile_elems&#125; head_dim=&#123;head_dim&#125;); using reference VSA&quot;)
        return &quot;reference&quot;
    if not simd_kernel_available():
        reason = simd_kernel_error() or &quot;SIMD-group VSA kernel is unavailable&quot;
        logger.warning_once(f&quot;SIMD VSA kernel unavailable (&#123;reason&#125;); using reference VSA&quot;)
        return &quot;reference&quot;
    return &quot;simd&quot;</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.h3_vsa_attention"><code>fastvideo.mlx_runtime.minimax_h3_vsa.h3_vsa_attention</code></h2>
<pre class="doc-signature"><code>h3_vsa_attention(query, key, value, geometry: MiniMaxH3VSAGeometry, *, sparsity: float, exempt: bool = True, gate_compress = None, impl: VSAImpl = &#x27;auto&#x27;, stats: MiniMaxH3VSAStats | None = None, ref_keep_rate: float | None = None)</code></pre>
<p>Packed <code>[S, H, D]</code> VSA attention. Falls back to dense SDPA when sparsity is 0.</p>
<p><code>ref_keep_rate</code> is the <code>p2_multi_region</code> keep rate of each reference-video
region of <code>geometry</code>; geometries with reference regions require it.</p>
<details><summary>Source</summary><pre><code>def h3_vsa_attention(
    query,
    key,
    value,
    geometry: MiniMaxH3VSAGeometry,
    *,
    sparsity: float,
    exempt: bool = True,
    gate_compress=None,
    impl: VSAImpl = &quot;auto&quot;,
    stats: MiniMaxH3VSAStats | None = None,
    ref_keep_rate: float | None = None,
):
    &quot;&quot;&quot;Packed ``&#91;S, H, D&#93;`` VSA attention. Falls back to dense SDPA when sparsity is 0.

    ``ref_keep_rate`` is the ``p2_multi_region`` keep rate of each reference-video
    region of ``geometry``; geometries with reference regions require it.
    &quot;&quot;&quot;
    import mlx.core as mx

    _, heads, dim = query.shape
    scale = dim**-0.5
    if stats is not None:
        stats.configured_sparsity = sparsity
        stats.layer_sparsity = sparsity
        stats.tile_size = geometry.tile_elems
        stats.prefix_mode = &quot;exempt&quot; if exempt else &quot;compete&quot;
        stats.num_prefix_tiles = geometry.num_prefix_tiles
        stats.num_video_tiles = geometry.num_video_tiles

    if sparsity &lt;= 0.0 and gate_compress is None:
        if stats is not None:
            stats.impl = &quot;dense&quot;
            stats.achieved_sparsity = 0.0
            stats.video_keep = geometry.num_video_tiles
        return _dense_sdpa(query, key, value, scale)

    q_tiled = _tile_hidden(query, geometry)
    k_tiled = _tile_hidden(key, geometry)
    v_tiled = _tile_hidden(value, geometry)
    q_pooled = _pool_tiles(q_tiled, geometry.variable_block_sizes, geometry.tile_elems)
    k_pooled = _pool_tiles(k_tiled, geometry.variable_block_sizes, geometry.tile_elems)
    scores = (q_pooled @ k_pooled.transpose(0, 2, 1)) / (dim**0.5)

    span_sparsities = region_sparsities(len(geometry.video_tile_spans), sparsity, ref_keep_rate)
    spans = geometry.video_tile_spans
    k_vid = sum(compute_topk(sp, end - start) for (start, end), sp in zip(spans, span_sparsities, strict=True))
    if stats is not None:
        stats.video_keep = k_vid if sparsity &gt; 0.0 else geometry.num_video_tiles
        stats.achieved_sparsity = (1.0 - (k_vid / geometry.num_video_tiles) if geometry.num_video_tiles else 0.0)

    if sparsity &lt;= 0.0:
        out_tiled = _tile_hidden(_dense_sdpa(query, key, value, scale), geometry)
        chosen = &quot;dense&quot;
    else:
        block_idx, block_num = _block_indices_from_scores(
            scores,
            geometry.num_prefix_tiles,
            geometry.num_video_tiles,
            sparsity,
            exempt,
            spans,
            span_sparsities,
        )
        if stats is not None and not exempt:
            stats.video_keep = float(mx.mean(mx.sum(block_idx &gt;= geometry.num_prefix_tiles, axis=-1)).item())
            stats.achieved_sparsity = 1.0 - stats.video_keep / geometry.num_video_tiles
        chosen = resolve_impl(impl, dim, geometry.tile_elems)
        if stats is not None and impl == &quot;simd&quot; and chosen != &quot;simd&quot;:
            from fastvideo.mlx_runtime.minimax_h3_vsa_simd import simd_kernel_error

            stats.dense_fallback_reason = (&quot;SIMD requires tile 64 or 128 and head dim 128&quot; if
                                           geometry.tile_elems not in (64, 128) or dim != 128 else simd_kernel_error())
        if not geometry.prefix_length:
            prefix_out = query&#91;:0&#93;
        else:
            dense_query = (query&#91;:geometry.prefix_length&#93;
                           if geometry.dense_rows_lead else query&#91;geometry.dense_row_index&#93;)
            prefix_out = _dense_sdpa(dense_query, key, value, scale)
        n_prefix_pad = geometry.num_prefix_tiles * geometry.tile_elems
        if chosen == &quot;simd&quot;:
            from fastvideo.mlx_runtime.minimax_h3_vsa_simd import disable_simd_kernel, simd_block_sparse

            try:
                video_tiled = simd_block_sparse(q_tiled, k_tiled, v_tiled, block_idx, block_num, geometry, scale)
                # MLX compiles and executes custom Metal kernels lazily.
                mx.eval(video_tiled)
                video_tiled = video_tiled&#91;n_prefix_pad:&#93;
            except Exception as error:  # noqa: BLE001 - keep generation alive on kernel failure
                disable_simd_kernel(error)
                logger.warning_once(f&quot;SIMD VSA kernel failed (&#123;error&#125;); falling back to reference gather+SDPA&quot;)
                chosen = &quot;reference&quot;
                if stats is not None:
                    stats.dense_fallback_reason = f&quot;simd kernel failed: &#123;error&#125;&quot;
                video_tiled = _reference_gather_sdpa(q_tiled, k_tiled, v_tiled, block_idx, geometry, scale)
        elif _reference_full_mask_fits(geometry, heads):
            scores_np = np.array(scores, dtype=np.float32)
            mask = build_block_mask(
                scores_np,
                geometry.num_prefix_tiles,
                geometry.num_video_tiles,
                sparsity,
                exempt,
                spans,
                span_sparsities,
            )
            video_tiled = _reference_token_sdpa(q_tiled, k_tiled, v_tiled, mask, geometry, scale)&#91;n_prefix_pad:&#93;
        else:
            video_tiled = _reference_gather_sdpa(q_tiled, k_tiled, v_tiled, block_idx, geometry, scale)
        video_tiled = video_tiled.astype(query.dtype)
        prefix_tiled = mx.concatenate(&#91;
            prefix_out,
            mx.zeros((1, heads, dim), dtype=query.dtype),
        &#93;)&#91;geometry.prefix_gather_index&#93;
        # Prefix query tiles are dense; keep fused-SDPA prefix rows and sparse video tiles.
        out_tiled = mx.concatenate(&#91;prefix_tiled, video_tiled&#93;, axis=0)

    if gate_compress is not None:
        gate_tiled = _tile_hidden(gate_compress, geometry)
        out_tiled = out_tiled + _gate_compress_output(scores, v_tiled, gate_tiled, geometry).astype(out_tiled.dtype)

    if stats is not None:
        stats.impl = chosen if sparsity &gt; 0.0 else &quot;dense&quot;
    return _untile_hidden(out_tiled, geometry)</code></pre></details>
<h2 id="fastvideo.mlx_runtime.minimax_h3_vsa.geometry_is_supported"><code>fastvideo.mlx_runtime.minimax_h3_vsa.geometry_is_supported</code></h2>
<pre class="doc-signature"><code>geometry_is_supported(prefix_segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;, dit_seq_shape: tuple&#91;int, int, int&#93;, tile_size: int) -&gt; str | None</code></pre>
<p>Return a fallback reason, or None when VSA can run.</p>
<details><summary>Source</summary><pre><code>def geometry_is_supported(prefix_segments: tuple&#91;int | tuple&#91;int, int, int&#93;, ...&#93;, dit_seq_shape: tuple&#91;int, int, int&#93;,
                          tile_size: int) -&gt; str | None:
    &quot;&quot;&quot;Return a fallback reason, or None when VSA can run.&quot;&quot;&quot;
    try:
        build_h3_segment_geometry((*prefix_segments, _grid(dit_seq_shape)), tile_size)
    except ValueError as error:
        return str(error)
    return None</code></pre></details>
</div>
