Introduction
Inverse folding asks for the sequence that folds into a given backbone. The input is the coordinates of the N, CA, C and O atoms of every residue. The output is a distribution over twenty amino acids per position. We are scored by sequence recovery, the fraction of positions where the most likely residue is the native one, and by perplexity, the exponential of the mean negative log likelihood of the native residue.
What the encoder must capture is the environment of a residue: which neighbours surround it, at what distances, and in which directions relative to its own backbone. Message passing on a nearest-neighbour graph, as in ProteinMPNN [1], summarises that environment as a sum over pairwise messages, so two arrangements of neighbours with the same set of pairwise messages cannot be told apart. Geometric vector networks add directional channels [2], PiFold is an efficient inverse folding model [3], and later methods add vector fields, unified molecular models and spatial reductions [4, 5, 6]. Diffusion models trade a lot of machinery for the same goal [7, 8]. The starter we were given is a plain three-layer message-passing network over dihedral and orientation features, with a two-layer perceptron as decoder.
Our proposal changes the encoder and leaves the training objective as the usual per-residue negative log likelihood. We ask two things of a layer. First, it should see the angular arrangement of a residue's neighbours, not only their messages. Second, it should see whether two residues in contact have neighbours in common, and how their edges to those neighbours co-vary. At inference we also average the predictions over a small, deterministic family of stochastic networks, which costs no extra labels.
Method
The encoder is a stack of eight layers on a nearest-neighbour graph over CA atoms, at twice the width the harness passes in (256 instead of 128). Apart from the training recipe below, only the encoder, the readout and the inference procedure differ from the starter; the training loss is the mean negative log likelihood of the native residue.
Features in a local frame
Each residue gets a frame built from its own backbone. With origin at CA, is the unit vector from CA to C, is the component of the vector from CA to N orthogonal to , normalised, and . The code falls back on the oxygen position if N, CA and C are nearly collinear. Node features are radial basis expansions of the six intra-residue atom distances, the backbone atoms of the residue and of its sequence neighbours in the local frame, three torsion-like terms, and a few contact-density summaries. Edge features are radial basis expansions of the distances among the N, CA, C, O and a virtual CB atom of the two residues, the directions of the neighbour's atoms in the receiver's frame, the relative rotation of the two frames, and a clipped sequence offset that is embedded. The first node embedding passes through an inverse hyperbolic sine.
Angular moments with the receiver removed
For a residue with neighbours , let be the unit vector to neighbour in the residue's frame and its five real degree-two harmonics. The layer turns each message into a channel density , with a learned sigmoid gate and the number of valid neighbours, and forms moments
These are the first two terms of an angular expansion of the neighbour density. Alongside them the layer computes the power of each moment with the diagonal removed,
which is a sum over distinct pairs of neighbours only. The moments and powers are projected back to the layer width and added to the node update.
The same moments give a per-edge message. For the edge to neighbour the code subtracts that neighbour's own contribution, , and likewise for the second moment. What remains is how the rest of the environment sits relative to neighbour , which the edge update consumes. The code's name for this is a cavity.
def forward(self, h, e, index, valid, first, second, triangles):
n, k, d = e.shape
pair = self.src(h)[:, None] + self.dst(h)[index] + self.edge(e) + self.overlap(e, triangles)
msg = self.message(pair)
scores = self.attention(F.gelu(pair)).masked_fill(~valid[..., None], -float('inf'))
weight = scores.softmax(1)
aggregate = (weight[..., None] * msg.reshape(n, k, self.heads, d//self.heads)).sum(1).reshape(n, d)
delta = self.out(aggregate)
cavity = None
if self.use_moments:
moment_valid = valid & (first.square().sum(-1) > 1e-6)
mw = self.moment_attention(F.gelu(pair)).sigmoid() * moment_valid[..., None]
mv = torch.tanh(self.moment_value(msg))
density = mw * mv / moment_valid.sum(1,keepdim=True).clamp_min(1).sqrt()[...,None]
m1 = torch.einsum('nkc,nka->nca', density, first)
m2 = torch.einsum('nkc,nka->nca', density, second)
if not self.second_order:
m2 = m2 * 0.0
# Remove the diagonal terms from the power spectrum: true distinct-neighbor correlations.
power1 = (m1*m1).sum(-1) - ((density*density) * (first*first).sum(-1,keepdim=True)).sum(1)
power2 = (m2*m2).sum(-1) - ((density*density) * (second*second).sum(-1,keepdim=True)).sum(1)
if not self.second_order:
power2 = power2 * 0.0
mf = torch.cat((m1.flatten(1), m2.flatten(1), power1, power2), -1)
delta = delta + self.moment_out(mf)
if self.use_cavity and not self.final_node_readout:
c1 = torch.einsum('nca,nka->nkc', m1, first) - density*(first*first).sum(-1,keepdim=True)
c2 = torch.einsum('nca,nka->nkc', m2, second) - density*(second*second).sum(-1,keepdim=True)
if not self.second_order:
c2 = c2 * 0.0
# Conditional mean of the environment with the receiving neighbor removed.
cavity = self.cavity_out(torch.cat((c1,c2), -1))
h = self.norm1(h + self.dropout(delta))
h = self.norm2(h + self.dropout(self.ff(h)))Correlations over shared neighbours
For an edge from residue to a contact , we enumerate the third residues that both and have among their own neighbours, with , . Two small projections of the edge features give and . The layer passes the means of and over the shared set and their unbiased sample covariance, together with the log of one plus the number of shared neighbours, scaled by the log of one plus , through a linear map into the pair representation of edge . The map is initialised to zero, so each layer begins as ordinary message passing and learns to use the statistic.
def _cm_common_neighbor_edges(selection, index, valid):
"""Three distinct residues, with both receivers connected to the same third site."""
n, k = index.shape
batch_size, length = selection.shape
batch, position = selection.nonzero(as_tuple=True)
destination = position[index]
edge_ids = torch.arange(n*k, device=index.device).reshape(n, k)+1
lookup = index.new_zeros((batch_size, length, length))
lookup[batch[:, None].expand_as(index)[valid],
position[:, None].expand_as(index)[valid], destination[valid]] = edge_ids[valid]
shared = lookup[batch[:, None, None], destination[:, :, None], destination[:, None, :]]
present = valid[:, :, None] & valid[:, None, :] & (shared > 0)
present = present & (index[:, :, None] != index[:, None, :])
present = present & (index[:, :, None] != torch.arange(n, device=index.device)[:, None, None])
present = present & (index[:, None, :] != torch.arange(n, device=index.device)[:, None, None])
receiver, contact, third = present.nonzero(as_tuple=True)
output_edge = receiver*k+contact
first_edge = receiver*k+third
second_edge = shared[receiver, contact, third]-1
counts = present.sum(-1).reshape(-1, 1)
return output_edge, first_edge, second_edge, countsclass _CMOverlapCovariance(nn.Module):
"""Connected cross-contact correlations on exactly shared neighbors."""
def __init__(self, width):
super().__init__()
self.count_scale = None
channels = max(8, width//8)
self.left = nn.Linear(width, channels)
self.right = nn.Linear(width, channels)
self.output = nn.Linear(3*channels+1, width, bias=False)
nn.init.zeros_(self.output.weight)
self.mode = 'covariance'
def forward(self, edges, triangles):
if self.mode == 'off':
return torch.zeros_like(edges)
flat = edges.flatten(0, 1)
a = torch.tanh(self.left(flat))
b = torch.tanh(self.right(flat))
mean_left, mean_right, product = _cm_overlap_statistics(a, b, triangles, self.mode != 'uncentered')
if self.mode == 'means':
product = product*0.0
count = triangles[-1].to(flat.dtype)
features = torch.cat((mean_left, mean_right, product, torch.log1p(count)/(self.count_scale if self.count_scale is not None else math.log1p(edges.shape[1]))), -1)
return self.output(features).reshape_as(edges)Readout with a per-structure composition term
The decoder is a batch-normalised linear map from the final node embedding to twenty logits. To that the model adds a global correction computed once per structure. A small network takes the mean and standard deviation of the node embeddings over the structure and the average of the position-wise softmax, and returns an additive logit shift shared by all positions. Its last layer is initialised to zero. The code also contains a projection of the predicted distribution onto a target composition and a count-based objective, but both are switched off in the submission, so only the additive shift is used.
def readout(self,h,selection):
mask=selection.float()
logits=self.decoder(h)
dense=logits.new_zeros(tuple(mask.shape)+(NUM_AA,))
dense[selection]=logits
n=mask.sum(1).clamp_min(1)
lengths=selection.sum(1)
mean=torch.segment_reduce(h, 'sum', lengths=lengths, unsafe=True)/n[:,None]
square=torch.segment_reduce(h.square(), 'sum', lengths=lengths, unsafe=True)/n[:,None]
sd=(square-mean.square()).clamp_min(1e-5).sqrt()
baseline=(F.softmax(dense,-1)*mask[...,None]).sum(1)/n[:,None]
global_parameters=self.composition(torch.cat((mean,sd,baseline),-1))
if not self.use_projection:
lp=F.log_softmax(dense+global_parameters[:,:NUM_AA,None].transpose(1,2),-1)
lp=torch.where(selection[...,None],lp,lp.new_full((),-math.log(NUM_AA)))
return lp,NoneInference by averaging over deterministic dropout masks
The model is evaluated in eval mode, and its forward pass then averages probabilities over several members of a family of networks, in log space:
Each member applies dropout masks with the training rate, but the masks are not random draws. They are produced by an integer hash of the residue's position in its chain, the channel, the neighbour and the layer, and are stratified across the members so that each unit is dropped in the right fraction of them. A prediction therefore does not depend on which other proteins share the batch or on a random seed. If dropout is zero, no masks are applied and the members differ only in their normalisation context.
Batch normalisation poses a second problem, because the statistics seen at inference differ from the running averages when dropout is on. Before evaluation the model re-estimates, for each normalisation layer except the first, the moments of its inputs on a reservoir of up to 256 training structures, cropped to 512 residues, sampled from the training loader before training starts. It keeps up to 32 such cohorts as separate normalisation contexts, one per ensemble member, and also records the range each activation takes, to clip activations that leave that range at test time. The structures carry no labels in this procedure, and the comment in the code calls the stored support a training-only geometric measure that contains neither identities nor labels.
contexts = torch.arange(start,start+width,device=X.device,dtype=torch.long)
for layer in normalizers:
layer.reference_context_index = contexts
if self.inference_samples > 0:
draws = contexts.to(torch.int32)
for dropout in node_dropouts:
dropout.set_draw(draws.repeat_interleave(len(positions)))
global_dropout.set_draw(draws.repeat_interleave(len(X)))
embedded = self.encoder.embed_context_input(repeated)
paths = self.readout(*self.encoder.encode_prepared(embedded))[0]
paths = paths.reshape(width,X.shape[0],X.shape[1],NUM_AA)
for probability in paths.unbind(0):
accumulated = probability if accumulated is None else torch.logaddexp(accumulated,probability)
finally:
for layer in normalizers:
layer.reference_context_index = None
for dropout in node_dropouts+[global_dropout]:
dropout.end_sampling()
return accumulated-math.log(count)Training recipe
The submission sets the allowed training overrides to eight encoder layers, a batch size of 8, an exponential moving average of the weights with decay 0.999, weight decay 0.2, and a one-cycle schedule that peaks after 25 percent of training. The reference results in this task include a published method with an EMA and weight decay variant, which is a training-recipe change of the same kind, so a comparison with the nearest baseline has to take that into account.
Results
| Method | ① | ② | ③ | |||
|---|---|---|---|---|---|---|
| Sequence recovery ↑ | Perplexity ↓ | Sequence recovery ↑ | Perplexity ↓ | Sequence recovery ↑ | Perplexity ↓ | |
| GPT-6 Astra | 0.552 | 3.962 | 0.544 | 3.840 | 0.559 | 3.857 |
| ProteinMPNN | 0.469 | 5.310 | 0.459 | 5.212 | 0.489 | 5.057 |
| PiFold | 0.521 | 4.811 | 0.517 | 4.574 | 0.528 | 4.857 |
| GVP | 0.407 | 6.426 | 0.400 | 6.276 | 0.417 | 6.171 |
| VFN-IF, as published | 0.540 | 4.328 | 0.531 | 4.240 | 0.560 | 4.243 |
| UniIF | 0.525 | 4.956 | 0.519 | 4.610 | 0.541 | 4.678 |
| ScFold | 0.518 | 5.049 | 0.512 | 4.659 | 0.525 | 4.813 |
| DIF-Large | 0.434 | 0.425 | 0.455 | |||
| MapDiff | 0.481 | 5.306 | 0.472 | 5.137 | 0.508 | 5.143 |
| ProteinMPNN, AR decoder | 0.474 | 5.502 | 0.461 | 5.536 | 0.489 | 5.495 |
| GVP, AR decoder | 0.409 | 6.750 | 0.406 | 6.634 | 0.420 | 6.546 |
| SurfFold | 0.280 | 9.905 | 0.282 | 9.840 | 0.286 | 9.897 |
| VFN-IF | 0.544 | 4.058 | 0.547 | 3.882 | 0.556 | 3.839 |
- ① CATH 4.2 · recovery / perplexity
- ② CATH 4.3 · recovery / perplexity
- ③ TS50 · trained on CATH 4.2
On CATH 4.2 the model reaches a recovery of 0.552 and a perplexity of 3.962, against 0.544 for the strongest baseline on recovery, VFN-IF EMA+WD, and 4.058 on perplexity, VFN-IF EMA+WD. On CATH 4.3 the figures are 0.544 and 3.840, against 0.547 (VFN-IF EMA+WD) and 3.882 (VFN-IF EMA+WD). Our margin over the strongest baseline is small, and on CATH 4.3 the strongest baseline on recovery is ahead of us. The strongest baselines there are recipe variants of VFN-IF, not new architectures.
On TS50 we reach a recovery of 0.559 and a perplexity of 3.857. The best baseline recovery there is 0.560 (VFN-IF [4]) and the best perplexity 3.839 (VFN-IF EMA+WD), so on this setting we are behind on both measures.
We have no ablation for this run, so the table cannot tell which of the parts, the moments, the shared-neighbour statistic, the ensemble or the recipe, accounts for the gain.
How we got here
The starter is a three-layer network with layer normalisation and an ordinary dropout decoder. The submission replaces all of it. The code keeps the starter's class names and call signature, which shows that the new layers were built to slot into the fixed harness, and a signature-compatible scalar message-passing layer, rewritten with batch normalisation and the hashed dropout, is kept in the file next to the new one, unused by the encoder.
The comments suggest what the design was meant to address. The module that handles shared neighbours is described as exact cross-contact correlations, and the moment layer as removing diagonal terms so that the power is a sum over distinct neighbours. Both indicate an effort to make the statistics of the neighbourhood free of diagonal terms, and the cavity term, by the code's comment, removes the receiving neighbour. Much of the code that follows concerns determinism: stateless hashed dropout, a fixed contact order at inference, padding that keeps a short graph's reductions the same whatever is appended to the batch, and comments saying that the training graph and its accumulation order are kept. These suggest that predictions were found to depend on batch composition and that this was fixed deliberately, but the code does not say so, and we do not know what was measured.
Two features of the file read as alternatives that were built and then switched off: the projection onto a target amino acid composition and the count-based objective are both implemented, and both are disabled in the submission. The final layer's edge branch is removed after construction because, as the comment states, nothing downstream uses it; the retained parameters keep their original initialisation.
Limitations
- Behind on TS50 and on recovery on CATH 4.3. The model is below the best baseline on both measures on TS50 and on recovery on CATH 4.3, so its advantage is not uniform.
- A small margin on CATH 4.2 and CATH 4.3. The gains over the best baseline are modest, and that baseline is a training-recipe variant that uses an exponential moving average and weight decay. Ours also uses both, with a wider and deeper encoder, so the comparison does not isolate the new layers.
- No ablations. We cannot say how much of the result comes from the moments, the shared-neighbour covariance, the composition shift, the ensemble or the recipe. All five changed together.
- Cost. The shared-neighbour enumeration builds tensors that grow with per residue, and the inference ensemble multiplies the encoder's forward cost by up to 32. The code bounds the size of each expanded tensor, which changes only how the ensemble members are grouped.
- Machinery that needs the training set at test time. Re-estimating normalisation statistics requires a stored sample of training structures to travel with the model. The stored structures carry no labels, but this makes the model less self-contained than a plain network.
- Complexity. The file is long, and several of its parts exist for numerical determinism and not for accuracy. A reader should expect to need an ablation before accepting that each part is needed.
- Structure-only and single-sequence. The method uses backbone coordinates alone and predicts each position independently given the structure, with no autoregressive or iterative refinement, so it cannot model dependencies between residues beyond what the encoder sees.
References
- J. Dauparas, I. Anishchenko, N. Bennett et al. (2022). Robust deep learning–based protein sequence design using ProteinMPNN. Science.
- Bowen Jing, Stephan Eismann, Patricia Suriana et al. (2021). Learning from Protein Structure with Geometric Vector Perceptrons. ICLR.
- Zhangyang Gao, Cheng Tan, Pablo Chacón et al. (2023). PiFold: Toward effective and efficient protein inverse folding. ICLR.
- Weian Mao, Muzhi Zhu, Zheng Sun et al. (2024). De novo protein design using geometric vector field networks. ICLR.
- Zhangyang Gao, Jue Wang, Cheng Tan et al. (2024). UniIF: Unified Molecule Inverse Folding. NeurIPS.
- Jiancheng Zhong, Zhiwei Zou, Jie Qiu et al. (2025). ScFold: a GNN-based model for efficient inverse folding of short-chain proteins via spatial reduction. Briefings in Bioinformatics.
- Peizhen Bai, Filip Miljković, Xianyuan Liu et al. (2024). Mask prior-guided denoising diffusion improves inverse protein folding.
- Yasha Ektefaie, Olivia Viessmann, Siddharth Narayanan et al. (2024). Reinforcement learning on structure-conditioned categorical diffusion for protein inverse folding.
- Darong Li, Lian Shen, Meijia Song et al. (2026). SurfFold: a unified model for protein inverse folding by integrating surface and structural information. Bioinformatics.