Skip to content

Accelerated API

The flashdreams.accelerated package provides optimized attention, quantization, and shared inference components. See Accelerated building blocks for usage and integration guidance.

Common components

flashdreams.accelerated.common.NonPersistentLinear

NonPersistentLinear(weight: Tensor, bias: Tensor | None)

Bases: Linear

Linear transformation backed by nonpersistent weight and bias buffers.

Initialize the transformation from existing tensors.

Parameters:

Name Type Description Default
weight Tensor

Projection weight shaped [out_features, in_features].

required
bias Tensor | None

Optional projection bias shaped [out_features].

required
Source code in flashdreams/flashdreams/accelerated/common/non_persistent_linear.py
12
13
14
15
16
17
18
19
20
21
22
23
def __init__(self, weight: Tensor, bias: Tensor | None) -> None:
    """Initialize the transformation from existing tensors.

    Args:
        weight: Projection weight shaped ``[out_features, in_features]``.
        bias: Optional projection bias shaped ``[out_features]``.
    """
    nn.Module.__init__(self)
    self.in_features = weight.shape[1]
    self.out_features = weight.shape[0]
    self.register_buffer("weight", weight, persistent=False)
    self.register_buffer("bias", bias, persistent=False)

flashdreams.accelerated.common.rms_norm

RMS normalization for accelerated inference paths.

rms_norm

rms_norm(input: Tensor, weight: Tensor, eps: float) -> Tensor

Apply RMSNorm through PyTorch's fused implementation.

The fused BF16 reduction can round differently from a decomposed module, so integrations must quality-qualify model output before enabling this path.

Source code in flashdreams/flashdreams/accelerated/common/rms_norm.py
12
13
14
15
16
17
18
19
20
21
22
23
def rms_norm(input: Tensor, weight: Tensor, eps: float) -> Tensor:
    """Apply RMSNorm through PyTorch's fused implementation.

    The fused BF16 reduction can round differently from a decomposed module, so
    integrations must quality-qualify model output before enabling this path.
    """
    if weight.ndim != 1 or weight.shape[0] != input.shape[-1]:
        raise ValueError(
            f"RMSNorm weight {tuple(weight.shape)} does not match input "
            f"dimension {input.shape[-1]}."
        )
    return F.rms_norm(input, (input.shape[-1],), weight, eps)

Quantization

flashdreams.accelerated.quantization.quantizer.Granularity

Bases: str, Enum

Scale granularity for tensor quantization.

SLICE class-attribute instance-attribute

SLICE = 'slice'

Use one scale per slice selected by axis in :func:quantize.

TENSOR class-attribute instance-attribute

TENSOR = 'tensor'

Use one scale for the complete tensor.

flashdreams.accelerated.quantization.quantizer.quantize

quantize(original: Tensor, format: dtype, granularity: Granularity, axis: int = -1, use_triton: bool = True) -> tuple[Tensor, Tensor]

Quantize a tensor using the requested format and scale granularity.

Parameters:

Name Type Description Default
original Tensor

Tensor to quantize.

required
format dtype

Data type of the quantized tensor.

required
granularity Granularity

Scope over which scales are computed. SLICE reduces along axis; TENSOR reduces over the complete tensor.

required
axis int

Dimension over which SLICE computes the maximum value. For a two-dimensional tensor, axis=1 produces one scale per row and axis=0 produces one scale per column. Defaults to -1.

-1
use_triton bool

Use Triton for CUDA tensors. CPU tensors retain the Torch implementation. Defaults to True.

True

Returns:

Type Description
Tensor

Quantized tensor and its FP32 scale tensor. The scale has the same

Tensor

number of dimensions as original and retains reduced dimensions

tuple[Tensor, Tensor]

with size one.

Raises:

Type Description
ValueError

format or granularity is unsupported.

Source code in flashdreams/flashdreams/accelerated/quantization/quantizer.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def quantize(
    original: Tensor,
    format: torch.dtype,
    granularity: Granularity,
    axis: int = -1,
    use_triton: bool = True,
) -> tuple[Tensor, Tensor]:
    """Quantize a tensor using the requested format and scale granularity.

    Args:
        original: Tensor to quantize.
        format: Data type of the quantized tensor.
        granularity: Scope over which scales are computed. ``SLICE`` reduces
            along ``axis``; ``TENSOR`` reduces over the complete tensor.
        axis: Dimension over which ``SLICE`` computes the maximum value. For a
            two-dimensional tensor, ``axis=1`` produces one scale per row and
            ``axis=0`` produces one scale per column. Defaults to ``-1``.
        use_triton: Use Triton for CUDA tensors. CPU tensors retain the Torch
            implementation. Defaults to ``True``.

    Returns:
        Quantized tensor and its FP32 scale tensor. The scale has the same
        number of dimensions as ``original`` and retains reduced dimensions
        with size one.

    Raises:
        ValueError: ``format`` or ``granularity`` is unsupported.
    """
    if format not in DTYPE_MAX:
        raise ValueError(f"unsupported quantization format: {format}")

    if granularity is Granularity.TENSOR:
        reduction_axis: int | tuple[int, ...] = tuple(range(original.ndim))
    elif granularity is Granularity.SLICE:
        reduction_axis = axis
    else:
        raise ValueError(f"unsupported quantization granularity: {granularity}")

    if use_triton and original.is_cuda:
        return quantize_triton(original, format, granularity, axis)

    original_float = original.detach().to(torch.float32)
    max_abs = original_float.abs().amax(dim=reduction_axis, keepdim=True)
    scale = (max_abs / DTYPE_MAX[format]).clamp_min(torch.finfo(torch.float32).tiny)
    quantized = (original_float / scale).clamp(-DTYPE_MAX[format], DTYPE_MAX[format])
    if not format.is_floating_point:
        quantized = quantized.round()
    return quantized.to(format), scale

flashdreams.accelerated.quantization.quantizer.dequantize

dequantize(quantized: Tensor, *scales: Tensor, dtype: dtype = float16, use_triton: bool = True) -> Tensor

Dequantize a tensor using its scale tensors.

Parameters:

Name Type Description Default
quantized Tensor

Tensor to dequantize.

required
scales Tensor

Scale tensors used to dequantize quantized.

()
dtype dtype

Data type of the dequantized tensor. Defaults to torch.float16.

float16
use_triton bool

Use Triton for CUDA tensors. CPU tensors retain the Torch implementation. Defaults to True.

True

Returns:

Type Description
Tensor

Dequantized tensor in dtype after applying every scale in order.

Tensor

Without scales, casts quantized directly to dtype.

Source code in flashdreams/flashdreams/accelerated/quantization/quantizer.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def dequantize(
    quantized: Tensor,
    *scales: Tensor,
    dtype: torch.dtype = torch.float16,
    use_triton: bool = True,
) -> Tensor:
    """Dequantize a tensor using its scale tensors.

    Args:
        quantized: Tensor to dequantize.
        scales: Scale tensors used to dequantize ``quantized``.
        dtype: Data type of the dequantized tensor. Defaults to ``torch.float16``.
        use_triton: Use Triton for CUDA tensors. CPU tensors retain the Torch
            implementation. Defaults to ``True``.

    Returns:
        Dequantized tensor in ``dtype`` after applying every scale in order.
        Without scales, casts ``quantized`` directly to ``dtype``.
    """
    if use_triton and quantized.is_cuda:
        return dequantize_triton(quantized, *scales, dtype=dtype)
    if not scales:
        return quantized.to(dtype)

    dequantized = quantized.to(scales[0].dtype)
    for scale in scales:
        dequantized = dequantized * scale
    return dequantized.to(dtype)

flashdreams.accelerated.quantization.linear.WeightGranularity

Bases: str, Enum

Scale granularity for quantized linear weights.

PER_OUT_CHANNEL class-attribute instance-attribute

PER_OUT_CHANNEL = 'per_out_channel'

Use one scale for every output channel.

TENSOR class-attribute instance-attribute

TENSOR = 'tensor'

Use one scale for the complete weight tensor.

flashdreams.accelerated.quantization.linear.QuantizedNonPersistentLinear

QuantizedNonPersistentLinear(weight: Tensor, bias: Tensor | None, granularity: WeightGranularity, dtype: dtype)

Bases: NonPersistentLinear

Apply a nonpersistent linear transformation with quantized weights.

The layer quantizes and stores weight [O, I] during construction, where I is in_features and O is out_features. At inference, it accepts activations x [..., I] and returns output [..., O]. The leading activation dimensions may represent any combination of batch, sequence, or spatial dimensions.

Examples:

Construct a layer and let it quantize full-precision activations using one scale per I-element slice::

import torch

from flashdreams.accelerated.quantization.linear import (
    QuantizedNonPersistentLinear,
    WeightGranularity,
)
from flashdreams.accelerated.quantization.quantizer import (
    Granularity,
    quantize,
)

weight = torch.randn(32, 64, device="cuda", dtype=torch.float16)
bias = torch.randn(32, device="cuda", dtype=torch.float16)
layer = QuantizedNonPersistentLinear(
    weight,
    bias,
    WeightGranularity.PER_OUT_CHANNEL,
    torch.float8_e4m3fn,
)
x = torch.randn(2, 8, 64, device="cuda", dtype=torch.float16)
output = layer(x, Granularity.SLICE)
assert output.shape == (2, 8, 32)

