Structure module, templates and recycling · INTEGRATION
Template geometry and pair features
AlphaFold2OpenFoldAlphaFold3RFdiffusion
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Describe each ordered template residue pair by its representative-atom distance, residue identities, and model-specific orientation. Return the representative coordinates, geometric validity, raw feature vector, and its learned embedding; the selected mode fixes the coordinate and feature conventions.
Function signature
template_pair_features(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
mode: str = 'af2',
eps: float = 1e-08,
type_count: int = 22,
norm_eps: float = 1e-05,
glycine_index: int = 7,
) -> dict[str, torch.Tensor]Worked example
An off-diagonal direction in a rotated frame
Consider the AF2 raw-feature stage for one template and two residues. Atom order is N, CA, C, CB. Residue 0 has atoms (-1,0,0),(0,0,0),(0,1,0),(0,0,1); residue 1 has (1,0,0),(2,0,0),(2,1,0),(2,0,1). All atoms and pairs are valid. Set residue_type=[0,1], type_count=2, glycine_index=1, distance_edges=[2], and eps=0.01. The representative atoms are (0,0,1) and glycine CA (2,0,0), with squared distance 5, so the distance one-hot is [0,1]. Residue 0 has local x along global y and local y along negative global x; therefore CA displacement (2,0,0) becomes local (0,-2,0). For pair (0,1), concatenate [0,1], [1], right type [0,1], left type [1,0], local direction [0,-2/sqrt(4.01),0], and [1]. The local y channel is approximately -0.998752; affine projection is the next stage.
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. |
modestrDefault 'af2' | Choose "af2", "af3", "rfdiffusion". mode='af2' (default) or 'af3': pseudo_beta is CA for \mathrm{residue\_type}=\mathrm{glycine\_index} (default 7), otherwise CB. |
epsfloatDefault 1e-08 | Positive geometric squared-norm floor for frame/angle construction and an additive squared-distance stabilizer for local unit directions; use the distinct placements in the selected feature rule. |
type_countintDefault 22 | Size of the residue-type vocabulary. |
norm_epsfloatDefault 1e-05 | Positive value added to final-axis population variance inside the query LayerNorm square root; used by the AF3 query-conditioning projection. |
glycine_indexintDefault 7 | Vocabulary index for glycine. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Construct template pair
featuresand theirembedding. PositiveB,T,N,A,\mathrm{Ct};T\ge 1, so no-template input is represented by all-Falsemasks.atom_positions[B,T,N,4,3] is orderedN,\mathrm{CA},C,\mathrm{CB}, withTrueatom_maskmeaning present. All supplied floats are finite, including masked entries. residue_type[B,T,N] is in[0,A);A=\mathrm{type\_count}(default22).pair_mask[B,N,N] allows a directed pair, e.g. an intrachain restriction.distance_edges[K]hasK\ge 1positive strictly increasing length cutoffs.- An exhaustive distance bin is
k=\sum(\mathrm{distance\_squared} > \mathrm{edge\_squared}): equality stays in the lower bin. This deliberate complete-bucket convention is not AF2's strict finite-interval distogram.\varepsilon>0(default10^{-8}) is a squared-norm threshold. mode='af2'(default) or 'af3':pseudo_betais CA for\mathrm{residue\_type}=\mathrm{glycine\_index}(default7), otherwise CB. Missing pseudo-\betacoordinates return zero.- Build
x=\operatorname{normalize}(C-\mathrm{CA}),y=\operatorname{normalize}((N-\mathrm{CA})-\operatorname{dot}(N-\mathrm{CA},x)x),z=\operatorname{cross}(x,y), with squared norms clamped below by\varepsilonbefore division. - A backbone frame is valid only if
N/\mathrm{CA}/Cexist and both tested squared norms exceed\varepsilon. - For pair
i,j,u=\frac{R_i^\top(\mathrm{CA}_j-\mathrm{CA}_i)}{\sqrt{\|R_i^\top(\mathrm{CA}_j-\mathrm{CA}_i)\|^2+\varepsilon}}, whereRcolumns arex,y,z. Its diagonal is zero.pair_validrequires both frames, both pseudo-betas andpair_mask. - Concatenate in this exact order: [distance one-hot
K+1,pair_valid1, residue-jone-hotA, residue-ione-hotA, u3,pair_valid1], givingF=K+2A+6. Zero every feature of invalid pairs.\mathrm{embedding}=\mathrm{features}\mathbin{@}w_{\mathrm{features}}+b_{\mathrm{features}}, also zeroed after bias for invalid pairs. mode='af3'additionally layer-normalizesquery[B,N,N,\mathrm{Cq}] overC_qwith population variance and\sqrt{\mathrm{var}+\mathrm{norm\_eps}},\mathrm{norm\_eps}>0default10^{-5}, then appliesquery_scale/query_biasand bias-freew_query. Add this projectedqueryto every templateembeddingbefore final masking.- This is the protein-template,
query-conditioned feature construction; independent input projections in AF3 can be represented by blocks of the concatenated projection. mode='rfdiffusion': ignore CB and reconstruct\beta=\mathrm{CA}-0.58273431\cdot \operatorname{cross}(CA-N,C-CA)+0.56802827\cdot (\mathrm{CA}-N)-0.54067466\cdot (C-\mathrm{CA}). RequireN/\mathrm{CA}/Cat both ends andpair_mask.- Nonself pairs with
\betadistance STRICTLY below the final distance edge have orientations\omega=\operatorname{dih}(\mathrm{CA\_i},\beta_{i},\beta_{j},\mathrm{CA\_j}),\theta=\operatorname{dih}(N_{i},\mathrm{CA\_i},\beta_{i},\beta_{j}),\phi=\operatorname{angle}(\mathrm{CA\_i},\beta_{i},\beta_{j}). - For
\operatorname{dih}(a,b,c,d), let\mathrm{axis}=\operatorname{normalize}(c-b),v=(a-b)-\bigl((a-b)\cdot\mathrm{axis}\bigr)\mathrm{axis},w=(d-c)-\bigl((d-c)\cdot\mathrm{axis}\bigr)\mathrm{axis};\operatorname{angle}=\operatorname{atan2}(\operatorname{dot}(\operatorname{cross}(\mathrm{axis},v),w),\operatorname{dot}(v,w)). - If axis,
vorwhas squared\operatorname{norm}\le \varepsilon, all six orientation channels are zero. Otherwise concatenate[\sin\omega,\sin\theta,\sin\phi,\cos\omega,\cos\theta,\cos\phi]. Diagonal/long-range orientations are zero and distance one-hot is the final (overflow) bin. - Concatenate [distance one-hot
K+1, orientations6,pair_valid1,type_jA,type_iA],F=K+2A+8; mask and project as above. - The
\phisine uses\sqrt{\operatorname{max}(\Vert \operatorname{cross}(\operatorname{unit}(\mathrm{CA\_i}-\beta_{i}),\operatorname{unit}(\beta_{j}-\beta_{i}))\Vert ^{2},\varepsilon)}; smooth fixtures stay away from this floor. Unlike upstream sentinel/NaNconventions, absent geometry has exact-zerofeatures. - Both alphafold modes require proper nondegenerate frame geometry when marked valid; all modes exclude exact bin/cutoff boundaries from differentiability claims. No template pair stack is hidden inside this function.
Why this matters
Templates contribute distances, local directions and residue identities. Missing coordinates determine whether a pair is usable; the selected AF2, AF3 or RFdiffusion mode determines which geometric features are included.
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 template_pair_features(
activations: dict,
parameters: dict,
masks: dict,
structure: dict,
mode: str = 'af2',
eps: float = 1e-08,
type_count: int = 22,
norm_eps: float = 1e-05,
glycine_index: int = 7,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
pseudo_beta: (B, T, N, 3).
pair_mask: (B, T, N, N).
features: (B, T, N, N, F).
embedding: (B, T, N, N, Ct)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement template_pair_features")
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.