Hybrid Attention and State Space Models › Code: Cache Accounting

Michael BrenndoerferNovember 17, 202614 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 134Hybrid Attention and State Space Models › Code: Cache Accounting
Reading section 8 of 12 · Code: Cache Accounting · 14 minSection 8 of 12 · 14 min

Section 8 of 12 · 14 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

At what context length does the key-value cache exceed the combined recurrent and convolution state? The calculation first finds where the two payloads are equal, then finds the first whole-token length where the KV cache is larger.

What this accounting excludes

The calculation counts persistent keys and values, recurrent state, and convolution state. It leaves out model and expert weights, communication buffers, transient activations, workspaces, and padding or allocator overhead. All BB sequences in the batch have the same length and each stored element uses the same number of bytes. Unequal lengths or different storage precision require separate terms.

Byte formulas

Each quantity has a different shape and a different scaling in LL. The formulas below use:

  • LL: the number of retained positions per sequence, counting the prompt and generated tokens already processed by the model
  • nattnn_{\text{attn}}: the number of attention layers
  • nssmn_{\text{ssm}}: the number of state space layers
  • nkvn_{\text{kv}}: the number of key-value heads (grouped-query attention)
  • dheadd_{\text{head}}: the dimension per attention head
  • dinnerd_{\text{inner}}: the state space inner width
  • dstated_{\text{state}}: the state size per channel
  • dconvd_{\text{conv}}: the short-convolution history length
  • BB (batch size) and nbytesn_{\text{bytes}}: batch size and bytes per element, which cancel in the crossover
PythonIn [13]
CollapseExpand
def kv_cache_bytes(L, cfg):
    """Key and value payload across attention layers for an equal-length batch."""
    return (
        2
        * cfg["batch"]
        * cfg["n_attn_layers"]
        * L
        * cfg["n_kv_heads"]
        * cfg["d_head"]
        * cfg["nbytes"]
    )


def recurrent_state_bytes(cfg):
    """Recurrent state payload across state-space layers and sequences."""
    return (
        cfg["batch"]
        * cfg["n_ssm_layers"]
        * cfg["d_inner"]
        * cfg["d_state"]
        * cfg["nbytes"]
    )


def conv_state_bytes(cfg):
    """Short convolution history kept per state space layer."""
    return (
        cfg["batch"]
        * cfg["n_ssm_layers"]
        * cfg["d_inner"]
        * cfg["d_conv"]
        * cfg["nbytes"]
    )

The factor of 2 in the key-value formula counts one key tensor and one value tensor per attention layer. Each modeled Mamba-1 layer has a recurrent state and a separate convolution buffer with an allocated history width.

We now instantiate a configuration in the spirit of a 50B-class hybrid: width 4096, expansion factor 2, four attention layers and 28 state space layers, grouped-query attention with eight key-value heads of dimension 128, and bfloat16 storage.

PythonIn [14]
CollapseExpand
CFG = dict(
    batch=1,
    n_attn_layers=4,  # attention layers
    n_ssm_layers=28,  # state space layers
    n_kv_heads=8,  # grouped-query attention
    d_head=128,
    d_inner=8192,  # 2 * d_model, d_model = 4096
    d_state=16,
    d_conv=4,
    nbytes=2,  # bfloat16
)

The layer dimensions match the public Jamba-v0.1 configuration. The calculation assumes two bytes per stored element across the KV cache, recurrent state, and convolution buffer. To apply it to another deployment, use the model's dimensions and the runtime's storage precisions.

PythonIn [15]
CollapseExpand
def human(nbytes):
    value = float(nbytes)
    for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
        if abs(value) < 1024.0:
            return f"{value:.2f} {unit}"
        value /= 1024.0
    return f"{value:.2f} PiB"


kv_one_token = kv_cache_bytes(1, CFG)
rec_state = recurrent_state_bytes(CFG)
conv_state = conv_state_bytes(CFG)
ConsoleOut [16]
CollapseExpand
KV cache per retained token    : 16.00 KiB
recurrent state, all layers    : 7.00 MiB
convolution state, all layers  : 1.75 MiB
constant part of the state     : 8.75 MiB

The four attention layers add 16 KiB of KV cache per retained token. Across all 28 state-space layers, the recurrent state uses 7 MiB and the convolution buffers use 1.75 MiB.

Deriving the crossover

