Geometry and structural losses
Within-Residue Distance Violation
AlphaFold2OpenFold
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Compare eligible atom-pair distances with supplied geometric bounds and return pair losses, their mean, and per-atom loss/violation summaries.
Function signature
within_residue_violation(
activations: dict,
masks: dict,
structure: dict,
count_eps: float = 1e-06,
distance_eps: float = 1e-10,
tighten: float = 0.0,
) -> dict[str, torch.Tensor]Worked example
Worked example
Only directed pairs (0, 1) and (1, 0) share a residue. Illustrative distance_eps=3 makes their stabilized distance 2; each lower-bound penalty is 1. The two eligible pairs and count_eps=1 give mean_loss=2/3. per_atom_loss is [2, 2, 0].
import torch
activations = {
'lower_bound': torch.full((1, 3, 3), 3.0, dtype=torch.float64, requires_grad=True),
'upper_bound': torch.full((1, 3, 3), 4.0, dtype=torch.float64, requires_grad=True),
}
masks = {
'atom_mask': torch.tensor([[True, True, True]], dtype=torch.bool),
}
structure = {
'positions': torch.tensor([[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [5.0, 0.0, 0.0]]], dtype=torch.float64, requires_grad=True),
'residue_index': torch.tensor([[0, 0, 1]], dtype=torch.int64),
'chain_id': torch.tensor([[0, 0, 0]], dtype=torch.int64),
}
count_eps = 1.0
distance_eps = 3.0
tighten = 0.0
result = within_residue_violation(activations=activations, masks=masks, structure=structure, count_eps=count_eps, distance_eps=distance_eps, tighten=tighten)Expected return
{
'pair_loss': torch.tensor([[[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], dtype=torch.float64),
'mean_loss': torch.tensor([0.6666666666666666], dtype=torch.float64),
'per_atom_loss': torch.tensor([[2.0, 2.0, 0.0]], dtype=torch.float64),
'atom_violation': torch.tensor([[True, True, False]], dtype=torch.bool),
}Parameters
| Parameter | Shape and meaning |
|---|---|
activationsdict | Supplied intermediate tensors. |
masksdict | Supplied masks. Each field below defines what True includes or permits. |
structuredict | Fields supplied together in this dictionary. |
count_epsfloatDefault 1e-06 | Positive value added to the number of eligible directed atom pairs in the mean_loss denominator. |
distance_epsfloatDefault 1e-10 | Positive value added to squared atom separation before sqrt. |
tightenfloatDefault 0.0 | Within-residue soft-loss tightening. Hard violations still use the original lower/upper distance bounds. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Atoms belong to the same residue only when BOTH residue_index and chain_id match. Exclude absent atoms and sanitize their coordinates before distance calculations.
- Include all directed same-residue pairs except the diagonal. Both(i,j) and (j,i) are present; do not halve the returned loss.
- Use stabilized distance
d=\sqrt{\|r_i-r_j\|^2+distance\_eps}, distance_eps default10^{-10}. - Soft loss is
\max(lower+tighten-d,0)+\max(d-upper+tighten,0), with tighten default 0. Hard flags compare d strictly to the ORIGINAL lower/upper bounds, without tighten. - Zero excluded pair losses. mean_loss divides their sum by the eligible pair count plus count_eps (default 1e-6). per_atom_loss adds row and column sums; atom_violation is any flagged pair incident to the atom.
- Tolerances are finite nonnegative numbers; distance_eps/count_eps must be positive. Even when no pair is eligible, return correctly shaped exact-zero losses and False flags.
- 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.
Why this matters
Within-residue bounds identify distorted local geometry. Every directed eligible pair contributes a soft distance penalty and an independent hard violation flag.
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 within_residue_violation(
activations: dict,
masks: dict,
structure: dict,
count_eps: float = 1e-06,
distance_eps: float = 1e-10,
tighten: float = 0.0,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
pair_loss: (B, A, A).
mean_loss: (B,).
per_atom_loss: (B, A).
atom_violation: (B, A)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement within_residue_violation")
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.