xuan-luo's picture
download
raw
13.6 kB
"""Shared-projection rolling attention with an exact local/distant softmax.
Projection layout is ``[Q(8*64), K(4*64), V(4*64)]``. K/V are always
projected in full. The same raw fresh K/V feed the local branch and update the
rolling state; RoPE is applied only after the complete 64-D keys are formed.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
from megatron.core.models.common.embeddings.rope_utils import apply_rotary_pos_emb
from megatron.core.models.common.embeddings.rotary_pos_embedding import RotaryEmbedding
from megatron.core.transformer.attention import Attention
from megatron.core.transformer.enums import AttnMaskType
from megatron.core.typed_torch import apply_module
LOCAL_WINDOW = 128
def update_rolling_state(previous: torch.Tensor | None, fresh: torch.Tensor,
roll_dim: int) -> torch.Tensor:
"""Production FIFO update on raw K or V; tensors end in the 64-D head dim."""
if fresh.shape[-1] != 64 or roll_dim not in (8, 16, 32, 64):
raise ValueError("fresh head dim must be 64 and roll_dim must be 8, 16, 32, or 64")
if previous is None or roll_dim == 64:
return fresh
if previous.shape != fresh.shape:
raise ValueError("previous and fresh rolling states must have identical shapes")
return torch.cat((previous[..., roll_dim:], fresh[..., -roll_dim:]), dim=-1)
def reference_attention(query: torch.Tensor, fresh_key: torch.Tensor,
fresh_value: torch.Tensor, rolling_key: torch.Tensor,
rolling_value: torch.Tensor, window: int = LOCAL_WINDOW) -> torch.Tensor:
"""Readable O(T^2) reference. Inputs/outputs use [T,B,H,D] Megatron layout."""
t = query.size(0)
repeats = query.size(2) // fresh_key.size(2)
fk = fresh_key.repeat_interleave(repeats, dim=2)
fv = fresh_value.repeat_interleave(repeats, dim=2)
rk = rolling_key.repeat_interleave(repeats, dim=2)
rv = rolling_value.repeat_interleave(repeats, dim=2)
local_score = torch.einsum("tbhd,sbhd->bhts", query, fk)
distant_score = torch.einsum("tbhd,sbhd->bhts", query, rk)
qpos = torch.arange(t, device=query.device)[:, None]
kpos = torch.arange(t, device=query.device)[None, :]
causal = kpos <= qpos
local = causal & ((qpos - kpos) < window)
score = torch.where(local[None, None], local_score, distant_score)
score = score.masked_fill(~causal[None, None], -torch.inf) / math.sqrt(query.size(-1))
probability = score.softmax(dim=-1)
values = torch.where(local[None, None, :, :, None],
fv.permute(1, 2, 0, 3)[:, :, None],
rv.permute(1, 2, 0, 3)[:, :, None])
return torch.einsum("bhts,bhtsd->tbhd", probability, values)
class _SegmentedFlashAttention(torch.autograd.Function):
"""Two FlashAttention segments with an exact common-softmax backward.
FlashAttention's public autograd function returns LSE but deliberately
ignores its gradient. A naive differentiable-looking LSE merge therefore
loses the Q/K gradient which moves probability mass between the local and
distant segments. For a segment with output ``O_i`` and mass ``w_i``, the
required score derivative is obtained by invoking the fused backward with
``dO_i = w_i*dO`` and the *combined* output in place of ``O_i``. The fused
kernel computes ``p_i * (dO_i V - dO_i O)``; using the combined output makes
this exactly the derivative of the common softmax, including its LSE term.
"""
@staticmethod
def forward(ctx, q, fk, fv, rk, rv, window):
from flash_attn.flash_attn_interface import _wrapped_flash_attn_forward
scale = 1.0 / math.sqrt(q.size(-1))
local_out, local_lse, _, local_rng = _wrapped_flash_attn_forward(
q, fk, fv, 0.0, scale, causal=True,
window_size_left=window - 1, window_size_right=0, softcap=0.0,
alibi_slopes=None, return_softmax=False)
ctx.window = window
ctx.scale = scale
if q.size(1) <= window:
ctx.short = True
ctx.save_for_backward(q, fk, fv, local_out, local_lse, local_rng)
return local_out
ctx.short = False
q_far = q[:, window:].contiguous()
rk_far = rk[:, :-window].contiguous()
rv_far = rv[:, :-window].contiguous()
far_out, far_lse, _, far_rng = _wrapped_flash_attn_forward(
q_far, rk_far, rv_far, 0.0, scale, causal=True,
window_size_left=-1, window_size_right=-1, softcap=0.0,
alibi_slopes=None, return_softmax=False)
local_tail_lse = local_lse[:, :, window:]
total_lse = torch.logaddexp(local_tail_lse, far_lse)
local_weight = ((local_tail_lse - total_lse).exp().permute(0, 2, 1)
.unsqueeze(-1).to(local_out.dtype))
far_weight = ((far_lse - total_lse).exp().permute(0, 2, 1)
.unsqueeze(-1).to(local_out.dtype))
tail = local_out[:, window:] * local_weight + far_out * far_weight
output = torch.cat((local_out[:, :window], tail), dim=1).contiguous()
ctx.save_for_backward(q, fk, fv, rk, rv, local_out, local_lse, local_rng,
far_out, far_lse, far_rng, output,
local_weight, far_weight)
return output
@staticmethod
def backward(ctx, dout):
from flash_attn.flash_attn_interface import _wrapped_flash_attn_backward
dout = dout.contiguous()
if ctx.short:
q, fk, fv, local_out, local_lse, local_rng = ctx.saved_tensors
dq, dfk, dfv = torch.empty_like(q), torch.empty_like(fk), torch.empty_like(fv)
_wrapped_flash_attn_backward(
dout, q, fk, fv, local_out, local_lse, dq, dfk, dfv,
0.0, ctx.scale, True, ctx.window - 1, 0, 0.0, None, False,
rng_state=local_rng)
return dq, dfk, dfv, torch.zeros_like(fk), torch.zeros_like(fv), None
(q, fk, fv, rk, rv, local_out, local_lse, local_rng,
far_out, far_lse, far_rng, output, local_weight, far_weight) = ctx.saved_tensors
window = ctx.window
# Prefix has only the local branch. Tail branch gradients are weighted
# by their common-softmax probability mass.
dlocal = dout.clone()
dlocal[:, window:] *= local_weight
local_reference = torch.cat((local_out[:, :window], output[:, window:]), dim=1).contiguous()
dq_local, dfk, dfv = torch.empty_like(q), torch.empty_like(fk), torch.empty_like(fv)
_wrapped_flash_attn_backward(
dlocal, q, fk, fv, local_reference, local_lse,
dq_local, dfk, dfv, 0.0, ctx.scale, True, window - 1, 0, 0.0,
None, False, rng_state=local_rng)
q_far = q[:, window:].contiguous()
rk_far = rk[:, :-window].contiguous()
rv_far = rv[:, :-window].contiguous()
dfar = (dout[:, window:] * far_weight).contiguous()
far_reference = output[:, window:].contiguous()
dq_far, drk_far, drv_far = (torch.empty_like(x) for x in (q_far, rk_far, rv_far))
_wrapped_flash_attn_backward(
dfar, q_far, rk_far, rv_far, far_reference, far_lse,
dq_far, drk_far, drv_far, 0.0, ctx.scale, True, -1, -1, 0.0,
None, False, rng_state=far_rng)
dq = dq_local
dq[:, window:] += dq_far
drk, drv = torch.zeros_like(rk), torch.zeros_like(rv)
drk[:, :-window] = drk_far
drv[:, :-window] = drv_far
return dq, dfk, dfv, drk, drv, None
def segmented_flash_attention(query: torch.Tensor, fresh_key: torch.Tensor,
fresh_value: torch.Tensor, rolling_key: torch.Tensor,
rolling_value: torch.Tensor,
window: int = LOCAL_WINDOW) -> torch.Tensor:
"""Exact common-softmax attention without a BxHxTxT score or 2T KV copy."""
q, fk, fv, rk, rv = (x.permute(1, 0, 2, 3).contiguous()
for x in (query, fresh_key, fresh_value, rolling_key, rolling_value))
output = _SegmentedFlashAttention.apply(q, fk, fv, rk, rv, window)
return output.permute(1, 0, 2, 3).contiguous()
@dataclass
class SharedProjectionSubmodules:
linear_proj: object
core_attention: object
linear_qkv: object
class SharedProjectionSelfAttention(Attention):
"""One full QKV projection serving fresh-local and raw rolling KV."""
def __init__(self, config, submodules, layer_number, attn_mask_type=AttnMaskType.causal,
cp_comm_type=None, pg_collection=None, pp_layer_offset=None, name=None):
if (config.tensor_model_parallel_size != 1 or config.pipeline_model_parallel_size != 1
or config.context_parallel_size != 1 or config.sequence_parallel
or config.recompute_granularity is not None):
raise ValueError("shared-projection rolling requires TP=PP=CP=1, no SP/recompute")
roll_dim = int(getattr(config, "rolling_state_dim"))
if (config.kv_channels != 64 or roll_dim not in (8, 16, 32, 64)
or config.attention_dropout or config.qk_layernorm):
raise ValueError("requires head_dim=64, r in {16,32,64}, no dropout/QK norm")
super().__init__(config=config, submodules=submodules, layer_number=layer_number,
attn_mask_type=attn_mask_type, attention_type="self",
cp_comm_type=cp_comm_type, pg_collection=pg_collection,
pp_layer_offset=pp_layer_offset, name=name)
self.roll_dim = roll_dim
self.q_size = config.num_attention_heads * config.kv_channels
self.kv_size = config.num_query_groups * config.kv_channels
self.linear_qkv = submodules.linear_qkv(
config.hidden_size, self.q_size + 2 * self.kv_size, config=config,
init_method=config.init_method, gather_output=False, bias=False,
skip_bias_add=False, is_expert=False, tp_comm_buffer_name="qkv",
tp_group=self.pg_collection.tp, pg_collection=self.pg_collection,
name=(name + ".linear_qkv") if name else None)
config.hetereogenous_dist_checkpoint = True
if not hasattr(config, "_sharedproj_rolling_holder"):
config._sharedproj_rolling_holder = {}
theta = getattr(config, "rotary_base", None)
if theta is None:
from megatron.training import get_args
theta = get_args().rotary_base
self.rotary_pos_emb = RotaryEmbedding(64, rotary_percent=1.0, rotary_base=theta,
cp_group=self.pg_collection.cp)
def get_query_key_value_tensors(self, *args, **kwargs):
raise NotImplementedError("shared-projection attention constructs Q/K/V in forward")
def forward(self, hidden_states, attention_mask, key_value_states=None,
inference_context=None, rotary_pos_emb=None, rotary_pos_cos=None,
rotary_pos_sin=None, rotary_pos_cos_sin=None, attention_bias=None,
packed_seq_params=None, sequence_len_offset=None, *, inference_params=None):
if any(x is not None for x in (key_value_states, inference_context, inference_params,
attention_bias, packed_seq_params, sequence_len_offset)):
raise NotImplementedError("this entrypoint supports unpacked training/prefill only")
if attention_mask is not None:
raise ValueError("shared-projection attention requires implicit causal masking")
seq, batch = hidden_states.shape[:2]
mixed, _ = apply_module(self.linear_qkv)(hidden_states)
query, raw_fresh_key, fresh_value = torch.split(
mixed, (self.q_size, self.kv_size, self.kv_size), dim=-1)
query = query.view(seq, batch, self.config.num_attention_heads, 64)
raw_fresh_key = raw_fresh_key.view(seq, batch, self.config.num_query_groups, 64)
fresh_value = fresh_value.view(seq, batch, self.config.num_query_groups, 64)
holder = self.config._sharedproj_rolling_holder
if self.layer_number == 1:
if holder:
raise RuntimeError("unconsumed shared-projection rolling state")
previous_key = previous_value = None
else:
if holder.get("next") != self.layer_number:
raise RuntimeError("missing or out-of-order rolling predecessor")
previous_key, previous_value = holder["key"], holder["value"]
rolling_key = update_rolling_state(previous_key, raw_fresh_key, self.roll_dim)
rolling_value = update_rolling_state(previous_value, fresh_value, self.roll_dim)
holder.clear()
if self.layer_number < self.config.num_layers:
holder.update(next=self.layer_number + 1, key=rolling_key, value=rolling_value)
rotary = self.rotary_pos_emb(seq)
query = apply_rotary_pos_emb(query, rotary, config=self.config).contiguous()
fresh_key = apply_rotary_pos_emb(raw_fresh_key, rotary, config=self.config).contiguous()
distant_key = apply_rotary_pos_emb(rolling_key, rotary, config=self.config).contiguous()
output = segmented_flash_attention(query, fresh_key, fresh_value.contiguous(),
distant_key, rolling_value.contiguous())
output = output.view(seq, batch, self.q_size)
return apply_module(self.linear_proj)(output)

Xet Storage Details

Size:
13.6 kB
·
Xet hash:
8aa20698068dc0f14f261f2445e23e630cd2ee3449d2adbe7289e0361d8459fa

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.