windowed_attention ¶
Chunked non-causal sliding-window self-attention for MLX scaling studies.
This module is intentionally standalone (mlx.core + stdlib only) so it can be micro-benchmarked without pulling in the DiT / FastVideo stack.
Window policy¶
Symmetric sliding window (non-causal). For query index i the allowed key indices are:
sinks: ``j in [0, sink)`` (always visible to every query, if ``sink > 0``)
local: ``j in [max(0, i - half), min(S, i + half + 1))``
where ``half = window // 2``
so each query sees roughly window + 1 local keys (plus any sinks outside that range). This is appropriate for a dense, bidirectional DiT denoise pass.
Implementation note (FLOPs)¶
A full-size additive attention mask still materialises an O(S^2) score matrix inside SDPA and does not reduce work. Instead we tile the sequence into query blocks and run mx.fast.scaled_dot_product_attention only against the union of keys that block needs (local slice ± sinks). That makes per-block work O(chunk * (window + sink) * D) and total work O(S * (window + sink) * D).
Functions:¶
fastvideo.mlx_runtime.windowed_attention.full_attention ¶
full_attention(q: array, k: array, v: array, scale: float | None = None) -> array
Compute dense scaled dot-product attention over the full sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale | float | Attention scaling factor. If omitted, uses the inverse square root of the head dimension. | None |
Returns:
| Type | Description |
|---|---|
array | mx.array: Attention output with shape |
Source code in fastvideo/mlx_runtime/windowed_attention.py
fastvideo.mlx_runtime.windowed_attention.windowed_attention ¶
windowed_attention(q: array, k: array, v: array, window: int, sink: int = 0, scale: float | None = None, *, chunk_size: int | None = None) -> array
Apply symmetric sliding-window self-attention with optional global sink positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q | array | Query tensor shaped | required |
k | array | Key tensor shaped | required |
v | array | Value tensor shaped | required |
window | int | Symmetric attention window width in tokens; must be at least 1. | required |
sink | int | Number of leading key positions available to every query; must be between 0 and the sequence length. | 0 |
scale | Optional[float] | Softmax scale. Defaults to | None |
chunk_size | Optional[int] | Query block length used for chunked processing. Defaults to the smaller of | None |
Returns:
| Type | Description |
|---|---|
array | mx.array: Attention output with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError | If the inputs or attention parameters are invalid. |
RuntimeError | If a query block has no available keys. |