All-atom folding · INTEGRATION
Local atom attention, encoder pooling and decoder skip/readout
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Update each usable atom by weighting values from its supplied key slots and applying a conditioned transition. Each attention entry describes one query atom, head, and key slot. Encoder mode averages projected hidden atoms into token features; decoder mode broadcasts token context first and returns a per-atom coordinate update after the block. Apply the selected AF3 or ESMFold2 rules.
Function signature
windowed_atom_attention(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
eps: float = 1e-05,
style: str = 'af3',
stage: str = 'decoder',
radius: int = -1,
) -> dict[str, torch.Tensor]Worked example
Worked example: competing neighbor slots, an excluded slot, and an active residual update
Use AF3 decoder mode with two valid atoms [1,3], [4,2] mapped to one valid token. After adding token context [1,1], then adaptive normalization with eps=3, the query/key inputs are [-0.25,0.25] and [0.25,-0.25]. Query 0 can use both key slots; scores are \pm0.125/\sqrt2, giving first-key weight p=\sigma(0.25/\sqrt2)\approx0.544079. The weighted value is [-0.25(2p-1),0.25(2p-1)]; half value and residual gates add [-d,d], where d=(2p-1)/16. Query 1 can use only key 1, so its update is [1/16,-1/16]. The first hidden vector is [2-d,4+d]. Its centered entries are [-(1+d),1+d]; final normalization, scale 2, and readout give [-a,a,-2a], a=2(1+d)/\sqrt{(1+d)^2+3}. Here \sigma(z)=1/(1+e^{-z}). The supplied transition is zero.
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-05 | Positive stabilizer inside every LayerNorm variance or RMS mean-square root used by this block. |
stylestrDefault 'af3' | Choose "af3" for adaptive LayerNorm and pair bias, or "esmfold2" for RMS/SiLU modulation with supplied spatial rotary features. |
stagestrDefault 'decoder' | Encoder pools to tokens; decoder produces an atom-coordinate update. |
radiusintDefault -1 | Maximum absolute difference between query and key atom indices; -1 disables this additional index-window restriction. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Implement one learned local
atomblock and its encoder or decoder boundary.B,A,T,K,C,S,H,D,V,M,U \ge 1; all active data/weights are finite and share dtype/device, indicesint64, masks bool. stageis 'decoder' (default) or 'encoder'; style is 'af3' (default) or 'esmfold2';\varepsilon>0defaults10^{-5}and radius is an integer\ge -1, default-1. Atom a is usable iffvalid[a],0\le \mathrm{atom\_to\_token}[a]<Tand itstoken_validisTrue.- Invalid payloads may be
NaN/Infand must be sanitized before normalization/projection. Encoder startsx=\mathrm{atom}. Decoder startsx=\mathrm{atom}(\mathrm{skip})+\operatorname{gather}(\mathrm{token}\mathbin{@}w_{\mathrm{token}},\mathrm{atom\_to\_token}); projection is bias-free and invalid atoms are zero. key_index[B,A,K] supplies global within-batchatomIDs; no batch mixing. A slot is permitted iff its key ID is in[0,A), query/key atoms are usable, andwindow_maskisTrue.- If
\mathrm{radius}\ge 0also require\left|\mathrm{key\_id}-\mathrm{query\_id}\right|\le \mathrm{radius}, a bidirectional INDEX window, not a spatial neighbor search.-1/\mathrm{out}-\mathrm{of}-\mathrm{range}keys are missing. Repeated slots count separately; repeated selection across queries accumulates gradients. - All-missing windows have zero
attention, butvalidatoms retain residual/transition computation. - AF3 style uses
A_{j}(z,c)=\operatorname{LN}(z)\cdot \operatorname{sigmoid}((\operatorname{LN}(c)\cdot \mathrm{cond\_scale}[j])\mathbin{@}w_{\mathrm{scale}}[j]+b_{\mathrm{scale}}[j])+(\operatorname{LN}(c)\cdot \mathrm{cond\_scale}[j])\mathbin{@}w_{\mathrm{shift}}[j], population LN with\varepsiloninside root;j=0query,1key,2transition. - Query/key normalized
atomstates project toQ/K; onlyQhasb_q. Values come from key-normalized atoms. Per-slot logit bias is(\operatorname{LN}(\mathrm{pair})\cdot \mathrm{pair\_scale})\mathbin{@}w_{\mathrm{pair}}. - Residual gates are
\operatorname{sigmoid}(\mathrm{raw} \mathrm{condition}\mathbin{@}w_{\mathrm{residual\_gate}}[j]+b_{\mathrm{residual\_gate}}[j]),j=0attention,1transition. - ESMFold2 style uses six vectors from
\operatorname{SiLU}(\mathrm{condition})contracted withw_mod[S,6,C], orderedattention_shift,attention_scale,attention_gate,transition_shift,transition_scale,transition_gate. - Attention
\mathrm{input}=\operatorname{RMS}(x)\cdot (1+\mathrm{attention\_scale})+\mathrm{attention\_shift}, shared byQ/K/Vand value gating. \operatorname{RMS}(z)=z/\sqrt{\operatorname{mean_last}(z^{2})+\varepsilon}, no affine; additionally\operatorname{RMS}-\operatorname{normalize} QandKindependently over each head'sDcoordinates.Dis even.- Apply supplied full-width
rope_cos/rope_sinby half-split rotation\operatorname{rotate_half}(q)=\operatorname{concat}(-q[D/2:],q[:D/2]); rotateQ/Kbefore gathering keys. The cosine/sine construction from3 Dcoordinates and reference UIDs belongs tospatial_rotary_embedding; here those tensors are supplied differentiable inputs. - There is no
b_qorpairbias in this style. Residual gates are the RAWattention_gateandtransition_gatevectors, not sigmoid gates. - In both styles,
attentionlogits are\operatorname{dot}(Q_{\mathrm{query}},K_{\mathrm{key}})/\sqrt{D}plus anypairbias, stabilized masked softmax overKslots, with exact zero empty rows. - Weighted values are multiplied by
\operatorname{sigmoid}(\mathrm{query}-\mathrm{normalized}-\mathrm{input} \mathrm{contracted} \mathrm{with} w_{\mathrm{value\_gate}}), flattened head-major, and projected withw_attention_out, without bias. Add the appropriateattention-gated update tox. - Normalize/modulate this NEW
xfor transition (AF3A_2; ESMFold2\operatorname{RMS}(x)\cdot (1+\mathrm{transition\_scale})+\mathrm{transition\_shift}).\mathrm{Transition}=\operatorname{SiLU}(z\mathbin{@}w_{\mathrm{ff\_gate}})\cdot (z\mathbin{@}w_{\mathrm{ff\_up}}), thenw_ff_out, then the style-specific transition residual gate. - Add it and mask to obtain
hidden. Decoder: af3\mathrm{position\_update}=(\operatorname{LN}(\mathrm{hidden})\cdot \mathrm{readout\_scale})\mathbin{@}w_{\mathrm{readout}}; esmfold2 adds learnedreadout_bias[C]after the LN scale and beforew_readout. - Mask the result to zero; it is a coordinate UPDATE, not final coordinates and not a residual with
atompositions. Encoder:token_outputis the exact per-tokenmean of\operatorname{ReLU}(\mathrm{hidden}\mathbin{@}w_{\mathrm{pool}})over usable assigned atoms; empty/masked tokens give zero. All boundary linear projections are bias-free. - Final LayerNorm has scale only for AF3 and both scale and bias for ESMFold2. Return
hidden/attentionplus only the stage-specificposition_updateortoken_output. No weights, geometry descriptors, UID encodings, schedules or window maps are inferred; no dropout, resampling, frame updates or input mutation. - Source ESMFold2
atomRMS\varepsilon=10^{-6}can be selected explicitly; one\varepsilongoverns this exercise's normalizers. Numerical domain:\varepsilonmust be finite and remain strictly positive when represented in the input dtype. - Active inputs and parameters must be bounded so the required arithmetic intermediates are finite and within that dtype's representable range: normalization sums/means, centered differences, squares, variance-plus-
\varepsilon, projections, residual/statistic updates, and intermediates for the graded first-order derivatives. - Finite inputs alone do not guarantee this; overflow-sized reductions or squares are outside the contract. Representable subnormal
\operatorname{sigmoid}/\operatorname{SiLU}tails are in scope and must not be prematurely discarded.
Why this matters
Atoms attend only to supplied key slots. Conditioning controls how attention and transition updates enter the residual state. The encoder pools atom features into tokens; the decoder combines token context with atom state to predict coordinate changes.
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 windowed_atom_attention(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
eps: float = 1e-05,
style: str = 'af3',
stage: str = 'decoder',
radius: int = -1,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
hidden: (B, A, C).
attention: (B, H, A, K).
position_update: (B, A, 3). Returned only for stage="decoder".
token_output: (B, T, U). Returned only for stage="encoder"."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement windowed_atom_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.
Related exercises
Sources and further reading
A primitive exercise, not an end-to-end reproduction of the named models. No affiliation or endorsement is implied.