FlexDM-LoRA-v2.0 / code /jevlab /attention.py
1000luca's picture
FlexDM-LoRA ver 2.0 (same files as in 1000luca/FlexDM-LoRA)
746fea7 verified
Raw History Blame Contribute Delete
3.47 kB
"""SDPA that skips the keys a block of queries cannot see.
With a boolean mask, torch's SDPA on CUDA runs the memory-efficient kernel over every query-key pair and only then applies
the mask. Gemma-4's sliding-window layers (50 of 60) let a token see the last 1,024 positions, and packed questions do not
see each other, so most of that work is thrown away on long rows. Here the queries are cut into blocks; each block attends
only to the span of keys from the first to the last one its mask allows (widened to a multiple of 16), with the same mask
on that span. A key outside the span is masked for every query of the block, so the result is the same attention.
from jevlab.attention import use_blocked_attention
use_blocked_attention(model, block=512)
"""
import weakref
import torch
from transformers import AttentionInterface
from transformers.integrations.sdpa_attention import repeat_kv, sdpa_attention_forward
from transformers.masking_utils import AttentionMaskInterface, sdpa_mask
NAME = "jev_blocked_sdpa"
ALIGN = 16
BLOCK = {"size": 512}
_spans = {} # id(mask) -> (weakref to mask, block, spans)
def key_spans(mask, block):
"""[(q0, q1, k0, k1)]: for each block of query rows, the span of key columns any of its rows may see."""
hit = _spans.get(id(mask))
if hit is not None and hit[0]() is mask and hit[1] == block:
return hit[2]
m = mask.reshape(-1, *mask.shape[-2:]).any(0)
lq, lk = m.shape
nb = -(-lq // block)
if nb * block > lq:
m = torch.cat([m, m.new_zeros(nb * block - lq, lk)])
seen = m.view(nb, block, lk).any(1)
first = seen.int().argmax(1).tolist()
last = (lk - 1 - seen.flip(1).int().argmax(1)).tolist()
spans = [(i * block, min(lq, (i + 1) * block), a // ALIGN * ALIGN, min(lk, -(-(b + 1) // ALIGN) * ALIGN))
for i, (a, b) in enumerate(zip(first, last))]
if len(_spans) > 64:
_spans.clear()
_spans[id(mask)] = (weakref.ref(mask), block, spans)
return spans
def blocked_sdpa(module, query, key, value, attention_mask, dropout=0.0, scaling=None, is_causal=None, **kwargs):
block = BLOCK["size"]
if attention_mask is None or attention_mask.dtype != torch.bool or dropout or key.shape[2] <= block:
return sdpa_attention_forward(module, query, key, value, attention_mask, dropout=dropout, scaling=scaling, is_causal=is_causal, **kwargs)
n_rep = getattr(module, "num_key_value_groups", 1)
if n_rep > 1:
key, value = repeat_kv(key, n_rep), repeat_kv(value, n_rep)
b, h, lq, _ = query.shape
out = query.new_empty(b, lq, h, value.shape[-1])
for q0, q1, k0, k1 in key_spans(attention_mask, block):
o = torch.nn.functional.scaled_dot_product_attention(query[:, :, q0:q1], key[:, :, k0:k1], value[:, :, k0:k1],
attn_mask=attention_mask[..., q0:q1, k0:k1], scale=scaling)
out[:, q0:q1] = o.transpose(1, 2)
return out, None
def use_blocked_attention(model, block=512):
"""Switch every attention layer of `model` to blocked_sdpa (the masks are built as for sdpa)."""
BLOCK["size"] = int(block)
AttentionInterface.register(NAME, blocked_sdpa)
AttentionMaskInterface.register(NAME, sdpa_mask)
configs = {id(m.config): m.config for m in model.modules() if hasattr(m, "config")}
for c in configs.values():
c._attn_implementation = NAME