gigl.nn.packed_attention#
Attention over packed variable-length sequences: the compute half of the packed backend.
This is the attention side of the packed backend of GraphTransformerEncoder.
The encoder builds one token sequence per anchor (for example, from its k-hop
neighborhood with gigl.transforms.static_khop), copies the real tokens of all
sequences into one [num_tokens, dim] buffer, and runs the transformer on that
buffer. packed_attention is the attention step and does not depend on how the
sequences were built: each sequence attends only to itself, with boundaries given
by cu_seqlens.
- Why this exists:
With uneven sequence lengths (about 90 real tokens out of 256 in our models), most of the linear-layer, FFN and attention work on a padded
[num_sequences, max_seq_len, dim]batch is spent on padding. Packed tokens spend it only on real ones.On CUDA this calls aten’s memory-efficient varlen attention kernel, wrapped in a custom op. The kernel is private because torch 2.8 has no public attention API that takes
cu_seqlens;_varlen_attentionexplains why the public options do not fit. The kernel runs in fp32, which inference needs for accuracy, and aten’s own backward kernel supplies the gradients.On CPU the same inputs go through SDPA on padded grids, one per length bucket of the layout. That is the reference the CUDA path is tested against, and it lets the packed backend run anywhere.
Packing needs one host read (the total token count, in
pack_sequences) so the buffer holds exactly the real tokens. Everything else has fixed shapes and no syncs, so the layers can be compiled withtorch.compile.
Data flow of a packed forward:
padded grid [num_sequences, max_seq_len, ...] lengths [num_sequences]
| |
| pack_sequences(lengths, max_seq_len) <------+
| -> PackedLayout(cu_seqlens, max_seq_len, flat_index, ...)
| grid.flatten()[flat_index]
v
packed buffer [num_tokens, dim]
|
| per layer, on real tokens only:
| norm -> q / k / v linears -> [num_tokens, num_heads, head_dim]
| packed_attention(q, k, v, layout, ...)
| CUDA: aten memory-efficient attention with cu_seqlens
| CUDA, per-pair bias on every token or dropout:
| SDPA per length bucket
| CPU: SDPA per length bucket (reference)
| output linear + residual -> FFN + residual
v
anchor readout: rows cu_seqlens[:-1], the first token of every sequence
- Constraints:
The varlen kernel is CUDA only; other devices use SDPA per length bucket.
head_dimneed not be a multiple of 8. The aligned kernels need it, sopacked_attentionzero-pads q, k and v up to a multiple of 8 and rescales q so the kernel’s scores match the unpadded head dim.A
PackedAttentionBiasis part of the call. The CPU path applies it. On CUDA aper_keybias runs on the kernel by folding it into q and k as an extra head-dim column. Aper_pairbias on every token runs SDPA per bucket. Withquery_is_first_token, row 0 of each sequence’sper_pairblock is a per-key bias, so it runs on the kernel too.Attention dropout always runs SDPA per bucket, never the varlen kernel: in torch 2.8 the kernel’s varlen dropout uses different masks in the forward and the backward pass when
cu_seqlensis given, so its gradients are wrong.cu_seqlensis int32, so the token count must fit in int32.
Example
>>> from gigl.transforms.sequence_layout import pack_sequences
>>> lengths = torch.tensor([3, 1, 2])
>>> layout = pack_sequences(lengths, max_seq_len=3)
>>> layout.flat_index.tolist()
[0, 1, 2, 3, 6, 7]
>>> num_tokens = int(lengths.sum())
>>> query = key = value = torch.randn(num_tokens, 2, 8)
>>> output = packed_attention(
... query, key, value, layout, query_is_first_token=False
... )
>>> output.shape
torch.Size([6, 2, 8])
>>> first_token_only = packed_attention(
... query[layout.cu_seqlens[:-1].long()],
... key,
... value,
... layout,
... query_is_first_token=True,
... )
>>> first_token_only.shape
torch.Size([3, 2, 8])
- Results:
We have seen the following with this path. These are observations on one production model, not benchmarks of this module alone.
One L4 GPU, 3-layer graph transformer (hidden 512, 8 heads), sequences of up to 256 tokens holding about 90 real tokens on average, realistic batches, steady state:
Forward, no compile: 225 -> 76 ms per batch (~3.0x).
Forward, per-layer
torch.compile: 53 ms per batch (~4.3x vs the padded path without compile).Training step: 944 -> 364 ms (~2.6x).
Peak GPU memory: 15.4 -> 6.8 GiB training, 6.9 -> 3.8 GiB forward.
120 L4 GPUs. These runs also include
torch.compileand loader changes, so the gain is not from packing alone:Training step: 6.62 -> 2.66 s (2.5x), peak memory 9.8 -> 4.3 GiB.
Full-graph inference over ~230M nodes: 1884 -> 1014 s end to end (1.9x). The model stopped being the bottleneck; sampling was.
Classes#
Additive attention-score bias for |
Functions#
|
Returns the buckets of |
|
Attention within each packed sequence; the entry point of this module. |
|
Returns the length of the flat |
|
Splits a flat per-pair bias into one 4-D view per bucket. |
|
Returns the cells of a flat per-pair bias for the given pairs. |
|
Returns where each packed sequence's block starts in the flat per-pair bias. |
Module Contents#
- class gigl.nn.packed_attention.PackedAttentionBias[source]#
Bases:
NamedTupleAdditive attention-score bias for
packed_attention.Both fields are optional and added to the scaled scores before the softmax.
- per_key[source]#
One bias per key token and head. Every query in a sequence sees the same value for a given key.
- per_pair[source]#
One bias per sequence, head, query position and key position, as one flat tensor in packed sequence order. It is the concatenation, over
layout_buckets(layout)in order, of the row-major[bucket_sequences, num_heads, bucket_len, bucket_len]block of each bucket, wherebucket_sequences = end_sequence - first_sequence. Without buckets it is one[num_sequences, num_heads, max_seq_len, max_seq_len]block. The cell of packed sequences, headh, query positionqand key positionkis atsequence_offset[s] + (h * L + q) * L + k, whereLis the bucket length ofsandsequence_offsetcomes fromper_pair_sequence_offsets;per_pair_linear_indexcomputes it. Cells beyond a sequence’s length are ignored: padded keys are masked and padded query rows are dropped.
- gigl.nn.packed_attention.layout_buckets(layout)[source]#
Returns the buckets of
layout, or the one bucket that covers everything.Reads shapes only, never the device.
- Parameters:
layout (gigl.transforms.sequence_layout.PackedLayout) – Layout from
pack_sequences.- Returns:
layout.buckets, or one bucket ofmax_seq_lenover all sequences and tokens when it is None.- Return type:
tuple[gigl.transforms.sequence_layout.PackedBucket, Ellipsis]
- gigl.nn.packed_attention.packed_attention(query, key, value, layout, query_is_first_token, bias=None, dropout_p=0.0)[source]#
Attention within each packed sequence; the entry point of this module.
Uses the CUDA varlen kernel on GPU and SDPA per length bucket elsewhere. With
query_is_first_token, only each sequence’s first token is queried, which is all the anchor readout of the last layer needs. An emptyPackedAttentionBiasbehaves likebias=None.The route is chosen in this order:
Not CUDA, or
dropout_p > 0: SDPA per bucket (_padded_packed_attention). Dropout never uses the varlen kernel, whose dropout is wrong in the backward pass in torch 2.8.A
per_pairbias withquery_is_first_token: row 0 of each sequence’s block becomes a per-key bias (_first_row_per_key_bias) and the call continues on the varlen kernel, with or without gradient.A
per_pairbias on every token, with or without gradient: SDPA per bucket.Otherwise the varlen kernel, with a
per_keybias folded into q and k by_fold_per_key_bias.
Every sequence must contain at least one token (
lengths >= 1). An empty sequence gives wrong output on the padded path and is not supported.Args and returns are as in
_padded_packed_attention.- Parameters:
query (jaxtyping.Float[torch.Tensor, num_queries num_heads head_dim])
key (jaxtyping.Float[torch.Tensor, num_tokens num_heads head_dim])
value (jaxtyping.Float[torch.Tensor, num_tokens num_heads head_dim])
query_is_first_token (bool)
bias (Optional[PackedAttentionBias])
dropout_p (float)
- Return type:
jaxtyping.Float[torch.Tensor, num_queries num_heads head_dim]
- gigl.nn.packed_attention.per_pair_bias_num_cells(layout, num_heads)[source]#
Returns the length of the flat
PackedAttentionBias.per_pairforlayout.- Parameters:
layout (gigl.transforms.sequence_layout.PackedLayout) – Layout from
pack_sequences.num_heads (int) – Number of attention heads.
- Returns:
The sum over buckets of
bucket_sequences * num_heads * bucket_len ** 2.- Return type:
int
- gigl.nn.packed_attention.per_pair_bias_views(per_pair, layout, num_heads)[source]#
Splits a flat per-pair bias into one 4-D view per bucket.
The views share memory with
per_pair; nothing is copied.- Parameters:
per_pair (jaxtyping.Float[torch.Tensor, num_pair_cells]) – Flat bias, laid out as described in
PackedAttentionBias.layout (gigl.transforms.sequence_layout.PackedLayout) – Layout from
pack_sequences.num_heads (int) – Number of attention heads.
- Returns:
For each bucket, its
[bucket_sequences, num_heads, bucket_len, bucket_len]block, in bucket order.- Raises:
ValueError – If
per_pairdoes not haveper_pair_bias_num_cellselements.- Return type:
list[torch.Tensor]
- gigl.nn.packed_attention.per_pair_linear_index(sequence_offset, sequence_bucket_len, sequence, head, query_position, key_position)[source]#
Returns the cells of a flat per-pair bias for the given pairs.
Computes
sequence_offset[sequence] + (head * L + query_position) * L + key_positionwithL = sequence_bucket_len[sequence]. The arguments broadcast against each other.- Parameters:
sequence_offset (jaxtyping.Int64[torch.Tensor, num_sequences]) – First cell of each packed sequence’s block, from
per_pair_sequence_offsets.sequence_bucket_len (jaxtyping.Int64[torch.Tensor, num_sequences]) – Bucket length of each packed sequence, from
per_pair_sequence_offsets.sequence (torch.Tensor) – Packed sequence of each pair.
head (torch.Tensor | int) – Head of each pair.
query_position (torch.Tensor | int) – Position of the query within its sequence.
key_position (torch.Tensor | int) – Position of the key within its sequence.
- Returns:
Long indices into the flat per-pair bias.
- Return type:
torch.Tensor
- gigl.nn.packed_attention.per_pair_sequence_offsets(layout, num_heads)[source]#
Returns where each packed sequence’s block starts in the flat per-pair bias.
Reads shapes only, never the device.
- Parameters:
layout (gigl.transforms.sequence_layout.PackedLayout) – Layout from
pack_sequences.num_heads (int) – Number of attention heads.
- Returns:
(sequence_offset, sequence_bucket_len), both int64 on the layout’s device.sequence_bucket_len[s]is the bucket length of packed sequences.sequence_offset[s]is the first cell of its[num_heads, bucket_len, bucket_len]block.- Return type:
tuple[jaxtyping.Int64[torch.Tensor, num_sequences], jaxtyping.Int64[torch.Tensor, num_sequences]]