Skip to content

Run relation attention on packed tokens with an out-of-place ragged bias - #916

Open
kmontemayor2-sc wants to merge 8 commits into
kmonte/gt2-pairwise-biasfrom
kmonte/gt2-relation-attention
Open

kmontemayor2-sc wants to merge 8 commits into
kmonte/gt2-pairwise-biasfrom
kmonte/gt2-relation-attention

Conversation

@kmontemayor2-sc

Copy link
Copy Markdown
Collaborator

Summary

relation_attention_mode edge_type_bilinear and edge_type_hgt now run on packed tokens on CUDA. Each layer adds
its per-edge relation scores to its own copy of the length-bucketed per-pair bias. The old version wrote the scores
into a new dense grid per layer through a permuted view, which cost 19 ms per write on an L4.

Approach

  • Mostly Run relation attention on packed tokens in GraphTransformerEncoder #857: forward_packed needs layout.relation_edges for relation attention or messages; the score computation
    is shared with the padded path (_relation_attention_scores: one batched matmul per relation segment, then one
    scatter). That removes the padded path's per-relation .item() reads.
  • What is different from Run relation attention on packed tokens in GraphTransformerEncoder #857 is the packed write in _relation_attention_pair_bias (the name is kept). With every
    token queried, the scores go into the ragged per_pair with an out-of-place index_add at
    per_pair_linear_index(sequence, head, query position, key position). The layer starts from the incoming pairwise bias
    when there is one and from zeros otherwise. It never writes into the incoming buffer: the layers share it, and an
    in-place write gives wrong outputs and gradients with no autograd error. It would also break the recompute contract of
    _run_packed_layer (per-layer checkpointing).
  • On the last anchor_only layer only query row 0 is read, which is a per-key bias. There the scores are added to a
    per-key bias at the edge's source token, and no per-pair buffer is built.

User-facing changes

  • Relation attention configs no longer fall back to the padded path on CUDA.
  • GraphTransformerEncoderLayer.forward_packed accepts relation attention; it raises ValueError only when
    layout.relation_edges is missing for a relation attention or message mode.

Verification

  • CPU: packed_graph_transformer_test.py 180 ran / 33 skipped (CUDA-only); graph_transformer_test.py (nn +
    transforms) 125 / 1; packed_attention_test.py 37 / 13; static_khop_test.py 24; all OK. ruff, ty, dprint
    clean.
  • Tests from Run relation attention on packed tokens in GraphTransformerEncoder #857 apply unchanged. New tests:
    • Parity with the padded path, outputs and training gradients, both readouts, 3 layers, on a batch that fills all four
      length buckets. Cases: bilinear, HGT, bilinear + pairwise, bilinear + anchor bias, HGT + pairwise + anchor bias.
    • Per-layer checkpointing matches plain gradients with relation attention, with and without a pairwise bias.
    • The incoming bias is unchanged after a layer.
    • CUDA parity with a pairwise bias.
  • Mutation checks, each of which fails tests:
    • An in-place write into the incoming bias.
    • A zeros buffer reused across layers.
    • Swapped query and key positions.
    • Dropping the per-key bias in the first-token branch. This one survived until the anchor-bias cases were added.
  • CUDA, one L4 (job gt2-pr4-unit, commit fea1d95e): 366 tests ran, 0 skipped. packed_attention_test passed 37 of 37,
    which includes the earlier bf16 fix. There was 1 error, in the new
    test_cuda_relation_attention_with_pairwise_bias_matches_cpu_in_eval_and_training: the test passed hid_dim=128
    without a matching hop_distance embedding. That was a test bug, and the fix is in commit c66dc919 on this branch.
    The re-run of the merged-up tip in job gt2-pr6-unit passed: 463 tests, 0 skipped, all OK, including this test.

Performance

One L4, torch 2.8.0+cu128, BAGL phase_profile.py --parts 1 --random_init, production A3-MAU user-to-user model
(3 layers, hidden 512, 8 heads, max_seq_len 256, anchor_only). Inference: 512 anchors per batch (45,170 tokens),
fp32 with TF32, eager. Training: bf16 autocast, 128 query + 256 random anchors per step, eager. Times are ms per batch
or step, with peak MiB in parentheses. Old tip = stack tip f93cdf2c. New = this PR (job gt2-pr4-perf). L4 run-to-run
noise is about 5%.

Config Old inference New inference Old training New training
relation attention, bilinear 138.1 (4110) 123.5 (3435) 343.9 (6624) 254.1 (5299), -26%
relation attention, HGT 141.0 126.9 (3444) 349.3 (6625) 260.0 (5304), -26%
pairwise + relation 184.3 (5138) 153.1 (3808) 444.5 (6948) 295.8 (5427), -33%
  • The relation-bias phase of inference (2 layers) drops from 53.4 ms to 16.8 ms.
  • Training also beats the dense-grid write fix that was measured separately on real code (bilinear training 304.9 ms
    with a 4-index write on the dense grid).
  • Inference attention still runs SDPA per bucket at this PR (34.7 ms). The next PR (inference routes) moves it to the
    varlen kernel per bucket, which brings bilinear inference to 101.4 ms. That matches the dense-grid write fix (about
    101 ms).

🤖 Generated with Claude Code

relation_attention_mode edge_type_bilinear and edge_type_hgt now run on the
packed path. Each layer scores its relation edges per relation segment and
adds the scores to its own copy of the length-bucketed per-pair bias with an
out-of-place index_add, so the bias shared by the layers is never written and
the per-layer recompute stays valid; attention then runs SDPA per bucket. The
last first-token layer adds the scores to a per-key bias instead and runs the
varlen kernel. The padded path shares the score computation, which no longer
reads one host value per relation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
layout.position[target].unsqueeze(1),
layout.position[source].unsqueeze(1),
) # [num_edges, num_heads]
if per_pair is None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When there is no incoming per-pair bias, could we use index_add_ on the freshly allocated zero buffer? It is not shared, so this avoids another full bias allocation

@kmontemayor2-sc
kmontemayor2-sc marked this pull request as ready for review November 25, 2026 00:14
kmonte and others added 6 commits November 25, 2026 00:40
The per-pair and first-token per-key buffers are zeros this method just
allocated and nobody else holds, so index_add_ avoids a second full
bias-sized allocation. The incoming shared bias stays out of place because
a write would leak this layer's scores into other layers and the recompute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ntion

# Conflicts:
#	tests/unit/nn/packed_graph_transformer_test.py
_relation_attention_scores scored each relation on
selected_query[start:end] / selected_key[start:end]. Each slice's
backward is a zero tensor the size of all the edges plus a copy, summed
once per relation. Tensor.split's backward is one concatenation. Same
change as for the relation messages; outputs are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@mkolodner-sc mkolodner-sc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conditioned on @yliu2-sc's approval

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants