Structure module, templates and recycling
Invariant point attention (IPA)
AlphaFold2AlphaFold-MultimerOpenFoldESMFold
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Let each residue gather information from allowed residues using both scalar similarity and distances between their projected 3D points. Return the projected feature update, each query’s per-head key probabilities, and the weighted value points expressed in that query’s own coordinate frame.
Function signature
invariant_point_attention(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
eps: float = 1e-08,
) -> dict[str, torch.Tensor]Worked example
Nearby frames receive more weight
Take B=1, N=2 and H=D=Dv=P=Q=Cz=Cout=1. Both rotations are the positive quarter-turn Rz=[[0,-1,0],[1,0,0],[0,0,1]]; translations are [0,0,0] and [1,0,0]. Both residues and all pairs are valid.
All local q_points and k_points: [0,0,0]
All local v_points: [1,0,0]
All scalar q, k and pair_bias: 0
Scalar values v: 2 and 6
pair_values (query, key): [[1,3],[4,2]]
eps=1; b_out=[0]
w_out = [[1],[0],[0],[0],[0],[1]]
Let w=2\log(3)\sqrt{27/2} and set point_weight_raw to \log(e^w-1). This makes the squared-distance coefficient \log3. The output weight order is [scalar,x,y,z,norm,pair].
- Attention. Logits
[[0,-log(3)],[-log(3),0]]give rows[3/4,1/4]and[1/4,3/4]. Scalar value averages are 3 and 5. - Points. The global value points are
[0,1,0]and[1,1,0]. Their averages are[0.25,1,0]and[0.75,1,0]. Subtract each query origin, then apply its inverse rotation:local_pointsare[1,-0.25,0]and[1,0.25,0]. Subtraction alone gives different coordinates. - Update. Pair-value averages are 1.5 and 2.5. The output projection adds each to its scalar average:
update=[[[4.5],[7.5]]].
Parameters
| Parameter | Shape and meaning |
|---|---|
activationsdict | Supplied intermediate tensors. |
parametersdict | Supplied model parameters, keyed as shown below. |
masksdict | Supplied masks. Each field below defines what True includes or permits. |
structuredict | Fields supplied together in this dictionary. |
epsfloatDefault 1e-08 | Positive offset inside the square root used for the norms of aggregated local value points. It is not added to attention logits or attention normalization. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Implement the complete scalar/point/pair AGGREGATION CORE of monomer-style IPA followed by its supplied affine output projection.
- This explicitly starts after input projections:
q,k,vare projected single-feature tensors;q_points,k_points,v_pointsare projected LOCAL points (including any learned point-projection biases);pair_biasis the projected per-head pair logit;pair_valuesis the pair representation to aggregate. - Do not invent input projections, layer norms or additional weights. All dimensions
B,N,H,D,\mathrm{Dv},P,Q,\mathrm{Cz},\mathrm{Cout}are positive, and all floating tensors are finite with common dtype/device. - Frames use column-vector convention
T_{i}(x)=\mathrm{rotation\_i}\mathbin{@}x+\mathrm{translation\_i}withrotation_ia proper\operatorname{SO}(3)matrix. Transform everyq/k/vpoint to global coordinates. - For each batch, query
i, keyjand headh, defineL_{ijh}=\frac{q_{ih}^{\top}k_{jh}}{\sqrt{3D}}+\frac{\texttt{pair\_bias}_{ijh}}{\sqrt3}-\frac12\operatorname{softplus}(\texttt{point\_weight\_raw}_h)\sqrt{\frac{2}{27P}}\sum_p\left\|T_i(\texttt{q\_points}_{ihp})-T_j(\texttt{k\_points}_{jhp})\right\|^2. \operatorname{softplus}(x)=\operatorname{log}(1+\operatorname{exp}(x)), implemented without overflow; distance has a NEGATIVE sign, sums over allPquery/key points and all three coordinates, and uses squared distance without\epsilon. The nonnegative distance weight is learned separately for every head.Trueis valid.- Permit key
jexactly whenmask_iANDmask_jANDpair_mask_ij. Stable softmax overjproducesattention[B,H,N,N]. An empty neighborhood gives all-zeroattention; no\epsilonis added to its denominator. - Aggregate scalar
o_{\mathrm{scalar\_ih}}=\sum_{j} a_{\mathrm{hij}}\cdot v_{\mathrm{jh}}and pairo_{\mathrm{pair\_ih}}=\sum_{j} a_{\mathrm{hij}}\cdot \mathrm{pair\_values\_ij}. - For every value point
p, aggregate its GLOBAL position, then inverse-transform into the query frame:\mathrm{local\_points\_ihp}=\mathrm{rotation\_i}^{\top}\mathbin{@}(\sum_{j} a_{\mathrm{hij}}\cdot T_{j}(v_{\mathrm{points\_jhp}})-\mathrm{translation\_i}). Explicitly setlocal_pointsto zero for an empty neighborhood. - Build features by concatenating, in THIS order: all scalar heads flattened (
H,\mathrm{Dv}); all localxcoordinates flattened (H,Q); all localy; all localz; all point lengths\sqrt{\sum_{\mathrm{xyz}}(\mathrm{local\_points}^{2})+\varepsilon}flattened (H,Q); all pair heads flattened (H,\mathrm{Cz}). - Each flatten is head-major. Feature length
F=H\cdot (\mathrm{Dv}+4\cdot Q+\mathrm{Cz}). Empty-neighborhood length features are also zero, not\sqrt{\varepsilon}.\mathrm{update}=\mathrm{features}\mathbin{@}w_{\mathrm{out}}+b_{\mathrm{out}}, then zero the entireupdatefor an empty neighborhood. - Return
update,attentionandlocal_points; there is no residual, final gate, dropout or frameupdate.hasonly\varepsilon>0(default10^{-8}), used inside the OUTPUT point-length square root, not theattentiondistance. - All three outputs are invariant when a common proper
rotationGandtranslationuchange frames torotation'i=G\mathbin{@}\mathrm{rotation\_i}andtranslation'i=G\mathbin{@}\mathrm{translation\_i}+u; local inputs and pair/scalar features stay fixed. - This is a full projected-input core, not a checkpoint-compatible full IPA layer.
Why this matters
Attention compares residue features and their positions in space. Value points are averaged globally and then described relative to the query frame, so the network can use geometry without depending on the structure’s global pose.
Starter code
You write the body of this function in the BioTorch workspace. Your code runs in an isolated PyTorch sandbox; Run checks the public examples and Submit grades the full test suite, including gradients.
import torch
def invariant_point_attention(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
eps: float = 1e-08,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
update: (B, N, Cout).
attention: (B, H, N, N).
local_points: (B, N, H, Q, 3)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement invariant_point_attention")
Ready to implement it?
3 progressive hints, a solution walkthrough, and grading that checks values, shapes and gradients are waiting in the workspace.
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Sources and further reading
A primitive exercise, not an end-to-end reproduction of the named models. No affiliation or endorsement is implied.