Single-cell and perturbations · INTEGRATION
Gene-token deletion and rank promotion
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Delete or promote requested gene identities within a token sequence. Preserve protected tokens, the order of unaffected genes, and the fixed output capacity.
Function signature
gene_token_intervention(
tokens: torch.Tensor,
valid_mask: torch.Tensor,
protected_mask: torch.Tensor,
target_ids: torch.Tensor,
target_mask: torch.Tensor,
mode: str = 'delete',
pad_token_id: int = 0,
) -> dict[str, torch.Tensor]Worked example
Promotion keeps identity and provenance
With mode="promote" and pad_token_id=0, take tokens=[[101,11,22,33,102,0]], valid_mask=[[True,True,True,True,True,False]], and protected_mask=[[True,False,False,False,True,False]]. Request target_ids=[[33,44,101]] with all three target masks true. Keep protected 101, move 33, insert 44, retain 11 and 22, then keep protected 102: output tokens are [[101,33,44,11,22,102]]. Their source_positions are [[0,3,-1,1,2,4]]; only 33 and 44 are interventions. All six output slots are valid and lengths=[6]. target_found=[[True,False,True]] refers to the original sequence, including protected 101.
Parameters
| Parameter | Shape and meaning |
|---|---|
tokenstorch.Tensor | [B, L]int64 [B,L], fixed-size ranked gene sequences |
valid_masktorch.Tensor | [B, L]bool [B,L], true valid prefix |
protected_masktorch.Tensor | [B, L]Immutable boundary prefix/suffix tokens |
target_idstorch.Tensor | [B, K]int64 [B,K], ordered intervention targets |
target_masktorch.Tensor | [B, K]True for active target requests |
modestrDefault 'delete' | Choose "delete" to remove mutable target genes or "promote" to move/insert them at the front of the mutable region. Protected boundary tokens remain in place. |
pad_token_idintDefault 0 | Token ID used in padded output positions. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Inputs are
tokens[B,L]int64withB,L\ge 1, prefix-contiguousvalid_mask[B,L],protected_mask[B,L](true only at valid boundary specialtokens),target_ids[B,K]int64andtarget_mask[B,K]withK\ge 1. Valid token IDs are unique within a cell, nonnegative and notpad_token_id. - Active target IDs obey the same rule and are unique within a cell. Invalid token and inactive target payloads are ignored. Protected positions may form a prefix and/or suffix of the valid sequence, never a protected token between two mutable genes. If every valid token is protected, treat the entire protected block as a prefix.
- For
mode='delete'(default), remove every mutable gene whose ID is an active target. Missing targets have no effect. - For
mode='promote', emit all active, nonprotected target IDs at the front of the MUTABLE gene region, in supplied target order: move an existing gene there once or insert a missing gene. Follow these with the nontarget mutable genes in their original order. - In either mode, a target equal to a protected token is ignored for editing; that protected token remains untouched. Keep the protected prefix, the first
L-prefix_length-suffix_lengthedited mutable entries, and the protected suffix. Thus truncation can drop mutable tail genes but never a protected suffix. - Pad the remaining tail to
Lwithpad_token_idand false validity. - Return
tokens[B,L],valid_mask[B,L],lengths[B],source_positions[B,L](original position for each retained/moved token;-1for an inserted or padded entry),intervention_mask[B,L](true only on a retained promoted/inserted target), andtarget_found[B,K](true iff that ACTIVE target occurred anywhere in the original valid sequence, including a protected token). - All integer outputs are
int64and masks Boolean. - For delete the intervention mask is all false. Empty cells and deleting every gene are supported. No mutation of inputs. Config: mode is 'delete' or 'promote';
pad_token_iddefaults to0and must be a nonnegative integer. - Unsupported mode, duplicate/invalid valid IDs or active targets, non-prefix validity, protected padding or interior protected
tokensraiseValueError. V1 ordinarily supplies no boundary specials:protected_maskis all false. - Optional protected boundaries are an explicit safety extension, not V2 tokenization parity, and no special
tokensare automatically inserted.
Why this matters
A perturbation changes token order or membership, so the result must carry both the edited identities and their original-position provenance.
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 gene_token_intervention(
tokens: torch.Tensor, # (B, L)
valid_mask: torch.Tensor, # (B, L)
protected_mask: torch.Tensor, # (B, L)
target_ids: torch.Tensor, # (B, K)
target_mask: torch.Tensor, # (B, K)
mode: str = 'delete',
pad_token_id: int = 0,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
tokens: (B, L).
source_positions: (B, L).
intervention_mask: (B, L). Always returned; all False in delete mode.
valid_mask: (B, L).
lengths: (B,).
target_found: (B, K)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement gene_token_intervention")
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.