Protein sequence and inverse folding
ESM-2 token-dropout scaling
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Look up token embeddings, remove mask-token content, and rescale each sequence by its observed mask fraction. Return the scaled embeddings and per-sequence diagnostics, with explicit rules for all-padding and all-mask rows.
Function signature
esm2_token_dropout(
tokens: torch.Tensor,
table: torch.Tensor,
token_dropout: bool = True,
padding_id: int = 0,
mask_id: int = 1,
) -> dict[str, torch.Tensor]Worked example
Different mask fractions, different sequence scales
Each sequence contains three nonpadding tokens. The first has one mask, so its scale is 0.88/(1−1/3)=1.32. The second has two masks, so its scale is 0.88/(1−2/3)=2.64. Mask and padding embeddings are zero; surviving table rows use their own sequence’s scale.
import torch
tokens = torch.tensor([[2, 1, 0, 3], [1, 1, 2, 0]], dtype=torch.int64)
table = torch.tensor([[50.0, 60.0], [70.0, 80.0], [1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0], [9.0, 10.0]], dtype=torch.float64, requires_grad=True)
token_dropout = True
padding_id = 0
mask_id = 1
result = esm2_token_dropout(tokens=tokens, table=table, token_dropout=token_dropout, padding_id=padding_id, mask_id=mask_id)Expected return
{
'output': torch.tensor([[[1.3199999999999998, 2.6399999999999997], [0.0, 0.0], [0.0, 0.0], [3.9599999999999995, 5.279999999999999]], [[0.0, 0.0], [0.0, 0.0], [2.6399999999999997, 5.279999999999999], [0.0, 0.0]]], dtype=torch.float64),
'mask_fraction': torch.tensor([0.3333333333333333, 0.6666666666666666], dtype=torch.float64),
'scale': torch.tensor([1.3199999999999998, 2.6399999999999997], dtype=torch.float64),
'padding_mask': torch.tensor([[False, False, True, False], [False, False, False, True]], dtype=torch.bool),
}Parameters
| Parameter | Shape and meaning |
|---|---|
tokenstorch.Tensor | [B, L]Integer vocabulary IDs [B,L], including supplied padding, mask and other special tokens. |
tabletorch.Tensor | [V, C]Finite learned embedding table [V,C]; repeated token IDs select the same trainable row. |
token_dropoutboolDefault True | True applies per-sequence 0.88/(1-mask_fraction) scaling and zeros mask-token content. False keeps mask-token embeddings and uses scale one; padding is zero in both modes. |
padding_idintDefault 0 | In-range integer vocabulary ID for padding; it must differ from mask_id. Padding positions return zero and are excluded from the mask-fraction denominator. |
mask_idintDefault 1 | In-range integer mask-token ID, default 1; must differ from padding_id. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Apply ESM-2 token dropout to a supplied embedding table. Inputs are
tokens[B,L], anint64tensor, and finitetable[V,C], with common CPU placement andfloat32orfloat64table dtype. RequireB,L,C\ge1andV\ge2. Every token ID must lie in[0,V-1]. Do not mutate either input; noncontiguous layouts are valid. - Config
padding_iddefaults to0,mask_idto1, andtoken_dropouttoTrue. The IDs are distinct in-range integers, not Booleans;token_dropoutmust be Boolean. These configurable IDs do not assert ESM-2's alphabet numbering. - Return Boolean
padding_mask[B,L], true exactly at padding, plusmask_fractionandscale[B]andoutput[B,L,C], all in the table's floating dtype. Letn_bcount nonpadding tokens andm_bcount mask tokens. Every nonpadding special token, including any supplied beginning/end token, contributes ton_b. - Define
r_b=m_b/n_bforn_b>0, andr_b=0for an all-pad row. Returnrasmask_fraction, even when token dropout is disabled. With token dropout enabled, uses_b=\begin{cases}(1-0.12)/(1-r_b),&n_b>m_b,\\0,&n_b=m_b.\end{cases}Returnscales. - For a token that is neither padding nor mask, set
y_{b\ell c}=s_b E_{t_{b\ell},c}; all padding/mask positions are exact zeros. A row with no masks still usess_b=0.88, not one. All-pad and all-mask rows have zero scale and connected-zero output: avoid evaluating a zero denominator and then hiding NaNs. - These two finite boundary definitions extend the upstream formula, which is singular there. With
token_dropout=False, every row has scale one, mask-token embeddings are retained, and padding is still zero. - No random corruption, ordinary elementwise dropout, embedding-width scaling, alphabet conversion, BOS/EOS insertion or Transformer layer is performed. Incompatible ranks/dtypes, out-of-range tokens and invalid ID/flag configuration raise
ValueError; nonfinite table values and overflowed arithmetic are outside the contract.
Why this matters
The model was trained with a mask-token rate of 0.15\times0.8=0.12. A sequence with more masks needs a larger scale on its surviving embeddings. Padding contributes no sequence content and must not dilute the observed rate.
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 esm2_token_dropout(
tokens: torch.Tensor, # (B, L)
table: torch.Tensor, # (V, C)
token_dropout: bool = True,
padding_id: int = 0,
mask_id: int = 1,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
output: (B, L, C).
mask_fraction: (B,).
scale: (B,).
padding_mask: (B, L)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement esm2_token_dropout")
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.
Sources and further reading
A primitive exercise, not an end-to-end reproduction of the named models. No affiliation or endorsement is implied.