"""Fine-tuned ESM2-8M EC classifier, forward pass written in NumPy (no PyTorch needed at inference). The network is the same as in the training notebook: ESM2-8M (6 transformer layers, 20 heads, hidden size 320, rotary positions), mean over residue vectors, then one linear layer to EC classes. Sequences are processed one at a time, so no padding or attention masks are needed. """ import json import math import numpy as np MAX_LEN = 512 # same truncation as used when the classifier was trained and evaluated VOCAB = ['', '', '', '', 'L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B', 'U', 'Z', 'O', '.', '-', '', ''] TOKEN_ID = {t: i for i, t in enumerate(VOCAB)} CLS, EOS, UNK = 0, 2, 3 def layer_norm(x, w, b, eps=1e-5): mean = x.mean(-1, keepdims=True) var = ((x - mean) ** 2).mean(-1, keepdims=True) return (x - mean) / np.sqrt(var + eps) * w + b def erf(x): """Abramowitz and Stegun formula 7.1.26: error below 1.5e-7, i.e. float32 precision, using fast numpy ops.""" sign = np.sign(x) a = np.abs(x) t = 1.0 / (1.0 + 0.3275911 * a) poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))) return sign * (1.0 - poly * np.exp(-a * a)) def gelu(x): # Exact (erf) GELU, as in the original ESM code return 0.5 * x * (1.0 + erf(x * np.float32(1 / math.sqrt(2.0)))) def rotate_half(x): half = x.shape[-1] // 2 return np.concatenate([-x[..., half:], x[..., :half]], axis=-1) class ECClassifierNumpy: def __init__(self, weights_path, classes_path): w = np.load(weights_path) self.w = {k: w[k].astype(np.float32) for k in w.files} self.classes = np.array(json.load(open(classes_path))) self.layers = sum(1 for k in self.w if k.endswith('attention.self.query.weight')) self.heads = 20 self.inv_freq = self.w['esm.rotary_embeddings.inv_freq'] def encode(self, seq): seq = seq[:MAX_LEN] return np.array([CLS] + [TOKEN_ID.get(c, UNK) for c in seq] + [EOS]) def pooled(self, seq): w = self.w ids = self.encode(seq) T = len(ids) # Token embeddings, scaled by (1 - 0.15 * 0.8) because ESM was trained with masked tokens zeroed out x = w['esm.embeddings.word_embeddings.weight'][ids] * np.float32(1 - 0.15 * 0.8) # Rotary position tables (only relative positions matter, so positions start at 0) freqs = np.arange(T, dtype=np.float32)[:, None] * self.inv_freq[None, :] emb = np.concatenate([freqs, freqs], axis=-1) cos, sin = np.cos(emb), np.sin(emb) d = x.shape[1] // self.heads for i in range(self.layers): p = 'esm.encoder.layer.%d.' % i # Self-attention block (pre-LayerNorm, residual connection) h = layer_norm(x, w[p + 'attention.LayerNorm.weight'], w[p + 'attention.LayerNorm.bias']) q = (h @ w[p + 'attention.self.query.weight'].T + w[p + 'attention.self.query.bias']) k = (h @ w[p + 'attention.self.key.weight'].T + w[p + 'attention.self.key.bias']) v = (h @ w[p + 'attention.self.value.weight'].T + w[p + 'attention.self.value.bias']) # Split into heads: (heads, T, d), stored contiguously so the matrix products stay fast q = np.ascontiguousarray(q.reshape(T, self.heads, d).transpose(1, 0, 2)) * np.float32(d ** -0.5) k = np.ascontiguousarray(k.reshape(T, self.heads, d).transpose(1, 0, 2)) v = np.ascontiguousarray(v.reshape(T, self.heads, d).transpose(1, 0, 2)) q = q * cos + rotate_half(q) * sin k = k * cos + rotate_half(k) * sin scores = q @ np.ascontiguousarray(k.transpose(0, 2, 1)) # Softmax over the last axis, done in place to avoid extra copies of the (heads, T, T) array scores -= scores.max(-1, keepdims=True) np.exp(scores, out=scores) scores /= scores.sum(-1, keepdims=True) context = (scores @ v).transpose(1, 0, 2).reshape(T, -1) x = x + context @ w[p + 'attention.output.dense.weight'].T + w[p + 'attention.output.dense.bias'] # Feed-forward block (pre-LayerNorm, residual connection) h = layer_norm(x, w[p + 'LayerNorm.weight'], w[p + 'LayerNorm.bias']) h = gelu(h @ w[p + 'intermediate.dense.weight'].T + w[p + 'intermediate.dense.bias']) x = x + h @ w[p + 'output.dense.weight'].T + w[p + 'output.dense.bias'] x = layer_norm(x, w['esm.encoder.emb_layer_norm_after.weight'], w['esm.encoder.emb_layer_norm_after.bias']) return x[1:-1].mean(0) # average over residues, skipping the start and end tokens def predict(self, seq, top=10): logits = self.pooled(seq) @ self.w['head.weight'].T + self.w['head.bias'] p = np.exp(logits - logits.max()) p /= p.sum() best = np.argsort(-p)[:top] return self.classes[best], p[best]