Reuse prequantized activations and their scale to avoid quantizing x inside each call::

quantized_x, x_scale = quantize(
    x,
    layer.dtype,
    Granularity.SLICE,
    axis=-1,
)
output = layer(quantized_x, x_scale, out_dtype=torch.float16)
assert output.shape == (2, 8, 32)

Initialize the transformation from existing tensors.

Parameters:

Name Type Description Default
weight Tensor

Projection weight shaped [out_features, in_features].

required
bias Tensor | None

Optional projection bias shaped [out_features].

required
granularity WeightGranularity

Scale granularity used to quantize weight.

required
dtype dtype

Quantized activation format.

required

Raises:

Type Description
ValueError

granularity or dtype is unsupported.

Source code in flashdreams/flashdreams/accelerated/quantization/linear.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    weight: Tensor,
    bias: Tensor | None,
    granularity: WeightGranularity,
    dtype: torch.dtype,
) -> None:
    """Initialize the transformation from existing tensors.

    Args:
        weight: Projection weight shaped ``[out_features, in_features]``.
        bias: Optional projection bias shaped ``[out_features]``.
        granularity: Scale granularity used to quantize ``weight``.
        dtype: Quantized activation format.

    Raises:
        ValueError: ``granularity`` or ``dtype`` is unsupported.
    """
    # Map the public weight modes onto ``quantize`` with ``axis=-1``:
    # ``[O, I] -> scale [O, 1]`` per output or ``scale [1, 1]`` per tensor.
    if granularity is WeightGranularity.PER_OUT_CHANNEL:
        quantizer_granularity = Granularity.SLICE
    elif granularity is WeightGranularity.TENSOR:
        quantizer_granularity = Granularity.TENSOR
    else:
        raise ValueError(f"unsupported weight granularity: {granularity}")

    # CUDA FP8 GEMM pairs E5M2 activations with an E4M3 weight operand.
    # All other formats use the same dtype for ``x`` and ``weight``.
    weight_dtype = torch.float8_e4m3fn if dtype is torch.float8_e5m2 else dtype
    quantized_weight, weight_scale = quantize(
        weight,
        weight_dtype,
        quantizer_granularity,
        axis=-1,
    )
    # Keep derived ``weight [O, I]`` and its scale out of ``state_dict``;
    # callers recreate both from the source weight when building the layer.
    super().__init__(quantized_weight.contiguous(), bias)
    self.dtype = dtype
    self.register_buffer(
        "weight_scale", weight_scale.contiguous(), persistent=False
    )
    self._refresh_rowwise_fp8_mm_backend()

weight_scale instance-attribute

weight_scale: Tensor

FP32 weight scale shaped [O, 1] or [1, 1].

dtype instance-attribute

dtype: dtype = dtype

Quantized activation format required by prequantized inputs.

forward

forward(x: Tensor, scale_or_granularity: Tensor, out_dtype: dtype = float16) -> Tensor
forward(x: Tensor, scale_or_granularity: Granularity, out_dtype: dtype = float16) -> Tensor
forward(x: Tensor, scale_or_granularity: Tensor | Granularity, out_dtype: dtype = float16) -> Tensor

Apply the quantized linear transformation.

Parameters:

Name Type Description Default
x Tensor

Activations shaped [..., in_features]. When a scale tensor is supplied, these must already use the layer's quantized dtype; when a granularity is supplied, these are full-precision activations quantized inside this call.

required
scale_or_granularity Tensor | Granularity

For prequantized x, an FP32 tensorwise scale shaped [1, ..., 1] or slice scale shaped [..., 1]. For full-precision x, the granularity used to produce one of those scale shapes.

required
out_dtype dtype

Data type of the projected activations. Defaults to torch.float16.

float16

Returns:

Type Description
Tensor

Projected activations shaped [..., out_features].

Raises:

Type Description
ValueError

x or its scale does not match the layer contract.

Source code in flashdreams/flashdreams/accelerated/quantization/linear.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def forward(
    self,
    x: Tensor,
    scale_or_granularity: Tensor | Granularity,
    out_dtype: torch.dtype = torch.float16,
) -> Tensor:
    """Apply the quantized linear transformation.

    Args:
        x: Activations shaped ``[..., in_features]``. When a scale tensor
            is supplied, these must already use the layer's quantized
            ``dtype``; when a granularity is supplied, these are
            full-precision activations quantized inside this call.
        scale_or_granularity: For prequantized ``x``, an FP32 tensorwise
            scale shaped ``[1, ..., 1]`` or slice scale shaped
            ``[..., 1]``. For full-precision ``x``, the granularity used
            to produce one of those scale shapes.
        out_dtype: Data type of the projected activations. Defaults to
            ``torch.float16``.

    Returns:
        Projected activations shaped ``[..., out_features]``.

    Raises:
        ValueError: ``x`` or its scale does not match the layer contract.
    """
    if x.ndim == 0 or x.shape[-1] != self.in_features:
        raise ValueError(
            f"expected input last dim {self.in_features}, got {tuple(x.shape)}"
        )

    if isinstance(scale_or_granularity, Tensor):
        # Prequantized path: preserve ``x [..., I]`` and its existing
        # tensorwise ``scale [1, ..., 1]`` or slice ``scale [..., 1]``.
        if x.dtype is not self.dtype:
            raise ValueError(
                f"expected quantized input dtype {self.dtype}, got {x.dtype}"
            )
        self._validate_scale(x, scale_or_granularity)
        quantized, scale = x, scale_or_granularity
    elif isinstance(scale_or_granularity, Granularity):
        # Dynamic path: quantization keeps ``x [..., I]`` unchanged in
        # shape and reduces either every dimension or only ``I`` for scale.
        if x.numel() == 0:
            return torch.empty(
                (*x.shape[:-1], self.out_features),
                device=x.device,
                dtype=out_dtype,
            )
        quantized, scale = quantize(
            x,
            self.dtype,
            scale_or_granularity,
            axis=-1,
        )
    else:
        raise ValueError(
            "scale_or_granularity must be a scale tensor or Granularity"
        )

    return self._forward_quantized(quantized, scale, out_dtype)

Attention contracts

flashdreams.accelerated.multi_head_attention.AttentionType

Bases: str, Enum

Relationship between query tokens and cached K/V context.

SELF_ATTENTION class-attribute instance-attribute

SELF_ATTENTION = 'self_attention'

Update K/V from each query chunk before attention.

CROSS_ATTENTION class-attribute instance-attribute

CROSS_ATTENTION = 'cross_attention'

Query a precomputed static K/V cache without updating it.

flashdreams.accelerated.multi_head_attention.AttentionConfig dataclass

AttentionConfig(query_dim: int, n_heads: int = 8, n_kv_heads: int | None = None, head_dim: int = 64, context_dim: int | None = None, qk_norm_scope: QKNormScope = HEAD, qk_norm_eps: float = 1e-06, rope_config: RoPEConfig | None = None)

Geometry, normalization, and rotary policy shared by attention backends.

query_dim instance-attribute

query_dim: int

Input and output token width.

n_heads class-attribute instance-attribute

n_heads: int = 8

Number of query heads.

n_kv_heads class-attribute instance-attribute

n_kv_heads: int | None = None

Number of key/value heads; None uses n_heads.

head_dim class-attribute instance-attribute

head_dim: int = 64

Feature width of each attention head.

context_dim class-attribute instance-attribute

context_dim: int | None = None

Context token width; None uses query_dim.

qk_norm_scope class-attribute instance-attribute

qk_norm_scope: QKNormScope = QKNormScope.HEAD

Feature scope used by query and key normalization.

qk_norm_eps class-attribute instance-attribute

qk_norm_eps: float = 1e-06

Positive finite epsilon used by query and key normalization.

rope_config class-attribute instance-attribute

rope_config: RoPEConfig | None = None

Rotary policy; None disables rotary embeddings.

inner_dim property

inner_dim: int

Return the concatenated width of all query heads.

kv_inner_dim property

kv_inner_dim: int

Return the concatenated width of all key/value heads.

__post_init__

__post_init__() -> None

Validate and normalize attention configuration values.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/__init__.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def __post_init__(self) -> None:
    """Validate and normalize attention configuration values."""
    context_dim = self.query_dim if self.context_dim is None else self.context_dim
    if self.query_dim <= 0:
        raise ValueError(f"query_dim must be positive; got {self.query_dim}")
    if context_dim <= 0:
        raise ValueError(f"context_dim must be positive; got {context_dim}")
    if self.n_heads <= 0:
        raise ValueError(f"n_heads must be positive; got {self.n_heads}")
    n_kv_heads = self.n_heads if self.n_kv_heads is None else self.n_kv_heads
    if n_kv_heads <= 0:
        raise ValueError(f"n_kv_heads must be positive; got {n_kv_heads}")
    if self.n_heads % n_kv_heads:
        raise ValueError(
            "n_heads must be divisible by n_kv_heads; "
            f"got {self.n_heads} and {n_kv_heads}"
        )
    if self.head_dim <= 0:
        raise ValueError(f"head_dim must be positive; got {self.head_dim}")
    if not isinstance(self.qk_norm_scope, QKNormScope):
        raise TypeError(
            f"qk_norm_scope must be a QKNormScope; got {self.qk_norm_scope!r}"
        )
    if not math.isfinite(self.qk_norm_eps) or self.qk_norm_eps <= 0:
        raise ValueError(
            f"qk_norm_eps must be finite and positive; got {self.qk_norm_eps}"
        )
    if self.rope_config is not None and not isinstance(
        self.rope_config, RoPEConfig
    ):
        raise TypeError(
            f"rope_config must be a RoPEConfig or None; got {self.rope_config!r}"
        )
    object.__setattr__(self, "context_dim", context_dim)
    object.__setattr__(self, "n_kv_heads", n_kv_heads)

flashdreams.accelerated.multi_head_attention.AttentionMask module-attribute

AttentionMask = Tensor | BlockMask

Dense or block-sparse visibility mask supplied to attention.

flashdreams.accelerated.multi_head_attention.QKNormScope

Bases: str, Enum

Feature scope for query and key normalization.

NONE class-attribute instance-attribute

NONE = 'none'

Skip query and key normalization.

HEAD class-attribute instance-attribute

HEAD = 'head'

Normalize each attention head independently.

INNER class-attribute instance-attribute

INNER = 'inner'

Normalize the complete projected inner width.

flashdreams.accelerated.multi_head_attention.RoPEStyle

Bases: str, Enum

Feature pairing convention for rotary position embeddings.

INTERLEAVED class-attribute instance-attribute

INTERLEAVED = 'interleaved'

Rotate adjacent feature pairs.

SPLIT class-attribute instance-attribute

SPLIT = 'split'

Rotate corresponding features from the two half-width blocks.

flashdreams.accelerated.multi_head_attention.RoPEScope

Bases: str, Enum

Point at which rotary position embeddings are applied to keys.

BEFORE_KV_CACHE class-attribute instance-attribute

BEFORE_KV_CACHE = 'before_kv_cache'

Rotate keys before writing them to the K/V cache.

AFTER_KV_CACHE class-attribute instance-attribute

AFTER_KV_CACHE = 'after_kv_cache'

Rotate cached keys immediately before attention.

flashdreams.accelerated.multi_head_attention.RoPEConfig dataclass

RoPEConfig(style: RoPEStyle = SPLIT, scope: RoPEScope = BEFORE_KV_CACHE)

Rotary position embedding policy.

style class-attribute instance-attribute

Feature pairing convention used by each rotary embedding.

scope class-attribute instance-attribute

Whether keys are rotated before or after K/V cache storage.

__post_init__

__post_init__() -> None

Validate rotary policy enum values.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/__init__.py
89
90
91
92
93
94
def __post_init__(self) -> None:
    """Validate rotary policy enum values."""
    if not isinstance(self.style, RoPEStyle):
        raise TypeError(f"style must be a RoPEStyle; got {self.style!r}")
    if not isinstance(self.scope, RoPEScope):
        raise TypeError(f"scope must be a RoPEScope; got {self.scope!r}")

flashdreams.accelerated.multi_head_attention.MultiHeadAttention

MultiHeadAttention(attention_type: AttentionType, attention_config: AttentionConfig)

Bases: Module, ABC, Generic[KVCacheT]

Generic multi-head attention interface over an implementation-owned cache.

The complete attention operation is the extension point so implementations may fuse projection, normalization, RoPE, cache mutation, attention, and output projection as needed. Streaming self-attention updates a caller-prepared rolling cache from x; cross-attention reads precomputed static K/V without changing it.

Shape descriptions use L for query tokens, S for cached context tokens, H for attention heads, and D for each head's feature dimension. Leading ... dimensions describe batch or grouping geometry; query and context layouts may differ when implementations flatten them to the same batch size.

Initialize shared attention geometry and implementation policies.

Parameters:

Name Type Description Default
attention_type AttentionType

Select self-attention or static cross-attention.

required
attention_config AttentionConfig

Shared geometry, normalization, and rotary policy.

required

Raises:

Type Description
TypeError

An argument has the wrong configuration type.

ValueError

Self-attention has different query and context dimensions.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/__init__.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def __init__(
    self,
    attention_type: AttentionType,
    attention_config: AttentionConfig,
) -> None:
    """Initialize shared attention geometry and implementation policies.

    Args:
        attention_type: Select self-attention or static cross-attention.
        attention_config: Shared geometry, normalization, and rotary policy.

    Raises:
        TypeError: An argument has the wrong configuration type.
        ValueError: Self-attention has different query and context dimensions.
    """
    super().__init__()

    if not isinstance(attention_type, AttentionType):
        raise TypeError(
            f"attention_type must be an AttentionType; got {attention_type!r}"
        )
    if not isinstance(attention_config, AttentionConfig):
        raise TypeError(
            f"attention_config must be an AttentionConfig; got {attention_config!r}"
        )
    context_dim = attention_config.context_dim
    assert context_dim is not None
    if (
        attention_type is AttentionType.SELF_ATTENTION
        and attention_config.query_dim != context_dim
    ):
        raise ValueError(
            "self-attention requires query_dim to equal context_dim; "
            f"got {attention_config.query_dim} and {context_dim}"
        )

    self.attention_type = attention_type
    self.attention_config = attention_config

attention_type instance-attribute

attention_type: AttentionType = attention_type

Whether forward performs self-attention or static cross-attention.

attention_config instance-attribute

attention_config: AttentionConfig = attention_config

Geometry, normalization, and rotary policy used by this module.

query_projection abstractmethod property

query_projection: Linear

Return the query projection module.

This logical accessor does not prescribe the module's registered attribute name. Model adapters can therefore expose checkpoint-native names while shared attention implementations consume one interface.

key_projection abstractmethod property

key_projection: Linear

Return the key projection module.

value_projection abstractmethod property

value_projection: Linear

Return the value projection module.

output_projection abstractmethod property

output_projection: Linear

Return the attention output projection module.

query_norm abstractmethod property

query_norm: Module

Return the query normalization module or identity.

key_norm abstractmethod property

key_norm: Module

Return the key normalization module or identity.

compute_kv abstractmethod

compute_kv(context: Tensor, rope_freqs: Tensor | None = None) -> KVCacheT

Project context and return a precomputed K/V cache.

Use this stage to materialize static cross-attention context. The cache is ready for repeated :meth:forward calls; implementations decide its physical layout, precision, and ownership.

Parameters:

Name Type Description Default
context Tensor

Key/value source, shape [..., S, context_dim].

required
rope_freqs Tensor | None

Optional key positional data for the S context tokens. Applied only by before-cache RoPE; after-cache RoPE stores unrotated keys and consumes cache-relative data in :meth:forward. Ignored when rope_config is None.

None

Returns:

Type Description
KVCacheT

Precomputed cache containing K/V for all S context tokens.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/__init__.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
@abstractmethod
def compute_kv(
    self,
    context: Tensor,
    rope_freqs: Tensor | None = None,
) -> KVCacheT:
    """Project context and return a precomputed K/V cache.

    Use this stage to materialize static cross-attention context. The cache
    is ready for repeated :meth:`forward` calls; implementations decide its
    physical layout, precision, and ownership.

    Args:
        context: Key/value source, shape ``[..., S, context_dim]``.
        rope_freqs: Optional key positional data for the ``S`` context
            tokens. Applied only by before-cache RoPE; after-cache RoPE
            stores unrotated keys and consumes cache-relative data in
            :meth:`forward`. Ignored when ``rope_config`` is ``None``.

    Returns:
        Precomputed cache containing K/V for all ``S`` context tokens.
    """

forward abstractmethod

forward(x: Tensor, kv_cache: KVCacheT, rope_freqs: Tensor | None = None, *, attn_mask: AttentionMask | None = None) -> Tensor

Apply the configured attention type to x and kv_cache.

Implementations own the complete operation so fused backends need not expose independently callable cache-update or cache-query stages.

Parameters:

Name Type Description Default
x Tensor

Query tokens, shape [..., L, query_dim].

required
kv_cache KVCacheT

Streaming cache for self-attention or precomputed static cache for cross-attention. A streaming cache must already be in its current-chunk update phase.

required
rope_freqs Tensor | None

Optional positional data. Before-cache RoPE expects the current L query/key positions. After-cache RoPE expects cache-relative positions for all visible keys and selects the current query positions from the cache write interval. Ignored when rope_config is None.

None
attn_mask AttentionMask | None

Optional dense or block-sparse visibility mask. Backend implementations define which representation they support.

None

Returns:

Type Description
Tensor

Attention result with shape [..., L, query_dim].

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/__init__.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
@abstractmethod
def forward(
    self,
    x: Tensor,
    kv_cache: KVCacheT,
    rope_freqs: Tensor | None = None,
    *,
    attn_mask: AttentionMask | None = None,
) -> Tensor:
    """Apply the configured attention type to ``x`` and ``kv_cache``.

    Implementations own the complete operation so fused backends need not
    expose independently callable cache-update or cache-query stages.

    Args:
        x: Query tokens, shape ``[..., L, query_dim]``.
        kv_cache: Streaming cache for self-attention or precomputed static
            cache for cross-attention. A streaming cache must already be in
            its current-chunk update phase.
        rope_freqs: Optional positional data. Before-cache RoPE expects the
            current ``L`` query/key positions. After-cache RoPE expects
            cache-relative positions for all visible keys and selects the
            current query positions from the cache write interval. Ignored
            when ``rope_config`` is ``None``.
        attn_mask: Optional dense or block-sparse visibility mask. Backend
            implementations define which representation they support.

    Returns:
        Attention result with shape ``[..., L, query_dim]``.
    """

Attention implementations

flashdreams.accelerated.multi_head_attention.torch.TorchMultiHeadAttention

TorchMultiHeadAttention(attention_type: AttentionType, attention_config: AttentionConfig)

Bases: MultiHeadAttention[BlockKVCache]

PyTorch reference for self- and cross-attention with a block cache.

This implementation owns the cache lifecycle dispatched by :meth:forward. Self-attention writes each current chunk to a prepared rolling cache; cross-attention reuses K/V materialized once by :meth:compute_kv.

Shape descriptions use B for the product of all leading batch or grouping dimensions, L for query tokens, S for visible cached context, H for heads, and D for head features. Projections collapse leading token dimensions into the cache's single B axis; query outputs restore their original leading layout. Query and context layouts may therefore differ as long as their flattened batch sizes agree.

Native PyTorch SDPA supplies the portable reference backend. Concrete subclasses own the projection and normalization modules and can override :meth:_attention while retaining the RoPE and cache contracts.

Initialize shared reference-attention policies.

Parameters:

Name Type Description Default
attention_type AttentionType

Select self-attention or static cross-attention.

required
attention_config AttentionConfig

Shared geometry, normalization, and rotary policy.

required
Source code in flashdreams/flashdreams/accelerated/multi_head_attention/torch.py
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    attention_type: AttentionType,
    attention_config: AttentionConfig,
) -> None:
    """Initialize shared reference-attention policies.

    Args:
        attention_type: Select self-attention or static cross-attention.
        attention_config: Shared geometry, normalization, and rotary policy.
    """
    super().__init__(attention_type, attention_config)

query_projection abstractmethod property

query_projection: Linear

Return the query projection module.

key_projection abstractmethod property

key_projection: Linear

Return the key projection module.

value_projection abstractmethod property

value_projection: Linear

Return the value projection module.

output_projection abstractmethod property

output_projection: Linear

Return the attention output projection module.

query_norm abstractmethod property

query_norm: Module

Return the query normalization module or identity.

key_norm abstractmethod property

key_norm: Module

Return the key normalization module or identity.

allocate_kv_cache

allocate_kv_cache(batch_size: int, chunk_size: int, window_size: int, sink_size: int, device: device | str, dtype: dtype) -> BlockKVCache

Allocate a native-precision rolling K/V cache.

The returned cache is empty. For every chunk, call :meth:BlockKVCache.before_update, invoke self-attention, and call :meth:BlockKVCache.after_update with the same chunk index.

Parameters:

Name Type Description Default
batch_size int

Product B of the input's leading dimensions.

required
chunk_size int

Exact number of current tokens L per update.

required
window_size int

Number of rolling context tokens retained after the sink.

required
sink_size int

Number of initial context tokens that are never evicted.

required
device device | str

Device on which to allocate K/V storage.

required
dtype dtype

Data type used by K/V storage.

required

Returns:

Type Description
BlockKVCache

Block cache with K/V storage shaped

BlockKVCache

[B, sink_size + window_size, H, D].

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/torch.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def allocate_kv_cache(
    self,
    batch_size: int,
    chunk_size: int,
    window_size: int,
    sink_size: int,
    device: torch.device | str,
    dtype: torch.dtype,
) -> BlockKVCache:
    """Allocate a native-precision rolling K/V cache.

    The returned cache is empty. For every chunk, call
    :meth:`BlockKVCache.before_update`, invoke self-attention, and call
    :meth:`BlockKVCache.after_update` with the same chunk index.

    Args:
        batch_size: Product ``B`` of the input's leading dimensions.
        chunk_size: Exact number of current tokens ``L`` per update.
        window_size: Number of rolling context tokens retained after the sink.
        sink_size: Number of initial context tokens that are never evicted.
        device: Device on which to allocate K/V storage.
        dtype: Data type used by K/V storage.

    Returns:
        Block cache with K/V storage shaped
        ``[B, sink_size + window_size, H, D]``.
    """
    # BlockKVCache rolls sequence dimension 1 while preserving independent
    # batch and head axes for SDPA.
    kv_heads = self.attention_config.n_kv_heads
    assert kv_heads is not None
    cache_shape = (
        batch_size,
        sink_size + window_size,
        kv_heads,
        self.attention_config.head_dim,
    )
    return BlockKVCache(
        k_shape=cache_shape,
        v_shape=cache_shape,
        seq_dim=1,
        chunk_size=chunk_size,
        window_size=window_size,
        sink_size=sink_size,
        device=device,
        dtype=dtype,
    )

compute_kv

compute_kv(context: Tensor, rope_freqs: Tensor | None = None) -> BlockKVCache

Project static context into a finalized, reusable K/V cache.

Parameters:

Name Type Description Default
context Tensor

Static key/value source, shape [..., S, context_dim]. Leading dimensions flatten into B.

required
rope_freqs Tensor | None

Optional key rotations with shape [S, 1, 1, D]. Applied only by before-cache RoPE; after-cache RoPE stores unrotated keys. Ignored when rope_config is None.

None

Returns:

Type Description
BlockKVCache

Static cache with K/V shape [B, S, H, D], ready for repeated

BlockKVCache

meth:forward calls without lifecycle bookkeeping.

Raises:

Type Description
ValueError

Context width or RoPE geometry is incompatible with the configured attention geometry.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/torch.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def compute_kv(
    self,
    context: Tensor,
    rope_freqs: Tensor | None = None,
) -> BlockKVCache:
    """Project static context into a finalized, reusable K/V cache.

    Args:
        context: Static key/value source, shape
            ``[..., S, context_dim]``. Leading dimensions flatten into ``B``.
        rope_freqs: Optional key rotations with shape ``[S, 1, 1, D]``.
            Applied only by before-cache RoPE; after-cache RoPE stores
            unrotated keys. Ignored when ``rope_config`` is ``None``.

    Returns:
        Static cache with K/V shape ``[B, S, H, D]``, ready for repeated
        :meth:`forward` calls without lifecycle bookkeeping.

    Raises:
        ValueError: Context width or RoPE geometry is incompatible with the
            configured attention geometry.
    """
    key, value = self._project_kv(context)
    if (
        self.attention_config.rope_config is not None
        and self.attention_config.rope_config.scope is RoPEScope.BEFORE_KV_CACHE
        and rope_freqs is not None
    ):
        key = self._apply_rope(key, rope_freqs)
    # ``from_tensor`` completes its one write internally, so static context
    # can be queried immediately and never enters the rolling lifecycle.
    return BlockKVCache.from_tensor(key, value, seq_dim=1)

forward

forward(x: Tensor, kv_cache: BlockKVCache, rope_freqs: Tensor | None = None, *, attn_mask: AttentionMask | None = None) -> Tensor

Apply self- or cross-attention using the configured cache lifecycle.

Parameters:

Name Type Description Default
x Tensor

Query tokens, shape [..., L, query_dim].

required
kv_cache BlockKVCache

Prepared rolling cache for self-attention or precomputed static cache for cross-attention.

required
rope_freqs Tensor | None

Optional positional data. Before-cache RoPE expects the current chunk. After-cache RoPE expects positions covering the query and visible cache. Ignored when rope_config is None.

None
attn_mask AttentionMask | None

Optional dense boolean visibility mask shaped [L, S].

None

Returns:

Type Description
Tensor

Output-projected tokens with the same shape as x.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/torch.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def forward(
    self,
    x: Tensor,
    kv_cache: BlockKVCache,
    rope_freqs: Tensor | None = None,
    *,
    attn_mask: AttentionMask | None = None,
) -> Tensor:
    """Apply self- or cross-attention using the configured cache lifecycle.

    Args:
        x: Query tokens, shape ``[..., L, query_dim]``.
        kv_cache: Prepared rolling cache for self-attention or precomputed
            static cache for cross-attention.
        rope_freqs: Optional positional data. Before-cache RoPE expects the
            current chunk. After-cache RoPE expects positions covering the
            query and visible cache. Ignored when ``rope_config`` is
            ``None``.
        attn_mask: Optional dense boolean visibility mask shaped ``[L, S]``.

    Returns:
        Output-projected tokens with the same shape as ``x``.
    """
    query_rope_freqs, key_rope_freqs = self._slice_rope_freqs(
        rope_freqs, kv_cache, x.shape[-2]
    )
    if self.attention_type is AttentionType.SELF_ATTENTION:
        kv_cache = self._update_kv(x, kv_cache, key_rope_freqs)
    return self._query_kv(
        x,
        kv_cache,
        query_rope_freqs,
        key_rope_freqs,
        attn_mask=attn_mask,
    )

flashdreams.accelerated.multi_head_attention.optimized.SDPABackend

Bases: str, Enum

Scaled-dot-product attention implementation.

CUDNN class-attribute instance-attribute

CUDNN = 'cudnn'

Use Torch cuDNN for FP16/BF16 and native cuDNN Frontend for FP8.

FA2 class-attribute instance-attribute

FA2 = 'fa2'

Use Triton FlashAttention2 (FA2).

FLEX class-attribute instance-attribute

FLEX = 'flex'

Use compiled PyTorch FlexAttention with a block-sparse mask.

flashdreams.accelerated.multi_head_attention.optimized.QKVFusionOption

Bases: str, Enum

Projection fusion policy.

NONE class-attribute instance-attribute

NONE = 'none'

Project queries, keys, and values independently.

FULL class-attribute instance-attribute

FULL = 'full'

Use one QKV GEMM; query and context feature widths must match.

FUSE_KV class-attribute instance-attribute

FUSE_KV = 'fuse_kv'

Use an independent Q GEMM and one KV GEMM, allowing unequal input widths.

flashdreams.accelerated.multi_head_attention.optimized.QuantizationOption dataclass

QuantizationOption(projection: dtype | None = None, output_projection: dtype | None = None, output_granularity: Granularity = SLICE, quantized_sdpa: bool = False)

Attention quantization policy.

projection class-attribute instance-attribute

projection: dtype | None = None

Q/K/V projection dtype; None preserves native precision.

output_projection class-attribute instance-attribute

output_projection: dtype | None = None

Output projection dtype; None preserves native precision.

output_granularity class-attribute instance-attribute

output_granularity: Granularity = Granularity.SLICE

Activation quantization granularity for the output projection.

quantized_sdpa class-attribute instance-attribute

quantized_sdpa: bool = False

Use unscaled FP8 e4m3 Q/K/V in scaled-dot-product attention; can reduce accuracy.

This directly casts Q, K, and V to FP8 e4m3 before calling the configured SDPA backend and stores the K/V cache in that dtype. The cuDNN path requires nvidia-cudnn-frontend. FA2 also casts the softmax probabilities used by P @ V to FP8 e4m3. This is not SageAttention3 quantization: it uses no accuracy-preserving quantization scheme or scaling. As noted by the SageAttention3 paper, this simple approach can make attention inaccurate, so output accuracy is not guaranteed.

__post_init__

__post_init__() -> None

Validate the projection quantization dtypes.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __post_init__(self) -> None:
    """Validate the projection quantization dtypes."""
    if self.projection is not None and self.projection not in DTYPE_MAX:
        raise ValueError(
            f"unsupported projection quantization dtype: {self.projection}"
        )
    if (
        self.output_projection is not None
        and self.output_projection not in DTYPE_MAX
    ):
        raise ValueError(
            "unsupported output projection quantization dtype: "
            f"{self.output_projection}"
        )
    if not isinstance(self.quantized_sdpa, bool):
        raise TypeError(
            f"quantized_sdpa must be a bool; got {self.quantized_sdpa!r}"
        )

flashdreams.accelerated.multi_head_attention.optimized.OptimizedImplConfig dataclass

OptimizedImplConfig(qkv_fusion_option: QKVFusionOption = FULL, sdpa_backend: SDPABackend = CUDNN, use_tma: bool = True, quantization: QuantizationOption = QuantizationOption(), flex_attention: FlexAttentionOptions = FlexAttentionOptions())

Optimized attention implementation policy.

qkv_fusion_option class-attribute instance-attribute

qkv_fusion_option: QKVFusionOption = QKVFusionOption.FULL

Projection fusion policy.

sdpa_backend class-attribute instance-attribute

sdpa_backend: SDPABackend = SDPABackend.CUDNN

Scaled-dot-product attention implementation.

use_tma class-attribute instance-attribute

use_tma: bool = True

Prefer TMA FlashAttention2 when the device and tensors support it.

quantization class-attribute instance-attribute

Attention quantization policy.

flex_attention class-attribute instance-attribute

FlexAttention mask, compilation, and kernel policy.

__post_init__

__post_init__() -> None

Validate optimized implementation policy values.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def __post_init__(self) -> None:
    """Validate optimized implementation policy values."""
    if not isinstance(self.qkv_fusion_option, QKVFusionOption):
        raise TypeError(
            "qkv_fusion_option must be a QKVFusionOption; "
            f"got {self.qkv_fusion_option!r}"
        )
    if not isinstance(self.quantization, QuantizationOption):
        raise TypeError(
            f"quantization must be a QuantizationOption; got {self.quantization!r}"
        )
    if not isinstance(self.flex_attention, FlexAttentionOptions):
        raise TypeError(
            "flex_attention must be a FlexAttentionOptions; "
            f"got {self.flex_attention!r}"
        )
    if not isinstance(self.sdpa_backend, SDPABackend):
        raise TypeError(
            f"sdpa_backend must be an SDPABackend; got {self.sdpa_backend!r}"
        )
    if not isinstance(self.use_tma, bool):
        raise TypeError(f"use_tma must be a bool; got {self.use_tma!r}")

flashdreams.accelerated.multi_head_attention.optimized.OptimizedMultiHeadAttention

OptimizedMultiHeadAttention(attention_type: AttentionType, attention_config: AttentionConfig, optimized_impl_config: OptimizedImplConfig)

Bases: MultiHeadAttention[BlockKVCache]

Provide inference-only streaming self- and static cross-attention.

Shape comments use B for the product of all leading batch dimensions, L for the current query/chunk length, S for visible cached context, H for the number of heads, D for the head dimension, Q for query_dim, and C for context_dim.

Full-fusion self-attention produces Q/K/V in one GEMM before PyTorch Q/K normalization, the shared RoPE kernel, and standard cache updates. Cross-attention precomputes K/V independently and reuses that static cache across forward calls.

Concrete subclasses own their checkpoint-native projection and normalization modules and map them to the logical module properties. Callers own the :class:BlockKVCache lifecycle: call before_update before streaming self-attention and after_update once every block has consumed that chunk.

Initialize shared optimized attention policies.

Parameters:

Name Type Description Default
attention_type AttentionType

Select self-attention or static cross-attention.

required
attention_config AttentionConfig

Shared geometry, normalization, and rotary policy.

required
optimized_impl_config OptimizedImplConfig

Projection and attention backend policy.

required

Raises:

Type Description
TypeError

optimized_impl_config has the wrong type.

ValueError

A fusion or head dimension is unsupported.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def __init__(
    self,
    attention_type: AttentionType,
    attention_config: AttentionConfig,
    optimized_impl_config: OptimizedImplConfig,
) -> None:
    """Initialize shared optimized attention policies.

    Args:
        attention_type: Select self-attention or static cross-attention.
        attention_config: Shared geometry, normalization, and rotary policy.
        optimized_impl_config: Projection and attention backend policy.

    Raises:
        TypeError: ``optimized_impl_config`` has the wrong type.
        ValueError: A fusion or head dimension is unsupported.
    """
    super().__init__(attention_type, attention_config)
    if not isinstance(optimized_impl_config, OptimizedImplConfig):
        raise TypeError(
            "optimized_impl_config must be an OptimizedImplConfig; "
            f"got {optimized_impl_config!r}"
        )
    qkv_fusion_option = optimized_impl_config.qkv_fusion_option
    if (
        qkv_fusion_option is QKVFusionOption.FULL
        and self.attention_config.query_dim != self.attention_config.context_dim
    ):
        raise ValueError(
            "full QKV fusion requires query_dim to equal context_dim; "
            f"got {self.attention_config.query_dim} and {self.attention_config.context_dim}"
        )
    if not (
        16 <= self.attention_config.head_dim <= 256
        and self.attention_config.head_dim & (self.attention_config.head_dim - 1)
        == 0
    ):
        raise ValueError(
            "accelerated attention requires a power-of-two head_dim in [16, 256]; "
            f"got {self.attention_config.head_dim}"
        )
    if (
        self.attention_config.n_kv_heads != self.attention_config.n_heads
        and self.attention_config.qk_norm_scope is QKNormScope.INNER
    ):
        raise ValueError(
            "grouped-query attention does not support INNER Q/K normalization"
        )

    self.optimized_impl_config = optimized_impl_config
    self.qkv_fusion_option = optimized_impl_config.qkv_fusion_option
    self.sdpa_backend = optimized_impl_config.sdpa_backend
    self.use_tma = optimized_impl_config.use_tma
    self._validated_cuda_device_index = None

query_projection abstractmethod property

query_projection: Linear

Return the query projection module.

key_projection abstractmethod property

key_projection: Linear

Return the key projection module.

value_projection abstractmethod property

value_projection: Linear

Return the value projection module.

output_projection abstractmethod property

output_projection: Linear

Return the attention output projection module.

query_norm abstractmethod property

query_norm: Module

Return the query normalization module or identity.

key_norm abstractmethod property

key_norm: Module

Return the key normalization module or identity.

fused_qkv instance-attribute

fused_qkv: NonPersistentLinear | None

Nonpersistent full-fusion Q/K/V projection.

fused_kv instance-attribute

fused_kv: NonPersistentLinear | None

Nonpersistent fused K/V projection.

quantized_query_projection instance-attribute

quantized_query_projection: QuantizedNonPersistentLinear | None

Nonpersistent quantized query projection.

quantized_key_projection instance-attribute

quantized_key_projection: QuantizedNonPersistentLinear | None

Nonpersistent quantized key projection.

quantized_value_projection instance-attribute

quantized_value_projection: QuantizedNonPersistentLinear | None

Nonpersistent quantized value projection.

quantized_output_projection instance-attribute

quantized_output_projection: QuantizedNonPersistentLinear | None

Nonpersistent quantized output projection.

optimized_impl_config instance-attribute

optimized_impl_config: OptimizedImplConfig = optimized_impl_config