A positive within-hybrid crossover requires a growing KV cache and a positive combined recurrent and convolution payload. Batch size and bytes per element cancel because both sides share those positive factors. The equality point L∗L^* can be fractional. The first integer length where the KV cache is larger is ⌊L∗⌋+1\lfloor L^*\rfloor+1. Use the component formulas to compare pure stacks. An all-attention stack has no fixed state in this accounting, and an all-state-space stack has no KV cache.

2 nattn L nkv dhead=nssm dinner(dstate+dconv)2 \, n_{\text{attn}} \, L \, n_{\text{kv}} \, d_{\text{head}} = n_{\text{ssm}} \, d_{\text{inner}} \left(d_{\text{state}} + d_{\text{conv}}\right) L∗=nssm dinner(dstate+dconv)2 nattn nkv dheadL^{*} = \frac{n_{\text{ssm}} \, d_{\text{inner}} \left(d_{\text{state}} + d_{\text{conv}}\right)}{2 \, n_{\text{attn}} \, n_{\text{kv}} \, d_{\text{head}}}

where:

  • L∗L^{*}: the positive real-valued equality point for the KV cache and the combined recurrent and convolution state
  • nattnn_{\text{attn}}: the number of attention layers
  • nssmn_{\text{ssm}}: the number of state space layers
  • nkvn_{\text{kv}}: the number of key-value heads
  • dheadd_{\text{head}}: the dimension per attention head
  • dinnerd_{\text{inner}}: the state space inner width
  • dstated_{\text{state}}: the state size per channel
  • dconvd_{\text{conv}}: the short-convolution history length
  • the factor of 2 accounts for the key and value tensors
PythonIn [17]
CollapseExpand
from fractions import Fraction


def crossover_length(cfg):
    """Return the equality length for positive KV and fixed-state components."""
    numerator = (
        cfg["n_ssm_layers"] * cfg["d_inner"] * (cfg["d_state"] + cfg["d_conv"])
    )
    denominator = 2 * cfg["n_attn_layers"] * cfg["n_kv_heads"] * cfg["d_head"]
    if denominator <= 0:
        raise ValueError("The KV cache must have a positive per-token slope")
    if numerator <= 0:
        raise ValueError(
            "The combined recurrent and convolution payload must be positive"
        )
    return Fraction(numerator, denominator)


L_star = crossover_length(CFG)
first_overtake = L_star.numerator // L_star.denominator + 1
fixed_state = rec_state + conv_state
assert kv_cache_bytes(first_overtake - 1, CFG) <= fixed_state
assert kv_cache_bytes(first_overtake, CFG) > fixed_state
ConsoleOut [18]
CollapseExpand
equality point                  : 560 tokens
first length with larger KV cache: 561 tokens
state at 1 token                : 8.77 MiB
state at equality               : 17.50 MiB
state at 262144 tokens           : 4.01 GiB

At 560 tokens, the four attention layers use the same 8.75 MiB as the recurrent and convolution states combined. At 561 tokens, the KV cache first exceeds that fixed payload. At 262,144 tokens, the KV term alone is 4 GiB.

When attention layers share a cache layout and precision, the all-attention stack's KV term scales with its layer count and the hybrid's KV term scales with its smaller attention count. With 32 versus four attention layers, their KV terms differ by a factor of eight at every length. Add the hybrid's fixed state to compare total persistent decode state. The hybrid's fraction of the all-attention total approaches 4/32=12.5%4/32=12.5\% as LL grows, which is a reduction approaching 87.5%87.5\% in the counted state.

The same accounting makes the ratio trade-off visible at a fixed long context. The next figure fixes the context at 256K tokens and varies the layer count while holding total depth at 32.

PythonIn [19]
CollapseExpand
# Attention counts span the 1:15, 1:7, 1:3, 1:1, and pure-attention endpoints.
# Total depth is fixed at 32 layers; n_ssm is the complement. Context is fixed at 262144.
ATTENTION_COUNTS = np.array([2, 4, 8, 16, 32])
CONTEXT_FOR_RATIO = 262144
ratio_bytes = []
for n_attn in ATTENTION_COUNTS:
    cfg = dict(CFG)
    cfg["n_attn_layers"] = int(n_attn)
    cfg["n_ssm_layers"] = int(32 - n_attn)
    ratio_bytes.append(
        kv_cache_bytes(CONTEXT_FOR_RATIO, cfg)
        + recurrent_state_bytes(cfg)
        + conv_state_bytes(cfg)
    )
ratio_bytes = np.array(ratio_bytes)
ratio_gib = ratio_bytes / (1024**3)
ratio_labels = [f"{int(n)}:{32 - int(n)}" for n in ATTENTION_COUNTS]
VisualizationOut [20]
CollapseExpand
Bar chart of decode-state bytes at 256K tokens across attention ratios.
Persistent decode state at 262,144 tokens for 32-layer stacks. Each additional attention layer adds a KV cache and replaces one layer's fixed recurrent and convolution state. At this length the KV term dominates the total.

Comparing three stacks at equal depth

Compare three equal-depth stacks. The all-attention stack has 32 attention layers. The hybrid has four attention layers and 28 state-space layers. The all-state-space stack has 32 state-space layers.

The equal-stack crossover concerns replacing 28 attention layers with 28 state-space layers. Divide both sides by 28 to compare the growing KV term and the constant state term for a single layer. This gives 80 tokens with the assumed layer dimensions. At that length all three totals agree. At longer lengths, each replaced layer reduces the total state, and the all-state-space stack uses the smallest state payload of the three.

PythonIn [21]
CollapseExpand
def stack_bytes(length, n_attn, n_ssm, cfg):
    layer_counts = dict(cfg, n_attn_layers=n_attn, n_ssm_layers=n_ssm)
    return (
        kv_cache_bytes(length, layer_counts)
        + recurrent_state_bytes(layer_counts)
        + conv_state_bytes(layer_counts)
    )


attention_layer = dict(CFG, n_attn_layers=1)
ssm_layer = dict(CFG, n_ssm_layers=1)
stack_crossover = (
    recurrent_state_bytes(ssm_layer) + conv_state_bytes(ssm_layer)
) / kv_cache_bytes(1, attention_layer)
PythonIn [22]
CollapseExpand
lengths = np.unique(np.round(np.logspace(0, np.log10(262144), 240)).astype(int))
mib = 2**20
pure_attn = stack_bytes(lengths, 32, 0, CFG) / mib
hybrid = stack_bytes(lengths, 4, 28, CFG) / mib
pure_ssm = np.full(lengths.shape, stack_bytes(1, 0, 32, CFG) / mib)
assert stack_bytes(stack_crossover, 32, 0, CFG) == stack_bytes(
    stack_crossover, 4, 28, CFG
)
ConsoleOut [23]
CollapseExpand
Equal per-stack state at 80 tokens
All-attention to hybrid state ratio at 262,144 tokens: 7.98x
VisualizationOut [24]
CollapseExpand
Log-log chart of three stack totals. The totals meet at 80 tokens. In the hybrid, the KV cache equals its fixed state at 560 tokens. The all-state-space line stays flat.
Three equal-depth stacks have equal persistent decode state at 80 tokens with these layer dimensions. The two components inside the hybrid match at 560 tokens. These crossovers compare different quantities.

At one token, the 32-layer attention stack uses the smallest state payload. After 80 tokens the ordering reverses. The hybrid's curve bends because it combines constant and linear terms. At long lengths its KV term dominates and the ratio of all-attention to hybrid state approaches eight. The plot holds model width and per-layer storage fixed and counts neither parameters nor execution time.

An idealized prefill model

Use the widths from the cache example and count a multiply and an addition as two floating point operations. Write dd for the model width and dkd_k for the combined width of the grouped key heads, also the combined width of the grouped value heads. The query and output matrices each map between two dd-dimensional spaces. The key and value projections map from width dd to dkd_k. The terms for those four matrices are 4Ld24Ld^2 for query and output and 4Lddk4Ldd_k for key and value.

For each of the L(L+1)/2L(L+1)/2 valid pairs, the score uses a query–key product and the value is scaled and added to the output. Summed across query heads, the leading operation count is about 4d4d per pair. Here we count exactly the valid pairs. An actual kernel can do more work on padded blocks. The selective mixer has two input projections from dd to the expanded width did_i and one output projection back to dd. Denote the two partial estimates by FattnF_{\mathrm{attn}} and FssmF_{\mathrm{ssm}}.

