Geometry and structural losses

Peptide Geometry Violation

HardRaw PyTorchAbout 30 min1 public example plus private tests

AlphaFold2OpenFold

Write and run your solution Sign in

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

Your task

Measure how much each consecutive peptide connection’s C–N length and two adjacent angle cosines exceed the supplied tolerances around their target statistics. Each link_losses entry is one nonnegative soft penalty. Return these penalties, separate means for the three term types, and half of each link’s total at each endpoint residue.

Function signature

peptide_geometry_violation(
    activations: dict,
    masks: dict,
    structure: dict,
    geometry_eps: float = 1e-06,
    error_eps: float = 1e-06,
    count_eps: float = 1e-06,
    soft_tolerance: float = 12.0,
    hard_tolerance: float = 12.0,
) -> dict[str, torch.Tensor]

Worked example

From a bond metric to a residue penalty

Consider the penalty stage for one valid peptide link. Its stabilized C–N distance is 2, and the next residue’s proline status selects mean 1.7 and standard deviation 0.1. With illustrative error_eps=0.07, the error is \sqrt{(2-1.7)^2+0.07}=0.4. Soft tolerance 2 gives penalty max(0.4−2*0.1,0)=0.2; hard tolerance 3 flags the link because 0.4>0.3. If both CA atoms are absent, the two angle terms are invalid and zero. With count_eps=1, mean_losses is [0.1,0,0], and each endpoint residue receives 0.1 and a True violation flag.

Parameters

ParameterShape and meaning
activationsdictSupplied intermediate tensors.
masksdictSupplied masks. Each field below defines what True includes or permits.
structuredictFields supplied together in this dictionary.
geometry_epsfloatDefault 1e-06Positive value inside sqrt(squared vector length + geometry_eps) for C–N distances and vectors used in angle cosines.
error_epsfloatDefault 1e-06Positive value inside sqrt((measured metric − target mean)² + error_eps), before soft/hard tolerance comparisons.
count_epsfloatDefault 1e-06Positive value added to each term’s own valid-link count when computing mean_losses.
soft_tolerancefloatDefault 12.0Standard-deviation multiplier for the soft peptide penalty.
hard_tolerancefloatDefault 12.0Standard-deviation multiplier for the hard peptide flag.

Return

dict[str, torch.Tensor]

Return exactly the named fields applicable to this operation.

Required behavior

  • backbone_atoms maps each residue to flattened N/CA/C atom indices. A connection joins consecutive entries only when residue_index increases by exactly1 and chain_id is unchanged. Each term also requires its own participating atom masks.
  • The three terms are C–N length, cosine(CA−C, N−C), and cosine (C−N, CA−N). Vector lengths use \sqrt{\|v\|^2+geometry\_eps}, with geometry_eps default 10^{-6}. Use the NEXT residue’s is_proline to choose the C–N target mean/std.
  • For each valid term compute e=\sqrt{(metric-mean)^2+error\_eps}, soft loss \max(e-soft\_tolerance\cdot std,0), and hard flag e>hard\_tolerance\cdot std. error_eps defaults to 10^{-6}; both tolerances default to 12.
  • link_losses has the three terms per connection. mean_losses averages EACH term by its own valid count plus count_eps (default 1e-6), separately per batch. Split the summed connection loss equally between its endpoints; a hard flag marks both residues.
  • Missing connections/atoms contribute exact zero. Tolerances are finite nonnegative numbers; all epsilons are finite positive numbers.
  • 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.
  • B, A and R are positive. All backbone indices are in [0,A). R=1 returns a zero-length link axis and zero residue losses/flags; empty atom or residue axes are outside the contract.

Why this matters

A peptide connection constrains one C–N bond length and the two adjacent angle cosines. Penalizing each connection and splitting its loss between endpoints makes residue-level diagnostics interpretable.

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 peptide_geometry_violation(
    activations: dict,
    masks: dict,
    structure: dict,
    geometry_eps: float = 1e-06,
    error_eps: float = 1e-06,
    count_eps: float = 1e-06,
    soft_tolerance: float = 12.0,
    hard_tolerance: float = 12.0,
) -> dict[str, torch.Tensor]:
    """Return dict[str, torch.Tensor]:
    
    link_losses: (B, R-1, 3).
    mean_losses: (B, 3).
    residue_loss: (B, R).
    residue_violation: (B, R)."""
    # Implement the operation. Inputs and test setup are supplied by BioTorch.
    raise NotImplementedError("Implement peptide_geometry_violation")

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.