Projection and attention backend policy.

allocate_kv_cache

allocate_kv_cache(batch_size: int, chunk_size: int, window_size: int, sink_size: int, device: device | str, dtype: dtype) -> BlockKVCache

Allocate a rolling cache for native or quantized SDPA.

Parameters:

Name Type Description Default
batch_size int

Flattened batch size B.

required
chunk_size int

Number of current tokens L written per update.

required
window_size int

Number of rolling context tokens retained after the sink.

required
sink_size int

Number of initial context tokens that are never evicted.

required
device device | str

Device on which to allocate K/V storage.

required
dtype dtype

FP16 or BF16 activation dtype. Quantized SDPA stores the cache in FP8 e4m3 instead.

required

Returns:

Type Description
BlockKVCache

Block cache with K/V storage shaped

BlockKVCache

[B, sink_size + window_size, H, D].

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def allocate_kv_cache(
    self,
    batch_size: int,
    chunk_size: int,
    window_size: int,
    sink_size: int,
    device: torch.device | str,
    dtype: torch.dtype,
) -> BlockKVCache:
    """Allocate a rolling cache for native or quantized SDPA.

    Args:
        batch_size: Flattened batch size ``B``.
        chunk_size: Number of current tokens ``L`` written per update.
        window_size: Number of rolling context tokens retained after the sink.
        sink_size: Number of initial context tokens that are never evicted.
        device: Device on which to allocate K/V storage.
        dtype: FP16 or BF16 activation dtype. Quantized SDPA stores the cache
            in FP8 e4m3 instead.

    Returns:
        Block cache with K/V storage shaped
        ``[B, sink_size + window_size, H, D]``.

    """
    # Keep ``[B, S, H, D]`` as the public cache shape: ``BlockKVCache``
    # rolls and slices axis 1, and both attention backends accept that logical
    # order.
    kv_heads = self.attention_config.n_kv_heads
    assert kv_heads is not None
    cache_shape = (
        batch_size,
        sink_size + window_size,
        kv_heads,
        self.attention_config.head_dim,
    )
    self._validate_cuda_device(device)
    return BlockKVCache(
        k_shape=cache_shape,
        v_shape=cache_shape,
        seq_dim=1,
        chunk_size=chunk_size,
        window_size=window_size,
        sink_size=sink_size,
        device=device,
        dtype=(
            torch.float8_e4m3fn
            if self.optimized_impl_config.quantization.quantized_sdpa
            else dtype
        ),
    )

compute_kv

compute_kv(context: Tensor, rope_freqs: Tensor | None = None) -> BlockKVCache

Project complete context into a reusable static K/V cache.

Parameters:

Name Type Description Default
context Tensor

Context tokens shaped [..., S, C].

required
rope_freqs Tensor | None

Optional key rotations shaped [S, 1, 1, D]. Applied only by before-cache RoPE; after-cache RoPE stores unrotated keys. Ignored when rope_config is None.

None

Returns:

Type Description
BlockKVCache

Filled cache with logical K/V shape [B, S, H, D]. Its sequence

BlockKVCache

length and window both equal S, so subsequent forward calls read all

BlockKVCache

context.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
@torch.no_grad()
def compute_kv(
    self,
    context: Tensor,
    rope_freqs: Tensor | None = None,
) -> BlockKVCache:
    """Project complete context into a reusable static K/V cache.

    Args:
        context: Context tokens shaped ``[..., S, C]``.
        rope_freqs: Optional key rotations shaped ``[S, 1, 1, D]``.
            Applied only by before-cache RoPE; after-cache RoPE stores
            unrotated keys. Ignored when ``rope_config`` is ``None``.

    Returns:
        Filled cache with logical K/V shape ``[B, S, H, D]``. Its sequence
        length and window both equal S, so subsequent forward calls read all
        context.
    """
    key, value = self._project_kv(context)
    if (
        self.attention_config.rope_config is not None
        and self.attention_config.rope_config.scope is RoPEScope.BEFORE_KV_CACHE
        and rope_freqs is not None
    ):
        # Position affects key directions used in Q·K; values are never rotated.
        key = self._apply_rope(key, rope_freqs)

    if self.optimized_impl_config.quantization.quantized_sdpa:
        key = key.to(torch.float8_e4m3fn)
        value = value.to(torch.float8_e4m3fn)

    return BlockKVCache.from_tensor(key, value, seq_dim=1)

forward

forward(x: Tensor, kv_cache: BlockKVCache, rope_freqs: Tensor | None = None, *, attn_mask: AttentionMask | None = None) -> Tensor

Apply self- or cross-attention using the configured cache lifecycle.

Self-attention updates the prepared rolling cache and computes Q in one backend-owned branch. Cross-attention computes Q while leaving its precomputed static cache unchanged.

Parameters:

Name Type Description Default
x Tensor

Query tokens shaped [..., L, Q].

required
kv_cache BlockKVCache

Prepared rolling cache for self-attention or precomputed static cache for cross-attention.

required
rope_freqs Tensor | None

Optional positional data. Before-cache RoPE expects the current chunk. After-cache RoPE expects positions covering the query and visible cache. Ignored when rope_config is None.

None
attn_mask AttentionMask | None

Optional dense or block-sparse visibility mask.

None

Returns:

Type Description
Tensor

Output-projected tokens with the same shape and dtype as x.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/optimized.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@torch.no_grad()
def forward(
    self,
    x: Tensor,
    kv_cache: BlockKVCache,
    rope_freqs: Tensor | None = None,
    *,
    attn_mask: AttentionMask | None = None,
) -> Tensor:
    """Apply self- or cross-attention using the configured cache lifecycle.

    Self-attention updates the prepared rolling cache and computes Q in one
    backend-owned branch. Cross-attention computes Q while leaving its
    precomputed static cache unchanged.

    Args:
        x: Query tokens shaped ``[..., L, Q]``.
        kv_cache: Prepared rolling cache for self-attention or precomputed
            static cache for cross-attention.
        rope_freqs: Optional positional data. Before-cache RoPE expects the
            current chunk. After-cache RoPE expects positions covering the
            query and visible cache. Ignored when ``rope_config`` is
            ``None``.
        attn_mask: Optional dense or block-sparse visibility mask.

    Returns:
        Output-projected tokens with the same shape and dtype as ``x``.
    """
    query_rope_freqs, key_rope_freqs = self._slice_rope_freqs(
        rope_freqs, kv_cache, x.shape[-2]
    )
    if self.attention_type is AttentionType.SELF_ATTENTION:
        query = self._update_kv_and_compute_query(x, kv_cache, query_rope_freqs)
    else:
        query = self._compute_query(x, query_rope_freqs)
        self._validate_cache(kv_cache, x)

    # ``cached_k/v`` expose only the valid prefix while a rolling cache fills,
    # and the complete fixed-size buffer after it reaches steady state.
    key = kv_cache.cached_k()
    if (
        self.attention_config.rope_config is not None
        and self.attention_config.rope_config.scope is RoPEScope.AFTER_KV_CACHE
        and key_rope_freqs is not None
    ):
        # The shared RoPE kernel is in-place; keep cache storage unrotated so
        # rolling positions can be applied again on the next attention call.
        key = self._apply_rope(key.to(x.dtype, copy=True), key_rope_freqs)
    value = kv_cache.cached_v()
    if self.optimized_impl_config.quantization.quantized_sdpa:
        query = query.to(torch.float8_e4m3fn)
        key = key.to(torch.float8_e4m3fn)
        value = value.to(torch.float8_e4m3fn)
    output = self._attention(
        query,
        key,
        value,
        attn_mask=attn_mask,
        output_dtype=x.dtype,
    )
    sequence_length = x.shape[-2]
    output = output.reshape(-1, sequence_length, self.attention_config.inner_dim)
    output = self._project_output(output)
    return output.reshape(
        x.shape[:-2] + (sequence_length, self.attention_config.query_dim)
    )

flashdreams.accelerated.multi_head_attention.flex.FlexAttentionOptions dataclass

FlexAttentionOptions(block_size: int = 128, mask_block_m: int | None = None, mask_block_n: int | None = None, compile_dynamic: bool | None = None, block_m: int | None = None, block_n: int | None = None, num_warps: int | None = None, num_stages: int | None = None, prescale_qk: bool | None = None, use_tma: bool | None = None, backend: str | None = None, rows_guaranteed_safe: bool = False)

Compilation, mask-block, and kernel policy for FlexAttention.

block_size class-attribute instance-attribute

block_size: int = 128

Square fallback used when building a block mask.

mask_block_m class-attribute instance-attribute

mask_block_m: int | None = None

Optional query block size; None uses block_size.

mask_block_n class-attribute instance-attribute

mask_block_n: int | None = None

Optional key/value block size; None uses block_size.

compile_dynamic class-attribute instance-attribute

compile_dynamic: bool | None = None

Dynamic-shape policy forwarded to :func:torch.compile.

block_m class-attribute instance-attribute

block_m: int | None = None

Optional forward query tile size; None lets PyTorch choose.

block_n class-attribute instance-attribute

block_n: int | None = None

Optional forward key/value tile size; None lets PyTorch choose.

num_warps class-attribute instance-attribute

num_warps: int | None = None

Optional Triton warp count; None lets PyTorch choose.

num_stages class-attribute instance-attribute

num_stages: int | None = None

Optional Triton pipeline-stage count; None lets PyTorch choose.

prescale_qk class-attribute instance-attribute

prescale_qk: bool | None = None

Whether to apply the attention scale before the QK reduction.

use_tma class-attribute instance-attribute

use_tma: bool | None = None

Whether to request TMA from FlexAttention; None uses its default.

backend class-attribute instance-attribute

backend: str | None = None

Optional FlexAttention kernel backend: TRITON or FLASH.

rows_guaranteed_safe class-attribute instance-attribute

rows_guaranteed_safe: bool = False

Skip empty-row guards when every query sees at least one key.

mask_block_size property

mask_block_size: int | tuple[int, int]

Return square or asymmetric (query, key/value) mask blocks.

kernel_options property

kernel_options: dict[str, int | bool | str]

Return only explicitly selected FlexAttention kernel options.

__post_init__

__post_init__() -> None

Reject invalid values before they reach a compiled kernel.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/flex.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __post_init__(self) -> None:
    """Reject invalid values before they reach a compiled kernel."""
    for name, value in (
        ("block_size", self.block_size),
        ("mask_block_m", self.mask_block_m),
        ("mask_block_n", self.mask_block_n),
        ("block_m", self.block_m),
        ("block_n", self.block_n),
    ):
        if value is not None and (value < 16 or value & (value - 1)):
            raise ValueError(
                f"FlexAttention {name} must be a power of two >= 16; got {value}"
            )
    if self.compile_dynamic is not None and not isinstance(
        self.compile_dynamic, bool
    ):
        raise TypeError(
            f"compile_dynamic must be bool or None; got {self.compile_dynamic!r}"
        )
    if self.num_warps is not None and self.num_warps not in (1, 2, 4, 8):
        raise ValueError(
            f"num_warps must be one of 1, 2, 4, or 8; got {self.num_warps}"
        )
    if self.num_stages is not None and self.num_stages <= 0:
        raise ValueError(f"num_stages must be positive; got {self.num_stages}")
    for name, value in (
        ("prescale_qk", self.prescale_qk),
        ("use_tma", self.use_tma),
    ):
        if value is not None and not isinstance(value, bool):
            raise TypeError(f"{name} must be bool or None; got {value!r}")
    if self.backend is not None and self.backend not in ("TRITON", "FLASH"):
        raise ValueError(
            f"backend must be TRITON, FLASH, or None; got {self.backend!r}"
        )
    if not isinstance(self.rows_guaranteed_safe, bool):
        raise TypeError(
            f"rows_guaranteed_safe must be bool; got {self.rows_guaranteed_safe!r}"
        )

flashdreams.accelerated.multi_head_attention.flex.compiled_flex_attention cached

compiled_flex_attention(*, dynamic: bool | None = None) -> Callable[..., Tensor]

Compile FlexAttention once for each dynamic-shape policy.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/flex.py
123
124
125
126
@functools.cache
def compiled_flex_attention(*, dynamic: bool | None = None) -> Callable[..., Tensor]:
    """Compile FlexAttention once for each dynamic-shape policy."""
    return torch.compile(cast(Callable[..., Tensor], flex_attention), dynamic=dynamic)

flashdreams.accelerated.multi_head_attention.MoTRoute

Bases: str, Enum

Homogeneous model-of-thought pathway selected for one attention call.

UNDERSTANDING class-attribute instance-attribute

UNDERSTANDING = 'understanding'

Use the understanding pathway.

GENERATION class-attribute instance-attribute

GENERATION = 'generation'

Use the generation pathway.

flashdreams.accelerated.multi_head_attention.mot.MoTMultiHeadAttention

MoTMultiHeadAttention(understanding: MultiHeadAttention[Any], generation: MultiHeadAttention[Any])

Bases: Module

Route homogeneous attention calls to one of two independently weighted paths.

Register the two model-of-thought attention pathways.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/mot.py
28
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(
    self,
    understanding: MultiHeadAttention[Any],
    generation: MultiHeadAttention[Any],
) -> None:
    """Register the two model-of-thought attention pathways."""
    super().__init__()
    if not isinstance(understanding, MultiHeadAttention):
        raise TypeError("understanding must be a MultiHeadAttention module")
    if not isinstance(generation, MultiHeadAttention):
        raise TypeError("generation must be a MultiHeadAttention module")
    self.understanding = understanding
    self.generation = generation

understanding instance-attribute

understanding: MultiHeadAttention[Any] = understanding

Attention module used for understanding tokens.

generation instance-attribute

generation: MultiHeadAttention[Any] = generation

Attention module used for generation tokens.

branch

branch(route: MoTRoute) -> MultiHeadAttention[Any]

Return the attention module selected by route.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/mot.py
42
43
44
45
46
47
def branch(self, route: MoTRoute) -> MultiHeadAttention[Any]:
    """Return the attention module selected by ``route``."""
    self._validate_route(route)
    if route is MoTRoute.UNDERSTANDING:
        return self.understanding
    return self.generation

compute_kv

compute_kv(context: Tensor, rope_freqs: Tensor | None = None, *, route: MoTRoute) -> Any

Project static context through one homogeneous pathway.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/mot.py
49
50
51
52
53
54
55
56
57
def compute_kv(
    self,
    context: Tensor,
    rope_freqs: Tensor | None = None,
    *,
    route: MoTRoute,
) -> Any:
    """Project static context through one homogeneous pathway."""
    return self.branch(route).compute_kv(context, rope_freqs)

forward

forward(x: Tensor, kv_cache: Any, rope_freqs: Tensor | None = None, *, route: MoTRoute, attn_mask: AttentionMask | None = None) -> Tensor

Apply one homogeneous model-of-thought pathway.

Parameters:

Name Type Description Default
x Tensor

Query tokens for a single pathway.

required
kv_cache Any

Cache owned by the selected attention module.

required
rope_freqs Tensor | None

Optional rotary-position data.

None
route MoTRoute

Understanding or generation pathway for the complete call.

required
attn_mask AttentionMask | None

Optional visibility mask supported by the selected backend.

None

Returns:

Type Description
Tensor

Output from the selected attention module.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/mot.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def forward(
    self,
    x: Tensor,
    kv_cache: Any,
    rope_freqs: Tensor | None = None,
    *,
    route: MoTRoute,
    attn_mask: AttentionMask | None = None,
) -> Tensor:
    """Apply one homogeneous model-of-thought pathway.

    Args:
        x: Query tokens for a single pathway.
        kv_cache: Cache owned by the selected attention module.
        rope_freqs: Optional rotary-position data.
        route: Understanding or generation pathway for the complete call.
        attn_mask: Optional visibility mask supported by the selected backend.

    Returns:
        Output from the selected attention module.
    """
    branch = self.branch(route)
    return branch(x, kv_cache, rope_freqs, attn_mask=attn_mask)

Masked attention functions

flashdreams.accelerated.multi_head_attention.functional.masked_attention

masked_attention(query: Tensor, key: Tensor, value: Tensor, mask: AttentionMask, *, enable_gqa: bool = False, flex_options: FlexAttentionOptions = FlexAttentionOptions()) -> Tensor

Apply dense or block-sparse attention selected by mask.

Parameters:

Name Type Description Default
query Tensor

Query heads shaped [B, Hq, Q, D].

required
key Tensor

Key heads shaped [B, Hkv, K, D].

required
value Tensor

Value heads shaped [B, Hkv, K, Dv].

required
mask AttentionMask

A boolean [Q, K] tensor or equivalent :class:BlockMask.

required
enable_gqa bool

Share each K/V head across a group of query heads.

False
flex_options FlexAttentionOptions

Mask geometry, compilation, and kernel policy used by FlexAttention. Ignored for a dense mask.

FlexAttentionOptions()

Returns:

Type Description
Tensor

Attention output shaped [B, Hq, Q, Dv].

Raises:

Type Description
TypeError

mask is neither a boolean tensor nor a block mask.

ValueError

Q/K/V or mask geometry is incompatible.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/functional.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def masked_attention(
    query: Tensor,
    key: Tensor,
    value: Tensor,
    mask: AttentionMask,
    *,
    enable_gqa: bool = False,
    flex_options: FlexAttentionOptions = FlexAttentionOptions(),
) -> Tensor:
    """Apply dense or block-sparse attention selected by ``mask``.

    Args:
        query: Query heads shaped ``[B, Hq, Q, D]``.
        key: Key heads shaped ``[B, Hkv, K, D]``.
        value: Value heads shaped ``[B, Hkv, K, Dv]``.
        mask: A boolean ``[Q, K]`` tensor or equivalent :class:`BlockMask`.
        enable_gqa: Share each K/V head across a group of query heads.
        flex_options: Mask geometry, compilation, and kernel policy used by
            FlexAttention. Ignored for a dense mask.

    Returns:
        Attention output shaped ``[B, Hq, Q, Dv]``.

    Raises:
        TypeError: ``mask`` is neither a boolean tensor nor a block mask.
        ValueError: Q/K/V or mask geometry is incompatible.
    """
    _validate_qkv(query, key, value, enable_gqa=enable_gqa)
    if not isinstance(flex_options, FlexAttentionOptions):
        raise TypeError(
            f"flex_options must be a FlexAttentionOptions; got {flex_options!r}."
        )
    expected = (query.shape[-2], key.shape[-2])
    if isinstance(mask, BlockMask):
        if tuple(mask.shape[-2:]) != expected:
            raise ValueError(
                f"block mask shape {tuple(mask.shape[-2:])} does not match {expected}."
            )
        return compiled_flex_attention(dynamic=flex_options.compile_dynamic)(
            query,
            key,
            value,
            block_mask=mask,
            enable_gqa=enable_gqa,
            kernel_options=flex_options.kernel_options or None,
        )
    if not isinstance(mask, Tensor):
        raise TypeError(f"mask must be a Tensor or BlockMask; got {type(mask)!r}.")
    if mask.ndim != 2:
        raise ValueError(
            "dense mask must be a two-dimensional [Q, KV] mask; "
            f"got {tuple(mask.shape)}."
        )
    if tuple(mask.shape) != expected:
        raise ValueError(
            f"dense mask shape {tuple(mask.shape)} does not match {expected}."
        )
    if mask.dtype is not torch.bool:
        raise ValueError(f"dense mask must be boolean; got {mask.dtype}.")
    if mask.device != query.device:
        raise ValueError("dense mask must be on the query device.")
    with backend_for(query):
        return F.scaled_dot_product_attention(
            query,
            key,
            value,
            attn_mask=mask,
            enable_gqa=enable_gqa,
        )

