All-atom folding

ESMFold 2 Atom Attention Decoder

HardRaw PyTorchAbout 30 min1 public example plus private tests

ESMFold2

Write and run your solution Sign in

Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.

Your task

Add each atom’s mapped token context, update the atom using its allowed key slots and conditioned transition, then read out a 3D coordinate update from its hidden feature vector. Each position_update is a displacement output, not a final atom position. Use ESMFold2 RMS modulation, rotary query/key features, and raw residual gates.

Function signature

esmfold2_atom_attention_decoder(
    activations: dict,
    parameters: dict,
    masks: dict,
    structure: dict,
    eps: float = 1e-05,
    radius: int = -1,
) -> dict[str, torch.Tensor]

Worked example

Worked example: competing neighbor slots, an excluded slot, and an active residual update

In ESMFold2 decoder mode with illustrative eps=1, adding token context [1,1] gives atom vectors [2,4], [4,2]. Write the first as [l,h] and let r=\sqrt{(l^2+h^2)/2+1}. RMS-normalized value vectors are [l,h]/r and [h,l]/r. After q/k RMS normalization, rotate the second atom’s q/k channels by \pi/2, making its key proportional to [-l,h]. Query 0’s self-key and second-key scores therefore differ by 2l^2/((l^2+h^2+1)\sqrt2); its self weight is the sigmoid of that difference. Condition 1 and residual-modulation weight 1+e^{-1} make the raw attention residual multiplier 1, while the value gate is 1/2, so its first hidden channel is l+[pl+(1-p)h]/(2r). Query 1 uses only its own key. For query 0 let \delta=(H_1-H_0)/2 from that hidden vector. The final LayerNorm, scale 2, bias [0.5,-0.5], and supplied readout return [-b,b,-2b], where b=2\delta/\sqrt{\delta^2+1}-0.5\approx0.928271. These are position updates, not absolute coordinates. The supplied transition update is zero.

Parameters

ParameterShape and meaning
activationsdictSupplied intermediate tensors.
parametersdictSupplied model parameters, keyed as shown below.
masksdictSupplied masks. Each field below defines what True includes or permits.
structuredictFields supplied together in this dictionary.
epsfloatDefault 1e-05Positive stabilizer inside every LayerNorm variance or RMS mean-square root used by this block.
radiusintDefault -1Maximum 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

  • An atom is usable only when valid=True, atom_to_token lies in range, and its mapped token_valid=True. Sanitize unusable atom/condition payloads. A key slot additionally requires an in-range usable key and window_mask=True.
  • radius defaults to −1 (unlimited). A nonnegative radius further requires abs(query_atom_index−key_atom_index) ≤ radius. This is an INDEX window, not a geometric radius. Repeated slots remain independent softmax entries.
  • Begin with the cleaned atom features plus the projected token feature token @ w_token gathered to each usable atom.
  • Compute SiLU(condition) @ w_mod as six vectors in order: attention shift, scale, gate; transition shift, scale, gate. Each modulated feature is RMSNorm(x) * (1 + scale) + shift. Residual gates are RAW modulation values, not sigmoids.
  • Project Q/K/V without biases; apply RMS normalization separately over each Q/K head width. Apply the supplied half-split rotary embedding to Q/K before gathering slots. The head width is even. There is no pair-logit bias.
  • Compute Q\cdot K/\sqrt D; softmax over allowed key slots only. Empty rows have exact zero attention weights. Weight V, multiply each head by sigmoid(query_features @ w_value_gate), flatten head-major, and apply w_attention_out before the gated residual.
  • Normalize the updated residual state for the transition. Compute SiLU(z @ w_ff_gate) * (z @ w_ff_up), then w_ff_out, then its gated residual. All normalization epsilons use eps (default 1e-5) inside the square root.
  • Return hidden, attention, and position_update. Apply LayerNorm to hidden, multiply readout_scale and add readout_bias, then w_readout. This is a coordinate UPDATE, not coordinates; zero unusable atom outputs.
  • All parameters and rotary values are supplied. There is no sampled dropout, neighbor search, or additional coordinate transformation.
  • Use CPU float32/float64 tensors with one shared floating dtype/device. Preserve strided layouts and do not mutate supplied tensors.
  • Use raw tensor operations, not a ready-made implementation of the requested primitive. Supplied parameters and random variates must not be reinitialized.
  • For even head width D, define \operatorname{rotate\_half}(q)=\operatorname{concat}(-q[...,D/2:],q[...,:D/2]). Replace Q and K by q\odot rope\_cos+\operatorname{rotate\_half}(q)\odot rope\_sin before gathering key slots.
  • RMSNorm is x/\sqrt{\operatorname{mean}_{last}(x^2)+eps}. LayerNorm is (x-\mu)/\sqrt{\operatorname{mean}_{last}((x-\mu)^2)+eps}, where \mu=\operatorname{mean}_{last}(x).

Why this matters

ESMFold2 broadcasts token context back to atom skip features, refines atoms with local RMS/RoPE attention, and predicts a coordinate change for every usable atom.

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 esmfold2_atom_attention_decoder(
    activations: dict,
    parameters: dict,
    masks: dict,
    structure: dict,
    eps: float = 1e-05,
    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)."""
    # Implement the operation. Inputs and test setup are supplied by BioTorch.
    raise NotImplementedError("Implement esmfold2_atom_attention_decoder")

Ready to implement it?

3 progressive hints, a solution walkthrough, and grading that checks values, shapes and gradients are waiting in the workspace.

Write and run your solution Sign in

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.