generative_modeling¶
This module contains the GenerativeModel class hierarchy, LogitFormatter protocol, MPNNTokenizer, and LoRA support. These are the building blocks for wrapping any generative model (masked LMs, flow-matching models, ProteinMPNN) into ProteinGen's interface.
GenerativeModel¶
A concrete ProbabilityModel subclass that wraps any nn.Module via composition:
forward(seq_SP, **kwargs)delegates toself.model(seq_SP, **kwargs)format_raw_to_logitsappliesself.logit_formatter(raw, seq_SP)get_log_probs_from_string(sequences)tokenizes input strings, then callsget_log_probs
Conditioning¶
GenerativeModel inherits two conditioning patterns from ProbabilityModel:
- Inference —
set_condition_()/conditioned_on()caches a single observation and tiles it to the batch viacollate_observations - Training — a collator prepares per-sample observations and the training loop passes them directly to
model.forward(input_ids, **observations)
See probability_model → Conditioning for the full explanation of both patterns, and data for the collator API.
Overriding for non-tensor outputs¶
When the wrapped model returns a dataclass (not a raw tensor), override format_raw_to_logits:
def format_raw_to_logits(self, raw_output, seq_SP, **kwargs):
logits = raw_output.sequence_logits.float()
return self.logit_formatter(logits, seq_SP)
GenerativeModelWithEmbedding¶
An ABC extending GenerativeModel for models that expose a differentiable embedding path. This is needed for two features:
- TAG gradients — backpropagation from predictive model through generative model embeddings
- LinearProbe — extracting and caching deep embeddings for probe training
Abstract methods¶
| Method | Signature | Purpose |
|---|---|---|
differentiable_embedding |
(ohe_seq_SPT: FloatTensor) → FloatTensor |
OHE → deep embeddings (through embedding layer + transformer body) |
embedding_to_outputs |
(embedding_SPD: FloatTensor) → Any |
Deep embeddings → raw model output (same type as forward) |
Subclass requirements¶
- Set
EMB_DIM: int— embedding dimensionality (e.g. 960 for ESMC, 1536 for ESM3) - The output of
embed()must be shape(S, P, EMB_DIM)
How OHE flows through¶
embed() creates a one-hot encoding at tokenizer.vocab_size (e.g. 33 for ESM). If the model's actual embedding table is wider (e.g. 64 for ESM's alignment padding), differentiable_embedding handles the mismatch internally via ohe @ embed.weight. Gradients flow back through the matmul to the vocab-sized OHE — TAG only sees vocab-sized gradients.
LogitFormatter¶
A @runtime_checkable Protocol defining __call__(logits, input_ids) → FloatTensor.
MaskedModelLogitFormatter¶
The standard formatter for masked language models. Key design decisions:
- Direct indexing (
mask_matrix[token_ids]) instead of one-hot matmul — because0.0 × (-inf) = NaN(IEEE float) - Additive masking (
0.0pass-through,-infblock) instead of multiplicative — multiplying logits by-infgives wrong signs for negative logits - Uses
register_bufferfor the mask matrix (automatic device tracking, no gradients)
output_dim vs vocab_size
output_dim can exceed vocab_size for alignment. For example, ESM models output 64 logits but only 33 are real vocabulary tokens. The extra columns are valid mask output positions.
PassThroughLogitFormatter¶
Returns logits.float() unchanged. For models that don't need output masking.
MPNNTokenizer¶
Wraps ProteinMPNN's amino acid vocabulary with an HF-compatible interface.
- Default: 20 standard AAs + UNK(X), indexed 0–20
include_mask_token=Trueappends<mask>at idx 21 (needed when TAG guidance requires an explicit predictor-side mask token).vocabreturnsdict[str, int]— same interface as HF tokenizers, used bypca_embed_initfor cross-tokenizer vocabulary mapping- No
cls_token_id,eos_token_id, orpad_token_id(allNone)
LoRA support¶
LoRA adapter support lives on GenerativeModel:
model.apply_lora(target_modules=None, r=8, lora_alpha=16)
model.save_lora("adapters/my_adapter")
model.load_lora("adapters/my_adapter")
target_modules=Noneauto-discovers allnn.Linearmodules vialora_target_modules()- After
apply_lora,self.modelbecomes aPeftModel— attribute access delegates through PEFT has_loraproperty checksisinstance(self.model, PeftModel)- Checkpointing is automatic:
save()writeslora_adapter/if present,from_checkpoint()loads it
LoRA learning rate
LoRA-adapted large models (e.g. ESM3 1.4B) can collapse to constant predictions with lr=1e-3. Use lr=1e-4 or lower. Consider separate optimizer param groups for LoRA parameters vs. the prediction head.
Lazy module loading
If a model loads submodules lazily (e.g. ESM3's VQ-VAE encoder loaded on first set_condition_() call), those parameters won't be frozen by apply_lora(). After triggering lazy load, re-freeze all base params then re-enable lora_ params.
API Reference¶
proteingen.modeling.generative_modeling
¶
Generative model utilities.
Currently provides the MPNNTokenizer for converting amino acid sequences to ProteinMPNN token indices.
GenerativeModel
¶
Bases: ProbabilityModel
Wraps a model + logit formatter into a ready-to-use probability model.
Pass in any nn.Module whose forward returns logits, a tokenizer, and a
LogitFormatter (e.g. MaskedModelLogitFormatter for masked diffusion,
PassThroughLogitFormatter for uniform noise). GenerativeModel handles
the rest: forward runs the wrapped model, applies logit formatting, and
get_log_probs (inherited from ProbabilityModel) adds temperature-scaled
log_softmax.
For structure-conditioned models, subclass and override
preprocess_observations and collate_observations, then use
set_condition_() / conditioned_on() to cache structure tensors.
Example::
esmc = ESMC.from_pretrained("esmc_300m")
tokenizer = EsmSequenceTokenizer()
formatter = MaskedModelLogitFormatter(tokenizer)
model = GenerativeModel(esmc, tokenizer, formatter)
# unconditional
log_probs = model.get_log_probs(seq_SP)
# with temperature
with model.with_temp(0.5):
log_probs = model.get_log_probs(seq_SP)
Source code in src/proteingen/modeling/generative_modeling.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
format_raw_to_logits
¶
format_raw_to_logits(raw_forward_output: FloatTensor, seq_SP: LongTensor, **kwargs) -> torch.FloatTensor
Default: model produces outputs, they might just not be masked properly. Most common function to override.
Source code in src/proteingen/modeling/generative_modeling.py
lora_target_modules
¶
Discover Linear modules in the wrapped model — potential LoRA targets.
Returns dict mapping name patterns to (in_features, out_features, count).
Block-level numeric indices are collapsed to * for readability.
Example for ESMC-300m::
{
'transformer.blocks.*.attn.layernorm_qkv.1': (960, 2880, 30),
'transformer.blocks.*.attn.out_proj': (960, 960, 30),
'transformer.blocks.*.ffn.1': (960, 5120, 30),
'transformer.blocks.*.ffn.3': (2560, 960, 30),
'sequence_head.0': (960, 960, 1),
'sequence_head.2': (960, 64, 1),
}
Source code in src/proteingen/modeling/generative_modeling.py
apply_lora
¶
apply_lora(target_modules: list[str] | None = None, r: int = 8, lora_alpha: int = 16, lora_dropout: float = 0.0, bias: str = 'none', **kwargs) -> None
Apply PEFT LoRA adapters to the wrapped model.
Freezes base model parameters and injects trainable low-rank adapters
into the targeted Linear layers. After this call, only LoRA parameters
in self.model have requires_grad=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_modules
|
list[str] | None
|
Which Linear layers to adapt (matched by name
substring). If |
None
|
r
|
int
|
LoRA rank (number of low-rank dimensions). |
8
|
lora_alpha
|
int
|
LoRA scaling factor. |
16
|
lora_dropout
|
float
|
Dropout probability on LoRA layers. |
0.0
|
bias
|
str
|
Bias training mode — |
'none'
|
**kwargs
|
Extra arguments passed to |
{}
|
Source code in src/proteingen/modeling/generative_modeling.py
save_lora
¶
Save only the LoRA adapter weights and config.
load_lora
¶
Load a saved LoRA adapter onto the base model.
Source code in src/proteingen/modeling/generative_modeling.py
save
¶
Save model to a directory. Includes LoRA adapter if applied.
from_checkpoint
classmethod
¶
Load model from a directory. Loads LoRA adapter if present.
Source code in src/proteingen/modeling/generative_modeling.py
GenerativeModelWithEmbedding
¶
Bases: GenerativeModel, ABC
GenerativeModel that exposes a differentiable embedding step.
Subclasses implement two methods that split the model's forward pass:
differentiable_embedding(ohe_seq_SPT)— OHE float input → deep embeddings (after transformer / encoder body).embedding_to_outputs(embedding_SPD)— deep embeddings → raw outputs
This class provides concrete forward and format_raw_to_logits
that compose these two steps, create a differentiable OHE from token IDs
(so gradients flow through the embedding step for TAG), and apply the
logit formatter.
Subclasses must set EMB_DIM (int) for downstream use (e.g. LinearProbe).
Source code in src/proteingen/modeling/generative_modeling.py
differentiable_embedding
abstractmethod
¶
OHE (or soft distribution) over tokens → deep embeddings (S, P, D).
Typically: ohe @ embed.weight → transformer body.
Source code in src/proteingen/modeling/generative_modeling.py
embedding_to_outputs
abstractmethod
¶
Deep embeddings → regular raw model outputs. IMPORTANT, the output of this function should be of the same type as the forward function!
Source code in src/proteingen/modeling/generative_modeling.py
embed
¶
Token IDs → deep embeddings (S, P, D).
Source code in src/proteingen/modeling/generative_modeling.py
LogitFormatter
¶
Bases: Protocol
Constrains model output logits based on input token identities.
Applied before log_softmax to enforce valid output distributions per input token (e.g. special tokens predict themselves, mask tokens predict only non-special tokens).
Implementations intended for use as model submodules should inherit
from nn.Module and use register_buffer for device tracking. When
inheriting from both nn.Module and LogitFormatter, nn.Module must
come first in the MRO (e.g. class Foo(nn.Module, LogitFormatter))
so that nn.Module.call (which dispatches to forward) is resolved
before Protocol.call.
Must return a FloatTensor so that the softmax doesn't have normalization issues due to a lack of precision.
Design note — possible implementation approaches:
- Reference implementation (MaskedModelLogitFomatter) uses a precomputed
dense additive mask matrix indexed by input token ids. The translation matrix
is built once at init and reused every forward pass, fully vectorized with
no branching. Alternative approaches include:
- In-place scatter: no precomputed matrix; loop over positions at forward
time and write -inf into invalid outputs. Simple but slow.
- Boolean mask + masked_fill: store a boolean matrix (1 bit vs 32 bits
per entry), index it the same way, then logits.masked_fill(~mask, -inf).
Saves memory at the cost of an extra op.
- Sparse allowlist: store a dict mapping each token id to a LongTensor
of valid output indices. More natural for huge vocabularies where the
valid set per token is tiny.
- Categorical branching: classify each input token as mask/special/regular
and apply a different rule per type. No matrix, but introduces branching.
- Post-softmax renormalization: run softmax normally, zero out invalid
probs, renormalize. Changes the gradient landscape vs. additive masking.
- Loss-side only: don't constrain logits at all; mask the loss instead
and trust the model learns the constraints. No guarantees at inference.
Source code in src/proteingen/modeling/generative_modeling.py
MaskedModelLogitFormatter
¶
Bases: Module, LogitFormatter
Enforces output constraints for masked language models via additive masking.
Builds a static mask matrix of shape (Ti, To) that defines which output tokens are valid for each input token. In forward, input token ids directly index into this matrix to select the per-position mask, which is then added to the raw logits before log_softmax.
Constraints
- Special tokens (CLS, EOS, PAD, etc.) can only predict themselves.
- The mask token can predict any non-special token (but not itself).
- All other tokens (standard vocabulary) predict only themselves.
The mask matrix contains 0.0 for valid outputs and -inf for invalid outputs, so adding it to logits zeros out invalid positions after softmax.
output_dim may exceed vocab_size when model designers pad the output space for memory alignment (e.g. ESM's 33-token vocab mapped to 64-dim output). Extra columns beyond vocab_size are valid mask outputs (not special tokens).
Tensor index conventions
Ti: input token index — rows of the mask matrix, size = vocab_size To: output token index — columns of the mask matrix, size = output_dim S: batch (sequence) index P: position index within a sequence T: token/vocab dimension in logits (same axis as To)
Source code in src/proteingen/modeling/generative_modeling.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
forward
¶
Apply per-position output constraints to raw logits.
Indexes the mask matrix by input token ids to select the constraint row for each position, then adds it to the logits. Positions with special tokens will have -inf at all output indices except their own; mask positions will have 0.0 at all non-special outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits_SPT
|
Tensor
|
Raw model logits, shape (S, P, T). |
required |
seq_SP
|
LongTensor
|
Input token ids, shape (S, P). |
required |
Returns:
| Type | Description |
|---|---|
|
Constrained logits as float32, shape (S, P, To). |
Source code in src/proteingen/modeling/generative_modeling.py
MPNNTokenizer
¶
Tokenizer using ProteinMPNN's amino acid vocabulary.
Maps single-letter amino acid sequences to/from PMPNN token indices.
Default vocabulary: 20 standard amino acids + UNK (X), indexed 0-20.
Optionally appends a <mask> token as an extra ID for guidance setups
that need explicit mask semantics at the tokenizer level.
Follows HuggingFace tokenizer conventions
- encode(sequence) -> list[int]
- decode(token_ids) -> str
- call(sequences) -> dict with 'input_ids' tensor
- vocab_size property
Source code in src/proteingen/modeling/generative_modeling.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | |
vocab
property
¶
Token-to-index mapping, compatible with HF tokenizer interface.
encode
¶
Convert a single-letter AA sequence to token indices.
decode
¶
Convert token indices back to a single-letter AA sequence.
Source code in src/proteingen/modeling/generative_modeling.py
__call__
¶
Tokenize one or more sequences, returning a dict with 'input_ids' tensor.