Fattn(L)=4Ld2+4Lddk+2dL(L+1),Fssm(L)=6Lddi.\begin{aligned} F_{\mathrm{attn}}(L) &= 4Ld^2 + 4Ldd_k + 2dL(L+1),\\ F_{\mathrm{ssm}}(L) &= 6Ldd_i . \end{aligned}

This estimate includes three projection products for the state-space layer. Its internal parameter projections, causal convolution, state updates, and gating add work outside the estimate. The attention estimate omits the softmax and score transformations. Both estimates omit the feed-forward layer and normalization. The estimates count arithmetic and do not predict elapsed time.

Both expressions have a common factor 2Ld2Ld for positive LL and dd. Divide by it to compare 2d+2dk+L+12d+2d_k+L+1 to 3di3d_i. The two estimates match at L=3di−2(d+dk)−1L=3d_i-2(d+d_k)-1 if that gives a positive length. The formula concerns the listed operations, so other costs can move the crossover for two implemented mixers.

PythonIn [25]
CollapseExpand
def attn_layer_flops(length, model_width, kv_width):
    q_and_o = 4 * length * model_width**2
    k_and_v = 4 * length * model_width * kv_width
    pair_products = 2 * model_width * length * (length + 1)
    return q_and_o + k_and_v + pair_products


def ssm_layer_flops(length, model_width, inner_width):
    return 6 * length * model_width * inner_width
PythonIn [26]
CollapseExpand
d_model = 4096
kv_width = CFG["n_kv_heads"] * CFG["d_head"]
d_inner = CFG["d_inner"]
attention_pair_crossover = 2 * (d_model + kv_width) - 1
flop_cross = 3 * d_inner - 2 * (d_model + kv_width) - 1

flop_lengths = np.unique(np.round(np.logspace(2, 6, 200)).astype(np.int64))
attn_f = attn_layer_flops(flop_lengths, d_model, kv_width)
ssm_f = ssm_layer_flops(flop_lengths, d_model, d_inner)

projection_work = 4 * attention_pair_crossover * d_model * (d_model + kv_width)
pair_work = (
    2 * d_model * attention_pair_crossover * (attention_pair_crossover + 1)
)
assert projection_work == pair_work
assert attn_layer_flops(flop_cross, d_model, kv_width) == ssm_layer_flops(
    flop_cross, d_model, d_inner
)
ConsoleOut [27]
CollapseExpand
Equal attention projection and pair work at 10,239 tokens
Equal attention-mixer and state-space projection estimates at 14,335 tokens

With model width 4,096, combined key or value width 1,024, and state-space inner width 8,192, attention projection work equals attention pair work at 10,239 tokens. From 10,240 through 14,334 tokens, pair work is already larger than attention projection work, while the attention total is still smaller than the state-space projection estimate. The two mixer estimates meet at 14,335 tokens. Above that point, the attention total is larger.

VisualizationOut [28]
CollapseExpand
Log-log chart of attention and state-space mixer operation counts intersecting near fourteen thousand tokens, with attention rising faster above that point.
Idealized operation counts for one attention mixer and the input and output projections of one Mamba-style mixer. The model counts the accessible causal attention pairs and omits several other operations in both mixers.

Where the attention layers go

Compare three hypothetical schedules with four attention layers and 28 state-space layers. Move the attention layers between the schedules, while keeping their count and the width of each mixer fixed. The periodic schedule shows the four attention positions listed in the original Jamba checkpoint configuration.

PythonIn [29]
CollapseExpand
n_layers = 32
patterns = {
    "Periodic": [4, 12, 20, 28],
    "Prefix": [0, 1, 2, 3],
    "Suffix": [28, 29, 30, 31],
}

placement_grid = np.zeros((len(patterns), n_layers), dtype=int)
for row, attention_positions in enumerate(patterns.values()):
    placement_grid[row, attention_positions] = 1
VisualizationOut [30]
CollapseExpand
Three rows identify the four attention layers among 32 mixer layers, distributed periodically or clustered at the beginning or end.
Three schedules with four attention layers. They add the same number of position-indexed caches when their attention layers and serving configuration match.

The schedules have different depths at which an attention layer can first combine representations across positions. The periodic pattern also leaves several state-space layers between attention layers. The placements alone give no quality ranking. To measure the effect, compare these schedules under the same training setup and evaluate the tasks and prompt lengths that matter for serving.

Jamba-v0.1 model configuration

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy