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 |
required |
bias
|
Tensor | None
|
Optional projection bias shaped |
required |
Source code in flashdreams/flashdreams/accelerated/common/non_persistent_linear.py
12 13 14 15 16 17 18 19 20 21 22 23 | |
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 | |
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. |
required |
axis
|
int
|
Dimension over which |
-1
|
use_triton
|
bool
|
Use Triton for CUDA tensors. CPU tensors retain the Torch
implementation. Defaults to |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Quantized tensor and its FP32 scale tensor. The scale has the same |
Tensor
|
number of dimensions as |
tuple[Tensor, Tensor]
|
with size one. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
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 | |
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 |
()
|
dtype
|
dtype
|
Data type of the dequantized tensor. Defaults to |
float16
|
use_triton
|
bool
|
Use Triton for CUDA tensors. CPU tensors retain the Torch
implementation. Defaults to |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Dequantized tensor in |
Tensor
|
Without scales, casts |
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 | |
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 |
required |
bias
|
Tensor | None
|
Optional projection bias shaped |
required |
granularity
|
WeightGranularity
|
Scale granularity used to quantize |
required |
dtype
|
dtype
|
Quantized activation format. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
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 | |
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 |
required |
scale_or_granularity
|
Tensor | Granularity
|
For prequantized |
required |
out_dtype
|
dtype
|
Data type of the projected activations. Defaults to
|
float16
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Projected activations shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
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 | |
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 | |
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
scope: RoPEScope = RoPEScope.BEFORE_KV_CACHE
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 | |
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 | |
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 |
required |
rope_freqs
|
Tensor | None
|
Optional key positional data for the |
None
|
Returns:
| Type | Description |
|---|---|
KVCacheT
|
Precomputed cache containing K/V for all |
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 | |
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 |
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 |
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 |
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 | |
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 | |
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 |
required |
chunk_size
|
int
|
Exact number of current tokens |
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
|
|
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 | |
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
|
required |
rope_freqs
|
Tensor | None
|
Optional key rotations with shape |
None
|
Returns:
| Type | Description |
|---|---|
BlockKVCache
|
Static cache with K/V shape |
BlockKVCache
|
meth: |
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 | |
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 |
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 |
None
|
attn_mask
|
AttentionMask | None
|
Optional dense boolean visibility mask shaped |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Output-projected tokens with the same shape as |
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 | |
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 | |
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
quantization: QuantizationOption = QuantizationOption()
Attention quantization policy.
flex_attention
class-attribute
instance-attribute
flex_attention: FlexAttentionOptions = FlexAttentionOptions()
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 | |
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
|
|
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 | |
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 |
required |
chunk_size
|
int
|
Number of current tokens |
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
|
|
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 | |
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 |
required |
rope_freqs
|
Tensor | None
|
Optional key rotations shaped |
None
|
Returns:
| Type | Description |
|---|---|
BlockKVCache
|
Filled cache with logical K/V shape |
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 | |
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 |
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 |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 |
required |
key
|
Tensor
|
Key heads shaped |
required |
value
|
Tensor
|
Value heads shaped |
required |
mask
|
AttentionMask
|
A boolean |
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 |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
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 | |
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 |
required |
key
|
Tensor
|
Keys shaped |
required |
value
|
Tensor
|
Values shaped |
required |
mask
|
Tensor
|
Boolean visibility mask shaped |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Attention values shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
Q/K/V or mask geometry is inconsistent. |
TypeError
|
|
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 | |
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 | |
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 | |
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 | |