flashdreams.accelerated.multi_head_attention.reference.reference_masked_attention

reference_masked_attention(query: Tensor, key: Tensor, value: Tensor, mask: Tensor) -> Tensor

Compute masked attention explicitly, without an SDPA backend.

Parameters:

Name Type Description Default
query Tensor

Queries shaped [B, H, Q, D].

required
key Tensor

Keys shaped [B, H, K, D].

required
value Tensor

Values shaped [B, H, K, Dv].

required
mask Tensor

Boolean visibility mask shaped [Q, K].

required

Returns:

Type Description
Tensor

Attention values shaped [B, H, Q, Dv].

Raises:

Type Description
ValueError

Q/K/V or mask geometry is inconsistent.

TypeError

mask is not boolean.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/reference.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def reference_masked_attention(
    query: Tensor,
    key: Tensor,
    value: Tensor,
    mask: Tensor,
) -> Tensor:
    """Compute masked attention explicitly, without an SDPA backend.

    Args:
        query: Queries shaped ``[B, H, Q, D]``.
        key: Keys shaped ``[B, H, K, D]``.
        value: Values shaped ``[B, H, K, Dv]``.
        mask: Boolean visibility mask shaped ``[Q, K]``.

    Returns:
        Attention values shaped ``[B, H, Q, Dv]``.

    Raises:
        ValueError: Q/K/V or mask geometry is inconsistent.
        TypeError: ``mask`` is not boolean.
    """
    if query.ndim != 4 or key.ndim != 4 or value.ndim != 4:
        raise ValueError("query, key, and value must have shape [B, H, S, D].")
    if query.shape[:2] != key.shape[:2] or key.shape[:3] != value.shape[:3]:
        raise ValueError("query, key, and value batch/head/token axes must agree.")
    expected = (query.shape[-2], key.shape[-2])
    if tuple(mask.shape) != expected:
        raise ValueError(f"mask shape must be {expected}; got {tuple(mask.shape)}.")
    if mask.dtype is not torch.bool:
        raise TypeError(f"mask must be boolean; got {mask.dtype}.")

    scores = torch.matmul(query, key.transpose(-1, -2))
    scores = scores * query.shape[-1] ** -0.5
    scores = scores.masked_fill(~mask[None, None], -torch.inf)
    weights = torch.softmax(scores, dim=-1).nan_to_num()
    return torch.matmul(weights, value)

KV arena

flashdreams.accelerated.multi_head_attention.kv_arena.KVSegmentLayout dataclass

KVSegmentLayout(static_tokens: int, current_tokens: int, memory_tokens: int)

Token offsets for [static | current | memory] K/V storage.

flashdreams.accelerated.multi_head_attention.kv_arena.allocate_kv_arena

allocate_kv_arena(static: KVPair, memory: KVPair, *, current_tokens: int, memory_tokens: int) -> tuple[KVPair, KVSegmentLayout]

Allocate [static | current | memory] and seed its persistent regions.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/kv_arena.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def allocate_kv_arena(
    static: KVPair,
    memory: KVPair,
    *,
    current_tokens: int,
    memory_tokens: int,
) -> tuple[KVPair, KVSegmentLayout]:
    """Allocate ``[static | current | memory]`` and seed its persistent regions."""
    _validate_pair(static, "static")
    _validate_pair(memory, "memory")
    static_key, static_value = static
    memory_key, memory_value = memory
    if (
        static_key.shape[:2] + static_key.shape[3:]
        != memory_key.shape[:2] + memory_key.shape[3:]
        or static_key.dtype is not memory_key.dtype
        or static_key.device != memory_key.device
    ):
        raise ValueError(
            "static and memory K/V batch, heads, width, dtype, and device must match"
        )
    if memory_key.shape[2] > memory_tokens:
        raise ValueError(
            f"memory contains {memory_key.shape[2]} tokens past capacity {memory_tokens}"
        )

    layout = KVSegmentLayout(static_key.shape[2], current_tokens, memory_tokens)
    shape = (*static_key.shape[:2], layout.total_tokens, static_key.shape[3])
    arena_key = static_key.new_zeros(shape)
    arena_value = static_value.new_zeros(shape)
    arena_key[:, :, : layout.static_tokens].copy_(static_key)
    arena_value[:, :, : layout.static_tokens].copy_(static_value)
    memory_end = layout.memory_start + memory_key.shape[2]
    arena_key[:, :, layout.memory_start : memory_end].copy_(memory_key)
    arena_value[:, :, layout.memory_start : memory_end].copy_(memory_value)
    return (arena_key, arena_value), layout

flashdreams.accelerated.multi_head_attention.kv_arena.validate_kv_arena_segments

validate_kv_arena_segments(arena: KVPair, static: KVPair, memory: KVPair, layout: KVSegmentLayout) -> None

Verify persistent inputs are the arena segments named by layout.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/kv_arena.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def validate_kv_arena_segments(
    arena: KVPair,
    static: KVPair,
    memory: KVPair,
    layout: KVSegmentLayout,
) -> None:
    """Verify persistent inputs are the arena segments named by ``layout``."""
    _validate_arena_storage(arena)
    _validate_pair(static, "static")
    _validate_pair(memory, "memory")

    for name, pair, start, tokens in (
        ("static", static, 0, layout.static_tokens),
        ("memory", memory, layout.memory_start, layout.memory_tokens),
    ):
        for arena_tensor, segment in zip(arena, pair, strict=True):
            expected_shape = (
                *arena_tensor.shape[:2],
                tokens,
                arena_tensor.shape[3],
            )
            expected_offset = (
                arena_tensor.storage_offset() + start * arena_tensor.stride(2)
            )
            if tuple(segment.shape) != expected_shape:
                raise ValueError(
                    f"{name} arena segment must have shape {expected_shape}, "
                    f"got {tuple(segment.shape)}"
                )
            if (
                segment.untyped_storage().data_ptr()
                != arena_tensor.untyped_storage().data_ptr()
                or segment.storage_offset() != expected_offset
                or segment.stride() != arena_tensor.stride()
            ):
                raise ValueError(
                    f"{name} K/V must alias its declared attention arena segment"
                )

flashdreams.accelerated.multi_head_attention.kv_arena.stage_current_kv_

stage_current_kv_(arena: KVPair, current: KVPair, layout: KVSegmentLayout) -> KVPair

Overwrite only the current segment and return the contiguous arena.

Source code in flashdreams/flashdreams/accelerated/multi_head_attention/kv_arena.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def stage_current_kv_(
    arena: KVPair,
    current: KVPair,
    layout: KVSegmentLayout,
) -> KVPair:
    """Overwrite only the current segment and return the contiguous arena."""
    _validate_arena_storage(arena)
    _validate_pair(current, "current")
    arena_key, arena_value = arena
    current_key, current_value = current
    expected = (*arena_key.shape[:2], layout.current_tokens, arena_key.shape[3])
    if tuple(arena_key.shape) != (
        *expected[:2],
        layout.total_tokens,
        expected[3],
    ):
        raise ValueError(
            f"arena shape {tuple(arena_key.shape)} does not match layout total "
            f"{layout.total_tokens}"
        )
    if tuple(current_key.shape) != expected:
        raise ValueError(
            f"current K/V must have shape {expected}, got {tuple(current_key.shape)}"
        )
    if (
        current_key.dtype is not arena_key.dtype
        or current_key.device != arena_key.device
    ):
        raise ValueError("current and arena K/V must have matching dtype and device")
    arena_storage = {
        arena_key.untyped_storage().data_ptr(),
        arena_value.untyped_storage().data_ptr(),
    }
    if (
        current_key.untyped_storage().data_ptr() in arena_storage
        or current_value.untyped_storage().data_ptr() in arena_storage
    ):
        raise ValueError("current K/V must not alias the destination arena")

    current_end = layout.current_start + layout.current_tokens
    arena_key[:, :, layout.current_start : current_end].copy_(current_key)
    arena_value[:, :, layout.current_start : current_end].copy_(current_value)
    return arena