Introduction
Inverse folding asks for the amino-acid sequence that a given protein backbone, the coordinates of N, CA, C and O for every residue, will fold into. The model is a function from a backbone to twenty-way log-probabilities for every position, and it is scored by how often its top choice is the native residue (sequence recovery, higher is better) and by the per-residue perplexity of the native sequence (lower is better).
The field's standard answer is a message-passing network on the -nearest-neighbour graph of the backbone that produces an embedding per residue, followed by a per-residue read-out [1, 2, 3]. Later models enrich the geometry, with vector-valued features [4] or with unified graph encoders [5], but most keep the read-out: each position's distribution is computed from its own embedding. Two things limit that design, and our method is built out of both.
The backbone says more than the usual featuriser asks it. The backbone fixes the position of the amide hydrogen, the possible places of the side-chain tip for each rotamer, which neighbours could hydrogen-bond, and whether a peptide bond is cis or broken. A network can learn some of this from distances and dihedral angles, but it has to rediscover it from a small training set, and it is prone to learn it from the coordinate noise of the particular structures it has seen.
Neighbouring residues are not independent. Two residues in contact in the core must pack, a pair of charges across a surface must be compatible, and a cysteine pair is only worth proposing in a geometry that can host a disulfide bond. A read-out that scores each residue alone cannot express any of this. The expressive alternative, autoregressive decoding, pays for it with an order and a sampling procedure, and the model here returns a marginal for each position, not one sampled sequence.
Method
We call the method RotamerTRW-Potts. It has an encoder that is physically informed and geometric (Section 1) and a decoder that is a pairwise random field with an iterative inference procedure (Sections 2 to 4). All of it consumes the backbone only. The training script, optimiser, data loading and the evaluation harness are the task's; our changes are to the model and to a single hyperparameter dictionary (a 14-layer encoder, learning rate , weight decay , EMA decay , dropout ).
The encoder: exact stereochemistry as input features
From N, CA and C we reconstruct the beta carbon with fixed coefficients and place three virtual gamma-carbon positions, one per staggered rotamer (, and ), at the bond length and angle of a side chain:
u1 = _safe_unit(CB_u - CA_u)
n_perp = (N_u - CA_u) - ((N_u - CA_u) * u1).sum(dim=-1, keepdim=True) * u1
u2 = _safe_unit(n_perp)
u3 = torch.cross(u1, u2, dim=-1)
c_th = 0.35020738
s_th = 0.93667219
cg_m60 = CB_u + 1.53 * (c_th * u1 + s_th * (0.5 * u2 - 0.8660254 * u3))
cg_p60 = CB_u + 1.53 * (c_th * u1 + s_th * (0.5 * u2 + 0.8660254 * u3))
cg_180 = CB_u + 1.53 * (c_th * u1 - s_th * u2)
CG_u = torch.stack([cg_m60, cg_p60, cg_180], dim=2) * valid[..., None, None].to(dtype)Pairs of such rotamer tips, between a residue and each neighbour, give steric clearances and "open" indicators, which the feature stack turns into inputs for the question that matters to a core pair: could a large side chain sit here, and next to that one. The same featuriser computes backbone dihedrals and bond angles as sine and cosine, flags broken peptide bonds from the C-N distance and cis peptide bonds from the omega dihedral, and a hydrogen-bond potential for every neighbour pair. For the last one we place the amide hydrogen from the previous residue's carbonyl and evaluate the Kabsch-Sander electrostatic energy,
clipped to the attractive range:
dNO = _safe_norm(N.unsqueeze(2) - O.unsqueeze(1), dim=-1).clamp(min=0.8)
if self.use_true_ks_stencil:
if self.training and self.tert_jitter > 0.0:
ks_jit = 0.5 * self.tert_jitter
dHO = (dHO + torch.randn_like(dHO) * ks_jit).clamp(min=0.8)
dHC = (dHC + torch.randn_like(dHC) * ks_jit).clamp(min=0.8)
dNC = (dNC + torch.randn_like(dNC) * ks_jit).clamp(min=0.8)
dNO = (dNO + torch.randn_like(dNO) * ks_jit).clamp(min=0.8)
E_raw = 27.888 * (1.0 / dNO + 1.0 / dHC - 1.0 / dHO - 1.0 / dNC)
else:
E_raw = 27.888 * (1.0 / dNC + 1.0 / dHO - 1.0 / dHC - 1.0 / dNO)
hb_att = torch.where(hb_elig, (-E_raw).clamp(min=0.0, max=4.5) / 3.0, torch.zeros_like(D_ca))In training the four distances are perturbed by Gaussian noise of scale (half of
tert_jitter), so the network sees the hydrogen-bond signal as a soft quantity rather than as the
coordinate noise of the specific crystal structure.
The encoder itself keeps, next to each residue's scalar embedding , a set of vectors in the residue's local frame, eight of them initialised from physical anchor points, and every layer exchanges messages in three channels at once: scalar attention over neighbours, attention that moves the neighbour's vectors into the receiver's frame, , and an edge channel that is updated from both the scalars and the distances and cosines between the two vector clouds. The vectors and the scalars are coupled in both directions (vector norms, distances and cosines enter the scalar update, a scalar-gated MLP updates the vectors), and the edge stream also receives the reverse edge so that directed information is not lost. A global gate from the protein's mean and standard deviation of embeddings closes each layer.
The decoder: a low-rank Potts model
For each edge in the neighbour graph the decoder produces a coupling as a rank-24 product, , with computed from residue and the edge and from the neighbour and the edge. The couplings are symmetrised with the reverse edge, bounded by a learned soft cap, and projected to the zero-sum gauge (rows, columns and total mean removed) so that the unary and pairwise parts do not trade off against each other. A per-edge weight lets the model decide how much to trust each message:
J_raw = torch.einsum("blkar,blkcr->blkac", U, V) / math.sqrt(self.rank)
if self.use_phys_pair_basis:
J_raw = J_raw + torch.einsum("blkm,mac->blkac", self.phys_pair_gate(e_in), self.phys_pair_basis)
J_flat = J_raw.reshape(B, L_v * K, NUM_AA * NUM_AA)
J_rev = torch.gather(
J_flat, 1, rev_flat_idx.unsqueeze(-1).expand(B, L_v * K, NUM_AA * NUM_AA)
).reshape(B, L_v, K, NUM_AA, NUM_AA).transpose(-1, -2)
J = torch.where(has_rev[..., None, None], 0.5 * (J_raw + J_rev), J_raw)
j_cap = self.log_j_cap.exp().clamp(min=0.5, max=5.0)
J = j_cap * torch.tanh(J / j_cap)
J = J - J.mean(dim=-1, keepdim=True) - J.mean(dim=-2, keepdim=True) + J.mean(dim=(-1, -2), keepdim=True)
J = J * m_hollow[..., None, None].to(J.dtype)
rho_logit = self.rho_head(e_in).squeeze(-1)
rho_rev = torch.gather(rho_logit.reshape(B, L_v * K), 1, rev_flat_idx).reshape(B, L_v, K)
rho_sym = torch.where(has_rev, 0.5 * (rho_logit + rho_rev), rho_logit)
rho = (0.15 + 0.85 * torch.sigmoid(rho_sym)) * m_hollow.to(J.dtype)
return J, rhoWith a unary field from the node embedding and the weights , the marginal logits are
where is the cavity belief of , its marginal with the message from removed (the multi-body field of the next subsection is added to after the sweeps), so that a pair does not hear its own voice back. The messages are damped, with and one learned per training sweep (the last is reused for the two extra test-time sweeps), and the cavity beliefs are tempered by , where is the number of neighbours that and share in the symmetrised graph, divided by 30. The tempering discounts the information that two residues receive from each other through a triangle of contacts as well as directly, which is where plain loopy belief propagation double-counts. The sweeps run in the forward pass, are differentiated through, and use 6 sweeps in training and 8 at test.
The multi-body correction and the leave-one-out cavity
A Potts model is pairwise; side-chain packing is not. A small attention layer reads the neighbours' beliefs (an embedding of the probabilities, their entropy and their maximum) and adds a multi-body field to the logits. In the loop we need that field for a cavity: the field that receives from its neighbours except . Recomputing it for each of edges would multiply the cost by , but because the field is an attention-weighted sum, the leave-one-out value follows from one subtraction and one renormalisation per edge:
for step in range(steps):
l_node = h0 + (rho_f * mu).sum(dim=2)
l_j = _gather_flat(l_node, flat_idx, B, L_v, K)
mu_i_to_j = torch.gather(
mu.reshape(B, L_v * K, NUM_AA), 1, rev_flat_idx.unsqueeze(-1).expand(B, L_v * K, NUM_AA)
).reshape(B, L_v, K, NUM_AA) * rev_f
if self.use_kikuchi_loo:
if self.use_multi_kikuchi:
do_kik = (step in (2, 4)) if steps <= 6 else (step in (2, 4, 6))
else:
do_kik = (step == mid_step)
if do_kik:
l_cav_pre = (l_j + dh_j_no_i - mu_i_to_j) if dh_j_no_i is not None else (l_j - mu_i_to_j)
cav_mid = F.softmax(beta_cav * l_cav_pre, dim=-1)
kik_w = torch.sigmoid(self.kikuchi_gate)
dh_new = kik_w * self._hollow_multibody_loo(
cav_mid, z, h_E, m_hollow, has_rev, rev_flat_idx, flat_idx
)
dh_j_no_i = dh_new if dh_j_no_i is None else (0.5 * dh_j_no_i + 0.5 * dh_new)
l_cav = (l_j + dh_j_no_i - mu_i_to_j) if dh_j_no_i is not None else (l_j - mu_i_to_j)
cav_log_b = F.log_softmax(beta_cav * l_cav, dim=-1)
raw_msg = torch.logsumexp(J + cav_log_b.unsqueeze(-2), dim=-1)
raw_msg = raw_msg - raw_msg.mean(dim=-1, keepdim=True)
alpha = torch.sigmoid(self.damp_logits[min(step, self.n_bp_steps - 1)])
mu = ((1.0 - alpha) * mu + alpha * raw_msg) * mh_fThe multi-body field enters the loop once, at the fourth sweep (step index 3, half of the six training sweeps), gated by a learned scalar (its development value was reported as about after a sigmoid, on the full-scale checkpoint). In the final file the injection runs once, so no averaging with an earlier value takes place.
Training objective, and what is added at test time
The loss combines five likelihoods of the native sequence: the marginal after belief propagation (weight ), the unary field alone (), a pseudo-likelihood of each residue given its neighbours' native identities (), a masked conditional likelihood in which a random fraction between 25% and 85% of the residues are hidden and the rest are given (), and a Bethe pair likelihood over the ten nearest edges that requires the joint belief of a pair to match the native pair (). A small entropy bonus is subtracted:
B, L_v = S_v.shape
mask_rate = torch.empty((B, 1), device=X.device, dtype=X.dtype).uniform_(0.25, 0.85)
is_masked = (torch.rand((B, L_v), device=X.device, dtype=X.dtype) < mask_rate) & valid_v
obs_mask = valid_v & (~is_masked)
logits_cond = self.decoder.conditional_logits_given_context(
z, h0, J, f["h_E"], f["E_idx"], m_hollow, S_v, obs_mask, cav_probs.detach(),
rho=rho, flat_idx=f["flat_idx"],
)
lp_cond = F.log_softmax(logits_cond, dim=-1)
mf = is_masked.to(X.dtype)
if mf.sum() > 0:
nll_cond = (F.nll_loss(lp_cond.permute(0, 2, 1), S_v, reduction="none") * mf).sum() / mf.sum().clamp(min=1.0)
else:
nll_cond = nll_pll * 0.0
nll_pair = self.decoder.bethe_pair_loss(
logits_marg, mu, mu_i_to_j, J, f["E_idx"], m_hollow, has_rev, S_v,
k_pair=10, c_tri=f["c_tri"],
)
loss = 0.58 * nll_marg + 0.10 * nll_unary + 0.11 * nll_pll + 0.11 * nll_cond + 0.10 * nll_pair
if self.ENT_REG > 0.0:
ent_marg = -(lp_marg.exp() * lp_marg).sum(dim=-1)
loss = loss - self.ENT_REG * ((ent_marg * vf).sum() / denom)At test time, with no new parameters, the decoder runs two more sweeps than in training and then three coupled refinement sweeps in which each residue's belief is recomputed from its neighbours' cavity beliefs, the logits are scaled by a temperature , where is how far an exponential moving average of the training negative log-likelihood has fallen below (capped at ), and the output is tilted back toward the running amino-acid frequency prior in proportion to its entropy:
if self.ema_tr_nll is not None and not self.training:
gap = (1.95 - self.ema_tr_nll.to(X.dtype)).clamp(0.0, 0.65)
tau = 1.0 + 0.11 * gap
inv_temp = 1.0 / tau
conv_w = gap / 0.65
lp_v, _ = self.decoder.run_cavity_bp(
z, h0, J, f["h_E"], f["E_idx"], m_hollow, has_rev, rev_flat_idx,
rho=f["rho"], flat_idx=f["flat_idx"], c_tri=f["c_tri"],
inv_temp=inv_temp,
)
if conv_w is not None and self.ema_aa_prior is not None and self.ENT_REG > 0.0:
q_v = lp_v.exp()
h_norm = (-(q_v * lp_v).sum(dim=-1, keepdim=True) / math.log(NUM_AA)).clamp(0.0, 1.0)
log_pi = self.ema_aa_prior.to(X.dtype).clamp(min=1e-4).log()
log_pi_c = (log_pi - log_pi.mean()).view(1, 1, NUM_AA)
lp_v = F.log_softmax(lp_v + (self.ENT_REG * conv_w * h_norm) * log_pi_c, dim=-1)
uniform_lp = -math.log(NUM_AA)
return self.encoder.unpack_nodes(lp_v, f["valid_v"], f["order"], f["full_L"], fill_value=uniform_lp)Results
| Method | ① | ② | ③ | |||
|---|---|---|---|---|---|---|
| Sequence recovery ↑ | Perplexity ↓ | Sequence recovery ↑ | Perplexity ↓ | Sequence recovery ↑ | Perplexity ↓ | |
| Gemini 4 Carbon | 0.558 | 3.937 | 0.546 | 3.832 | 0.553 | 3.848 |
| 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 has the best values in the table on both measures: a sequence recovery of 0.558 against 0.544 for the strongest baseline, VFN-IF EMA+WD, and a perplexity of 3.937 against 4.058 (VFN-IF EMA+WD).
On CATH 4.3 the perplexity of 3.832 is below the best baseline's 3.882 (VFN-IF EMA+WD), but the sequence recovery of 0.546 is slightly below 0.547 (VFN-IF EMA+WD).
On TS50 the model is behind on both measures: a sequence recovery of 0.553 against 0.560 (VFN-IF [4]), and a perplexity of 3.848 against 3.839 (VFN-IF EMA+WD). The margin to the best baseline is small on that setting and the advantage the model has on CATH 4.2 does not carry to it.
The agent measured the decoder's stages on its own full-scale development holdout, which it built from public training and validation data with no test structures and with no fold in common with the training split. On the full-scale checkpoint (the version without the later prior tilt) it reported, in order, a unary read-out at 54.24% recovery and a perplexity of 4.068, the pairwise tree-reweighted messages at 57.29% and 3.848, the leave-one-out multi-body field at 58.17% and 3.648, the coupled refinement at 58.18% and 3.648, and the temperature calibration at 58.18% and 3.634. By its numbers the pairwise messages carry most of the recovery gain, the multi-body field adds a further point of recovery and lowers perplexity by about as much as the pairwise messages do, the refinement leaves recovery and perplexity almost unchanged, and the temperature calibration lowers perplexity. It also reported that a decoder with access to the native identities of the neighbours reached 61.88% and 3.246, which the agent used as the gap that the approximate inference leaves open.
How we got here
The sequence of changes below was run as controlled waves of one to three variants each on a small training subset, then confirmed at full scale, and the account is drawn from the agent's own reports in the trace.
- Stereochemistry first, then pairwise decoding. The first wave added exact backbone-derived features and a vector encoder (v2, v3a), and then a Potts decoder with belief propagation (v3b). The Potts decoder (v3b) became the base that the later waves refine. Wave 2 tried side-chain-surface-proportional label smoothing, a Cys-Pro steric rule and a calibrated Potts variant; none beat the earlier model on its validation and holdout recovery and perplexity (the coupled pair variant did raise cysteine recovery) and the earlier model was kept.
- A bug that the physics test found. While checking the hydrogen-bond feature against known
structure, the agent found that the sign convention of the first version made the
residue helix hydrogen bond almost invisible: 16 detected bonds against 4,365 with the
exact Kabsch-Sander formula on one sample of 15,455 residues. Fixing it changed the signal for
capping residues: serine, threonine, aspartate and asparagine made up 37.2% of the residues that
the corrected feature marked as capping, against 29.1% under the inverted one and a background of
22.5%. This is the
use_true_ks_stencilbranch of the code above. - More physics did not mean better. Several rich features hurt on the development measures: a rigid distal-tip electrostatic block with a Debye screening (the agent saw faster early epochs but a worse final result, attributing it to the amplification of coordinate noise), a block of deep steric and electrostatic terms, a whole-domain inertia ellipsoid, a smoothed electrostatic field, and an edge-depth fusion bypass. Each was removed after a controlled comparison. One apparent failure turned out to be a configuration mismatch (warm-up fraction, weight decay and dropout differed between candidates), which the agent found by diffing the two builds, and it reran with the proven recipe.
- Pairwise couplings need guard rails. The agent inspected trained couplings and calibration repeatedly, and the soft cap on , the zero-sum gauge, the entropy bonus and the training-statistics temperature rule above are the result of those inspections. Tempering the cavity by shared triangles was found by a zero-shot test on a trained model and then made a learned parameter. The agent noted that the pair likelihood was pushing that parameter from toward , and tried decoupling it; the decoupled variant finished slightly behind the coupled one on validation and holdout recovery and perplexity as the agent reported them, so the coupled form stayed in the final file.
- One cavity injection beats several. A variant that injected the leave-one-out field at three sweeps (together with a smoothed electrostatic field and a wider feed-forward layer) trained worse than its predecessor, and the agent read the lower learned message damping as a consequence of the repeated injection; the final decoder injects it once.
- Scale. Training on the full development training set for 18 epochs, with the final decoder, was the step that brought the development numbers above 52% recovery. A variant with an edge-depth fusion and a different global gate was run alongside and did not beat the simpler encoder on validation recovery.
- Inference without parameters. The coupled refinement and the temperature calibration were found by probing trained checkpoints, not by training: a probe over refinement depth put the optimum at three sweeps, and the prior tilt lowered perplexity on every one of twelve checkpoint-and-split pairs the agent tried.
The trace shows the agent reading the baseline files, among them VFN-IF [4] and ProteinMPNN, and a literature search that returned VFN-IF; it does not record any component as taken from them. What we hold to be new is the decoder: an explicit pairwise random field whose inference is a differentiated, damped, triangle-tempered cavity propagation with a leave-one-out multi-body field.
Limitations
- The advantage is not uniform. The model is first on both measures on CATH 4.2 and first on perplexity on CATH 4.3, but it is behind the strongest baseline on sequence recovery on CATH 4.3 and on both measures on TS50. We do not know why CATH 4.2 is favoured.
- Hand-built, many-part featuriser. Many constants are physical (bond lengths, the Kabsch-Sander coefficient, rotamer angles) and the rest were chosen by development waves on a small training subset; we ran controlled comparisons, not a search over all of them, and each comparison used one seed except a late version of the model (v13a), which the agent ran with three seeds (the means and standard deviations are in the trace, not reproduced here).
- Perplexity is calibrated by a heuristic. The temperature and the prior tilt depend on a running average of the training negative log-likelihood and on a frequency prior. They were checked on the agent's own development splits only; their behaviour on a different data distribution is not measured.
- Inference is approximate. Belief propagation on a -nearest-neighbour graph with loops is not exact, and the agent's own oracle comparison (native neighbours given) shows a gap of several points of recovery that the model does not close.
- Cost. The decoder holds a coupling per edge and runs several sweeps in both training and test. The agent kept it within a parameter limit that its own verification script checked, with a 14-layer encoder of width 176; it also ran a 15-layer variant and a wider feed-forward layer in Wave 10, which did not replace the 14-layer encoder.
- Development splits. All the development measurements above come from splits the agent drew from public training and validation data; they are not the scored settings and they were not the model-selection criterion for every choice.
References
- J. Dauparas, I. Anishchenko, N. Bennett et al. (2022). Robust deep learning–based protein sequence design using ProteinMPNN. Science.
- Zhangyang Gao, Cheng Tan, Pablo Chacón et al. (2023). PiFold: Toward effective and efficient protein inverse folding. ICLR.
- Bowen Jing, Stephan Eismann, Patricia Suriana et al. (2021). Learning from Protein Structure with Geometric Vector Perceptrons. 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.
- Yasha Ektefaie, Olivia Viessmann, Siddharth Narayanan et al. (2024). Reinforcement learning on structure-conditioned categorical diffusion for protein inverse folding.
- Peizhen Bai, Filip Miljković, Xianyuan Liu et al. (2024). Mask prior-guided denoising diffusion improves inverse protein 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.