delete
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888#!/usr/bin/env python3"""All-in-one standalone predictor for StructEstimator (zero local package imports required).
Requires only `torch` and `transformers` (plus the bundled `StructEstimator_esm2_650m.pth` file —no `struct_estimator` package installation and no internet access required).
Examples: # Predict a FASTA file -> CSV python3 predict_standalone.py \ --model StructEstimator_esm2_650m.pth \ --input examples/sample.fasta \ --output predictions.csv
# Predict a FASTA file -> both CSV and JSON inside a folder python3 predict_standalone.py \ --model StructEstimator_esm2_650m.pth \ --input examples/sample.fasta \ --output predictions/
# Predict a raw amino acid sequence directly -> JSON python3 predict_standalone.py \ --model StructEstimator_esm2_650m.pth \ --input MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG \ --output ubiquitin.json"""
from __future__ import annotations
import argparseimport csvimport jsonimport mathimport osfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import EsmConfig, EsmModel
# =============================================================================# 1. Constants & Sequence Utilities# =============================================================================
AA_ALPHABET = "ACDEFGHIKLMNPQRSTVWY"AA_TO_INDEX: Dict[str, int] = {aa: idx for idx, aa in enumerate(AA_ALPHABET)}UNK_AA_INDEX = len(AA_ALPHABET) # 20NUM_AA_TOKENS = len(AA_ALPHABET) + 1 # 21VALID_ESM_AAS = set(AA_ALPHABET + "XUBZO")
Q8_LABELS: Tuple[str, ...] = ("G", "H", "I", "B", "E", "S", "T", "C")Q3_LABELS: Tuple[str, ...] = ("H", "E", "C")
# Tien et al. (2013) maximum ASA (Å^2) per residue (standard NetSurfP ASA = RSA * ASA_max)MAX_ASA_TIEN: Dict[str, float] = { "A": 129.0, "R": 274.0, "N": 195.0, "D": 193.0, "C": 167.0, "E": 223.0, "Q": 225.0, "G": 104.0, "H": 224.0, "I": 197.0, "L": 201.0, "K": 236.0, "M": 224.0, "F": 240.0, "P": 159.0, "S": 155.0, "T": 172.0, "W": 285.0, "Y": 263.0, "V": 174.0, "X": 195.0,}
CSV_COLUMNS = [ "id", "seq", "n", "rsa", "asa", "q3", "p_q3_H", "p_q3_E", "p_q3_C", "q8", "p_q8_G", "p_q8_H", "p_q8_I", "p_q8_B", "p_q8_E", "p_q8_S", "p_q8_T", "p_q8_C", "phi", "psi", "disorder", "plddt",]
def get_default_device() -> torch.device: if torch.cuda.is_available(): return torch.device("cuda") if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return torch.device("mps") return torch.device("cpu")
def sanitize_protein_sequence(seq: str) -> str: """Clean raw sequence so every character maps 1-to-1 to a single ESM-2 residue token.""" cleaned = "".join(seq.split()).upper().rstrip("*") return "".join(ch if ch in VALID_ESM_AAS else "X" for ch in cleaned)
def encode_aa_indices(seq: str) -> List[int]: return [AA_TO_INDEX.get(ch, UNK_AA_INDEX) for ch in seq]
def load_input_sequences(input_arg: str) -> List[Tuple[str, str]]: """Load sequences from a FASTA file, plain-text sequence file, or a raw sequence string.""" path = Path(input_arg) if path.is_file(): records: List[Tuple[str, str]] = [] cur_id: Optional[str] = None cur_chunks: List[str] = [] with open(path, "r", encoding="utf-8") as fh: for raw_line in fh: line = raw_line.strip() if not line: continue if line.startswith(">"): if cur_id is not None: seq = sanitize_protein_sequence("".join(cur_chunks)) if seq: records.append((cur_id, seq)) cur_id = line[1:].split()[0] or f"seq_{len(records) + 1}" cur_chunks = [] else: if cur_id is None: cur_id = path.stem or "query_1" cur_chunks.append(line) if cur_id is not None: seq = sanitize_protein_sequence("".join(cur_chunks)) if seq: records.append((cur_id, seq)) if not records: raise ValueError(f"No valid protein sequences found in file '{path}'.") return records
# Otherwise treat `--input` as a direct amino acid sequence string if os.sep in input_arg or input_arg.endswith((".fa", ".faa", ".fasta", ".txt")): raise FileNotFoundError(f"Input file not found: '{input_arg}'") clean = sanitize_protein_sequence(input_arg) if not clean: raise ValueError(f"Could not parse input '{input_arg}' as a FASTA file or amino acid sequence.") return [("query_1", clean)]
# =============================================================================# 2. Offline Bundled Multi-Layer Frozen ESM-2 Embedder# =============================================================================
class _BundledESMTokenizer: """Zero-network offline tokenizer matching Hugging Face `EsmTokenizer` bit-for-bit."""
def __init__(self, vocab: Dict[str, int]) -> None: self.vocab = dict(vocab) self.cls_id = int(self.vocab["<cls>"]) self.pad_id = int(self.vocab["<pad>"]) self.eos_id = int(self.vocab["<eos>"]) self.unk_id = int(self.vocab["<unk>"])
def __call__( self, sequences: Union[str, List[str]], return_tensors: str = "pt", padding: bool = False, add_special_tokens: bool = True, ) -> Dict[str, torch.Tensor]: seq_list = [sequences] if isinstance(sequences, str) else list(sequences) encoded_rows: List[List[int]] = [] for seq in seq_list: tok_ids = [self.vocab.get(ch, self.unk_id) for ch in seq] if add_special_tokens: tok_ids = [self.cls_id, *tok_ids, self.eos_id] encoded_rows.append(tok_ids)
max_len = max((len(r) for r in encoded_rows), default=0) if padding else len(encoded_rows[0]) bsz = len(encoded_rows) input_ids = torch.full((bsz, max_len), self.pad_id, dtype=torch.long) attention_mask = torch.zeros((bsz, max_len), dtype=torch.long) for i, row in enumerate(encoded_rows): n = len(row) input_ids[i, :n] = torch.tensor(row, dtype=torch.long) attention_mask[i, :n] = 1 return {"input_ids": input_ids, "attention_mask": attention_mask}
class StandaloneESM2Embedder: """Extracts stacked `(L, K, D)` hidden states strictly offline from bundled `StructEstimator_esm2_650m.pth`."""
def __init__( self, esm_model: EsmModel, tokenizer: Any, layers: Sequence[int], device: torch.device, half_precision: bool = True, max_chunk_len: int = 1022, chunk_overlap: int = 128, ) -> None: self.device = device self.layers = [int(x) for x in layers] self.num_model_layers = int(esm_model.config.num_hidden_layers) self.embed_dim = int(esm_model.config.hidden_size) self.max_chunk_len = int(max_chunk_len) self.chunk_overlap = int(chunk_overlap) self.dtype = torch.float16 if (half_precision and device.type in ("cuda", "mps")) else torch.float32 self.tokenizer = tokenizer self.model = esm_model.to(device=self.device, dtype=self.dtype) self.model.eval()
@classmethod def from_checkpoint( cls, ckpt: Dict[str, Any], device: torch.device, layers: Sequence[int], half_precision: bool = True, max_chunk_len: int = 1022, chunk_overlap: int = 128, ) -> "StandaloneESM2Embedder": required = ("esm_state_dict", "esm_config", "esm_vocab") missing = [k for k in required if k not in ckpt] if missing: raise ValueError( f"Expected a self-contained bundled `StructEstimator_esm2_650m.pth` checkpoint, " f"but missing bundled ESM-2 field(s): {missing}." ) config = EsmConfig.from_dict(ckpt["esm_config"]) esm_model = EsmModel(config, add_pooling_layer=False) esm_model.load_state_dict(ckpt["esm_state_dict"], strict=True) tokenizer = _BundledESMTokenizer(ckpt["esm_vocab"]) del ckpt["esm_state_dict"]
return cls( esm_model=esm_model, tokenizer=tokenizer, layers=layers, device=device, half_precision=half_precision, max_chunk_len=max_chunk_len, chunk_overlap=chunk_overlap, )
@torch.no_grad() def _forward_single(self, seq: str) -> torch.Tensor: encoded = self.tokenizer(seq, return_tensors="pt", add_special_tokens=True) encoded = {k: v.to(self.device) for k, v in encoded.items()} need_hidden = any(layer_idx != self.num_model_layers for layer_idx in self.layers) outputs = self.model(**encoded, output_hidden_states=need_hidden)
selected: List[torch.Tensor] = [] for layer_idx in self.layers: if layer_idx == self.num_model_layers: selected.append(outputs.last_hidden_state) else: selected.append(outputs.hidden_states[layer_idx]) stacked = torch.stack(selected, dim=2) # (1, L+2, K, D) return stacked[0, 1 : len(seq) + 1, :, :].to(dtype=torch.float32).cpu()
@torch.no_grad() def embed_sequence(self, clean_seq: str) -> torch.Tensor: seq_len = len(clean_seq) if seq_len == 0: return torch.empty((0, len(self.layers), self.embed_dim), dtype=torch.float32) if seq_len <= self.max_chunk_len: return self._forward_single(clean_seq)
stride = self.max_chunk_len - self.chunk_overlap accum = torch.zeros((seq_len, len(self.layers), self.embed_dim), dtype=torch.float32) counts = torch.zeros((seq_len, 1, 1), dtype=torch.float32) start = 0 while start < seq_len: end = min(start + self.max_chunk_len, seq_len) accum[start:end] += self._forward_single(clean_seq[start:end]) counts[start:end] += 1.0 if end == seq_len: break start += stride return accum / counts.clamp_min(1.0)
# =============================================================================# 3. StructEstimator Architecture (Exact `state_dict` Match)# =============================================================================
class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6) -> None: super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor: x_fp32 = x.float() inv_rms = torch.rsqrt(x_fp32.pow(2).mean(dim=-1, keepdim=True) + self.eps) return (x_fp32 * inv_rms * self.weight.float()).to(dtype=x.dtype)
class DropPath(nn.Module): def __init__(self, drop_prob: float = 0.0) -> None: super().__init__() self.drop_prob = float(drop_prob)
def forward(self, x: torch.Tensor) -> torch.Tensor: return x
class MultiLayerScalarMix(nn.Module): def __init__(self, num_layers: int, embed_dim: int) -> None: super().__init__() self.num_layers = num_layers self.embed_dim = embed_dim self.layer_norms = nn.ModuleList([RMSNorm(embed_dim) for _ in range(num_layers)]) self.layer_logits = nn.Parameter(torch.zeros(num_layers)) self.gamma = nn.Parameter(torch.ones(1))
def forward(self, x: torch.Tensor) -> torch.Tensor: if self.num_layers == 1: return (self.gamma.float() * self.layer_norms[0](x[:, :, 0, :]).float()).to(dtype=x.dtype) weights = F.softmax(self.layer_logits.float(), dim=0) mixed = weights[0] * self.layer_norms[0](x[:, :, 0, :]).float() for idx in range(1, self.num_layers): mixed = mixed + weights[idx] * self.layer_norms[idx](x[:, :, idx, :]).float() return (self.gamma.float() * mixed).to(dtype=x.dtype)
class SwiGLUFFN(nn.Module): def __init__(self, d_model: int, hidden_dim: int, dropout: float = 0.15) -> None: super().__init__() self.w_gate_up = nn.Linear(d_model, hidden_dim * 2, bias=False) self.w_down = nn.Linear(hidden_dim, d_model, bias=False) self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor: gate, up = self.w_gate_up(x).chunk(2, dim=-1) return self.dropout(self.w_down(F.silu(gate) * up))
class RotaryEmbedding(nn.Module): def __init__(self, head_dim: int, base: float = 10000.0) -> None: super().__init__() self.head_dim = head_dim inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) self._cached_len = 0 self._cached_cos: Optional[torch.Tensor] = None self._cached_sin: Optional[torch.Tensor] = None
def _build_cache(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]: if ( self._cached_cos is not None and self._cached_sin is not None and self._cached_len >= seq_len and self._cached_cos.device == device ): return self._cached_cos[:seq_len], self._cached_sin[:seq_len] t = torch.arange(seq_len, device=device, dtype=torch.float32) freqs = torch.outer(t, self.inv_freq.to(device=device)) emb = torch.cat([freqs, freqs], dim=-1) self._cached_cos = emb.cos() self._cached_sin = emb.sin() self._cached_len = seq_len return self._cached_cos, self._cached_sin
@staticmethod def _rotate_half(x: torch.Tensor) -> torch.Tensor: half = x.shape[-1] // 2 return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: cos, sin = self._build_cache(q.shape[2], q.device) cos = cos.to(dtype=q.dtype).unsqueeze(0).unsqueeze(0) sin = sin.to(dtype=q.dtype).unsqueeze(0).unsqueeze(0) return (q * cos) + (self._rotate_half(q) * sin), (k * cos) + (self._rotate_half(k) * sin)
class RoPEMultiHeadAttention(nn.Module): def __init__(self, d_model: int, num_heads: int = 8, dropout: float = 0.1) -> None: super().__init__() self.d_model = d_model self.num_heads = num_heads self.head_dim = d_model // num_heads self.qkv = nn.Linear(d_model, d_model * 3, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) self.resid_dropout = nn.Dropout(dropout) self.rope = RotaryEmbedding(self.head_dim)
def forward( self, x: torch.Tensor, valid_mask: torch.Tensor, has_padding: bool = False ) -> torch.Tensor: bsz, seq_len, _ = x.shape qkv = self.qkv(x).view(bsz, seq_len, 3, self.num_heads, self.head_dim) q = qkv[:, :, 0].transpose(1, 2) k = qkv[:, :, 1].transpose(1, 2) v = qkv[:, :, 2].transpose(1, 2) q, k = self.rope(q, k) attn_mask = valid_mask[:, None, None, :] if has_padding else None out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0) out = out.transpose(1, 2).contiguous().view(bsz, seq_len, self.d_model) return self.resid_dropout(self.out_proj(out))
class ConformerConvModule(nn.Module): def __init__(self, d_model: int, kernel_size: int = 9, dropout: float = 0.15) -> None: super().__init__() self.pw_in = nn.Conv1d(d_model, d_model * 2, kernel_size=1) self.dw_conv = nn.Conv1d( d_model, d_model, kernel_size=kernel_size, padding=kernel_size // 2, groups=d_model ) self.norm = RMSNorm(d_model) self.pw_out = nn.Conv1d(d_model, d_model, kernel_size=1) self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, mask_f: torch.Tensor) -> torch.Tensor: h = self.pw_in((x * mask_f).transpose(1, 2)) h = F.glu(h, dim=1) h = self.dw_conv(h).transpose(1, 2) h = F.silu(self.norm(h)) h = self.pw_out(h.transpose(1, 2)).transpose(1, 2) return self.dropout(h) * mask_f
class MultiScaleConvStem(nn.Module): def __init__( self, d_model: int, kernel_sizes: Sequence[int] = (3, 7, 15, 31), dropout: float = 0.15 ) -> None: super().__init__() self.kernel_sizes = tuple(kernel_sizes) branch_dim = d_model // len(self.kernel_sizes) self.in_norm = RMSNorm(d_model) self.branches = nn.ModuleList( [ nn.Sequential( nn.Conv1d(d_model, branch_dim, kernel_size=1, bias=False), nn.Conv1d(branch_dim, branch_dim, kernel_size=k, padding=k // 2, groups=branch_dim), nn.SiLU(), ) for k in self.kernel_sizes ] ) self.out_proj = nn.Linear(d_model, d_model, bias=False) self.gate_proj = nn.Linear(d_model, d_model) self.out_norm = RMSNorm(d_model) self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, mask_f: torch.Tensor) -> torch.Tensor: h = self.in_norm(x) * mask_f h_t = h.transpose(1, 2) cat = self.out_norm(torch.cat([b(h_t) for b in self.branches], dim=1).transpose(1, 2)) out = self.dropout(self.out_proj(cat) * torch.sigmoid(self.gate_proj(h))) return (x + out) * mask_f
class RoPEConformerBlock(nn.Module): def __init__( self, d_model: int, num_heads: int = 8, ffn_hidden: int = 1024, conv_kernel: int = 9, dropout: float = 0.15, drop_path: float = 0.0, ) -> None: super().__init__() self.norm_ffn1 = RMSNorm(d_model) self.ffn1 = SwiGLUFFN(d_model, ffn_hidden, dropout=dropout) self.norm_attn = RMSNorm(d_model) self.attn = RoPEMultiHeadAttention(d_model, num_heads=num_heads, dropout=dropout) self.norm_conv = RMSNorm(d_model) self.conv = ConformerConvModule(d_model, kernel_size=conv_kernel, dropout=dropout) self.norm_ffn2 = RMSNorm(d_model) self.ffn2 = SwiGLUFFN(d_model, ffn_hidden, dropout=dropout) self.drop_path = DropPath(drop_path)
def forward( self, x: torch.Tensor, valid_mask: torch.Tensor, mask_f: torch.Tensor, has_padding: bool = False ) -> torch.Tensor: x = (x + 0.5 * self.drop_path(self.ffn1(self.norm_ffn1(x)))) * mask_f x = (x + self.drop_path(self.attn(self.norm_attn(x), valid_mask, has_padding=has_padding))) * mask_f x = x + self.drop_path(self.conv(self.norm_conv(x), mask_f)) x = (x + 0.5 * self.drop_path(self.ffn2(self.norm_ffn2(x)))) * mask_f return x
class AttentiveStatsPoolingFiLM(nn.Module): def __init__(self, d_model: int, bottleneck: int = 128) -> None: super().__init__() self.attn_score = nn.Sequential( nn.Linear(d_model, bottleneck), nn.Tanh(), nn.Linear(bottleneck, 1, bias=False), ) self.film = nn.Sequential( nn.Linear(d_model * 2, d_model), nn.SiLU(), nn.Linear(d_model, d_model * 2), )
def forward(self, x: torch.Tensor, valid_mask: torch.Tensor, mask_f: torch.Tensor) -> torch.Tensor: scores = self.attn_score(x).squeeze(-1).float().masked_fill(~valid_mask, -1e9) alpha = F.softmax(scores, dim=-1).unsqueeze(-1) x_fp32 = x.float() mean = (x_fp32 * alpha).sum(dim=1) var = ((x_fp32 - mean.unsqueeze(1)).pow(2) * alpha).sum(dim=1) std = torch.sqrt(var.clamp_min(1e-6)) stats = torch.cat([mean, std], dim=-1).to(dtype=x.dtype) gamma, beta = self.film(stats).chunk(2, dim=-1) return (x * (1.0 + gamma.unsqueeze(1)) + beta.unsqueeze(1)) * mask_f
class StructEstimator(nn.Module): def __init__( self, embed_dim: int = 1280, esm_layers: Sequence[int] = (18, 24, 30, 33), d_model: int = 512, num_layers: int = 6, num_heads: int = 8, ffn_hidden: int = 1024, stem_kernels: Sequence[int] = (3, 7, 15, 31), conv_kernel: int = 9, aa_embed_dim: int = 32, plddt_bins: int = 50, dropout: float = 0.15, embed_dropout: float = 0.15, drop_path_rate: float = 0.10, ) -> None: super().__init__() self.embed_dim = int(embed_dim) self.esm_layers = [int(x) for x in esm_layers] self.num_esm_layers = len(self.esm_layers) self.d_model = int(d_model) self.num_layers = int(num_layers) self.plddt_bins = int(plddt_bins)
bin_edges = torch.linspace(0.0, 1.0, self.plddt_bins + 1) self.register_buffer("plddt_bin_centers", 0.5 * (bin_edges[:-1] + bin_edges[1:]), persistent=False)
self.shared_layer_mix = MultiLayerScalarMix(self.num_esm_layers, self.embed_dim) self.local_skip_mix = MultiLayerScalarMix(self.num_esm_layers, self.embed_dim) self.global_skip_mix = MultiLayerScalarMix(self.num_esm_layers, self.embed_dim) self.aa_embedding = nn.Embedding(NUM_AA_TOKENS, int(aa_embed_dim)) self.embed_dropout = nn.Dropout(float(embed_dropout))
self.input_proj = nn.Sequential( nn.Linear(self.embed_dim + int(aa_embed_dim), self.d_model, bias=False), RMSNorm(self.d_model), nn.Dropout(float(dropout)), ) self.local_skip_proj = nn.Sequential( nn.Linear(self.embed_dim, self.d_model, bias=False), RMSNorm(self.d_model), ) self.global_skip_proj = nn.Sequential( nn.Linear(self.embed_dim, self.d_model, bias=False), RMSNorm(self.d_model), )
self.stem = MultiScaleConvStem(self.d_model, kernel_sizes=stem_kernels, dropout=float(dropout)) dp_rates = torch.linspace(0.0, float(drop_path_rate), self.num_layers).tolist() self.blocks = nn.ModuleList( [ RoPEConformerBlock( d_model=self.d_model, num_heads=int(num_heads), ffn_hidden=int(ffn_hidden), conv_kernel=int(conv_kernel), dropout=float(dropout), drop_path=dp_rates[i], ) for i in range(self.num_layers) ] ) self.final_norm = RMSNorm(self.d_model) self.mid_layer_idx = max(0, (self.num_layers // 2) - 1)
self.local_fuse = nn.Sequential(nn.Linear(self.d_model * 3, self.d_model, bias=False), RMSNorm(self.d_model)) self.local_adapter = SwiGLUFFN(self.d_model, self.d_model * 2, dropout=float(dropout)) self.local_out_norm = RMSNorm(self.d_model)
self.global_film = AttentiveStatsPoolingFiLM(self.d_model) self.global_fuse = nn.Sequential(nn.Linear(self.d_model * 2, self.d_model, bias=False), RMSNorm(self.d_model)) self.global_adapter = SwiGLUFFN(self.d_model, self.d_model * 2, dropout=float(dropout)) self.global_out_norm = RMSNorm(self.d_model)
self.q8_head_s1 = nn.Linear(self.d_model, 8) self.q3_head_s1 = nn.Linear(self.d_model, 3) self.phi_head_s1 = nn.Linear(self.d_model, 2) self.psi_head_s1 = nn.Linear(self.d_model, 2) self.plddt_head_s1 = nn.Linear(self.d_model, self.plddt_bins) self.rsa_head_s1 = nn.Linear(self.d_model, 1) self.disorder_head_s1 = nn.Linear(self.d_model, 2)
refine_dim = 256 self.stage2_in = nn.Linear(self.d_model * 2 + 19, refine_dim, bias=False) self.stage2_norm1 = RMSNorm(refine_dim) self.stage2_dw = nn.Conv1d(refine_dim, refine_dim, kernel_size=5, padding=2, groups=refine_dim) self.stage2_norm2 = RMSNorm(refine_dim) self.stage2_ffn = SwiGLUFFN(refine_dim, refine_dim * 2, dropout=float(dropout)) self.stage2_norm3 = RMSNorm(refine_dim)
self.q8_delta = nn.Linear(refine_dim, 8) self.q3_delta = nn.Linear(refine_dim, 3) self.phi_delta = nn.Linear(refine_dim, 2) self.psi_delta = nn.Linear(refine_dim, 2) self.plddt_delta = nn.Linear(refine_dim, self.plddt_bins) self.rsa_delta = nn.Linear(refine_dim, 1) self.disorder_delta = nn.Linear(refine_dim, 2)
def _decode_plddt(self, logits: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: probs = F.softmax(logits.float(), dim=-1) centers = self.plddt_bin_centers.to(device=logits.device, dtype=torch.float32) expected = (probs * centers).sum(dim=-1) gt70_idx = int(math.floor(0.70 * self.plddt_bins)) gt70_prob = probs[..., gt70_idx:].sum(dim=-1).clamp(1e-6, 1.0 - 1e-6) return expected.to(dtype=logits.dtype), gt70_prob.to(dtype=logits.dtype)
@staticmethod def _unit_sincos(raw: torch.Tensor) -> torch.Tensor: norm = torch.linalg.vector_norm(raw.float(), dim=-1, keepdim=True).clamp_min(1e-6) return (raw.float() / norm).to(dtype=raw.dtype)
def forward( self, embeddings: torch.Tensor, lengths: Optional[torch.Tensor] = None, aa_ids: Optional[torch.Tensor] = None, ) -> Dict[str, torch.Tensor]: if embeddings.ndim == 3: embeddings = embeddings.unsqueeze(2) bsz, max_len, _, _ = embeddings.shape
if lengths is not None: safe_lengths = lengths.clamp_min(1) has_padding = bool((safe_lengths < max_len).any().item()) pos = torch.arange(max_len, device=embeddings.device).unsqueeze(0) valid_mask = pos < safe_lengths.to(embeddings.device).unsqueeze(1) else: has_padding = False valid_mask = torch.ones((bsz, max_len), dtype=torch.bool, device=embeddings.device) mask_f = valid_mask.unsqueeze(-1).to(dtype=embeddings.dtype)
if aa_ids is None: aa_ids = torch.full((bsz, max_len), UNK_AA_INDEX, dtype=torch.long, device=embeddings.device) else: aa_ids = aa_ids.to(device=embeddings.device, dtype=torch.long).clamp(0, NUM_AA_TOKENS - 1)
shared_esm = self.embed_dropout(self.shared_layer_mix(embeddings)) local_skip = self.local_skip_proj(self.embed_dropout(self.local_skip_mix(embeddings))) * mask_f global_skip = self.global_skip_proj(self.embed_dropout(self.global_skip_mix(embeddings))) * mask_f aa_feat = self.aa_embedding(aa_ids)
x = self.input_proj(torch.cat([shared_esm, aa_feat], dim=-1)) * mask_f x = self.stem(x, mask_f) h_mid = x for idx, block in enumerate(self.blocks): x = block(x, valid_mask, mask_f, has_padding=has_padding) if idx == self.mid_layer_idx: h_mid = x h_final = self.final_norm(x) * mask_f
h_local_in = self.local_fuse(torch.cat([h_final, h_mid, local_skip], dim=-1)) * mask_f h_local = self.local_out_norm(h_local_in + self.local_adapter(h_local_in)) * mask_f
h_glob_ctx = self.global_film(h_final, valid_mask, mask_f) h_global_in = self.global_fuse(torch.cat([h_glob_ctx, global_skip], dim=-1)) * mask_f h_global = self.global_out_norm(h_global_in + self.global_adapter(h_global_in)) * mask_f
q8_s1 = self.q8_head_s1(h_local) q3_s1 = self.q3_head_s1(h_local) phi_s1 = self.phi_head_s1(h_local) psi_s1 = self.psi_head_s1(h_local) plddt_s1 = self.plddt_head_s1(h_global) rsa_s1 = self.rsa_head_s1(h_global) dis_s1 = self.disorder_head_s1(h_global)
plddt_exp_s1, plddt_gt70_s1 = self._decode_plddt(plddt_s1) task_summary = torch.cat( [ F.softmax(q3_s1, dim=-1), F.softmax(q8_s1, dim=-1), plddt_exp_s1.unsqueeze(-1), plddt_gt70_s1.unsqueeze(-1), torch.sigmoid(rsa_s1), F.softmax(dis_s1, dim=-1)[..., 1:2], self._unit_sincos(phi_s1), self._unit_sincos(psi_s1), ], dim=-1, ) r = self.stage2_norm1(self.stage2_in(torch.cat([h_local, h_global, task_summary], dim=-1))) * mask_f r = (r + F.silu(self.stage2_norm2(self.stage2_dw(r.transpose(1, 2)).transpose(1, 2)))) * mask_f r = self.stage2_norm3(r + self.stage2_ffn(r)) * mask_f
plddt_exp, _ = self._decode_plddt(plddt_s1 + self.plddt_delta(r)) return { "q8": q8_s1 + self.q8_delta(r), "q3": q3_s1 + self.q3_delta(r), "disorder": dis_s1 + self.disorder_delta(r), "rsa": torch.sigmoid(rsa_s1 + self.rsa_delta(r)).squeeze(-1), "phi": self._unit_sincos(phi_s1 + self.phi_delta(r)), "psi": self._unit_sincos(psi_s1 + self.psi_delta(r)), "plddt": plddt_exp, }
# =============================================================================# 4. Decoding, I/O & CLI# =============================================================================
@torch.no_grad()def decode_predictions( seq_id: str, sequence: str, preds: Dict[str, torch.Tensor]) -> List[Dict[str, object]]: q8_probs = F.softmax(preds["q8"][0].float(), dim=-1).cpu() q3_probs = F.softmax(preds["q3"][0].float(), dim=-1).cpu() dis_probs = F.softmax(preds["disorder"][0].float(), dim=-1)[:, 1].cpu() rsa_vals = preds["rsa"][0].float().cpu() plddt_vals = (preds["plddt"][0].float() * 100.0).cpu() phi_sc = preds["phi"][0].float().cpu() psi_sc = preds["psi"][0].float().cpu() phi_deg = torch.atan2(phi_sc[:, 0], phi_sc[:, 1]) * (180.0 / math.pi) psi_deg = torch.atan2(psi_sc[:, 0], psi_sc[:, 1]) * (180.0 / math.pi)
rows: List[Dict[str, object]] = [] for idx, aa in enumerate(sequence): rsa = float(rsa_vals[idx].item()) asa = rsa * MAX_ASA_TIEN.get(aa, MAX_ASA_TIEN["X"]) p3 = q3_probs[idx] p8 = q8_probs[idx] rows.append( { "id": seq_id, "seq": aa, "n": idx + 1, "rsa": round(rsa, 4), "asa": round(asa, 2), "q3": Q3_LABELS[int(p3.argmax().item())], "p_q3_H": round(float(p3[0].item()), 4), "p_q3_E": round(float(p3[1].item()), 4), "p_q3_C": round(float(p3[2].item()), 4), "q8": Q8_LABELS[int(p8.argmax().item())], "p_q8_G": round(float(p8[0].item()), 4), "p_q8_H": round(float(p8[1].item()), 4), "p_q8_I": round(float(p8[2].item()), 4), "p_q8_B": round(float(p8[3].item()), 4), "p_q8_E": round(float(p8[4].item()), 4), "p_q8_S": round(float(p8[5].item()), 4), "p_q8_T": round(float(p8[6].item()), 4), "p_q8_C": round(float(p8[7].item()), 4), "phi": round(float(phi_deg[idx].item()), 2), "psi": round(float(psi_deg[idx].item()), 2), "disorder": round(float(dis_probs[idx].item()), 4), "plddt": round(float(plddt_vals[idx].item()), 2), } ) return rows
def resolve_model_path(model_arg: str, hf_repo: Optional[str] = None) -> Path: path = Path(model_arg) if path.exists(): return path if hf_repo: from huggingface_hub import hf_hub_download
filename = path.name or "StructEstimator_esm2_650m.pth" print(f"Downloading '{filename}' from Hugging Face Hub ({hf_repo})...") return Path(hf_hub_download(repo_id=hf_repo, filename=filename)) raise FileNotFoundError( f"Model file '{model_arg}' not found. Pass `--model /path/to/StructEstimator_esm2_650m.pth` " "or `--hf-repo cpdong/StructEstimator`." )
def save_outputs( output_arg: str, all_rows: List[Dict[str, object]], per_protein_json: Dict[str, object],) -> List[Path]: """Write CSV, JSON, or both depending on `--output` suffix (`.csv`, `.json`, or directory).""" out = Path(output_arg) written: List[Path] = []
if out.suffix.lower() == ".csv": out.parent.mkdir(parents=True, exist_ok=True) with open(out, "w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=CSV_COLUMNS) writer.writeheader() writer.writerows(all_rows) written.append(out) elif out.suffix.lower() == ".json": out.parent.mkdir(parents=True, exist_ok=True) with open(out, "w", encoding="utf-8") as fh: json.dump(per_protein_json, fh, indent=2) written.append(out) else: out.mkdir(parents=True, exist_ok=True) csv_path = out / "predictions.csv" json_path = out / "predictions.json" with open(csv_path, "w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=CSV_COLUMNS) writer.writeheader() writer.writerows(all_rows) with open(json_path, "w", encoding="utf-8") as fh: json.dump(per_protein_json, fh, indent=2) written.extend([csv_path, json_path])
return written
@torch.no_grad()def main() -> None: parser = argparse.ArgumentParser( description="All-in-one standalone StructEstimator predictor (Q3, Q8, RSA, ASA, Disorder, Phi, Psi, pLDDT)." ) parser.add_argument( "--model", type=str, required=True, help="Path to standalone bundled `StructEstimator_esm2_650m.pth`.", ) parser.add_argument( "--input", type=str, required=True, help="Input FASTA file path OR raw amino acid sequence string.", ) parser.add_argument( "--output", type=str, required=True, help="Output `.csv` file, `.json` file, or output directory (writes both CSV and JSON).", ) parser.add_argument("--device", type=str, default=None, help="Override device (cuda, mps, cpu).") parser.add_argument( "--hf-repo", type=str, default=None, help="Optional Hugging Face repo ID to auto-download `--model` if missing locally.", ) parser.add_argument("--max-chunk-len", type=int, default=1022, help="Sliding window size for >1022 aa chains.") parser.add_argument("--chunk-overlap", type=int, default=128, help="Sliding window overlap for >1022 aa chains.") parser.add_argument( "--dummy-esm", action="store_true", help="Use random embeddings instead of running ESM-2 (offline smoke test only).", ) args = parser.parse_args()
device = torch.device(args.device) if args.device else get_default_device() ckpt_path = resolve_model_path(args.model, hf_repo=args.hf_repo) records = load_input_sequences(args.input)
print(f"Loading '{ckpt_path}' on {device}...") ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) model_cfg = dict(ckpt["model_config"]) esm_layers = list(ckpt.get("esm_layers") or model_cfg.get("esm_layers", [18, 24, 30, 33])) esm_name = str(ckpt.get("hf_name") or ckpt.get("esm_model", "esm2_650m"))
model = StructEstimator(**model_cfg).to(device) model.load_state_dict(ckpt["state_dict"], strict=True) model.eval()
embedder: Optional[StandaloneESM2Embedder] = None if not args.dummy_esm: embedder = StandaloneESM2Embedder.from_checkpoint( ckpt=ckpt, device=device, layers=esm_layers, half_precision=True, max_chunk_len=args.max_chunk_len, chunk_overlap=args.chunk_overlap, )
all_rows: List[Dict[str, object]] = [] per_protein_json: Dict[str, object] = {}
for seq_id, clean_seq in records: if embedder is not None: emb = embedder.embed_sequence(clean_seq) else: emb = torch.randn((len(clean_seq), len(esm_layers), int(model_cfg["embed_dim"])), dtype=torch.float32)
emb_batch = emb.unsqueeze(0).to(device) aa_ids = torch.tensor([encode_aa_indices(clean_seq)], dtype=torch.long, device=device) lengths = torch.tensor([len(clean_seq)], dtype=torch.long) preds = model(emb_batch, lengths, aa_ids)
rows = decode_predictions(seq_id, clean_seq, preds) all_rows.extend(rows) per_protein_json[seq_id] = { "sequence": clean_seq, "length": len(clean_seq), "esm_backbone": esm_name, "esm_layers": esm_layers, "residues": rows, }
written = save_outputs(args.output, all_rows, per_protein_json) out_str = ", ".join(str(p) for p in written) print(f"Predicted {len(records)} protein(s) ({len(all_rows)} residues) -> {out_str}")
if __name__ == "__main__": main()predict_standalone.pyDeleted-888