triangle-attention-neuron-kernels
Triangle attention (Algorithms 13 and 14 of AlphaFold 2 / 3, as used in Boltz-2's Pairformer) for AWS Trainium2
(trn2) with PyTorch Native (torch.compile(backend="neuron")), written in NKI. Since 1.1.0 it also provides
triangle multiplication (Algorithms 11 and 12), the Pairformer's other N^3 operation; see
Triangle multiplication. Since 1.2.0 patch_boltz() also runs each Pairformer layer as
fewer, larger graphs; see Larger graphs per layer.
For a pair representation z of N x N tokens with H heads of size D, each row i of the pair matrix runs its
own attention with a bias shared by all rows:
o[i, h] = softmax(q[i, h] k[i, h]^T / sqrt(D) + bias[h] + key_mask) v[i, h]
That is N * H independent N x N attentions per module, 64 Pairformer layers x 2 modules (start and end nodes)
per recycle in Boltz-2. On one Trainium2 core it is 72-86% of the trunk's time at 384-704 tokens.
The kernel is a modified copy of attention_cte from the AWS Neuron NKI Library (the SDK's production flash
attention), vendored under k24nkilib/ (Apache-2.0). Changes:
- Shared per-head bias (
bias_heads=H): the[H, N, N]bias is loaded into SBUF once per head and reused by every row, instead of a dense per-batch bias ([N*H, N, N]would not fit in memory). - Bias added through an identity matmul: PSUM is initialised by a matmul and the QK matmul accumulates onto it. The library's own bias preload (a Vector/Scalar copy into PSUM followed by an accumulating matmul) is undefined on NeuronCore-v3, and gave wrong results for the first query block on trn2 when another operation had run on the core first.
- Static DMA descriptors for the K, V and output transfers (frees the GpSimd engine; 1-14% faster).
- Optional fp32-accurate bias (
TRI_ATTN_BIAS=hilo, two bf16 parts), and the P transpose on the PE instead of DMA (TRI_ATTN_PT=pe).
Results (trn2.3xlarge, Neuron SDK 2.33, one logical NeuronCore, LNC=2)
One triangle-attention module (Boltz-2 layer 0 weights; LayerNorm, projections and gating in torch, attention core in this kernel; whole module one compiled graph), against the stock Boltz module as it runs on Neuron:
| tokens | stock (ms) | this kernel (ms) | speedup |
|---|---|---|---|
| 384 | 18.0 | 9.0 | 2.0x |
| 544 | 64.0 | 22.7 | 2.8x |
| 704 | 106.2 | 31.6 | 3.4x |
| 1,024 | 275.1 | 67.4 | 4.1x |
| 1,408 | 530.2 | 207.3 * | 2.6x |
* measured before the static-descriptor change.
Accuracy. The module's output is closer to an fp32 reference than the stock bf16 module's (relative error 0.019-0.021 vs 0.024-0.026). Boltz-2 predictions with MSAs, scored against crystal structures, match the stock path:
| structure (tokens) | CA-RMSD, seeds 0 / 1 | stock | lDDT-CA |
|---|---|---|---|
| 3W7T (760) | 0.88 / 0.89 A | 0.92 / 0.88 A | 0.980-0.981 |
| 5A7M (760) | 0.61 / 0.61 A | 0.61 / 0.61 A | 0.982-0.983 |
| 6EA2 (889) | 0.50 / 0.45 A | 0.48 / 0.50 A | 0.995-0.996 |
End to end in Boltz-2 (boltz-neuron, one trn2 device, 4 workers, no MSA), structures per hour go up 1.4-2.1x at 1 diffusion sample for 384-682 tokens, and 1.2-1.7x at 25 samples.
Triangle multiplication (1.1.0)
This part is not an NKI kernel. Compiled as one graph, the module's [N, N, C] x [N, N, C] contraction is lowered
20-100x slower than running the same ops eagerly (neuronx-cc 2.28; reported). Split at the contraction, into a
compiled prologue (LayerNorm, projections, gate, mask), one batched matmul over the channels, and a compiled
epilogue (LayerNorm, output projection, gate), it is faster than eager. The math is the same as the stock module.
One module, Boltz-2 trunk weights (layers 0 / 31 / 63, both directions), one logical NeuronCore:
| tokens | eager, op by op (ms) | one compiled graph (ms) | this package (ms) | vs eager |
|---|---|---|---|---|
| 384 | 5.1-5.4 | 94-115 | 3.7-4.0 | 1.4x |
| 544 (30 padded) | 10.1-11.9 | -- | 7.3-7.6 | 1.4-1.6x |
| 704 | 15.0-17.1 | 56-1,836 | 10.8-11.2 | 1.4-1.5x |
| 1,024 | 45-53 | -- | 19.5-20.2 | 2.3-2.6x |
Relative error vs an fp32 reference is 0.0071-0.0097 (eager bf16: 0.0073-0.0101). In Boltz-2 with both parts of this package, structures per hour went up another 4-12% end to end (one trn2 device, 4 workers); crystal-structure accuracy was unchanged. If a later compiler lowers the one-graph version well, this split may stop helping.
Larger graphs per layer (1.2.0)
At LNC=2 every graph launch synchronises the two physical NeuronCores of a logical core, and small graphs speed up
well under 2x on two cores. patch_boltz() (with layer_fuse=True, the default when both modules are patched) runs
each PairformerLayer as fewer, larger graphs: the two triangle multiplications share a graph at their boundary,
the residual adds move into the neighbouring graphs, and the pair transition plus the whole sequence stack
(pre-norm, single-track attention, transition, post-norm) is one compiled graph. The triangle-attention end node
also projects straight into the kernel's layout (no per-chunk copies).
One Pairformer layer, Boltz-2 trunk weights, one logical NeuronCore: 192 tokens 11.4 -> 8.8 ms, 384 tokens 29.8 -> 26.7 ms, 704 tokens 103.9 -> 99.2 ms (vs 1.1.0's per-module patching), same values (error vs fp32 0.0714 vs 0.0716). In Boltz-2 (boltz-neuron, one trn2 device, 4 workers) structures per hour went up another 5-18% at 1 diffusion sample.
Usage
Requires the Neuron SDK 2.33 PyTorch Native environment (/opt/aws_neuronx_venv_torch_neuronx_2_14_0 on the SDK
2.33 DLAMI) and pip install kernels.
import torch, torch_neuronx # registers the neuron device
from kernels import get_kernel
ta = get_kernel("jburtoft/triangle-attention-neuron-kernels", version=1, trust_remote_code=True)
# 1) Boltz-2: patch every TriangleAttention and TriangleMultiplication module (trunk, MSA, template, confidence)
ta.patch_boltz() # both modules + larger layer graphs
# ta.patch_boltz(layer_fuse=False) # 1.1.0 behaviour: per-module patching only
# ta.patch_boltz(multiplication=False) # triangle attention only
# 2) Or call the attention core directly
# q, k, v: [I, H, N, D] bf16 on "neuron" (q not pre-scaled); bias: [H, N, N], shared by all I rows
o = ta.triangle_attention_core(q, k, v, bias, scale=1 / D ** 0.5)
# 3) Triangle multiplication directly: x [B, N, N, C] bf16, mask [B, N, N], Boltz module weights
y = ta.triangle_multiplication(x, mask, norm_in_w, norm_in_b, p_in_w, g_in_w,
norm_out_w, norm_out_b, p_out_w, g_out_w, outgoing=True)
examples/check_core.py checks the core against an fp64 reference.
Settings (environment variables, read at import):
| variable | default | meaning |
|---|---|---|
TRI_ATTN_I_CHUNK |
64 |
pair rows per kernel call |
TRI_ATTN_BIAS |
bf16 |
hilo carries the bias at ~fp32 precision: core error 4.5x lower, module ~3% lower, ~7% slower |
TRI_ATTN_DGE |
none |
DMA descriptor mode for K/V/O (none = static descriptors; sw = library default) |
TRI_ATTN_LAYOUT |
auto |
v2 projects q/k/v/g straight into the kernel's layout (faster for the end node); auto = v2 for the end node and from 1,024 tokens |
TRI_ATTN_PT |
dma |
engine for the P transpose (pe is faster on-core at <= 544 tokens, slower above) |
Limitations
- Inference only, batch 1 (Boltz-2's inference batch),
D <= 128. Tested with H=4, D=32 (Boltz-2). - Triangle multiplication: bf16 on the neuron device (other dtypes / CPU fall back to the original forward). Tested with C=128 (Boltz-2).
- Larger layer graphs: bf16, batch 1, Boltz-2's v2 single-track attention; other layers fall back to the original
forward. Validated end to end through boltz-neuron's bf16 configuration; plain
boltzkeeps some fp32 islands elsewhere in the model, so run it in bf16 (as boltz-neuron does). - The key mask must be an outer product of a token mask (true for Boltz's trunk, MSA, template and confidence modules). Other masks (Boltz-2's affinity module) fall back to the original forward.
- Tested on trn2 at LNC=2 only. Not tested on Inferentia2, Trainium1 or LNC=1.
- One compiled graph per (token count, start/end node); first call compiles (about 30 s at 384 tokens, 220 s at 1,024).
Licence
Apache-2.0. The k24nkilib/ directory is a modified subset of the AWS Neuron NKI Library (Apache-2.0,
Copyright Amazon.com, Inc. or its affiliates).
- Downloads last month
- -