s42chen commited on
Commit
32d1b4a
·
verified ·
1 Parent(s): ffcc0e3

Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 51)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S052/unified.py +643 -0
  3. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/PUBLISHED.json +5 -0
  4. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/README.md +61 -0
  5. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/config.json +134 -0
  6. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/esm2.py +250 -0
  7. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/infer.sh +4 -0
  8. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/provenance.json +291 -0
  9. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/replay.py +166 -0
  10. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/selection.json +46 -0
  11. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/unified.py +643 -0
  12. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/PUBLISHED.json +5 -0
  13. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/README.md +78 -0
  14. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/config.json +134 -0
  15. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/esm2.py +250 -0
  16. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/infer.sh +4 -0
  17. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/provenance.json +460 -0
  18. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/replay.py +166 -0
  19. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/selection.json +116 -0
  20. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/unified.py +643 -0
  21. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/PUBLISHED.json +5 -0
  22. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/README.md +66 -0
  23. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/config.json +142 -0
  24. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/esm2.py +250 -0
  25. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/infer.sh +4 -0
  26. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/provenance.json +0 -0
  27. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/replay.py +166 -0
  28. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/selection.json +180 -0
  29. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/unified.py +695 -0
  30. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/PUBLISHED.json +5 -0
  31. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/README.md +68 -0
  32. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/config.json +153 -0
  33. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/esm2.py +250 -0
  34. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/infer.sh +4 -0
  35. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/replay.py +166 -0
  36. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/selection.json +489 -0
  37. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/unified.py +718 -0
  38. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/PUBLISHED.json +5 -0
  39. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/README.md +53 -0
  40. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/config.json +146 -0
  41. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/esm2.py +250 -0
  42. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/infer.sh +4 -0
  43. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/replay.py +166 -0
  44. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/selection.json +189 -0
  45. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/unified.py +746 -0
  46. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/PUBLISHED.json +5 -0
  47. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/README.md +41 -0
  48. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/config.json +146 -0
  49. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/esm2.py +250 -0
  50. tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/infer.sh +4 -0
.gitattributes CHANGED
@@ -1161,3 +1161,5 @@ tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/session
1161
  tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
1162
  tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-38-50-01a161b0-ac23-78b3-96d0-140821a2d85b.jsonl filter=lfs diff=lfs merge=lfs -text
1163
  tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
 
1161
  tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
1162
  tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-38-50-01a161b0-ac23-78b3-96d0-140821a2d85b.jsonl filter=lfs diff=lfs merge=lfs -text
1163
  tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
1164
+ tasks/single-cell-perturbation-prediction/single-cell-perturbation-prediction-astra-xhigh-1h100-48h-20261020b/logs/sessions/2026/10/21/rollout-2026-10-21T03-57-13-01a15c9b-2307-7ab2-8e3e-1edc93189eb1.jsonl filter=lfs diff=lfs merge=lfs -text
1165
+ tasks/single-cell-perturbation-prediction/single-cell-perturbation-prediction-astra-xhigh-1h100-48h-20261020b/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S052/unified.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class ResidualSequenceConvHead(nn.Module):
117
+ """Learn local sequence motifs alongside the retained summary classifier."""
118
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
119
+ super().__init__()
120
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
121
+ self.register_buffer('mean', torch.zeros(dim))
122
+ self.register_buffer('scale', torch.ones(dim))
123
+ self.project = nn.Linear(dim, channels)
124
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
125
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
126
+ self.output = nn.Linear(4 * channels, outputs)
127
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
128
+ self.dropout = dropout
129
+
130
+ def forward(self, features):
131
+ valid = features['valid'].bool().unsqueeze(-1)
132
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
133
+ summaries = []
134
+ for conv,norm in zip(self.convs,self.norms):
135
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
136
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
137
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
138
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
139
+ summaries.extend([center,maximum])
140
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
141
+ logits=self.output(pooled)
142
+ return self.base(features['summary']) + logits if self.base is not None else logits
143
+
144
+
145
+ class TokenLogMeanExpHead(nn.Module):
146
+ """Class-specific local evidence, pooled without sequence-length bias."""
147
+ def __init__(self, dim, outputs):
148
+ super().__init__()
149
+ self.register_buffer('mean', torch.zeros(dim))
150
+ self.register_buffer('scale', torch.ones(dim))
151
+ self.linear = nn.Linear(dim, outputs)
152
+
153
+ def forward(self, representation):
154
+ values, valid = representation['hidden'].float(), representation['valid']
155
+ logits = self.linear((values-self.mean)/self.scale)
156
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
157
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
158
+
159
+ def packed(self, values, lengths):
160
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
161
+ logits = self.linear((values.float()-self.mean)/self.scale)
162
+ # The stabilizing maximum cancels in the derivative; detach avoids
163
+ # retaining another large token-by-class gradient path.
164
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
165
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
166
+ output_size=len(values))
167
+ exponent = (logits-maximum[index]).exp()
168
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
169
+ return maximum+total.log()-lengths.float().log()[:, None]
170
+
171
+
172
+ class SharedPairResidueInteraction(nn.Module):
173
+ """A shared nonlinear comparison of local states from both protein chains."""
174
+ def __init__(self, dim, settings, classes):
175
+ super().__init__()
176
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
177
+ self.register_buffer('mean', torch.zeros(dim))
178
+ self.register_buffer('scale', torch.ones(dim))
179
+ self.project = nn.Linear(dim, width)
180
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
181
+ nn.Linear(hidden, channels), nn.GELU())
182
+ self.dropout = settings['dropout']
183
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
184
+ for task in sorted(esm2.Model.PAIR)})
185
+ for head in self.heads.values():
186
+ nn.init.zeros_(head.weight)
187
+ nn.init.zeros_(head.bias)
188
+
189
+ def forward(self, task, first, second):
190
+ first = F.gelu(self.project((first-self.mean)/self.scale))
191
+ second = F.gelu(self.project((second-self.mean)/self.scale))
192
+ first = F.dropout(first, self.dropout, self.training)
193
+ second = F.dropout(second, self.dropout, self.training)
194
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
195
+ first[:, :, None]*second[:, None, :]], dim=-1)
196
+ local = self.compare(pair)
197
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
198
+ return self.heads[task](summary)
199
+
200
+
201
+ class SSChainDecoder(nn.Module):
202
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
203
+ def __init__(self):
204
+ super().__init__()
205
+ self.transition = nn.Parameter(torch.empty(3, 3))
206
+ self.start = nn.Parameter(torch.empty(3))
207
+ self.end = nn.Parameter(torch.empty(3))
208
+ for parameter in self.parameters():
209
+ nn.init.normal_(parameter, std=.01)
210
+
211
+ def decode(self, probabilities):
212
+ from ss_chain import decode_probabilities
213
+ values = [parameter.detach().double().cpu().numpy()
214
+ for parameter in (self.transition, self.start, self.end)]
215
+ return decode_probabilities(probabilities, *values)
216
+
217
+
218
+ class UnifiedModel(esm2.Model):
219
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
220
+ 'subcellular_localization', 'binary_localization', 'fold',
221
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
222
+
223
+ def __init__(self, config):
224
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
225
+ self.config = config
226
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
227
+ dim = config['dim']
228
+ if config.get('extension_layers', 0):
229
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
230
+ before_norm=config.get('extension_before_norm', False))
231
+ if config.get('task_conditioning', False):
232
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
233
+ if config.get('pooling', 'mean') == 'rich':
234
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
235
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
236
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
237
+ self.pool_fuse = nn.Linear(6 * dim, dim)
238
+ nn.init.zeros_(self.pool_fuse.weight)
239
+ nn.init.zeros_(self.pool_fuse.bias)
240
+ if config.get('pair_interaction', False):
241
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
242
+ nn.init.zeros_(self.pair_fuse.weight)
243
+ nn.init.zeros_(self.pair_fuse.bias)
244
+ if config.get('ss_context', False):
245
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
246
+ for task in config.get('linear_heads', []):
247
+ width = dim * 2 if task in self.PAIR else dim
248
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
249
+ for task, settings in config.get('residue_readouts', {}).items():
250
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
251
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
252
+ bins = config['residue_readouts'][task]['bins']
253
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
254
+ for task in config.get('summary_readouts', []):
255
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
256
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
257
+ for task in config.get('sequence_composition_readouts', []):
258
+ from sequence_composition import WIDTH
259
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
260
+ assert all(task not in config.get(key,[]) for key in
261
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
262
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
263
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
264
+ for task, temperature in config.get('cosine_heads', {}).items():
265
+ assert task in config.get('summary_readouts', [])
266
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
267
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
268
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
269
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
270
+ for task in config.get('calibrated_heads', []):
271
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
272
+ assert task not in config.get('linear_heads', [])
273
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
274
+ for task in config.get('expanded_pair_readouts', []):
275
+ assert task in self.PAIR
276
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
277
+ if task in config.get('pair_summary_readouts', []):
278
+ assert config.get('pooling') == 'rich'
279
+ width *= 8
280
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
281
+ if config.get('ss_linear_context'):
282
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
283
+ if config.get('ss_calibrated'):
284
+ assert not config.get('ss_linear_context')
285
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
286
+ for task in config.get('ss_summary_readouts', []):
287
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
288
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
289
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
290
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
291
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
292
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
293
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
294
+ assert all(task not in config.get(key, {}) for key in
295
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
296
+ bins = settings['bins']
297
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
298
+ for key in ['prefix_residues', 'suffix_residues'])
299
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
300
+ if config.get('pair_bilinear_rank', 0):
301
+ rank = config['pair_bilinear_rank']
302
+ assert not config.get('pair_summary_readouts')
303
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
304
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
305
+ with torch.no_grad():
306
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
307
+ self.pair_bilinear_heads = nn.ModuleDict({
308
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
309
+ for task in sorted(self.PAIR)})
310
+ for head in self.pair_bilinear_heads.values():
311
+ nn.init.zeros_(head.weight)
312
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
313
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
314
+ if config.get('pair_residue_interaction'):
315
+ self.pair_residue_interaction = SharedPairResidueInteraction(
316
+ dim, config['pair_residue_interaction'], self.CLASSES)
317
+ for task in config.get('token_logmeanexp_heads', []):
318
+ assert task in self.CLASSES and task not in self.PAIR
319
+ assert task not in config.get('sequence_windows', [])
320
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
321
+ if config.get('ss_chain_decoder', False):
322
+ self.ss_chain_decoder = SSChainDecoder()
323
+ if config.get('shared_summary_residual'):
324
+ settings = config['shared_summary_residual']
325
+ tasks = settings['tasks']
326
+ assert all(task in config.get('summary_readouts', []) and
327
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
328
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
329
+ {task: self.CLASSES[task] for task in tasks})
330
+
331
+ def pair_representation(self, task, first, second, base):
332
+ if task in self.config.get('pair_bilinear_tasks', []):
333
+ return {'base': base, 'chain_a': first, 'chain_b': second}
334
+ return base
335
+
336
+ def apply_head(self, task, representation):
337
+ if task in self.config.get('summary_residual_tasks', []):
338
+ head = self.heads[task]
339
+ normalized = (representation-head.mean)/head.scale
340
+ return head(representation) + self.summary_residual(task, normalized)
341
+ if isinstance(representation, dict) and 'residue_a' in representation:
342
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
343
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
344
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
345
+ if isinstance(representation, dict) and 'chain_a' in representation:
346
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
347
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
348
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
349
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
350
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
351
+ return self.heads[task](representation)
352
+
353
+ def encode_residues(self, tokens, task):
354
+ condition = None
355
+ if self.config.get('task_conditioning', False):
356
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
357
+ condition = self.task_condition[ti]
358
+ return self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
359
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
360
+
361
+ def pool(self, tokens, task):
362
+ hidden, pad_mask = self.encode_residues(tokens, task)
363
+ return self.summarize(hidden, tokens, pad_mask, task)
364
+
365
+ def summarize(self, hidden, tokens, pad_mask, task):
366
+ valid = (~pad_mask).unsqueeze(-1)
367
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
368
+ if self.config.get('pooling', 'mean') == 'mean':
369
+ return mean
370
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
371
+ # Empty/nonstandard-only inputs still produce a finite representation.
372
+ residues[:, 0] |= ~residues.any(1)
373
+ keep = residues.unsqueeze(-1)
374
+ count = keep.sum(1).clamp_min(1)
375
+ center = (hidden * keep).sum(1) / count
376
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
377
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
378
+ torch.cos(position * math.pi)], dim=-1)
379
+ ti = self.task_index[task]
380
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
381
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
382
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
383
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
384
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
385
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
386
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
387
+ first = residues & (residues.cumsum(1) <= 32)
388
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
389
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
390
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
391
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
392
+ deviation, maximum, prefix, suffix], dim=-1)
393
+ if task in self.config.get('summary_readouts', []):
394
+ return torch.cat([mean, summary], dim=-1)
395
+ if task in self.config.get('pair_summary_readouts', []):
396
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
397
+ return mean + self.pool_fuse(summary)
398
+
399
+ def pool_sequences(self, sequences, task, device, max_len):
400
+ if self.training and not self.config.get('window_pooling_training', True):
401
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
402
+ return self.pool(tokens,task)
403
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
404
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
405
+ results=[None]*len(sequences)
406
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
407
+ if short:
408
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
409
+ for j,index in enumerate(short):results[index]=pooled[j]
410
+ width=max_len-2;stride=min(768,width)
411
+ if self.training and self.config.get('batch_window_training',False):
412
+ pieces=[];starts_by_index={};encoded={}
413
+ for index,sequence in enumerate(sequences):
414
+ if len(sequence)<=width:continue
415
+ starts=list(range(0,len(sequence)-width+1,stride))
416
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
417
+ starts_by_index[index]=starts
418
+ pieces.extend((index,start) for start in starts)
419
+ count=max(1,16384//max_len)
420
+ for begin in range(0,len(pieces),count):
421
+ part=pieces[begin:begin+count]
422
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
423
+ hidden,_=self.encode_residues(tokens,task)
424
+ for j,key in enumerate(part):encoded[key]=hidden[j]
425
+ positions=torch.arange(width,device=device)
426
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
427
+ for index,starts in starts_by_index.items():
428
+ sequence=sequences[index];length=len(sequence)
429
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
430
+ for start in starts:
431
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
432
+ counts.index_add_(0,positions+start,weight)
433
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
434
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
435
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
436
+ return torch.stack(results)
437
+ for index,sequence in enumerate(sequences):
438
+ length=len(sequence)
439
+ if length<=width:continue
440
+ starts=list(range(0,length-width+1,stride))
441
+ if starts[-1]!=length-width:starts.append(length-width)
442
+ total=torch.zeros(length,self.config['dim'],device=device)
443
+ counts=torch.zeros(length,1,device=device)
444
+ first=last=None
445
+ for begin in range(0,len(starts),max(1,16384//max_len)):
446
+ part=starts[begin:begin+max(1,16384//max_len)]
447
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
448
+ hidden,_=self.encode_residues(tokens,task)
449
+ for j,start in enumerate(part):
450
+ if start==0:first=hidden[j,0:1]
451
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
452
+ positions=torch.arange(width,device=device)
453
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
454
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
455
+ counts.index_add_(0,positions+start,weight)
456
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
457
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
458
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
459
+ return torch.stack(results)
460
+
461
+ def represent(self, task, batch, device, max_len=1024):
462
+ if task in self.config.get('sequence_composition_readouts', []):
463
+ from sequence_composition import composition_features
464
+ sequences=[item['sequence'] for item in batch]
465
+ pooled=self.pool_sequences(sequences,task,device,max_len)
466
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
467
+ if task in self.config.get('token_logmeanexp_heads', []):
468
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
469
+ hidden, _ = self.encode_residues(tokens, task)
470
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
471
+ valid[:, 0] |= ~valid.any(1)
472
+ return {'hidden':hidden, 'valid':valid}
473
+ if task in self.config.get('terminal_summary_readouts', {}):
474
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
475
+ if task in self.config.get('ss_summary_readouts', []):
476
+ sequences=[x['sequence'] for x in batch]
477
+ summary=self.pool_sequences(sequences,task,device,max_len)
478
+ structure=self.secondary_structure_summary(sequences,device,max_len)
479
+ return torch.cat([summary.float(),structure],-1)
480
+ if task in self.config.get('sequence_conv_readouts',{}):
481
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
482
+ hidden,pad_mask=self.encode_residues(tokens,task)
483
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
484
+ width=max(1,int(lengths.max()))
485
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
486
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
487
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
488
+ if task in self.config.get('residue_readouts', {}):
489
+ bins = self.config['residue_readouts'][task]['bins']
490
+ sequences = [x['sequence'] for x in batch]
491
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
492
+ hidden, _ = self.encode_residues(tokens, task)
493
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
494
+ if task in self.PAIR:
495
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
496
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
497
+ if task in self.config.get('expanded_pair_readouts', []):
498
+ if task in self.config.get('symmetric_pair_readouts',[]):
499
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
500
+ else:
501
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
502
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
503
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
504
+ output = torch.cat([a, b], dim=-1)
505
+ if self.config.get('pair_interaction', False):
506
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
507
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
508
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
509
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
510
+
511
+ def add_pair_residues(self, task, batch, device, max_len, base):
512
+ if task not in self.config.get('pair_residue_tasks', []):
513
+ return base
514
+ result = dict(base) if isinstance(base, dict) else {'base': base}
515
+ bins = self.config['pair_residue_interaction']['bins']
516
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
517
+ result['residue_'+role] = self.pool_residue_bins(
518
+ [row[name] for row in batch], task, device, max_len, bins)
519
+ return result
520
+
521
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
522
+ """Average every residue into fixed relative bins, with full-chain context."""
523
+ width = max_len-2
524
+ assert width > 0 and bins > 0
525
+ output = [None]*len(sequences)
526
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
527
+ if short:
528
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
529
+ hidden, _ = self.encode_residues(tokens, task)
530
+ for j, index in enumerate(short):
531
+ length = len(sequences[index])
532
+ values = hidden[j, 1:1+length].float()
533
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
534
+ else torch.zeros(bins, self.config['dim'], device=device))
535
+ for index, sequence in enumerate(sequences):
536
+ if len(sequence) <= width:
537
+ continue
538
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
539
+ if starts[-1] != len(sequence)-width:
540
+ starts.append(len(sequence)-width)
541
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
542
+ count = torch.zeros(len(sequence), 1, device=device)
543
+ position = torch.arange(width, device=device)
544
+ weight = torch.minimum(torch.minimum(position+1, width-position),
545
+ torch.full_like(position, 128)).float()[:, None]
546
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
547
+ part = starts[begin:begin+max(1, 16384//max_len)]
548
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
549
+ hidden, _ = self.encode_residues(tokens, task)
550
+ for j, start in enumerate(part):
551
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
552
+ count.index_add_(0, position+start, weight)
553
+ values = total/count.clamp_min(1)
554
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
555
+ return torch.stack(output)
556
+
557
+ @staticmethod
558
+ def terminal_bins(states, width, bins, align_end=False):
559
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
560
+ assert width > 0 and bins > 0 and width % bins == 0
561
+ states = (states[-width:] if align_end else states[:width]).float()
562
+ count = states.shape[0]
563
+ padded = states.new_zeros(width, states.shape[-1])
564
+ valid = states.new_zeros(width)
565
+ offset = width-count if align_end else 0
566
+ padded[offset:offset+count] = states
567
+ valid[offset:offset+count] = 1
568
+ total = padded.reshape(bins, width//bins, -1).sum(1)
569
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
570
+ return (total/denominator).flatten()
571
+
572
+ def terminal_summary_features(self, task, sequences, device, max_len):
573
+ settings = self.config['terminal_summary_readouts'][task]
574
+ width = max_len-2
575
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
576
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
577
+ hidden, padding = self.encode_residues(tokens, task)
578
+ summary = self.summarize(hidden, tokens, padding, task)
579
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
580
+ tails = {}
581
+ if long_ids:
582
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
583
+ for index in long_ids], device)
584
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
585
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
586
+ terminals = []
587
+ for index, sequence in enumerate(sequences):
588
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
589
+ suffix = tails.get(index, prefix)
590
+ terminals.append(torch.cat([
591
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
592
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
593
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
594
+
595
+ @staticmethod
596
+ def position_features(hidden, lengths, bins):
597
+ features = []
598
+ for index, length in enumerate(lengths):
599
+ if length:
600
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
601
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
602
+ else:
603
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
604
+ return torch.stack(features)
605
+
606
+ def secondary_structure_summary(self, sequences, device, max_len):
607
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
608
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
609
+ with torch.autocast(device_type=device.type,enabled=False):
610
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
611
+ summaries=[]
612
+ for index,sequence in enumerate(sequences):
613
+ length=min(len(sequence),max_len-2)
614
+ if not length:
615
+ summaries.append(probabilities.new_zeros(40));continue
616
+ value=probabilities[index,1:1+length]
617
+ mean=value.mean(0);std=value.std(0,unbiased=False)
618
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
619
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
620
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
621
+ return torch.stack(summaries)
622
+
623
+ def normalize(self, task, values):
624
+ stats = self.config.get('regression_stats', {}).get(task)
625
+ return (values - stats['mean']) / stats['std'] if stats else values
626
+
627
+ def unscale(self, task, values):
628
+ stats = self.config.get('regression_stats', {}).get(task)
629
+ return values * stats['std'] + stats['mean'] if stats else values
630
+
631
+ def transfer(self, state, normalized_source=False):
632
+ """Transfer our own lineage only; retain random init for new parameters."""
633
+ current = self.state_dict()
634
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
635
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
636
+ if not normalized_source:
637
+ with torch.no_grad():
638
+ for task, stats in self.config.get('regression_stats', {}).items():
639
+ # Preserve predictions when moving a trained head to standardized units.
640
+ if f'heads.{task}.3.weight' in fitting:
641
+ self.heads[task][3].weight.div_(stats['std'])
642
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
643
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-stability-lengthweight1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 214711015
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ One shared rotary transformer serves all eleven tasks: 12 layers, width 512,
4
+ 8 attention heads, plus two shared extension blocks. Exact parameter count:
5
+ **53,000,306 total**, **44,150,303 encoder**, including **37,845,535 original
6
+ encoder parameters used by every task**. Beta-lactamase and stability use both
7
+ extension blocks; other tasks use the original encoder exit.
8
+
9
+ All parameters originated from random initialization and training in this
10
+ session. The common encoder received one hour of MLM on mounted decontaminated
11
+ UniRef50 (1,713,641,682 token presentations), then joint supervision across all
12
+ eleven fit tasks. The retained checkpoint has 600 active seconds / 11,899
13
+ updates. Task conditioning and extension training also used all eleven fit
14
+ tasks. No external weights, embeddings or data were used.
15
+
16
+ Heads:
17
+
18
+ - Fluorescence/beta-lactamase: normalized linear heads over 256/320 interpolated
19
+ residue positions, empirical rank targets and ridge 1.
20
+ - Fold, solubility and both localization tasks: seven-summary normalized linear
21
+ heads. Binary localization adds a 475,906-parameter nonlinear summary residual
22
+ jointly trained across solubility and both localization tasks.
23
+ - Human PPI: ordered chain summaries, product and absolute difference.
24
+ Yeast/affinity use symmetric averages, product and absolute difference. Yeast
25
+ additionally uses shared rank-32 bilinear and 64-bin residue interaction
26
+ modules, each jointly trained across all three PPI tasks.
27
+ - Stability: MLP with normalized final linear head; the six learned head
28
+ tensors use the fixed continuation midpoint described below.
29
+ - Secondary structure: local convolution and residue MLP with normalized final
30
+ layer. Its head received 64 supervised epochs and 64 distillation epochs on
31
+ 2,221,507 valid fit residues, combining equal hard CE and temperature-2 KL.
32
+ The teacher was an own-session 85M model with two-hour MLM and joint all-task
33
+ supervision/conditioning. Teacher parameters and caches are absent here.
34
+
35
+ Fold, fluorescence, beta-lactamase and affinity heads retain the parent fit+tune label fits. Each recipe passed a two-half added-label pilot before fitting the full permitted pool. Their production Tune scores and aggregate are in-sample and excluded from development selection.
36
+
37
+ Stability starts from the previously selected fit-only head (including its
38
+ earlier continuation midpoint). The new study compared natural weighting with
39
+ equal total loss mass for the 36,446 length-43 and 17,168 length-50 fit rows.
40
+ Both arms used identical batches, dropout RNG and 1,680 updates: whole-head
41
+ AdamW, peak lr 0.0001, weight decay 0.01, batch 512, 16 epochs, cosine decay to
42
+ 10%, original fit-standardized MSE, clipping 1. Feature-normalization buffers
43
+ were fixed. Only the predeclared final 50:50 parameter midpoint was eligible;
44
+ raw endpoints and earlier checkpoints were not selected. Balanced weighting
45
+ scored 0.7311607643 on cached Tune features versus 0.7274924149 for its parent
46
+ and 0.7291215997 for the matched control; conditional paired 95% differences
47
+ were [0.0019018632, 0.0054815226] and [0.0012832147, 0.0028118185].
48
+ Complete independent production replay is valid: stability predictions exactly match the accepted fit-only candidate, and all ten other prediction files are byte-identical to the previous production package. Separate fit-only development mean is0.7166638090; stability is0.7311607643. Native paired stability gain is0.0036683835, conditional95%[0.0017767471,0.0054419975].
49
+
50
+ Tune selects regularization, checkpoints, conditioning and task exits. This
51
+ length-weighting hypothesis was informed by the observed Tune length
52
+ distribution. Repeated Tune selection and protein-family dependence are not
53
+ corrected by the conditional intervals. Small PPI splits and weak fold
54
+ generalization remain limitations. SS and pair windows cover full chains;
55
+ other tasks use a 1022-residue prefix. Human windows allow 1536 tokens and
56
+ yeast 1024. GFP/beta rank outputs are not calibrated for absolute error.
57
+ No held-out test measurement is available.
58
+
59
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. This is one parameter set
60
+ and needs no live trainer, research files, feature cache, sequence lookup,
61
+ prediction ensemble or test-time fitting.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/config.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ]
134
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/provenance.json ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "parent_package": "/workspace/research/production-stability-midpoint1/candidate/package",
3
+ "parent_sha256": "5a5e8f90a608f84f0592bad0213117ba9b3d056d6dc3feb325965a830f25a3e0",
4
+ "parent_provenance": {
5
+ "method": "Retain production model and replace only six stability head tensors with the accepted fit-only parameter midpoint.",
6
+ "production_parent": "/workspace/research/production-fullpool-summary1/candidate/package",
7
+ "production_parent_sha256": "195b60bcb0833ce75ed07c8846fb50ccd840c137ee4f4616d9c8b5d1427107a9",
8
+ "development": "/workspace/research/selected-stability-midpoint1/candidate/package",
9
+ "development_sha256": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c",
10
+ "parent_provenance": {
11
+ "method": "Retain every production tensor and add the accepted jointly trained nonlinear summary residual.",
12
+ "production_parent": "/workspace/research/production-fullpool-ss-distill64/candidate/package",
13
+ "production_parent_sha256": "37fc717aeb0cab3f68c4311ac9b5d6c8b0a56aecad738ab093bd4d986ea4c766",
14
+ "addition_source": "/workspace/research/shared-summary-residual1/candidate/package",
15
+ "addition_source_sha256": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
16
+ "added_parameters": 475906,
17
+ "parameters": 53000306,
18
+ "original_production_tensors_exact": true,
19
+ "one_shared_encoder_for_all_tasks": true,
20
+ "data": "Own from-scratch shared lineage; fit-only residual gradients and normalization; tune model selection. Fold/GFP/beta/affinity retain permitted fit+tune heads.",
21
+ "changed_tasks": [
22
+ "binary_localization"
23
+ ],
24
+ "tasks_reusing_tune_labels": [
25
+ "fold",
26
+ "fluorescence",
27
+ "beta_lactamase",
28
+ "ppi_affinity"
29
+ ],
30
+ "feature_cache_exported": false,
31
+ "inference_dependencies_outside_package": false
32
+ },
33
+ "development_provenance": {
34
+ "method": "One fixed 50:50 parameter midpoint of parent and fit-only 16-epoch stability head continuation; no ensemble.",
35
+ "source_parent": "/workspace/research/shared-summary-residual1/candidate/package",
36
+ "source_candidate": "/workspace/research/selected-stability-head64/candidate/package",
37
+ "source_model_sha256": {
38
+ "/workspace/research/shared-summary-residual1/candidate/package": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
39
+ "/workspace/research/selected-stability-head64/candidate/package": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79"
40
+ },
41
+ "parent_provenance": {
42
+ "method": "One jointly learned nonlinear residual map over frozen shared sequence summaries, with task-specific zero-initialized outputs.",
43
+ "fit_tasks": [
44
+ "solubility",
45
+ "subcellular_localization",
46
+ "binary_localization"
47
+ ],
48
+ "selected_tasks": [
49
+ "binary_localization"
50
+ ],
51
+ "selected_global_step": 3000,
52
+ "source": "/workspace/research/ss-distillation-continuation1/candidate/package",
53
+ "export_base": "/workspace/research/ss-distillation-continuation1/candidate/package",
54
+ "export_base_model_sha256": "4fee0a0154af24665de9a95f11a722017f3fa6d92354475bec8e81235a219f00",
55
+ "rebased_SS_tensors": [],
56
+ "seed": 20270102,
57
+ "steps": 6000,
58
+ "lr": 0.001,
59
+ "weight_decay": 0.01,
60
+ "dropout": 0.2,
61
+ "data": "Fit only for gradients and existing normalization; Tune chooses oneglobalcheckpoint andresidualexits usingpredeclaredconditionalCIgate.",
62
+ "original_parameters_exact": true,
63
+ "parameters": 53000306,
64
+ "encoder_parameters": 44150303,
65
+ "feature_cache_exported": false
66
+ },
67
+ "fit_recipe": {
68
+ "seed": 20270129,
69
+ "epochs": 64,
70
+ "evaluate_epochs": [
71
+ 4,
72
+ 16,
73
+ 32,
74
+ 64
75
+ ],
76
+ "batch_size": 512,
77
+ "lr": 0.0001,
78
+ "weight_decay": 0.01,
79
+ "loss": "MSE to original fit-standardized stabilitylabels, matching selectedmodeltarget semantics;clip1;originaldropout active inbotharms;fixednormalizationbuffers. No newranktargetchange.",
80
+ "optimizer": "FreshCPUAdamW,cosine64epochs to0.1floor; matcheddataorder/dropoutRNG/updatecounts; per-epochatomicresume."
81
+ },
82
+ "source_selected_epoch": 16,
83
+ "diagnostic": {
84
+ "utc": "2026-10-25T13:39:33.197851+00:00",
85
+ "status": "CPU_diagnostic_complete_no_export",
86
+ "alpha": 0.5,
87
+ "points": {
88
+ "parent": 0.7226969980994319,
89
+ "midpoint": 0.7274924148853711,
90
+ "whole": 0.7274598466634085
91
+ },
92
+ "midpoint_delta_vs_parent": 0.004795416785939199,
93
+ "conditional95": [
94
+ 0.0017412267324550784,
95
+ 0.007940572842815559
96
+ ],
97
+ "draws": 1000,
98
+ "seed": 20270130,
99
+ "parameters": 53000306,
100
+ "six_changed_learned_tensors": [
101
+ "heads.stability.0.weight",
102
+ "heads.stability.0.bias",
103
+ "heads.stability.2.weight",
104
+ "heads.stability.2.bias",
105
+ "heads.stability.3.linear.weight",
106
+ "heads.stability.3.linear.bias"
107
+ ],
108
+ "all_other_tensors_and_buffers_exact": true,
109
+ "eligible_for_manual_complete_replay": true,
110
+ "publication": false,
111
+ "GPU_used": false,
112
+ "limitations": "Singlepredeclaredparameter midpoint, notpredictionensemble. Conditionalrowbootstrapuncorrectedforpriorcheckpointselectionandfamilydependence. CPUdiagnosticisnotan11taskreplay.",
113
+ "source_sha256": {
114
+ "/workspace/research/check_selected_stability_midpoint.py": "13615a5b2689a0bd503cbc8a9a8a722014962677f6769cec871e13aa5133ff77",
115
+ "/workspace/research/shared-summary-residual1/candidate/package/model.pt": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
116
+ "/workspace/research/selected-stability-head64/candidate/package/model.pt": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79"
117
+ }
118
+ },
119
+ "data": "Fit-only labels and fixed normalization; tune selects epoch and evaluates one predeclared midpoint.",
120
+ "parameters": 53000306,
121
+ "feature_cache_exported": false
122
+ },
123
+ "parameters": 53000306,
124
+ "all_other_production_tensors_exact": true,
125
+ "data": "Mounted fit labels and own from-scratch shared encoder lineage; tune model selection for stability. Four prior fullpool heads retain their permitted fit+tune training and crossfit evidence.",
126
+ "tasks_reusing_tune_labels": [
127
+ "fold",
128
+ "fluorescence",
129
+ "beta_lactamase",
130
+ "ppi_affinity"
131
+ ],
132
+ "feature_cache_exported": false,
133
+ "inference_dependencies_outside_package": false
134
+ },
135
+ "fit_plan": {
136
+ "utc": "2026-10-25T16:08:33.461759+00:00",
137
+ "status": "queued",
138
+ "CPU_only": true,
139
+ "recovery_registered": false,
140
+ "source_package": "/workspace/research/selected-stability-midpoint1/candidate/package",
141
+ "source_report": "/workspace/research/selected-stability-midpoint1/candidate/report.json",
142
+ "features": "/workspace/research/rank-target-functions2/features-stability",
143
+ "feature_producer": "/workspace/research/rank-target-fluorescence1/candidate/package",
144
+ "arms": [
145
+ "natural",
146
+ "balanced"
147
+ ],
148
+ "expected_fit_lengths": [
149
+ 43,
150
+ 50
151
+ ],
152
+ "seed": 20270208,
153
+ "threads": 6,
154
+ "epochs": 16,
155
+ "batch_size": 512,
156
+ "lr": 0.0001,
157
+ "weight_decay": 0.01,
158
+ "alpha": 0.5,
159
+ "minimum_gain": 0.001,
160
+ "bootstrap_seed": 20270209,
161
+ "bootstrap_draws": 1000,
162
+ "hypothesis": "Natural stability fit data are68%43-residue proteins but all observed Tune chains have50residues. Equal loss mass for the two fit-length groups may reduce interference on the50-residue domain. This is a test prompted by visible Tune distribution, not evidence of benefit.",
163
+ "loss": "Original-fit-standardized-label MSE. Identical shuffled full-fit batches in both arms; natural unit weights; balanced weights N/(2*N_group), averaged over minibatch without per-batch renormalization. Both train all six existing head tensors, fixed feature-normalization buffers.",
164
+ "schedule": "FreshAdamW,16epochs/1680updates,cosine to0.1floor,clip1; originaldropoutactive with identical RNG and data order. Same current selected initial head.",
165
+ "selection": "Only one fixed50:50 parameter midpoint at the final16epoch endpoint per arm is eligible. Raw endpoints are descriptive. Require gain>=.001 and positive conditional95versus selected; balanced additionally requires positive conditional95versus natural control. No intermediate Tune selection, no seed/mixture grid. Manual review then full11 native replay before any publication.",
166
+ "all_task_policy": "Only six stabilityheadparameters may change. Shared encoder remains jointly learned for all11. All10otherparameters/config/outputfiles must remain exact on native replay. No automatic export or publication.",
167
+ "resume": "CPU per-epoch atomic optimizer/head/NumPy/torchRNG checkpoints; rerun same script after interruption. Planhash verified on resume.",
168
+ "recovery_command": [
169
+ "env",
170
+ "CUDA_VISIBLE_DEVICES=",
171
+ "OMP_NUM_THREADS=6",
172
+ "MKL_NUM_THREADS=6",
173
+ "OPENBLAS_NUM_THREADS=1",
174
+ "python3",
175
+ "-u",
176
+ "/workspace/research/run_stability_length_weighting.py",
177
+ "--run",
178
+ "/workspace/research/selected-stability-lengthweight1"
179
+ ],
180
+ "frozen_sha256": {
181
+ "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6",
182
+ "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990",
183
+ "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632",
184
+ "/workspace/research/stability-length-shift-diagnostic.json": "36a890f702bb6709e893c5f9d94c5cf15959f83f4a91d71e58a7b5f681065f6d",
185
+ "/workspace/research/selected-stability-midpoint1/candidate/report.json": "feedb171d285a4fa4d3c2a2bdd819873caaad1308ef90fd59df9df1ace166827",
186
+ "/workspace/research/selected-stability-midpoint1/candidate/package/model.pt": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c",
187
+ "/workspace/research/selected-stability-midpoint1/candidate/package/config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625",
188
+ "/workspace/research/selected-stability-midpoint1/candidate/package/unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3",
189
+ "/workspace/research/selected-stability-midpoint1/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9",
190
+ "/workspace/research/selected-stability-midpoint1/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85",
191
+ "/workspace/research/selected-stability-midpoint1/candidate/package/infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468",
192
+ "/workspace/research/rank-target-fluorescence1/candidate/package/model.pt": "a13dad3c4f0cd7a1917d5b6763b27aaf3d38f3b7d775e747b61241ea36b681e0",
193
+ "/workspace/research/rank-target-fluorescence1/candidate/package/config.json": "e3da1d0ea2df3e6d6cc8b069016bffca2a37fd05accf1597cc6453f946d8fd89",
194
+ "/workspace/research/rank-target-functions2/features-stability/stability-fit.pt": "3fde47645a74370a003dd5f509a73ccecbaaac36ce4e8871938979a003ba3862",
195
+ "/workspace/research/rank-target-functions2/features-stability/stability-tune.pt": "92066e0c8abfcfc4ac3b8f2c7edcc4319cb8f8b4b97b53dd6e589147a1c460bf"
196
+ }
197
+ },
198
+ "fit_outcome": {
199
+ "utc": "2026-10-25T16:08:53.918703+00:00",
200
+ "status": "cached_analysis_complete",
201
+ "arms": {
202
+ "natural": {
203
+ "arm": "natural",
204
+ "endpoint_reward": 0.7291215996959544,
205
+ "raw_reward_descriptive_only": 0.72991937369715,
206
+ "step": 1680,
207
+ "active_seconds": 5.326252081984421,
208
+ "final_numpy_rng": {
209
+ "bit_generator": "PCG64",
210
+ "state": {
211
+ "state": 264542032468656517169208881192101401107,
212
+ "inc": 100251262600960163324587047460976422035
213
+ },
214
+ "has_uint32": 1,
215
+ "uinteger": 637011686
216
+ },
217
+ "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52",
218
+ "optimizer_steps": [
219
+ 1680.0
220
+ ],
221
+ "lr": 1.0000078679859099e-05,
222
+ "fixed_buffers_exact": true
223
+ },
224
+ "balanced": {
225
+ "arm": "balanced",
226
+ "endpoint_reward": 0.7311607642876724,
227
+ "raw_reward_descriptive_only": 0.7330130871638806,
228
+ "step": 1680,
229
+ "active_seconds": 5.340115340979537,
230
+ "final_numpy_rng": {
231
+ "bit_generator": "PCG64",
232
+ "state": {
233
+ "state": 264542032468656517169208881192101401107,
234
+ "inc": 100251262600960163324587047460976422035
235
+ },
236
+ "has_uint32": 1,
237
+ "uinteger": 637011686
238
+ },
239
+ "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52",
240
+ "optimizer_steps": [
241
+ 1680.0
242
+ ],
243
+ "lr": 1.0000078679859099e-05,
244
+ "fixed_buffers_exact": true
245
+ }
246
+ },
247
+ "comparisons": {
248
+ "natural_vs_parent": {
249
+ "delta": 0.001629184810583273,
250
+ "conditional_95": [
251
+ 0.00024683637661263025,
252
+ 0.003237432482155497
253
+ ]
254
+ },
255
+ "balanced_vs_parent": {
256
+ "delta": 0.0036683494023013186,
257
+ "conditional_95": [
258
+ 0.0019018632266723152,
259
+ 0.0054815225624275
260
+ ]
261
+ },
262
+ "balanced_vs_natural": {
263
+ "delta": 0.0020391645917180456,
264
+ "conditional_95": [
265
+ 0.0012832147204794586,
266
+ 0.0028118185483942955
267
+ ]
268
+ }
269
+ },
270
+ "eligible_arms": [
271
+ "natural",
272
+ "balanced"
273
+ ],
274
+ "published": false,
275
+ "GPU_used": false,
276
+ "candidate_exported": false,
277
+ "matched_order_dropout_optimizer_clocks": true,
278
+ "ten_other_tasks": "No state edited; any proposed export must keep their parameters/configuration exact and independently replay all eleven.",
279
+ "limitations": "Conditional example bootstrap after repeated tune inspection; family dependence and selection uncertainty omitted. Tune length distribution informed this hypothesis. Raw endpoints are descriptive only. No full-pool or test-time fitting."
280
+ },
281
+ "changed_tensors": [
282
+ "heads.stability.0.weight",
283
+ "heads.stability.0.bias",
284
+ "heads.stability.2.weight",
285
+ "heads.stability.2.bias",
286
+ "heads.stability.3.linear.weight",
287
+ "heads.stability.3.linear.bias"
288
+ ],
289
+ "all_other_tensors_and_buffers_exact": true,
290
+ "method": "One fixed final balanced-length continuation midpoint; no output averaging or test-time fitting."
291
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/replay.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained replay shared by research evaluation and frozen packages."""
3
+ import contextlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ import esm2
12
+
13
+ TASKS = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
14
+ 'subcellular_localization', 'binary_localization', 'fold',
15
+ 'secondary_structure', 'yeast_ppi', 'human_ppi', 'ppi_affinity')
16
+
17
+
18
+ def autocast(device):
19
+ return torch.autocast('cuda', dtype=torch.bfloat16) if device.type == 'cuda' else contextlib.nullcontext()
20
+
21
+
22
+ def head_output(model, task, representation, device, fp32=False):
23
+ apply = model.apply_head if hasattr(model, 'apply_head') else lambda task, value: model.heads[task](value)
24
+ if fp32:
25
+ with torch.autocast(device.type, enabled=False):
26
+ values={k:v.float() if v.is_floating_point() else v for k,v in representation.items()} if isinstance(representation,dict) else representation.float()
27
+ return apply(task, values).float()
28
+ return apply(task, representation).float()
29
+
30
+
31
+ def residue_states(model, tokens, task):
32
+ return model.encode_residues(tokens, task) if hasattr(model, 'encode_residues') else model.encoder(tokens)
33
+
34
+
35
+ def windows(length, width=1022, stride=768):
36
+ if length <= width:
37
+ return [(0, length)]
38
+ starts = list(range(0, length - width + 1, stride))
39
+ if starts[-1] != length - width:
40
+ starts.append(length - width)
41
+ return [(s, min(s + width, length)) for s in starts]
42
+
43
+
44
+ def batches(rows, task, token_budget=16384, max_len=1024, max_batch=128):
45
+ lengths = [min(max(map(len, r['features'].values())) + 2, max_len) for r in rows]
46
+ order = sorted(range(len(rows)), key=lengths.__getitem__)
47
+ current, width = [], 0
48
+ for i in order:
49
+ length = lengths[i]
50
+ # Pair sequences require two separate passes, but the peak tensor size is unchanged.
51
+ if current and (max(width, length) * (len(current) + 1) > token_budget or len(current) >= max_batch):
52
+ yield current
53
+ current, width = [], 0
54
+ current.append(i)
55
+ width = max(width, length)
56
+ if current:
57
+ yield current
58
+
59
+
60
+ @torch.inference_mode()
61
+ def predict_records(model, rows, task, device, config=None, token_budget=16384):
62
+ config = config or {}
63
+ max_len = config.get('task_max_len', {}).get(task, config.get('max_len', 1024))
64
+ full_ss = config.get('full_ss', True)
65
+ fp32_option = config.get('fp32_heads', False)
66
+ fp32_heads = fp32_option is True or (isinstance(fp32_option, list) and task in fp32_option)
67
+ was_training = model.training
68
+ model.eval()
69
+ result = {}
70
+ for ids in batches(rows, task, token_budget, max_len):
71
+ chunk = [rows[i] for i in ids]
72
+ features = [r['features'] for r in chunk]
73
+ if task == 'secondary_structure':
74
+ if full_ss and any(len(f['sequence']) > max_len - 2 for f in features):
75
+ for record in chunk:
76
+ seq = record['features']['sequence']
77
+ pieces = windows(len(seq), max_len - 2, min(768, max_len - 2))
78
+ total = np.zeros((len(seq), 3), dtype=np.float32)
79
+ weight_sum = np.zeros((len(seq), 1), dtype=np.float32)
80
+ for begin in range(0, len(pieces), max(1, token_budget // max_len)):
81
+ part = pieces[begin:begin + max(1, token_budget // max_len)]
82
+ tokens = esm2.pad_batch([esm2.encode(seq[s:e], max_len) for s, e in part], device)
83
+ with autocast(device):
84
+ hidden, _ = residue_states(model, tokens, task)
85
+ logits = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
86
+ for j, (s, e) in enumerate(part):
87
+ size = e - s
88
+ # Smooth boundaries, without discarding any residue.
89
+ weight = np.minimum(np.arange(1, size + 1), np.arange(size, 0, -1))
90
+ weight = np.minimum(weight, 128).astype(np.float32)[:, None]
91
+ total[s:e] += logits[j, 1:1+size] * weight
92
+ weight_sum[s:e] += weight
93
+ scores = total / np.maximum(weight_sum, 1)
94
+ result[record['example_id']] = {'ss3_scores': scores.tolist()}
95
+ else:
96
+ tokens = esm2.pad_batch([esm2.encode(f['sequence'], max_len) for f in features], device)
97
+ with autocast(device):
98
+ hidden, _ = residue_states(model, tokens, task)
99
+ probabilities = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
100
+ for j, record in enumerate(chunk):
101
+ length = len(record['features']['sequence'])
102
+ used = min(length, max_len - 2)
103
+ scores = probabilities[j, 1:1+used].tolist()
104
+ scores.extend([[1.0, 1.0, 1.0] for _ in range(length-used)])
105
+ result[record['example_id']] = {'ss3_scores': scores}
106
+ continue
107
+ with autocast(device):
108
+ representation = model.represent(task, features, device, max_len)
109
+ output = head_output(model, task, representation, device, fp32_heads)
110
+ if task in model.CLASSES:
111
+ output = output.softmax(-1)
112
+ if task in config.get('symmetric_pairs', []):
113
+ swapped = [{'sequence_a': f['sequence_b'], 'sequence_b': f['sequence_a']} for f in features]
114
+ swapped_rep = model.represent(task, swapped, device, max_len)
115
+ second = head_output(model, task, swapped_rep, device, fp32_heads)
116
+ if task in model.CLASSES:
117
+ second = second.softmax(-1)
118
+ output = (output + second) * 0.5
119
+ if task in model.CLASSES:
120
+ output = output.clamp_min(1e-9)
121
+ elif hasattr(model, 'unscale'):
122
+ output = model.unscale(task, output)
123
+ values = output.cpu().tolist()
124
+ for record, value in zip(chunk, values):
125
+ result[record['example_id']] = {'scores': value} if task in model.CLASSES else {'value': value[0]}
126
+ if task == 'secondary_structure' and hasattr(model, 'ss_chain_decoder'):
127
+ # Decode complete chains only after all overlapping-window probabilities
128
+ # have been aggregated. No labels or parameter updates enter replay.
129
+ identifiers = [record['example_id'] for record in rows]
130
+ probabilities = [result[identifier]['ss3_scores'] for identifier in identifiers]
131
+ decoded = model.ss_chain_decoder.decode(probabilities)
132
+ for identifier, scores in zip(identifiers, decoded):
133
+ result[identifier] = {'ss3_scores': scores.tolist()}
134
+ model.train(was_training)
135
+ return result
136
+
137
+
138
+ def load_model(package, device):
139
+ config = json.loads((package / 'config.json').read_text())
140
+ if config.get('architecture') == 'unified':
141
+ from unified import UnifiedModel
142
+ model = UnifiedModel(config)
143
+ else:
144
+ model = esm2.Model(layers=config['layers'], dim=config['dim'], heads=config['heads'])
145
+ model.load_state_dict(torch.load(package / 'model.pt', map_location='cpu', weights_only=True))
146
+ return model.to(device).eval(), config
147
+
148
+
149
+ def main():
150
+ if len(sys.argv) != 3:
151
+ raise SystemExit('usage: replay.py INPUT_ROOT OUTPUT_ROOT')
152
+ torch.set_num_threads(6)
153
+ source, destination = Path(sys.argv[1]), Path(sys.argv[2]) / 'predictions'
154
+ destination.mkdir(parents=True, exist_ok=True)
155
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
+ model, config = load_model(Path(__file__).resolve().parent, device)
157
+ for task in TASKS:
158
+ rows = [json.loads(line) for line in (source / f'{task}.jsonl').open()]
159
+ predictions = predict_records(model, rows, task, device, config)
160
+ with (destination / f'{task}.jsonl').open('w') as sink:
161
+ for row in rows:
162
+ sink.write(json.dumps({'example_id': row['example_id'], 'prediction': predictions[row['example_id']]}, separators=(',', ':')) + '\n')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/selection.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_and_ppi_affinity",
3
+ "tasks_reusing_tune_labels": [
4
+ "fold",
5
+ "fluorescence",
6
+ "beta_lactamase",
7
+ "ppi_affinity"
8
+ ],
9
+ "fit_only_development_reward": 0.7166638090200526,
10
+ "stability_fit_only_evidence": {
11
+ "kind": "fit_only_complete_tune_replay",
12
+ "task": "stability",
13
+ "before": 0.7274923808177973,
14
+ "after": 0.7311607642876724,
15
+ "delta": 0.0036683834698750806,
16
+ "conditional_95_percentile_interval": [
17
+ 0.0017767471141417273,
18
+ 0.00544199745819068
19
+ ],
20
+ "examples": 2512,
21
+ "mean_delta": 0.0003334894063522801,
22
+ "conditional_mean95": [
23
+ 0.0001615224649219752,
24
+ 0.0004947270416536983
25
+ ],
26
+ "matched_natural_mixture_control": {
27
+ "delta": 0.0020391645917180456,
28
+ "conditional_95": [
29
+ 0.0012832147204794586,
30
+ 0.0028118185483942955
31
+ ]
32
+ },
33
+ "fixed_endpoint_updates": 1680,
34
+ "alpha": 0.5,
35
+ "ten_other_prediction_files_exact": true,
36
+ "limitations": "Conditional on already-selected models. Does not account for repeated tune selection, shared proteins across tasks, or family dependence within splits; not an independent generalization guarantee. The visible Tune length distribution informed the group-weighting hypothesis."
37
+ },
38
+ "production_aggregate_excluded_from_selection": true,
39
+ "pending_independent_replay": false,
40
+ "stability_length_weighting": "balanced",
41
+ "stability_weighting_endpoint_epochs": 16,
42
+ "stability_weighting_parameter_midpoint": 0.5,
43
+ "independent_replay_verified": true,
44
+ "other_ten_predictions_exact_previous_production": true,
45
+ "stability_predictions_exact_accepted_development": true
46
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S053/unified.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class ResidualSequenceConvHead(nn.Module):
117
+ """Learn local sequence motifs alongside the retained summary classifier."""
118
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
119
+ super().__init__()
120
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
121
+ self.register_buffer('mean', torch.zeros(dim))
122
+ self.register_buffer('scale', torch.ones(dim))
123
+ self.project = nn.Linear(dim, channels)
124
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
125
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
126
+ self.output = nn.Linear(4 * channels, outputs)
127
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
128
+ self.dropout = dropout
129
+
130
+ def forward(self, features):
131
+ valid = features['valid'].bool().unsqueeze(-1)
132
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
133
+ summaries = []
134
+ for conv,norm in zip(self.convs,self.norms):
135
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
136
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
137
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
138
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
139
+ summaries.extend([center,maximum])
140
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
141
+ logits=self.output(pooled)
142
+ return self.base(features['summary']) + logits if self.base is not None else logits
143
+
144
+
145
+ class TokenLogMeanExpHead(nn.Module):
146
+ """Class-specific local evidence, pooled without sequence-length bias."""
147
+ def __init__(self, dim, outputs):
148
+ super().__init__()
149
+ self.register_buffer('mean', torch.zeros(dim))
150
+ self.register_buffer('scale', torch.ones(dim))
151
+ self.linear = nn.Linear(dim, outputs)
152
+
153
+ def forward(self, representation):
154
+ values, valid = representation['hidden'].float(), representation['valid']
155
+ logits = self.linear((values-self.mean)/self.scale)
156
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
157
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
158
+
159
+ def packed(self, values, lengths):
160
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
161
+ logits = self.linear((values.float()-self.mean)/self.scale)
162
+ # The stabilizing maximum cancels in the derivative; detach avoids
163
+ # retaining another large token-by-class gradient path.
164
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
165
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
166
+ output_size=len(values))
167
+ exponent = (logits-maximum[index]).exp()
168
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
169
+ return maximum+total.log()-lengths.float().log()[:, None]
170
+
171
+
172
+ class SharedPairResidueInteraction(nn.Module):
173
+ """A shared nonlinear comparison of local states from both protein chains."""
174
+ def __init__(self, dim, settings, classes):
175
+ super().__init__()
176
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
177
+ self.register_buffer('mean', torch.zeros(dim))
178
+ self.register_buffer('scale', torch.ones(dim))
179
+ self.project = nn.Linear(dim, width)
180
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
181
+ nn.Linear(hidden, channels), nn.GELU())
182
+ self.dropout = settings['dropout']
183
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
184
+ for task in sorted(esm2.Model.PAIR)})
185
+ for head in self.heads.values():
186
+ nn.init.zeros_(head.weight)
187
+ nn.init.zeros_(head.bias)
188
+
189
+ def forward(self, task, first, second):
190
+ first = F.gelu(self.project((first-self.mean)/self.scale))
191
+ second = F.gelu(self.project((second-self.mean)/self.scale))
192
+ first = F.dropout(first, self.dropout, self.training)
193
+ second = F.dropout(second, self.dropout, self.training)
194
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
195
+ first[:, :, None]*second[:, None, :]], dim=-1)
196
+ local = self.compare(pair)
197
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
198
+ return self.heads[task](summary)
199
+
200
+
201
+ class SSChainDecoder(nn.Module):
202
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
203
+ def __init__(self):
204
+ super().__init__()
205
+ self.transition = nn.Parameter(torch.empty(3, 3))
206
+ self.start = nn.Parameter(torch.empty(3))
207
+ self.end = nn.Parameter(torch.empty(3))
208
+ for parameter in self.parameters():
209
+ nn.init.normal_(parameter, std=.01)
210
+
211
+ def decode(self, probabilities):
212
+ from ss_chain import decode_probabilities
213
+ values = [parameter.detach().double().cpu().numpy()
214
+ for parameter in (self.transition, self.start, self.end)]
215
+ return decode_probabilities(probabilities, *values)
216
+
217
+
218
+ class UnifiedModel(esm2.Model):
219
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
220
+ 'subcellular_localization', 'binary_localization', 'fold',
221
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
222
+
223
+ def __init__(self, config):
224
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
225
+ self.config = config
226
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
227
+ dim = config['dim']
228
+ if config.get('extension_layers', 0):
229
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
230
+ before_norm=config.get('extension_before_norm', False))
231
+ if config.get('task_conditioning', False):
232
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
233
+ if config.get('pooling', 'mean') == 'rich':
234
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
235
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
236
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
237
+ self.pool_fuse = nn.Linear(6 * dim, dim)
238
+ nn.init.zeros_(self.pool_fuse.weight)
239
+ nn.init.zeros_(self.pool_fuse.bias)
240
+ if config.get('pair_interaction', False):
241
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
242
+ nn.init.zeros_(self.pair_fuse.weight)
243
+ nn.init.zeros_(self.pair_fuse.bias)
244
+ if config.get('ss_context', False):
245
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
246
+ for task in config.get('linear_heads', []):
247
+ width = dim * 2 if task in self.PAIR else dim
248
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
249
+ for task, settings in config.get('residue_readouts', {}).items():
250
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
251
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
252
+ bins = config['residue_readouts'][task]['bins']
253
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
254
+ for task in config.get('summary_readouts', []):
255
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
256
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
257
+ for task in config.get('sequence_composition_readouts', []):
258
+ from sequence_composition import WIDTH
259
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
260
+ assert all(task not in config.get(key,[]) for key in
261
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
262
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
263
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
264
+ for task, temperature in config.get('cosine_heads', {}).items():
265
+ assert task in config.get('summary_readouts', [])
266
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
267
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
268
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
269
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
270
+ for task in config.get('calibrated_heads', []):
271
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
272
+ assert task not in config.get('linear_heads', [])
273
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
274
+ for task in config.get('expanded_pair_readouts', []):
275
+ assert task in self.PAIR
276
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
277
+ if task in config.get('pair_summary_readouts', []):
278
+ assert config.get('pooling') == 'rich'
279
+ width *= 8
280
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
281
+ if config.get('ss_linear_context'):
282
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
283
+ if config.get('ss_calibrated'):
284
+ assert not config.get('ss_linear_context')
285
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
286
+ for task in config.get('ss_summary_readouts', []):
287
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
288
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
289
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
290
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
291
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
292
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
293
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
294
+ assert all(task not in config.get(key, {}) for key in
295
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
296
+ bins = settings['bins']
297
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
298
+ for key in ['prefix_residues', 'suffix_residues'])
299
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
300
+ if config.get('pair_bilinear_rank', 0):
301
+ rank = config['pair_bilinear_rank']
302
+ assert not config.get('pair_summary_readouts')
303
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
304
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
305
+ with torch.no_grad():
306
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
307
+ self.pair_bilinear_heads = nn.ModuleDict({
308
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
309
+ for task in sorted(self.PAIR)})
310
+ for head in self.pair_bilinear_heads.values():
311
+ nn.init.zeros_(head.weight)
312
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
313
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
314
+ if config.get('pair_residue_interaction'):
315
+ self.pair_residue_interaction = SharedPairResidueInteraction(
316
+ dim, config['pair_residue_interaction'], self.CLASSES)
317
+ for task in config.get('token_logmeanexp_heads', []):
318
+ assert task in self.CLASSES and task not in self.PAIR
319
+ assert task not in config.get('sequence_windows', [])
320
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
321
+ if config.get('ss_chain_decoder', False):
322
+ self.ss_chain_decoder = SSChainDecoder()
323
+ if config.get('shared_summary_residual'):
324
+ settings = config['shared_summary_residual']
325
+ tasks = settings['tasks']
326
+ assert all(task in config.get('summary_readouts', []) and
327
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
328
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
329
+ {task: self.CLASSES[task] for task in tasks})
330
+
331
+ def pair_representation(self, task, first, second, base):
332
+ if task in self.config.get('pair_bilinear_tasks', []):
333
+ return {'base': base, 'chain_a': first, 'chain_b': second}
334
+ return base
335
+
336
+ def apply_head(self, task, representation):
337
+ if task in self.config.get('summary_residual_tasks', []):
338
+ head = self.heads[task]
339
+ normalized = (representation-head.mean)/head.scale
340
+ return head(representation) + self.summary_residual(task, normalized)
341
+ if isinstance(representation, dict) and 'residue_a' in representation:
342
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
343
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
344
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
345
+ if isinstance(representation, dict) and 'chain_a' in representation:
346
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
347
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
348
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
349
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
350
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
351
+ return self.heads[task](representation)
352
+
353
+ def encode_residues(self, tokens, task):
354
+ condition = None
355
+ if self.config.get('task_conditioning', False):
356
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
357
+ condition = self.task_condition[ti]
358
+ return self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
359
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
360
+
361
+ def pool(self, tokens, task):
362
+ hidden, pad_mask = self.encode_residues(tokens, task)
363
+ return self.summarize(hidden, tokens, pad_mask, task)
364
+
365
+ def summarize(self, hidden, tokens, pad_mask, task):
366
+ valid = (~pad_mask).unsqueeze(-1)
367
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
368
+ if self.config.get('pooling', 'mean') == 'mean':
369
+ return mean
370
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
371
+ # Empty/nonstandard-only inputs still produce a finite representation.
372
+ residues[:, 0] |= ~residues.any(1)
373
+ keep = residues.unsqueeze(-1)
374
+ count = keep.sum(1).clamp_min(1)
375
+ center = (hidden * keep).sum(1) / count
376
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
377
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
378
+ torch.cos(position * math.pi)], dim=-1)
379
+ ti = self.task_index[task]
380
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
381
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
382
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
383
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
384
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
385
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
386
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
387
+ first = residues & (residues.cumsum(1) <= 32)
388
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
389
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
390
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
391
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
392
+ deviation, maximum, prefix, suffix], dim=-1)
393
+ if task in self.config.get('summary_readouts', []):
394
+ return torch.cat([mean, summary], dim=-1)
395
+ if task in self.config.get('pair_summary_readouts', []):
396
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
397
+ return mean + self.pool_fuse(summary)
398
+
399
+ def pool_sequences(self, sequences, task, device, max_len):
400
+ if self.training and not self.config.get('window_pooling_training', True):
401
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
402
+ return self.pool(tokens,task)
403
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
404
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
405
+ results=[None]*len(sequences)
406
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
407
+ if short:
408
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
409
+ for j,index in enumerate(short):results[index]=pooled[j]
410
+ width=max_len-2;stride=min(768,width)
411
+ if self.training and self.config.get('batch_window_training',False):
412
+ pieces=[];starts_by_index={};encoded={}
413
+ for index,sequence in enumerate(sequences):
414
+ if len(sequence)<=width:continue
415
+ starts=list(range(0,len(sequence)-width+1,stride))
416
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
417
+ starts_by_index[index]=starts
418
+ pieces.extend((index,start) for start in starts)
419
+ count=max(1,16384//max_len)
420
+ for begin in range(0,len(pieces),count):
421
+ part=pieces[begin:begin+count]
422
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
423
+ hidden,_=self.encode_residues(tokens,task)
424
+ for j,key in enumerate(part):encoded[key]=hidden[j]
425
+ positions=torch.arange(width,device=device)
426
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
427
+ for index,starts in starts_by_index.items():
428
+ sequence=sequences[index];length=len(sequence)
429
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
430
+ for start in starts:
431
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
432
+ counts.index_add_(0,positions+start,weight)
433
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
434
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
435
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
436
+ return torch.stack(results)
437
+ for index,sequence in enumerate(sequences):
438
+ length=len(sequence)
439
+ if length<=width:continue
440
+ starts=list(range(0,length-width+1,stride))
441
+ if starts[-1]!=length-width:starts.append(length-width)
442
+ total=torch.zeros(length,self.config['dim'],device=device)
443
+ counts=torch.zeros(length,1,device=device)
444
+ first=last=None
445
+ for begin in range(0,len(starts),max(1,16384//max_len)):
446
+ part=starts[begin:begin+max(1,16384//max_len)]
447
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
448
+ hidden,_=self.encode_residues(tokens,task)
449
+ for j,start in enumerate(part):
450
+ if start==0:first=hidden[j,0:1]
451
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
452
+ positions=torch.arange(width,device=device)
453
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
454
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
455
+ counts.index_add_(0,positions+start,weight)
456
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
457
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
458
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
459
+ return torch.stack(results)
460
+
461
+ def represent(self, task, batch, device, max_len=1024):
462
+ if task in self.config.get('sequence_composition_readouts', []):
463
+ from sequence_composition import composition_features
464
+ sequences=[item['sequence'] for item in batch]
465
+ pooled=self.pool_sequences(sequences,task,device,max_len)
466
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
467
+ if task in self.config.get('token_logmeanexp_heads', []):
468
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
469
+ hidden, _ = self.encode_residues(tokens, task)
470
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
471
+ valid[:, 0] |= ~valid.any(1)
472
+ return {'hidden':hidden, 'valid':valid}
473
+ if task in self.config.get('terminal_summary_readouts', {}):
474
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
475
+ if task in self.config.get('ss_summary_readouts', []):
476
+ sequences=[x['sequence'] for x in batch]
477
+ summary=self.pool_sequences(sequences,task,device,max_len)
478
+ structure=self.secondary_structure_summary(sequences,device,max_len)
479
+ return torch.cat([summary.float(),structure],-1)
480
+ if task in self.config.get('sequence_conv_readouts',{}):
481
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
482
+ hidden,pad_mask=self.encode_residues(tokens,task)
483
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
484
+ width=max(1,int(lengths.max()))
485
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
486
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
487
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
488
+ if task in self.config.get('residue_readouts', {}):
489
+ bins = self.config['residue_readouts'][task]['bins']
490
+ sequences = [x['sequence'] for x in batch]
491
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
492
+ hidden, _ = self.encode_residues(tokens, task)
493
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
494
+ if task in self.PAIR:
495
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
496
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
497
+ if task in self.config.get('expanded_pair_readouts', []):
498
+ if task in self.config.get('symmetric_pair_readouts',[]):
499
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
500
+ else:
501
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
502
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
503
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
504
+ output = torch.cat([a, b], dim=-1)
505
+ if self.config.get('pair_interaction', False):
506
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
507
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
508
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
509
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
510
+
511
+ def add_pair_residues(self, task, batch, device, max_len, base):
512
+ if task not in self.config.get('pair_residue_tasks', []):
513
+ return base
514
+ result = dict(base) if isinstance(base, dict) else {'base': base}
515
+ bins = self.config['pair_residue_interaction']['bins']
516
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
517
+ result['residue_'+role] = self.pool_residue_bins(
518
+ [row[name] for row in batch], task, device, max_len, bins)
519
+ return result
520
+
521
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
522
+ """Average every residue into fixed relative bins, with full-chain context."""
523
+ width = max_len-2
524
+ assert width > 0 and bins > 0
525
+ output = [None]*len(sequences)
526
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
527
+ if short:
528
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
529
+ hidden, _ = self.encode_residues(tokens, task)
530
+ for j, index in enumerate(short):
531
+ length = len(sequences[index])
532
+ values = hidden[j, 1:1+length].float()
533
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
534
+ else torch.zeros(bins, self.config['dim'], device=device))
535
+ for index, sequence in enumerate(sequences):
536
+ if len(sequence) <= width:
537
+ continue
538
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
539
+ if starts[-1] != len(sequence)-width:
540
+ starts.append(len(sequence)-width)
541
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
542
+ count = torch.zeros(len(sequence), 1, device=device)
543
+ position = torch.arange(width, device=device)
544
+ weight = torch.minimum(torch.minimum(position+1, width-position),
545
+ torch.full_like(position, 128)).float()[:, None]
546
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
547
+ part = starts[begin:begin+max(1, 16384//max_len)]
548
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
549
+ hidden, _ = self.encode_residues(tokens, task)
550
+ for j, start in enumerate(part):
551
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
552
+ count.index_add_(0, position+start, weight)
553
+ values = total/count.clamp_min(1)
554
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
555
+ return torch.stack(output)
556
+
557
+ @staticmethod
558
+ def terminal_bins(states, width, bins, align_end=False):
559
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
560
+ assert width > 0 and bins > 0 and width % bins == 0
561
+ states = (states[-width:] if align_end else states[:width]).float()
562
+ count = states.shape[0]
563
+ padded = states.new_zeros(width, states.shape[-1])
564
+ valid = states.new_zeros(width)
565
+ offset = width-count if align_end else 0
566
+ padded[offset:offset+count] = states
567
+ valid[offset:offset+count] = 1
568
+ total = padded.reshape(bins, width//bins, -1).sum(1)
569
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
570
+ return (total/denominator).flatten()
571
+
572
+ def terminal_summary_features(self, task, sequences, device, max_len):
573
+ settings = self.config['terminal_summary_readouts'][task]
574
+ width = max_len-2
575
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
576
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
577
+ hidden, padding = self.encode_residues(tokens, task)
578
+ summary = self.summarize(hidden, tokens, padding, task)
579
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
580
+ tails = {}
581
+ if long_ids:
582
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
583
+ for index in long_ids], device)
584
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
585
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
586
+ terminals = []
587
+ for index, sequence in enumerate(sequences):
588
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
589
+ suffix = tails.get(index, prefix)
590
+ terminals.append(torch.cat([
591
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
592
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
593
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
594
+
595
+ @staticmethod
596
+ def position_features(hidden, lengths, bins):
597
+ features = []
598
+ for index, length in enumerate(lengths):
599
+ if length:
600
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
601
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
602
+ else:
603
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
604
+ return torch.stack(features)
605
+
606
+ def secondary_structure_summary(self, sequences, device, max_len):
607
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
608
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
609
+ with torch.autocast(device_type=device.type,enabled=False):
610
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
611
+ summaries=[]
612
+ for index,sequence in enumerate(sequences):
613
+ length=min(len(sequence),max_len-2)
614
+ if not length:
615
+ summaries.append(probabilities.new_zeros(40));continue
616
+ value=probabilities[index,1:1+length]
617
+ mean=value.mean(0);std=value.std(0,unbiased=False)
618
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
619
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
620
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
621
+ return torch.stack(summaries)
622
+
623
+ def normalize(self, task, values):
624
+ stats = self.config.get('regression_stats', {}).get(task)
625
+ return (values - stats['mean']) / stats['std'] if stats else values
626
+
627
+ def unscale(self, task, values):
628
+ stats = self.config.get('regression_stats', {}).get(task)
629
+ return values * stats['std'] + stats['mean'] if stats else values
630
+
631
+ def transfer(self, state, normalized_source=False):
632
+ """Transfer our own lineage only; retain random init for new parameters."""
633
+ current = self.state_dict()
634
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
635
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
636
+ if not normalized_source:
637
+ with torch.no_grad():
638
+ for task, stats in self.config.get('regression_stats', {}).items():
639
+ # Preserve predictions when moving a trained head to standardized units.
640
+ if f'heads.{task}.3.weight' in fitting:
641
+ self.heads[task][3].weight.div_(stats['std'])
642
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
643
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-stability-lengthweight-fullpool1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 214725002
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ One shared rotary transformer serves all eleven tasks: 12 layers, width 512,
4
+ 8 attention heads, plus two shared extension blocks. Exact parameter count:
5
+ **53,000,306 total**, **44,150,303 encoder**, including **37,845,535 original
6
+ encoder parameters used by every task**. Beta-lactamase and stability use both
7
+ extension blocks; other tasks use the original encoder exit.
8
+
9
+ All parameters originated from random initialization and training in this
10
+ session. The common encoder received one hour of MLM on mounted decontaminated
11
+ UniRef50 (1,713,641,682 token presentations), then joint supervision across all
12
+ eleven fit tasks. The retained checkpoint has 600 active seconds / 11,899
13
+ updates. Task conditioning and extension training also used all eleven fit
14
+ tasks. No external weights, embeddings or data were used.
15
+
16
+ Heads:
17
+
18
+ - Fluorescence/beta-lactamase: normalized linear heads over 256/320 interpolated
19
+ residue positions, empirical rank targets and ridge 1.
20
+ - Fold, solubility and both localization tasks: seven-summary normalized linear
21
+ heads. Binary localization adds a 475,906-parameter nonlinear summary residual
22
+ jointly trained across solubility and both localization tasks.
23
+ - Human PPI: ordered chain summaries, product and absolute difference.
24
+ Yeast/affinity use symmetric averages, product and absolute difference. Yeast
25
+ additionally uses shared rank-32 bilinear and 64-bin residue interaction
26
+ modules, each jointly trained across all three PPI tasks.
27
+ - Stability: MLP with normalized final linear head; the six learned head
28
+ tensors use the fixed continuation midpoint described below.
29
+ - Secondary structure: local convolution and residue MLP with normalized final
30
+ layer. Its head received 64 supervised epochs and 64 distillation epochs on
31
+ 2,221,507 valid fit residues, combining equal hard CE and temperature-2 KL.
32
+ The teacher was an own-session 85M model with two-hour MLM and joint all-task
33
+ supervision/conditioning. Teacher parameters and caches are absent here.
34
+
35
+ Fold, fluorescence, beta-lactamase and affinity heads retain the parent fit+tune label fits. Each recipe passed a two-half added-label pilot before fitting the full permitted pool. Their production Tune scores and aggregate are in-sample and excluded from development selection.
36
+
37
+ Stability starts from the previously selected fit-only head (including its
38
+ earlier continuation midpoint). The new study compared natural weighting with
39
+ equal total loss mass for the 36,446 length-43 and 17,168 length-50 fit rows.
40
+ Both arms used identical batches, dropout RNG and 1,680 updates: whole-head
41
+ AdamW, peak lr 0.0001, weight decay 0.01, batch 512, 16 epochs, cosine decay to
42
+ 10%, original fit-standardized MSE, clipping 1. Feature-normalization buffers
43
+ were fixed. Only the predeclared final 50:50 parameter midpoint was eligible;
44
+ raw endpoints and earlier checkpoints were not selected. Balanced weighting
45
+ scored 0.7311607643 on cached Tune features versus 0.7274924149 for its parent
46
+ and 0.7291215997 for the matched control; conditional paired 95% differences
47
+ were [0.0019018632, 0.0054815226] and [0.0012832147, 0.0028118185].
48
+ The accepted fit-only development reference has mean0.7166638090 and stability
49
+ 0.7311607643. A fixed two-half added-label pilot then reproduced its fit-only
50
+ head bit-for-bit and obtained out-of-fold stability0.7337159020, gain0.0025551377,
51
+ conditional95%[0.0015641030,0.0036431410]. Both held-out halves improved. Halves
52
+ were label-stratified, not protein-family or scaffold splits; prior Tune
53
+ selection still biases this evidence.
54
+
55
+ The production stability head now applies that same fixed recipe to all
56
+ 53,614fit plus2,512Tune labels: same original head initialization, fixed
57
+ normalization,1,680updates and50:50parameter midpoint, with equal total loss
58
+ mass per length group. The larger pool ends during its16th epoch. This is
59
+ one ordinary head, not the two research cross-fit heads. Stability is now a
60
+ fifth head using Tune labels, alongside fold, fluorescence, beta-lactamase and
61
+ affinity. All five production Tune scores and the aggregate are IN-SAMPLE and
62
+ excluded from development selection. The extra-label recipe was accepted
63
+ before its full-pool fit; its in-sample score is not a selection criterion.
64
+ Complete independent production replay is valid for all eleven tasks; the ten other prediction files are byte-identical to the previous production package. Only the six learned stability-head tensors changed.
65
+
66
+
67
+ Tune selects regularization, checkpoints, conditioning and task exits. This
68
+ length-weighting hypothesis was informed by the observed Tune length
69
+ distribution. Repeated Tune selection and protein-family dependence are not
70
+ corrected by the conditional intervals. Small PPI splits and weak fold
71
+ generalization remain limitations. SS and pair windows cover full chains;
72
+ other tasks use a 1022-residue prefix. Human windows allow 1536 tokens and
73
+ yeast 1024. GFP/beta rank outputs are not calibrated for absolute error.
74
+ No held-out test measurement is available.
75
+
76
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. This is one parameter set
77
+ and needs no live trainer, research files, feature cache, sequence lookup,
78
+ prediction ensemble or test-time fitting.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/config.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ]
134
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/provenance.json ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "parent_package": "/workspace/research/production-stability-lengthweight1/candidate/package",
3
+ "parent_model_sha256": "6cae7d0e4fd47e56a27acc11bfcb299e858437351abd554cdc25c3aa5b187b0d",
4
+ "parent_provenance": {
5
+ "parent_package": "/workspace/research/production-stability-midpoint1/candidate/package",
6
+ "parent_sha256": "5a5e8f90a608f84f0592bad0213117ba9b3d056d6dc3feb325965a830f25a3e0",
7
+ "parent_provenance": {
8
+ "method": "Retain production model and replace only six stability head tensors with the accepted fit-only parameter midpoint.",
9
+ "production_parent": "/workspace/research/production-fullpool-summary1/candidate/package",
10
+ "production_parent_sha256": "195b60bcb0833ce75ed07c8846fb50ccd840c137ee4f4616d9c8b5d1427107a9",
11
+ "development": "/workspace/research/selected-stability-midpoint1/candidate/package",
12
+ "development_sha256": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c",
13
+ "parent_provenance": {
14
+ "method": "Retain every production tensor and add the accepted jointly trained nonlinear summary residual.",
15
+ "production_parent": "/workspace/research/production-fullpool-ss-distill64/candidate/package",
16
+ "production_parent_sha256": "37fc717aeb0cab3f68c4311ac9b5d6c8b0a56aecad738ab093bd4d986ea4c766",
17
+ "addition_source": "/workspace/research/shared-summary-residual1/candidate/package",
18
+ "addition_source_sha256": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
19
+ "added_parameters": 475906,
20
+ "parameters": 53000306,
21
+ "original_production_tensors_exact": true,
22
+ "one_shared_encoder_for_all_tasks": true,
23
+ "data": "Own from-scratch shared lineage; fit-only residual gradients and normalization; tune model selection. Fold/GFP/beta/affinity retain permitted fit+tune heads.",
24
+ "changed_tasks": [
25
+ "binary_localization"
26
+ ],
27
+ "tasks_reusing_tune_labels": [
28
+ "fold",
29
+ "fluorescence",
30
+ "beta_lactamase",
31
+ "ppi_affinity"
32
+ ],
33
+ "feature_cache_exported": false,
34
+ "inference_dependencies_outside_package": false
35
+ },
36
+ "development_provenance": {
37
+ "method": "One fixed 50:50 parameter midpoint of parent and fit-only 16-epoch stability head continuation; no ensemble.",
38
+ "source_parent": "/workspace/research/shared-summary-residual1/candidate/package",
39
+ "source_candidate": "/workspace/research/selected-stability-head64/candidate/package",
40
+ "source_model_sha256": {
41
+ "/workspace/research/shared-summary-residual1/candidate/package": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
42
+ "/workspace/research/selected-stability-head64/candidate/package": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79"
43
+ },
44
+ "parent_provenance": {
45
+ "method": "One jointly learned nonlinear residual map over frozen shared sequence summaries, with task-specific zero-initialized outputs.",
46
+ "fit_tasks": [
47
+ "solubility",
48
+ "subcellular_localization",
49
+ "binary_localization"
50
+ ],
51
+ "selected_tasks": [
52
+ "binary_localization"
53
+ ],
54
+ "selected_global_step": 3000,
55
+ "source": "/workspace/research/ss-distillation-continuation1/candidate/package",
56
+ "export_base": "/workspace/research/ss-distillation-continuation1/candidate/package",
57
+ "export_base_model_sha256": "4fee0a0154af24665de9a95f11a722017f3fa6d92354475bec8e81235a219f00",
58
+ "rebased_SS_tensors": [],
59
+ "seed": 20270102,
60
+ "steps": 6000,
61
+ "lr": 0.001,
62
+ "weight_decay": 0.01,
63
+ "dropout": 0.2,
64
+ "data": "Fit only for gradients and existing normalization; Tune chooses oneglobalcheckpoint andresidualexits usingpredeclaredconditionalCIgate.",
65
+ "original_parameters_exact": true,
66
+ "parameters": 53000306,
67
+ "encoder_parameters": 44150303,
68
+ "feature_cache_exported": false
69
+ },
70
+ "fit_recipe": {
71
+ "seed": 20270129,
72
+ "epochs": 64,
73
+ "evaluate_epochs": [
74
+ 4,
75
+ 16,
76
+ 32,
77
+ 64
78
+ ],
79
+ "batch_size": 512,
80
+ "lr": 0.0001,
81
+ "weight_decay": 0.01,
82
+ "loss": "MSE to original fit-standardized stabilitylabels, matching selectedmodeltarget semantics;clip1;originaldropout active inbotharms;fixednormalizationbuffers. No newranktargetchange.",
83
+ "optimizer": "FreshCPUAdamW,cosine64epochs to0.1floor; matcheddataorder/dropoutRNG/updatecounts; per-epochatomicresume."
84
+ },
85
+ "source_selected_epoch": 16,
86
+ "diagnostic": {
87
+ "utc": "2026-10-25T13:39:33.197851+00:00",
88
+ "status": "CPU_diagnostic_complete_no_export",
89
+ "alpha": 0.5,
90
+ "points": {
91
+ "parent": 0.7226969980994319,
92
+ "midpoint": 0.7274924148853711,
93
+ "whole": 0.7274598466634085
94
+ },
95
+ "midpoint_delta_vs_parent": 0.004795416785939199,
96
+ "conditional95": [
97
+ 0.0017412267324550784,
98
+ 0.007940572842815559
99
+ ],
100
+ "draws": 1000,
101
+ "seed": 20270130,
102
+ "parameters": 53000306,
103
+ "six_changed_learned_tensors": [
104
+ "heads.stability.0.weight",
105
+ "heads.stability.0.bias",
106
+ "heads.stability.2.weight",
107
+ "heads.stability.2.bias",
108
+ "heads.stability.3.linear.weight",
109
+ "heads.stability.3.linear.bias"
110
+ ],
111
+ "all_other_tensors_and_buffers_exact": true,
112
+ "eligible_for_manual_complete_replay": true,
113
+ "publication": false,
114
+ "GPU_used": false,
115
+ "limitations": "Singlepredeclaredparameter midpoint, notpredictionensemble. Conditionalrowbootstrapuncorrectedforpriorcheckpointselectionandfamilydependence. CPUdiagnosticisnotan11taskreplay.",
116
+ "source_sha256": {
117
+ "/workspace/research/check_selected_stability_midpoint.py": "13615a5b2689a0bd503cbc8a9a8a722014962677f6769cec871e13aa5133ff77",
118
+ "/workspace/research/shared-summary-residual1/candidate/package/model.pt": "f890eebb10bb2dc08b84c28e7e0378960af5df4fb0d646ab2e8b33e130c74202",
119
+ "/workspace/research/selected-stability-head64/candidate/package/model.pt": "8fe80a673a65650bb5769b1cf75a59f10a65961da91cc62a491094f874042c79"
120
+ }
121
+ },
122
+ "data": "Fit-only labels and fixed normalization; tune selects epoch and evaluates one predeclared midpoint.",
123
+ "parameters": 53000306,
124
+ "feature_cache_exported": false
125
+ },
126
+ "parameters": 53000306,
127
+ "all_other_production_tensors_exact": true,
128
+ "data": "Mounted fit labels and own from-scratch shared encoder lineage; tune model selection for stability. Four prior fullpool heads retain their permitted fit+tune training and crossfit evidence.",
129
+ "tasks_reusing_tune_labels": [
130
+ "fold",
131
+ "fluorescence",
132
+ "beta_lactamase",
133
+ "ppi_affinity"
134
+ ],
135
+ "feature_cache_exported": false,
136
+ "inference_dependencies_outside_package": false
137
+ },
138
+ "fit_plan": {
139
+ "utc": "2026-10-25T16:08:33.461759+00:00",
140
+ "status": "queued",
141
+ "CPU_only": true,
142
+ "recovery_registered": false,
143
+ "source_package": "/workspace/research/selected-stability-midpoint1/candidate/package",
144
+ "source_report": "/workspace/research/selected-stability-midpoint1/candidate/report.json",
145
+ "features": "/workspace/research/rank-target-functions2/features-stability",
146
+ "feature_producer": "/workspace/research/rank-target-fluorescence1/candidate/package",
147
+ "arms": [
148
+ "natural",
149
+ "balanced"
150
+ ],
151
+ "expected_fit_lengths": [
152
+ 43,
153
+ 50
154
+ ],
155
+ "seed": 20270208,
156
+ "threads": 6,
157
+ "epochs": 16,
158
+ "batch_size": 512,
159
+ "lr": 0.0001,
160
+ "weight_decay": 0.01,
161
+ "alpha": 0.5,
162
+ "minimum_gain": 0.001,
163
+ "bootstrap_seed": 20270209,
164
+ "bootstrap_draws": 1000,
165
+ "hypothesis": "Natural stability fit data are68%43-residue proteins but all observed Tune chains have50residues. Equal loss mass for the two fit-length groups may reduce interference on the50-residue domain. This is a test prompted by visible Tune distribution, not evidence of benefit.",
166
+ "loss": "Original-fit-standardized-label MSE. Identical shuffled full-fit batches in both arms; natural unit weights; balanced weights N/(2*N_group), averaged over minibatch without per-batch renormalization. Both train all six existing head tensors, fixed feature-normalization buffers.",
167
+ "schedule": "FreshAdamW,16epochs/1680updates,cosine to0.1floor,clip1; originaldropoutactive with identical RNG and data order. Same current selected initial head.",
168
+ "selection": "Only one fixed50:50 parameter midpoint at the final16epoch endpoint per arm is eligible. Raw endpoints are descriptive. Require gain>=.001 and positive conditional95versus selected; balanced additionally requires positive conditional95versus natural control. No intermediate Tune selection, no seed/mixture grid. Manual review then full11 native replay before any publication.",
169
+ "all_task_policy": "Only six stabilityheadparameters may change. Shared encoder remains jointly learned for all11. All10otherparameters/config/outputfiles must remain exact on native replay. No automatic export or publication.",
170
+ "resume": "CPU per-epoch atomic optimizer/head/NumPy/torchRNG checkpoints; rerun same script after interruption. Planhash verified on resume.",
171
+ "recovery_command": [
172
+ "env",
173
+ "CUDA_VISIBLE_DEVICES=",
174
+ "OMP_NUM_THREADS=6",
175
+ "MKL_NUM_THREADS=6",
176
+ "OPENBLAS_NUM_THREADS=1",
177
+ "python3",
178
+ "-u",
179
+ "/workspace/research/run_stability_length_weighting.py",
180
+ "--run",
181
+ "/workspace/research/selected-stability-lengthweight1"
182
+ ],
183
+ "frozen_sha256": {
184
+ "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6",
185
+ "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990",
186
+ "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632",
187
+ "/workspace/research/stability-length-shift-diagnostic.json": "36a890f702bb6709e893c5f9d94c5cf15959f83f4a91d71e58a7b5f681065f6d",
188
+ "/workspace/research/selected-stability-midpoint1/candidate/report.json": "feedb171d285a4fa4d3c2a2bdd819873caaad1308ef90fd59df9df1ace166827",
189
+ "/workspace/research/selected-stability-midpoint1/candidate/package/model.pt": "e01ae99a458b5d8d2aba968e1efc663b3d346220fd16b5498a3f91b5cf29626c",
190
+ "/workspace/research/selected-stability-midpoint1/candidate/package/config.json": "162a2f4985944bba7492854315bd594fd3a38386548ab1c6b0c7a4f0d2bd7625",
191
+ "/workspace/research/selected-stability-midpoint1/candidate/package/unified.py": "bb00abef5853bc8badfef6a8d38ef8cb11f0ff6d9fe143eb7deebd582058efa3",
192
+ "/workspace/research/selected-stability-midpoint1/candidate/package/esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9",
193
+ "/workspace/research/selected-stability-midpoint1/candidate/package/replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85",
194
+ "/workspace/research/selected-stability-midpoint1/candidate/package/infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468",
195
+ "/workspace/research/rank-target-fluorescence1/candidate/package/model.pt": "a13dad3c4f0cd7a1917d5b6763b27aaf3d38f3b7d775e747b61241ea36b681e0",
196
+ "/workspace/research/rank-target-fluorescence1/candidate/package/config.json": "e3da1d0ea2df3e6d6cc8b069016bffca2a37fd05accf1597cc6453f946d8fd89",
197
+ "/workspace/research/rank-target-functions2/features-stability/stability-fit.pt": "3fde47645a74370a003dd5f509a73ccecbaaac36ce4e8871938979a003ba3862",
198
+ "/workspace/research/rank-target-functions2/features-stability/stability-tune.pt": "92066e0c8abfcfc4ac3b8f2c7edcc4319cb8f8b4b97b53dd6e589147a1c460bf"
199
+ }
200
+ },
201
+ "fit_outcome": {
202
+ "utc": "2026-10-25T16:08:53.918703+00:00",
203
+ "status": "cached_analysis_complete",
204
+ "arms": {
205
+ "natural": {
206
+ "arm": "natural",
207
+ "endpoint_reward": 0.7291215996959544,
208
+ "raw_reward_descriptive_only": 0.72991937369715,
209
+ "step": 1680,
210
+ "active_seconds": 5.326252081984421,
211
+ "final_numpy_rng": {
212
+ "bit_generator": "PCG64",
213
+ "state": {
214
+ "state": 264542032468656517169208881192101401107,
215
+ "inc": 100251262600960163324587047460976422035
216
+ },
217
+ "has_uint32": 1,
218
+ "uinteger": 637011686
219
+ },
220
+ "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52",
221
+ "optimizer_steps": [
222
+ 1680.0
223
+ ],
224
+ "lr": 1.0000078679859099e-05,
225
+ "fixed_buffers_exact": true
226
+ },
227
+ "balanced": {
228
+ "arm": "balanced",
229
+ "endpoint_reward": 0.7311607642876724,
230
+ "raw_reward_descriptive_only": 0.7330130871638806,
231
+ "step": 1680,
232
+ "active_seconds": 5.340115340979537,
233
+ "final_numpy_rng": {
234
+ "bit_generator": "PCG64",
235
+ "state": {
236
+ "state": 264542032468656517169208881192101401107,
237
+ "inc": 100251262600960163324587047460976422035
238
+ },
239
+ "has_uint32": 1,
240
+ "uinteger": 637011686
241
+ },
242
+ "final_torch_rng_sha256": "fd56e05488c9ae31e940c2b1d859f13ca90497826206c0e3602aaba9c339ef52",
243
+ "optimizer_steps": [
244
+ 1680.0
245
+ ],
246
+ "lr": 1.0000078679859099e-05,
247
+ "fixed_buffers_exact": true
248
+ }
249
+ },
250
+ "comparisons": {
251
+ "natural_vs_parent": {
252
+ "delta": 0.001629184810583273,
253
+ "conditional_95": [
254
+ 0.00024683637661263025,
255
+ 0.003237432482155497
256
+ ]
257
+ },
258
+ "balanced_vs_parent": {
259
+ "delta": 0.0036683494023013186,
260
+ "conditional_95": [
261
+ 0.0019018632266723152,
262
+ 0.0054815225624275
263
+ ]
264
+ },
265
+ "balanced_vs_natural": {
266
+ "delta": 0.0020391645917180456,
267
+ "conditional_95": [
268
+ 0.0012832147204794586,
269
+ 0.0028118185483942955
270
+ ]
271
+ }
272
+ },
273
+ "eligible_arms": [
274
+ "natural",
275
+ "balanced"
276
+ ],
277
+ "published": false,
278
+ "GPU_used": false,
279
+ "candidate_exported": false,
280
+ "matched_order_dropout_optimizer_clocks": true,
281
+ "ten_other_tasks": "No state edited; any proposed export must keep their parameters/configuration exact and independently replay all eleven.",
282
+ "limitations": "Conditional example bootstrap after repeated tune inspection; family dependence and selection uncertainty omitted. Tune length distribution informed this hypothesis. Raw endpoints are descriptive only. No full-pool or test-time fitting."
283
+ },
284
+ "changed_tensors": [
285
+ "heads.stability.0.weight",
286
+ "heads.stability.0.bias",
287
+ "heads.stability.2.weight",
288
+ "heads.stability.2.bias",
289
+ "heads.stability.3.linear.weight",
290
+ "heads.stability.3.linear.bias"
291
+ ],
292
+ "all_other_tensors_and_buffers_exact": true,
293
+ "method": "One fixed final balanced-length continuation midpoint; no output averaging or test-time fitting."
294
+ },
295
+ "fullpool_training_plan": {
296
+ "utc": "2026-10-25T16:17:50.660603+00:00",
297
+ "status": "queued",
298
+ "recovery_registered": true,
299
+ "fit_recipe_plan": "/workspace/research/selected-stability-lengthweight1/plan.json",
300
+ "accepted_fit_only_head": "/workspace/research/selected-stability-lengthweight1/balanced/midpoint-head.pt",
301
+ "reference_predictions": "/workspace/research/selected-stability-lengthweight1-replay/candidate/replay/predictions/stability.jsonl",
302
+ "required_development_decision": "/workspace/research/selected-stability-lengthweight1-replay/decision.json",
303
+ "fixed_split_artifact": "/workspace/research/crossfit-stability-data1/research-predictions.pt",
304
+ "threads": 6,
305
+ "updates": 1680,
306
+ "bootstrap_seed": 20270210,
307
+ "bootstrap_draws": 1000,
308
+ "hypothesis": "Apply the already accepted fixed extra-label recipe to all permitted stability labels; no further model selection on its in-sample Tune output.",
309
+ "initialization": "Exact original selected-stability-midpoint1 head used in the accepted fit-only balanced recipe, not the later fitted midpoint; old feature-normalization buffers and target affine normalization remain fixed.",
310
+ "matching": "Exactly1680updates,16-epoch-equivalent control LR horizon,seed20270208,AdamW1e-4,wd.01,clip1,batch512,cosinefloor.1. Control must reproduce all accepted head tensors bitexact before either added-label arm. Added pools are larger and end in a partial16thepoch; batch membership and partial-batch sizes necessarily differ.",
311
+ "data": "Fit pooled features plus one fixed previously declared label-stratified Tune half per arm; evaluate only the other half. Group weights N/(2*N_group) recomputed using that arm training pool only. No heldout labels enter gradients, target normalization or head normalization.",
312
+ "selection": "No fullpoolTune quality selection. Exactly one fixed1680update midpoint; complete all11native replay and ten other production files exact before manual publication.",
313
+ "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection.",
314
+ "GPU_used": false,
315
+ "fullpool_fitting_queued": true,
316
+ "candidate_export_capability": false,
317
+ "frozen_sha256": {
318
+ "/workspace/research/crossfit_stability_lengthweight.py": "c78dd44a2408b8302d2bac9b130f6b1d0ed8583e0addd849e704306cae1895e1",
319
+ "/workspace/research/run_stability_length_weighting.py": "3c5aac6a79a1397e5c50278a7635e32d7c3583438f64996c8a42a372d16a29f6",
320
+ "/workspace/research/selected-stability-lengthweight1/plan.json": "4bb848e73639ce379a55de765634624cda8428354bc004368715cc6be0ce4f2d",
321
+ "/workspace/research/selected-stability-lengthweight1/outcome.json": "48f960b5897432f316e1422d72ba59d793187e467d0479991eda05eaa307f9a9",
322
+ "/workspace/research/selected-stability-lengthweight1/balanced/midpoint-head.pt": "efb5afa7ce15a6b175a304a81fb4f4704947d93922c32e57eb18128b27586f22",
323
+ "/workspace/research/crossfit-stability-data1/research-predictions.pt": "bb127c6773051e5186bf6e1c373da1648e243334316627aea4912098031245c3",
324
+ "/workspace/research/selected-stability-lengthweight1-replay/candidate/replay/predictions/stability.jsonl": "b95864102e42933f1fb9c4c112077404db01e01275752af27ddef7bb67ce701c",
325
+ "/workspace/research/selected-stability-lengthweight1-replay/decision.json": "13e26f3f1cd7d1f2e30bbe55084a7db7971d8ee12402095a0d0375cea4aec220",
326
+ "/workspace/research/check_shared_adapters_cpu.py": "db7d8d846b90929decad5865de36dd55fb95139aaa116b6ae2987cd96786c990",
327
+ "/workspace/research/crossfit_beta_labels.py": "bd1d29e2ab78cb0273213ef1a00657cef450a91f155ba7d9aa7f3db7721bd632",
328
+ "/workspace/research/fit_fullpool_stability_lengthweight.py": "c0636f0b4a895a3333b33b9a3a9e9675690954e799b318cce2f912d9e8190a3b",
329
+ "/workspace/research/crossfit-stability-lengthweight1/decision.json": "aad9faa0a791551afc0f3dd9a68c2960533e0b4782652a144b54a79ba001e147",
330
+ "/workspace/research/crossfit-stability-lengthweight1/outcome.json": "9ff04cfd9fac3d4c4cd71b09c0c51262af468c3c0a73e2f73d665bdcaa928b65"
331
+ },
332
+ "queued_utc": "2026-10-25T16:16:33.916922+00:00",
333
+ "required_crossfit_decision": "/workspace/research/crossfit-stability-lengthweight1/decision.json"
334
+ },
335
+ "fullpool_training": {
336
+ "utc": "2026-10-25T16:18:12.158869+00:00",
337
+ "status": "fullpool_head_fit_complete_pending_assembly",
338
+ "training": {
339
+ "step": 1680,
340
+ "epochs_started": 16,
341
+ "active_seconds": 7.640217978012515,
342
+ "training_rows": 56126,
343
+ "added_tune_rows": 2512,
344
+ "fixed_buffers_exact": true,
345
+ "group_counts": {
346
+ "43": 36446,
347
+ "50": 19680
348
+ },
349
+ "final_lr": 1.0000078679859099e-05
350
+ },
351
+ "source_initialization": "/workspace/research/selected-stability-midpoint1/candidate/package",
352
+ "head": "/workspace/research/fullpool-stability-lengthweight1/fullpool/final-head.pt",
353
+ "head_sha256": "f531855c132c8fca7b1def6827ef4b2cf30d0af7c1c14e39c33afaa017f482c2",
354
+ "changed_head_tensors": [
355
+ "0.weight",
356
+ "0.bias",
357
+ "2.weight",
358
+ "2.bias",
359
+ "3.linear.weight",
360
+ "3.linear.bias"
361
+ ],
362
+ "fixed_normalization_buffers_exact": true,
363
+ "same_training_function_as_crossfit": true,
364
+ "published": false,
365
+ "candidate_exported": false,
366
+ "GPU_used": false,
367
+ "Tune_labels_used": 2512,
368
+ "in_sample_metric_used_for_selection": false,
369
+ "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection."
370
+ },
371
+ "crossfit_recipe_approval": {
372
+ "utc": "2026-10-25T16:17:50.640175+00:00",
373
+ "status": "accepted_fixed_recipe_for_fullpool_stability_head",
374
+ "published": false,
375
+ "fullpool_head_fitted": false,
376
+ "evidence": {
377
+ "utc": "2026-10-25T16:17:04.539090+00:00",
378
+ "status": "research_only_crossfit_complete",
379
+ "scores": {
380
+ "incumbent": 0.7311607642876724,
381
+ "matched_fit_only": 0.7311607642876724,
382
+ "crossfit": 0.7337159019671029
383
+ },
384
+ "comparisons": {
385
+ "incumbent": {
386
+ "delta": 0.002555137679430497,
387
+ "conditional_95": [
388
+ 0.0015641029747572976,
389
+ 0.0036431410475218527
390
+ ]
391
+ },
392
+ "matched_fit_only": {
393
+ "delta": 0.002555137679430497,
394
+ "conditional_95": [
395
+ 0.0015641029747572976,
396
+ 0.0036431410475218527
397
+ ]
398
+ }
399
+ },
400
+ "fold_results": [
401
+ {
402
+ "heldout_half": 0,
403
+ "heldout_rows": 1256,
404
+ "incumbent_same_half": 0.7325449010474826,
405
+ "matched_control_same_half": 0.7325449010474826,
406
+ "crossfit_same_half": 0.7351256285381212,
407
+ "step": 1680,
408
+ "epochs_started": 16,
409
+ "active_seconds": 7.389840035961242,
410
+ "training_rows": 54870,
411
+ "added_tune_rows": 1256,
412
+ "fixed_buffers_exact": true,
413
+ "group_counts": {
414
+ "43": 36446,
415
+ "50": 18424
416
+ },
417
+ "final_lr": 1.0000078679859099e-05
418
+ },
419
+ {
420
+ "heldout_half": 1,
421
+ "heldout_rows": 1256,
422
+ "incumbent_same_half": 0.7298113878884595,
423
+ "matched_control_same_half": 0.7298113878884595,
424
+ "crossfit_same_half": 0.7327158507790285,
425
+ "step": 1680,
426
+ "epochs_started": 16,
427
+ "active_seconds": 7.374784096988151,
428
+ "training_rows": 54870,
429
+ "added_tune_rows": 1256,
430
+ "fixed_buffers_exact": true,
431
+ "group_counts": {
432
+ "43": 36446,
433
+ "50": 18424
434
+ },
435
+ "final_lr": 1.0000078679859099e-05
436
+ }
437
+ ],
438
+ "passes_predeclared_fullpool_gate": true,
439
+ "fit_only_reproduction_all_head_tensors_bit_exact": true,
440
+ "updates_per_arm": 1680,
441
+ "published": false,
442
+ "fullpool_head_fitted": false,
443
+ "candidate_exported": false,
444
+ "GPU_used": false,
445
+ "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection."
446
+ },
447
+ "reason": "The fixed whole-head balanced-length recipe passes all prior policy gates: positive OOFdelta versus nativeincumbent and bitexact matchedcontrol, positivepaired95interval, both heldout halves improve. Shared encoder and normalization stay unchanged. FullpoolTune metrics will be in-sample and excluded from developmentselection.",
448
+ "all_other_tasks": "Exactly unchanged weights/features; subsequent full11production replay must verify ten byte-exact files."
449
+ },
450
+ "changed_tensors": [
451
+ "heads.stability.0.weight",
452
+ "heads.stability.0.bias",
453
+ "heads.stability.2.weight",
454
+ "heads.stability.2.bias",
455
+ "heads.stability.3.linear.weight",
456
+ "heads.stability.3.linear.bias"
457
+ ],
458
+ "all_other_tensors_and_feature_normalization_buffers_exact": true,
459
+ "method": "One fixed1680update balanced-length whole-head continuation and50:50parameter midpoint, initial head fromownselected-stability-midpoint1; allfit+tune labels permitted bycontract; no head averaging at inference."
460
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/replay.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained replay shared by research evaluation and frozen packages."""
3
+ import contextlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ import esm2
12
+
13
+ TASKS = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
14
+ 'subcellular_localization', 'binary_localization', 'fold',
15
+ 'secondary_structure', 'yeast_ppi', 'human_ppi', 'ppi_affinity')
16
+
17
+
18
+ def autocast(device):
19
+ return torch.autocast('cuda', dtype=torch.bfloat16) if device.type == 'cuda' else contextlib.nullcontext()
20
+
21
+
22
+ def head_output(model, task, representation, device, fp32=False):
23
+ apply = model.apply_head if hasattr(model, 'apply_head') else lambda task, value: model.heads[task](value)
24
+ if fp32:
25
+ with torch.autocast(device.type, enabled=False):
26
+ values={k:v.float() if v.is_floating_point() else v for k,v in representation.items()} if isinstance(representation,dict) else representation.float()
27
+ return apply(task, values).float()
28
+ return apply(task, representation).float()
29
+
30
+
31
+ def residue_states(model, tokens, task):
32
+ return model.encode_residues(tokens, task) if hasattr(model, 'encode_residues') else model.encoder(tokens)
33
+
34
+
35
+ def windows(length, width=1022, stride=768):
36
+ if length <= width:
37
+ return [(0, length)]
38
+ starts = list(range(0, length - width + 1, stride))
39
+ if starts[-1] != length - width:
40
+ starts.append(length - width)
41
+ return [(s, min(s + width, length)) for s in starts]
42
+
43
+
44
+ def batches(rows, task, token_budget=16384, max_len=1024, max_batch=128):
45
+ lengths = [min(max(map(len, r['features'].values())) + 2, max_len) for r in rows]
46
+ order = sorted(range(len(rows)), key=lengths.__getitem__)
47
+ current, width = [], 0
48
+ for i in order:
49
+ length = lengths[i]
50
+ # Pair sequences require two separate passes, but the peak tensor size is unchanged.
51
+ if current and (max(width, length) * (len(current) + 1) > token_budget or len(current) >= max_batch):
52
+ yield current
53
+ current, width = [], 0
54
+ current.append(i)
55
+ width = max(width, length)
56
+ if current:
57
+ yield current
58
+
59
+
60
+ @torch.inference_mode()
61
+ def predict_records(model, rows, task, device, config=None, token_budget=16384):
62
+ config = config or {}
63
+ max_len = config.get('task_max_len', {}).get(task, config.get('max_len', 1024))
64
+ full_ss = config.get('full_ss', True)
65
+ fp32_option = config.get('fp32_heads', False)
66
+ fp32_heads = fp32_option is True or (isinstance(fp32_option, list) and task in fp32_option)
67
+ was_training = model.training
68
+ model.eval()
69
+ result = {}
70
+ for ids in batches(rows, task, token_budget, max_len):
71
+ chunk = [rows[i] for i in ids]
72
+ features = [r['features'] for r in chunk]
73
+ if task == 'secondary_structure':
74
+ if full_ss and any(len(f['sequence']) > max_len - 2 for f in features):
75
+ for record in chunk:
76
+ seq = record['features']['sequence']
77
+ pieces = windows(len(seq), max_len - 2, min(768, max_len - 2))
78
+ total = np.zeros((len(seq), 3), dtype=np.float32)
79
+ weight_sum = np.zeros((len(seq), 1), dtype=np.float32)
80
+ for begin in range(0, len(pieces), max(1, token_budget // max_len)):
81
+ part = pieces[begin:begin + max(1, token_budget // max_len)]
82
+ tokens = esm2.pad_batch([esm2.encode(seq[s:e], max_len) for s, e in part], device)
83
+ with autocast(device):
84
+ hidden, _ = residue_states(model, tokens, task)
85
+ logits = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
86
+ for j, (s, e) in enumerate(part):
87
+ size = e - s
88
+ # Smooth boundaries, without discarding any residue.
89
+ weight = np.minimum(np.arange(1, size + 1), np.arange(size, 0, -1))
90
+ weight = np.minimum(weight, 128).astype(np.float32)[:, None]
91
+ total[s:e] += logits[j, 1:1+size] * weight
92
+ weight_sum[s:e] += weight
93
+ scores = total / np.maximum(weight_sum, 1)
94
+ result[record['example_id']] = {'ss3_scores': scores.tolist()}
95
+ else:
96
+ tokens = esm2.pad_batch([esm2.encode(f['sequence'], max_len) for f in features], device)
97
+ with autocast(device):
98
+ hidden, _ = residue_states(model, tokens, task)
99
+ probabilities = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
100
+ for j, record in enumerate(chunk):
101
+ length = len(record['features']['sequence'])
102
+ used = min(length, max_len - 2)
103
+ scores = probabilities[j, 1:1+used].tolist()
104
+ scores.extend([[1.0, 1.0, 1.0] for _ in range(length-used)])
105
+ result[record['example_id']] = {'ss3_scores': scores}
106
+ continue
107
+ with autocast(device):
108
+ representation = model.represent(task, features, device, max_len)
109
+ output = head_output(model, task, representation, device, fp32_heads)
110
+ if task in model.CLASSES:
111
+ output = output.softmax(-1)
112
+ if task in config.get('symmetric_pairs', []):
113
+ swapped = [{'sequence_a': f['sequence_b'], 'sequence_b': f['sequence_a']} for f in features]
114
+ swapped_rep = model.represent(task, swapped, device, max_len)
115
+ second = head_output(model, task, swapped_rep, device, fp32_heads)
116
+ if task in model.CLASSES:
117
+ second = second.softmax(-1)
118
+ output = (output + second) * 0.5
119
+ if task in model.CLASSES:
120
+ output = output.clamp_min(1e-9)
121
+ elif hasattr(model, 'unscale'):
122
+ output = model.unscale(task, output)
123
+ values = output.cpu().tolist()
124
+ for record, value in zip(chunk, values):
125
+ result[record['example_id']] = {'scores': value} if task in model.CLASSES else {'value': value[0]}
126
+ if task == 'secondary_structure' and hasattr(model, 'ss_chain_decoder'):
127
+ # Decode complete chains only after all overlapping-window probabilities
128
+ # have been aggregated. No labels or parameter updates enter replay.
129
+ identifiers = [record['example_id'] for record in rows]
130
+ probabilities = [result[identifier]['ss3_scores'] for identifier in identifiers]
131
+ decoded = model.ss_chain_decoder.decode(probabilities)
132
+ for identifier, scores in zip(identifiers, decoded):
133
+ result[identifier] = {'ss3_scores': scores.tolist()}
134
+ model.train(was_training)
135
+ return result
136
+
137
+
138
+ def load_model(package, device):
139
+ config = json.loads((package / 'config.json').read_text())
140
+ if config.get('architecture') == 'unified':
141
+ from unified import UnifiedModel
142
+ model = UnifiedModel(config)
143
+ else:
144
+ model = esm2.Model(layers=config['layers'], dim=config['dim'], heads=config['heads'])
145
+ model.load_state_dict(torch.load(package / 'model.pt', map_location='cpu', weights_only=True))
146
+ return model.to(device).eval(), config
147
+
148
+
149
+ def main():
150
+ if len(sys.argv) != 3:
151
+ raise SystemExit('usage: replay.py INPUT_ROOT OUTPUT_ROOT')
152
+ torch.set_num_threads(6)
153
+ source, destination = Path(sys.argv[1]), Path(sys.argv[2]) / 'predictions'
154
+ destination.mkdir(parents=True, exist_ok=True)
155
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
+ model, config = load_model(Path(__file__).resolve().parent, device)
157
+ for task in TASKS:
158
+ rows = [json.loads(line) for line in (source / f'{task}.jsonl').open()]
159
+ predictions = predict_records(model, rows, task, device, config)
160
+ with (destination / f'{task}.jsonl').open('w') as sink:
161
+ for row in rows:
162
+ sink.write(json.dumps({'example_id': row['example_id'], 'prediction': predictions[row['example_id']]}, separators=(',', ':')) + '\n')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/selection.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pending_independent_replay": false,
3
+ "independent_replay_verified": true,
4
+ "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_ppi_affinity_and_stability",
5
+ "tasks_reusing_tune_labels": [
6
+ "fold",
7
+ "fluorescence",
8
+ "beta_lactamase",
9
+ "ppi_affinity",
10
+ "stability"
11
+ ],
12
+ "fit_only_development_reward": 0.7166638090200526,
13
+ "fit_only_development_package": "/workspace/research/selected-stability-lengthweight1-replay/candidate/package",
14
+ "stability_fit_only_evidence": {
15
+ "kind": "fit_only_complete_tune_replay",
16
+ "task": "stability",
17
+ "before": 0.7274923808177973,
18
+ "after": 0.7311607642876724,
19
+ "delta": 0.0036683834698750806,
20
+ "conditional_95_percentile_interval": [
21
+ 0.0017767471141417273,
22
+ 0.00544199745819068
23
+ ],
24
+ "examples": 2512,
25
+ "mean_delta": 0.0003334894063522801,
26
+ "conditional_mean95": [
27
+ 0.0001615224649219752,
28
+ 0.0004947270416536983
29
+ ],
30
+ "matched_natural_mixture_control": {
31
+ "delta": 0.0020391645917180456,
32
+ "conditional_95": [
33
+ 0.0012832147204794586,
34
+ 0.0028118185483942955
35
+ ]
36
+ },
37
+ "fixed_endpoint_updates": 1680,
38
+ "alpha": 0.5,
39
+ "ten_other_prediction_files_exact": true,
40
+ "limitations": "Conditional on already-selected models. Does not account for repeated tune selection, shared proteins across tasks, or family dependence within splits; not an independent generalization guarantee. The visible Tune length distribution informed the group-weighting hypothesis."
41
+ },
42
+ "stability_extra_label_recipe_evidence": {
43
+ "utc": "2026-10-25T16:17:04.539090+00:00",
44
+ "status": "research_only_crossfit_complete",
45
+ "scores": {
46
+ "incumbent": 0.7311607642876724,
47
+ "matched_fit_only": 0.7311607642876724,
48
+ "crossfit": 0.7337159019671029
49
+ },
50
+ "comparisons": {
51
+ "incumbent": {
52
+ "delta": 0.002555137679430497,
53
+ "conditional_95": [
54
+ 0.0015641029747572976,
55
+ 0.0036431410475218527
56
+ ]
57
+ },
58
+ "matched_fit_only": {
59
+ "delta": 0.002555137679430497,
60
+ "conditional_95": [
61
+ 0.0015641029747572976,
62
+ 0.0036431410475218527
63
+ ]
64
+ }
65
+ },
66
+ "fold_results": [
67
+ {
68
+ "heldout_half": 0,
69
+ "heldout_rows": 1256,
70
+ "incumbent_same_half": 0.7325449010474826,
71
+ "matched_control_same_half": 0.7325449010474826,
72
+ "crossfit_same_half": 0.7351256285381212,
73
+ "step": 1680,
74
+ "epochs_started": 16,
75
+ "active_seconds": 7.389840035961242,
76
+ "training_rows": 54870,
77
+ "added_tune_rows": 1256,
78
+ "fixed_buffers_exact": true,
79
+ "group_counts": {
80
+ "43": 36446,
81
+ "50": 18424
82
+ },
83
+ "final_lr": 1.0000078679859099e-05
84
+ },
85
+ {
86
+ "heldout_half": 1,
87
+ "heldout_rows": 1256,
88
+ "incumbent_same_half": 0.7298113878884595,
89
+ "matched_control_same_half": 0.7298113878884595,
90
+ "crossfit_same_half": 0.7327158507790285,
91
+ "step": 1680,
92
+ "epochs_started": 16,
93
+ "active_seconds": 7.374784096988151,
94
+ "training_rows": 54870,
95
+ "added_tune_rows": 1256,
96
+ "fixed_buffers_exact": true,
97
+ "group_counts": {
98
+ "43": 36446,
99
+ "50": 18424
100
+ },
101
+ "final_lr": 1.0000078679859099e-05
102
+ }
103
+ ],
104
+ "passes_predeclared_fullpool_gate": true,
105
+ "fit_only_reproduction_all_head_tensors_bit_exact": true,
106
+ "updates_per_arm": 1680,
107
+ "published": false,
108
+ "fullpool_head_fitted": false,
109
+ "candidate_exported": false,
110
+ "GPU_used": false,
111
+ "limitations": "Earlier Tune checkpoint/architecture selection biases estimates. Fixed label-stratified halves do not enforce protein-family or designed-scaffold independence. OOF predicts with two research heads trained on half the extra labels; it is recipe evidence, not a single final model measurement. Conditional bootstrap omits family dependence and prior selection."
112
+ },
113
+ "production_aggregate_excluded_from_selection": true,
114
+ "other_ten_predictions_exact_previous_production": true,
115
+ "stability_Tune_metric_is_in_sample": true
116
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S054/unified.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class ResidualSequenceConvHead(nn.Module):
117
+ """Learn local sequence motifs alongside the retained summary classifier."""
118
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
119
+ super().__init__()
120
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
121
+ self.register_buffer('mean', torch.zeros(dim))
122
+ self.register_buffer('scale', torch.ones(dim))
123
+ self.project = nn.Linear(dim, channels)
124
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
125
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
126
+ self.output = nn.Linear(4 * channels, outputs)
127
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
128
+ self.dropout = dropout
129
+
130
+ def forward(self, features):
131
+ valid = features['valid'].bool().unsqueeze(-1)
132
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
133
+ summaries = []
134
+ for conv,norm in zip(self.convs,self.norms):
135
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
136
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
137
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
138
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
139
+ summaries.extend([center,maximum])
140
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
141
+ logits=self.output(pooled)
142
+ return self.base(features['summary']) + logits if self.base is not None else logits
143
+
144
+
145
+ class TokenLogMeanExpHead(nn.Module):
146
+ """Class-specific local evidence, pooled without sequence-length bias."""
147
+ def __init__(self, dim, outputs):
148
+ super().__init__()
149
+ self.register_buffer('mean', torch.zeros(dim))
150
+ self.register_buffer('scale', torch.ones(dim))
151
+ self.linear = nn.Linear(dim, outputs)
152
+
153
+ def forward(self, representation):
154
+ values, valid = representation['hidden'].float(), representation['valid']
155
+ logits = self.linear((values-self.mean)/self.scale)
156
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
157
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
158
+
159
+ def packed(self, values, lengths):
160
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
161
+ logits = self.linear((values.float()-self.mean)/self.scale)
162
+ # The stabilizing maximum cancels in the derivative; detach avoids
163
+ # retaining another large token-by-class gradient path.
164
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
165
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
166
+ output_size=len(values))
167
+ exponent = (logits-maximum[index]).exp()
168
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
169
+ return maximum+total.log()-lengths.float().log()[:, None]
170
+
171
+
172
+ class SharedPairResidueInteraction(nn.Module):
173
+ """A shared nonlinear comparison of local states from both protein chains."""
174
+ def __init__(self, dim, settings, classes):
175
+ super().__init__()
176
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
177
+ self.register_buffer('mean', torch.zeros(dim))
178
+ self.register_buffer('scale', torch.ones(dim))
179
+ self.project = nn.Linear(dim, width)
180
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
181
+ nn.Linear(hidden, channels), nn.GELU())
182
+ self.dropout = settings['dropout']
183
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
184
+ for task in sorted(esm2.Model.PAIR)})
185
+ for head in self.heads.values():
186
+ nn.init.zeros_(head.weight)
187
+ nn.init.zeros_(head.bias)
188
+
189
+ def forward(self, task, first, second):
190
+ first = F.gelu(self.project((first-self.mean)/self.scale))
191
+ second = F.gelu(self.project((second-self.mean)/self.scale))
192
+ first = F.dropout(first, self.dropout, self.training)
193
+ second = F.dropout(second, self.dropout, self.training)
194
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
195
+ first[:, :, None]*second[:, None, :]], dim=-1)
196
+ local = self.compare(pair)
197
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
198
+ return self.heads[task](summary)
199
+
200
+
201
+ class SSChainDecoder(nn.Module):
202
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
203
+ def __init__(self):
204
+ super().__init__()
205
+ self.transition = nn.Parameter(torch.empty(3, 3))
206
+ self.start = nn.Parameter(torch.empty(3))
207
+ self.end = nn.Parameter(torch.empty(3))
208
+ for parameter in self.parameters():
209
+ nn.init.normal_(parameter, std=.01)
210
+
211
+ def decode(self, probabilities):
212
+ from ss_chain import decode_probabilities
213
+ values = [parameter.detach().double().cpu().numpy()
214
+ for parameter in (self.transition, self.start, self.end)]
215
+ return decode_probabilities(probabilities, *values)
216
+
217
+
218
+ class UnifiedModel(esm2.Model):
219
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
220
+ 'subcellular_localization', 'binary_localization', 'fold',
221
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
222
+
223
+ def __init__(self, config):
224
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
225
+ self.config = config
226
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
227
+ dim = config['dim']
228
+ if config.get('extension_layers', 0):
229
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
230
+ before_norm=config.get('extension_before_norm', False))
231
+ if config.get('task_conditioning', False):
232
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
233
+ if config.get('pooling', 'mean') == 'rich':
234
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
235
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
236
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
237
+ self.pool_fuse = nn.Linear(6 * dim, dim)
238
+ nn.init.zeros_(self.pool_fuse.weight)
239
+ nn.init.zeros_(self.pool_fuse.bias)
240
+ if config.get('pair_interaction', False):
241
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
242
+ nn.init.zeros_(self.pair_fuse.weight)
243
+ nn.init.zeros_(self.pair_fuse.bias)
244
+ if config.get('ss_context', False):
245
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
246
+ for task in config.get('linear_heads', []):
247
+ width = dim * 2 if task in self.PAIR else dim
248
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
249
+ for task, settings in config.get('residue_readouts', {}).items():
250
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
251
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
252
+ bins = config['residue_readouts'][task]['bins']
253
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
254
+ for task in config.get('summary_readouts', []):
255
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
256
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
257
+ for task in config.get('sequence_composition_readouts', []):
258
+ from sequence_composition import WIDTH
259
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
260
+ assert all(task not in config.get(key,[]) for key in
261
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
262
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
263
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
264
+ for task, temperature in config.get('cosine_heads', {}).items():
265
+ assert task in config.get('summary_readouts', [])
266
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
267
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
268
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
269
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
270
+ for task in config.get('calibrated_heads', []):
271
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
272
+ assert task not in config.get('linear_heads', [])
273
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
274
+ for task in config.get('expanded_pair_readouts', []):
275
+ assert task in self.PAIR
276
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
277
+ if task in config.get('pair_summary_readouts', []):
278
+ assert config.get('pooling') == 'rich'
279
+ width *= 8
280
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
281
+ if config.get('ss_linear_context'):
282
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
283
+ if config.get('ss_calibrated'):
284
+ assert not config.get('ss_linear_context')
285
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
286
+ for task in config.get('ss_summary_readouts', []):
287
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
288
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
289
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
290
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
291
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
292
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
293
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
294
+ assert all(task not in config.get(key, {}) for key in
295
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
296
+ bins = settings['bins']
297
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
298
+ for key in ['prefix_residues', 'suffix_residues'])
299
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
300
+ if config.get('pair_bilinear_rank', 0):
301
+ rank = config['pair_bilinear_rank']
302
+ assert not config.get('pair_summary_readouts')
303
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
304
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
305
+ with torch.no_grad():
306
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
307
+ self.pair_bilinear_heads = nn.ModuleDict({
308
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
309
+ for task in sorted(self.PAIR)})
310
+ for head in self.pair_bilinear_heads.values():
311
+ nn.init.zeros_(head.weight)
312
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
313
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
314
+ if config.get('pair_residue_interaction'):
315
+ self.pair_residue_interaction = SharedPairResidueInteraction(
316
+ dim, config['pair_residue_interaction'], self.CLASSES)
317
+ for task in config.get('token_logmeanexp_heads', []):
318
+ assert task in self.CLASSES and task not in self.PAIR
319
+ assert task not in config.get('sequence_windows', [])
320
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
321
+ if config.get('ss_chain_decoder', False):
322
+ self.ss_chain_decoder = SSChainDecoder()
323
+ if config.get('shared_summary_residual'):
324
+ settings = config['shared_summary_residual']
325
+ tasks = settings['tasks']
326
+ assert all(task in config.get('summary_readouts', []) and
327
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
328
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
329
+ {task: self.CLASSES[task] for task in tasks})
330
+
331
+ def pair_representation(self, task, first, second, base):
332
+ if task in self.config.get('pair_bilinear_tasks', []):
333
+ return {'base': base, 'chain_a': first, 'chain_b': second}
334
+ return base
335
+
336
+ def apply_head(self, task, representation):
337
+ if task in self.config.get('summary_residual_tasks', []):
338
+ head = self.heads[task]
339
+ normalized = (representation-head.mean)/head.scale
340
+ return head(representation) + self.summary_residual(task, normalized)
341
+ if isinstance(representation, dict) and 'residue_a' in representation:
342
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
343
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
344
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
345
+ if isinstance(representation, dict) and 'chain_a' in representation:
346
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
347
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
348
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
349
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
350
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
351
+ return self.heads[task](representation)
352
+
353
+ def encode_residues(self, tokens, task):
354
+ condition = None
355
+ if self.config.get('task_conditioning', False):
356
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
357
+ condition = self.task_condition[ti]
358
+ return self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
359
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
360
+
361
+ def pool(self, tokens, task):
362
+ hidden, pad_mask = self.encode_residues(tokens, task)
363
+ return self.summarize(hidden, tokens, pad_mask, task)
364
+
365
+ def summarize(self, hidden, tokens, pad_mask, task):
366
+ valid = (~pad_mask).unsqueeze(-1)
367
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
368
+ if self.config.get('pooling', 'mean') == 'mean':
369
+ return mean
370
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
371
+ # Empty/nonstandard-only inputs still produce a finite representation.
372
+ residues[:, 0] |= ~residues.any(1)
373
+ keep = residues.unsqueeze(-1)
374
+ count = keep.sum(1).clamp_min(1)
375
+ center = (hidden * keep).sum(1) / count
376
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
377
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
378
+ torch.cos(position * math.pi)], dim=-1)
379
+ ti = self.task_index[task]
380
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
381
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
382
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
383
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
384
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
385
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
386
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
387
+ first = residues & (residues.cumsum(1) <= 32)
388
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
389
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
390
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
391
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
392
+ deviation, maximum, prefix, suffix], dim=-1)
393
+ if task in self.config.get('summary_readouts', []):
394
+ return torch.cat([mean, summary], dim=-1)
395
+ if task in self.config.get('pair_summary_readouts', []):
396
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
397
+ return mean + self.pool_fuse(summary)
398
+
399
+ def pool_sequences(self, sequences, task, device, max_len):
400
+ if self.training and not self.config.get('window_pooling_training', True):
401
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
402
+ return self.pool(tokens,task)
403
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
404
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
405
+ results=[None]*len(sequences)
406
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
407
+ if short:
408
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
409
+ for j,index in enumerate(short):results[index]=pooled[j]
410
+ width=max_len-2;stride=min(768,width)
411
+ if self.training and self.config.get('batch_window_training',False):
412
+ pieces=[];starts_by_index={};encoded={}
413
+ for index,sequence in enumerate(sequences):
414
+ if len(sequence)<=width:continue
415
+ starts=list(range(0,len(sequence)-width+1,stride))
416
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
417
+ starts_by_index[index]=starts
418
+ pieces.extend((index,start) for start in starts)
419
+ count=max(1,16384//max_len)
420
+ for begin in range(0,len(pieces),count):
421
+ part=pieces[begin:begin+count]
422
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
423
+ hidden,_=self.encode_residues(tokens,task)
424
+ for j,key in enumerate(part):encoded[key]=hidden[j]
425
+ positions=torch.arange(width,device=device)
426
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
427
+ for index,starts in starts_by_index.items():
428
+ sequence=sequences[index];length=len(sequence)
429
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
430
+ for start in starts:
431
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
432
+ counts.index_add_(0,positions+start,weight)
433
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
434
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
435
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
436
+ return torch.stack(results)
437
+ for index,sequence in enumerate(sequences):
438
+ length=len(sequence)
439
+ if length<=width:continue
440
+ starts=list(range(0,length-width+1,stride))
441
+ if starts[-1]!=length-width:starts.append(length-width)
442
+ total=torch.zeros(length,self.config['dim'],device=device)
443
+ counts=torch.zeros(length,1,device=device)
444
+ first=last=None
445
+ for begin in range(0,len(starts),max(1,16384//max_len)):
446
+ part=starts[begin:begin+max(1,16384//max_len)]
447
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
448
+ hidden,_=self.encode_residues(tokens,task)
449
+ for j,start in enumerate(part):
450
+ if start==0:first=hidden[j,0:1]
451
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
452
+ positions=torch.arange(width,device=device)
453
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
454
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
455
+ counts.index_add_(0,positions+start,weight)
456
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
457
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
458
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
459
+ return torch.stack(results)
460
+
461
+ def represent(self, task, batch, device, max_len=1024):
462
+ if task in self.config.get('sequence_composition_readouts', []):
463
+ from sequence_composition import composition_features
464
+ sequences=[item['sequence'] for item in batch]
465
+ pooled=self.pool_sequences(sequences,task,device,max_len)
466
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
467
+ if task in self.config.get('token_logmeanexp_heads', []):
468
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
469
+ hidden, _ = self.encode_residues(tokens, task)
470
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
471
+ valid[:, 0] |= ~valid.any(1)
472
+ return {'hidden':hidden, 'valid':valid}
473
+ if task in self.config.get('terminal_summary_readouts', {}):
474
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
475
+ if task in self.config.get('ss_summary_readouts', []):
476
+ sequences=[x['sequence'] for x in batch]
477
+ summary=self.pool_sequences(sequences,task,device,max_len)
478
+ structure=self.secondary_structure_summary(sequences,device,max_len)
479
+ return torch.cat([summary.float(),structure],-1)
480
+ if task in self.config.get('sequence_conv_readouts',{}):
481
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
482
+ hidden,pad_mask=self.encode_residues(tokens,task)
483
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
484
+ width=max(1,int(lengths.max()))
485
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
486
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
487
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
488
+ if task in self.config.get('residue_readouts', {}):
489
+ bins = self.config['residue_readouts'][task]['bins']
490
+ sequences = [x['sequence'] for x in batch]
491
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
492
+ hidden, _ = self.encode_residues(tokens, task)
493
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
494
+ if task in self.PAIR:
495
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
496
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
497
+ if task in self.config.get('expanded_pair_readouts', []):
498
+ if task in self.config.get('symmetric_pair_readouts',[]):
499
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
500
+ else:
501
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
502
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
503
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
504
+ output = torch.cat([a, b], dim=-1)
505
+ if self.config.get('pair_interaction', False):
506
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
507
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
508
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
509
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
510
+
511
+ def add_pair_residues(self, task, batch, device, max_len, base):
512
+ if task not in self.config.get('pair_residue_tasks', []):
513
+ return base
514
+ result = dict(base) if isinstance(base, dict) else {'base': base}
515
+ bins = self.config['pair_residue_interaction']['bins']
516
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
517
+ result['residue_'+role] = self.pool_residue_bins(
518
+ [row[name] for row in batch], task, device, max_len, bins)
519
+ return result
520
+
521
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
522
+ """Average every residue into fixed relative bins, with full-chain context."""
523
+ width = max_len-2
524
+ assert width > 0 and bins > 0
525
+ output = [None]*len(sequences)
526
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
527
+ if short:
528
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
529
+ hidden, _ = self.encode_residues(tokens, task)
530
+ for j, index in enumerate(short):
531
+ length = len(sequences[index])
532
+ values = hidden[j, 1:1+length].float()
533
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
534
+ else torch.zeros(bins, self.config['dim'], device=device))
535
+ for index, sequence in enumerate(sequences):
536
+ if len(sequence) <= width:
537
+ continue
538
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
539
+ if starts[-1] != len(sequence)-width:
540
+ starts.append(len(sequence)-width)
541
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
542
+ count = torch.zeros(len(sequence), 1, device=device)
543
+ position = torch.arange(width, device=device)
544
+ weight = torch.minimum(torch.minimum(position+1, width-position),
545
+ torch.full_like(position, 128)).float()[:, None]
546
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
547
+ part = starts[begin:begin+max(1, 16384//max_len)]
548
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
549
+ hidden, _ = self.encode_residues(tokens, task)
550
+ for j, start in enumerate(part):
551
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
552
+ count.index_add_(0, position+start, weight)
553
+ values = total/count.clamp_min(1)
554
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
555
+ return torch.stack(output)
556
+
557
+ @staticmethod
558
+ def terminal_bins(states, width, bins, align_end=False):
559
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
560
+ assert width > 0 and bins > 0 and width % bins == 0
561
+ states = (states[-width:] if align_end else states[:width]).float()
562
+ count = states.shape[0]
563
+ padded = states.new_zeros(width, states.shape[-1])
564
+ valid = states.new_zeros(width)
565
+ offset = width-count if align_end else 0
566
+ padded[offset:offset+count] = states
567
+ valid[offset:offset+count] = 1
568
+ total = padded.reshape(bins, width//bins, -1).sum(1)
569
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
570
+ return (total/denominator).flatten()
571
+
572
+ def terminal_summary_features(self, task, sequences, device, max_len):
573
+ settings = self.config['terminal_summary_readouts'][task]
574
+ width = max_len-2
575
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
576
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
577
+ hidden, padding = self.encode_residues(tokens, task)
578
+ summary = self.summarize(hidden, tokens, padding, task)
579
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
580
+ tails = {}
581
+ if long_ids:
582
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
583
+ for index in long_ids], device)
584
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
585
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
586
+ terminals = []
587
+ for index, sequence in enumerate(sequences):
588
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
589
+ suffix = tails.get(index, prefix)
590
+ terminals.append(torch.cat([
591
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
592
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
593
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
594
+
595
+ @staticmethod
596
+ def position_features(hidden, lengths, bins):
597
+ features = []
598
+ for index, length in enumerate(lengths):
599
+ if length:
600
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
601
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
602
+ else:
603
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
604
+ return torch.stack(features)
605
+
606
+ def secondary_structure_summary(self, sequences, device, max_len):
607
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
608
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
609
+ with torch.autocast(device_type=device.type,enabled=False):
610
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
611
+ summaries=[]
612
+ for index,sequence in enumerate(sequences):
613
+ length=min(len(sequence),max_len-2)
614
+ if not length:
615
+ summaries.append(probabilities.new_zeros(40));continue
616
+ value=probabilities[index,1:1+length]
617
+ mean=value.mean(0);std=value.std(0,unbiased=False)
618
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
619
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
620
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
621
+ return torch.stack(summaries)
622
+
623
+ def normalize(self, task, values):
624
+ stats = self.config.get('regression_stats', {}).get(task)
625
+ return (values - stats['mean']) / stats['std'] if stats else values
626
+
627
+ def unscale(self, task, values):
628
+ stats = self.config.get('regression_stats', {}).get(task)
629
+ return values * stats['std'] + stats['mean'] if stats else values
630
+
631
+ def transfer(self, state, normalized_source=False):
632
+ """Transfer our own lineage only; retain random init for new parameters."""
633
+ current = self.state_dict()
634
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
635
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
636
+ if not normalized_source:
637
+ with torch.no_grad():
638
+ for task, stats in self.config.get('regression_stats', {}).items():
639
+ # Preserve predictions when moving a trained head to standardized units.
640
+ if f'heads.{task}.3.weight' in fitting:
641
+ self.heads[task][3].weight.div_(stats['std'])
642
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
643
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-dual-summary-subcellular1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 555777281
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ One jointly learned 12-layer, width-512, 8-head transformer supplies all eleven
4
+ tasks. Its original **37,845,535 parameters** are used by every task; two shared
5
+ extension blocks serve beta-lactamase and stability. Exact total:
6
+ **138,135,449 parameters** in one inference state dictionary.
7
+
8
+ Subcellular localization concatenates seven summaries from this common
9
+ backbone with seven from one 12-layer, width-768, 12-head auxiliary encoder
10
+ (85,079,839 parameters). That encoder was also jointly trained on all eleven
11
+ tasks in this session. Only its active pooling row is included. The subcellular
12
+ head substantially depends on both representations: replacing primary features
13
+ by their fixed fit mean reduces Tune accuracy from 0.7908 to 0.7364; removing
14
+ auxiliary features reduces it to 0.5991. Other tasks retain their existing paths.
15
+
16
+ All weights originated from random initialization and training in this session.
17
+ The primary encoder received one hour of MLM on mounted decontaminated UniRef50
18
+ (1,713,641,682 token presentations), then joint all-task supervision, task
19
+ conditioning and shared-extension training. The auxiliary received eight hours
20
+ of MLM (10,254,509,402 token presentations) and 8,486 joint supervised updates.
21
+ Only the mounted UniRef50, fit and permitted Tune data were used. No external
22
+ pretrained weights or embeddings were used.
23
+
24
+ Heads:
25
+
26
+ - Fluorescence and beta-lactamase: normalized linear heads over interpolated
27
+ residue positions, trained on rank targets.
28
+ - Fold and solubility: normalized linear heads over seven sequence summaries.
29
+ - Subcellular localization: one fit-normalized linear head over both encoders'
30
+ summaries, fixed ridge 0.01 and 15 blocks of at most 10 LBFGS iterations.
31
+ - Binary localization: summary head with a shared nonlinear residual jointly
32
+ trained across solubility and both localization tasks.
33
+ - Stability: MLP and normalized final linear head, with balanced length-group
34
+ loss and a fixed 50:50 continuation midpoint.
35
+ - Human PPI: ordered summaries, product and absolute difference. Yeast and
36
+ affinity use symmetric summaries; yeast also uses shared bilinear and residue
37
+ interaction modules jointly trained across all three PPI tasks.
38
+ - Secondary structure: local convolution and residue MLP, with fit-only
39
+ supervision and distillation from an own-session jointly trained teacher.
40
+ Teacher parameters and cached features are absent.
41
+
42
+ Model selection uses complete fit-only Tune replays and fixed matched controls.
43
+ The new development mean is **0.7200272190**, versus 0.7166638090. Subcellular
44
+ accuracy improves from 0.7538242618 to 0.7908217716 (+104/2,811 cases), with a
45
+ conditional paired 95% difference interval [0.02418, 0.05052]; the other ten
46
+ development prediction files are byte-identical. Both matched single-source
47
+ controls score lower. Only final, predeclared readout endpoints were eligible.
48
+
49
+ Production retains the five previously accepted extra-label heads: fold,
50
+ fluorescence, beta-lactamase, affinity and stability. Each used fixed two-half
51
+ cross-fit evidence before fitting its full permitted fit+Tune pool. Their
52
+ features and parameters remain exactly unchanged. Their production Tune scores
53
+ and the aggregate are IN-SAMPLE and excluded from development selection.
54
+ The new subcellular head uses fit labels and fit normalization only.
55
+ Complete independent production replay is valid for all eleven tasks. The ten
56
+ other prediction files are byte-identical to previous production, and the new
57
+ subcellular file is byte-identical to the accepted development candidate.
58
+
59
+ Repeated Tune selection and protein-family dependence limit the conditional
60
+ intervals. Fold generalization remains weak, and PPI validation sets are small.
61
+ SS and PPI use full-chain windows; other tasks retain a 1,022-residue prefix.
62
+ Rank outputs are not calibrated for absolute error. No held-out test results
63
+ are available.
64
+
65
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. This single parameter set
66
+ needs no live trainer, research files, lookup tables or test-time fitting.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/config.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ],
134
+ "dual_summary": {
135
+ "layers": 12,
136
+ "dim": 768,
137
+ "heads": 12,
138
+ "tasks": [
139
+ "subcellular_localization"
140
+ ]
141
+ }
142
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/provenance.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/replay.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained replay shared by research evaluation and frozen packages."""
3
+ import contextlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ import esm2
12
+
13
+ TASKS = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
14
+ 'subcellular_localization', 'binary_localization', 'fold',
15
+ 'secondary_structure', 'yeast_ppi', 'human_ppi', 'ppi_affinity')
16
+
17
+
18
+ def autocast(device):
19
+ return torch.autocast('cuda', dtype=torch.bfloat16) if device.type == 'cuda' else contextlib.nullcontext()
20
+
21
+
22
+ def head_output(model, task, representation, device, fp32=False):
23
+ apply = model.apply_head if hasattr(model, 'apply_head') else lambda task, value: model.heads[task](value)
24
+ if fp32:
25
+ with torch.autocast(device.type, enabled=False):
26
+ values={k:v.float() if v.is_floating_point() else v for k,v in representation.items()} if isinstance(representation,dict) else representation.float()
27
+ return apply(task, values).float()
28
+ return apply(task, representation).float()
29
+
30
+
31
+ def residue_states(model, tokens, task):
32
+ return model.encode_residues(tokens, task) if hasattr(model, 'encode_residues') else model.encoder(tokens)
33
+
34
+
35
+ def windows(length, width=1022, stride=768):
36
+ if length <= width:
37
+ return [(0, length)]
38
+ starts = list(range(0, length - width + 1, stride))
39
+ if starts[-1] != length - width:
40
+ starts.append(length - width)
41
+ return [(s, min(s + width, length)) for s in starts]
42
+
43
+
44
+ def batches(rows, task, token_budget=16384, max_len=1024, max_batch=128):
45
+ lengths = [min(max(map(len, r['features'].values())) + 2, max_len) for r in rows]
46
+ order = sorted(range(len(rows)), key=lengths.__getitem__)
47
+ current, width = [], 0
48
+ for i in order:
49
+ length = lengths[i]
50
+ # Pair sequences require two separate passes, but the peak tensor size is unchanged.
51
+ if current and (max(width, length) * (len(current) + 1) > token_budget or len(current) >= max_batch):
52
+ yield current
53
+ current, width = [], 0
54
+ current.append(i)
55
+ width = max(width, length)
56
+ if current:
57
+ yield current
58
+
59
+
60
+ @torch.inference_mode()
61
+ def predict_records(model, rows, task, device, config=None, token_budget=16384):
62
+ config = config or {}
63
+ max_len = config.get('task_max_len', {}).get(task, config.get('max_len', 1024))
64
+ full_ss = config.get('full_ss', True)
65
+ fp32_option = config.get('fp32_heads', False)
66
+ fp32_heads = fp32_option is True or (isinstance(fp32_option, list) and task in fp32_option)
67
+ was_training = model.training
68
+ model.eval()
69
+ result = {}
70
+ for ids in batches(rows, task, token_budget, max_len):
71
+ chunk = [rows[i] for i in ids]
72
+ features = [r['features'] for r in chunk]
73
+ if task == 'secondary_structure':
74
+ if full_ss and any(len(f['sequence']) > max_len - 2 for f in features):
75
+ for record in chunk:
76
+ seq = record['features']['sequence']
77
+ pieces = windows(len(seq), max_len - 2, min(768, max_len - 2))
78
+ total = np.zeros((len(seq), 3), dtype=np.float32)
79
+ weight_sum = np.zeros((len(seq), 1), dtype=np.float32)
80
+ for begin in range(0, len(pieces), max(1, token_budget // max_len)):
81
+ part = pieces[begin:begin + max(1, token_budget // max_len)]
82
+ tokens = esm2.pad_batch([esm2.encode(seq[s:e], max_len) for s, e in part], device)
83
+ with autocast(device):
84
+ hidden, _ = residue_states(model, tokens, task)
85
+ logits = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
86
+ for j, (s, e) in enumerate(part):
87
+ size = e - s
88
+ # Smooth boundaries, without discarding any residue.
89
+ weight = np.minimum(np.arange(1, size + 1), np.arange(size, 0, -1))
90
+ weight = np.minimum(weight, 128).astype(np.float32)[:, None]
91
+ total[s:e] += logits[j, 1:1+size] * weight
92
+ weight_sum[s:e] += weight
93
+ scores = total / np.maximum(weight_sum, 1)
94
+ result[record['example_id']] = {'ss3_scores': scores.tolist()}
95
+ else:
96
+ tokens = esm2.pad_batch([esm2.encode(f['sequence'], max_len) for f in features], device)
97
+ with autocast(device):
98
+ hidden, _ = residue_states(model, tokens, task)
99
+ probabilities = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
100
+ for j, record in enumerate(chunk):
101
+ length = len(record['features']['sequence'])
102
+ used = min(length, max_len - 2)
103
+ scores = probabilities[j, 1:1+used].tolist()
104
+ scores.extend([[1.0, 1.0, 1.0] for _ in range(length-used)])
105
+ result[record['example_id']] = {'ss3_scores': scores}
106
+ continue
107
+ with autocast(device):
108
+ representation = model.represent(task, features, device, max_len)
109
+ output = head_output(model, task, representation, device, fp32_heads)
110
+ if task in model.CLASSES:
111
+ output = output.softmax(-1)
112
+ if task in config.get('symmetric_pairs', []):
113
+ swapped = [{'sequence_a': f['sequence_b'], 'sequence_b': f['sequence_a']} for f in features]
114
+ swapped_rep = model.represent(task, swapped, device, max_len)
115
+ second = head_output(model, task, swapped_rep, device, fp32_heads)
116
+ if task in model.CLASSES:
117
+ second = second.softmax(-1)
118
+ output = (output + second) * 0.5
119
+ if task in model.CLASSES:
120
+ output = output.clamp_min(1e-9)
121
+ elif hasattr(model, 'unscale'):
122
+ output = model.unscale(task, output)
123
+ values = output.cpu().tolist()
124
+ for record, value in zip(chunk, values):
125
+ result[record['example_id']] = {'scores': value} if task in model.CLASSES else {'value': value[0]}
126
+ if task == 'secondary_structure' and hasattr(model, 'ss_chain_decoder'):
127
+ # Decode complete chains only after all overlapping-window probabilities
128
+ # have been aggregated. No labels or parameter updates enter replay.
129
+ identifiers = [record['example_id'] for record in rows]
130
+ probabilities = [result[identifier]['ss3_scores'] for identifier in identifiers]
131
+ decoded = model.ss_chain_decoder.decode(probabilities)
132
+ for identifier, scores in zip(identifiers, decoded):
133
+ result[identifier] = {'ss3_scores': scores.tolist()}
134
+ model.train(was_training)
135
+ return result
136
+
137
+
138
+ def load_model(package, device):
139
+ config = json.loads((package / 'config.json').read_text())
140
+ if config.get('architecture') == 'unified':
141
+ from unified import UnifiedModel
142
+ model = UnifiedModel(config)
143
+ else:
144
+ model = esm2.Model(layers=config['layers'], dim=config['dim'], heads=config['heads'])
145
+ model.load_state_dict(torch.load(package / 'model.pt', map_location='cpu', weights_only=True))
146
+ return model.to(device).eval(), config
147
+
148
+
149
+ def main():
150
+ if len(sys.argv) != 3:
151
+ raise SystemExit('usage: replay.py INPUT_ROOT OUTPUT_ROOT')
152
+ torch.set_num_threads(6)
153
+ source, destination = Path(sys.argv[1]), Path(sys.argv[2]) / 'predictions'
154
+ destination.mkdir(parents=True, exist_ok=True)
155
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
+ model, config = load_model(Path(__file__).resolve().parent, device)
157
+ for task in TASKS:
158
+ rows = [json.loads(line) for line in (source / f'{task}.jsonl').open()]
159
+ predictions = predict_records(model, rows, task, device, config)
160
+ with (destination / f'{task}.jsonl').open('w') as sink:
161
+ for row in rows:
162
+ sink.write(json.dumps({'example_id': row['example_id'], 'prediction': predictions[row['example_id']]}, separators=(',', ':')) + '\n')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/selection.json ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_ppi_affinity_and_stability",
3
+ "tasks_reusing_tune_labels": [
4
+ "beta_lactamase",
5
+ "fluorescence",
6
+ "fold",
7
+ "ppi_affinity",
8
+ "stability"
9
+ ],
10
+ "production_aggregate_excluded_from_selection": true,
11
+ "fit_only_development_reference": {
12
+ "reward": 0.720027219000325,
13
+ "tasks": {
14
+ "beta_lactamase": {
15
+ "invalid_reason": null,
16
+ "reward": 0.8851158090618965,
17
+ "spearman": 0.8851158090618965
18
+ },
19
+ "binary_localization": {
20
+ "accuracy": 0.9462116830537883,
21
+ "balanced_accuracy": 0.9419155998103367,
22
+ "invalid_reason": null,
23
+ "macro_f1": 0.9439947337349208,
24
+ "reward": 0.9462116830537883
25
+ },
26
+ "fluorescence": {
27
+ "invalid_reason": null,
28
+ "reward": 0.826705913429907,
29
+ "spearman": 0.826705913429907
30
+ },
31
+ "fold": {
32
+ "accuracy": 0.24864130434782608,
33
+ "balanced_accuracy": 0.16124022176653757,
34
+ "invalid_reason": null,
35
+ "macro_f1": 0.03846637235687955,
36
+ "reward": 0.24864130434782608
37
+ },
38
+ "human_ppi": {
39
+ "accuracy": 0.7968253968253968,
40
+ "balanced_accuracy": 0.8005952380952381,
41
+ "invalid_reason": null,
42
+ "macro_f1": 0.7968233491897122,
43
+ "reward": 0.7968253968253968
44
+ },
45
+ "ppi_affinity": {
46
+ "invalid_reason": null,
47
+ "reward": 0.5341420012716276,
48
+ "rmse": 1.9334586965956642,
49
+ "spearman": 0.7162121646852028
50
+ },
51
+ "secondary_structure": {
52
+ "accuracy": 0.7441316787896526,
53
+ "invalid_reason": null,
54
+ "reward": 0.7441316787896526,
55
+ "valid_residues": 556931
56
+ },
57
+ "solubility": {
58
+ "accuracy": 0.7533851915874388,
59
+ "balanced_accuracy": 0.7392508255204544,
60
+ "invalid_reason": null,
61
+ "macro_f1": 0.742264399722415,
62
+ "reward": 0.7533851915874388
63
+ },
64
+ "stability": {
65
+ "invalid_reason": null,
66
+ "reward": 0.7311607642876724,
67
+ "spearman": 0.7311607642876724
68
+ },
69
+ "subcellular_localization": {
70
+ "accuracy": 0.7908217716115261,
71
+ "balanced_accuracy": 0.6999121500389823,
72
+ "invalid_reason": null,
73
+ "macro_f1": 0.7198401417205603,
74
+ "reward": 0.7908217716115261
75
+ },
76
+ "yeast_ppi": {
77
+ "accuracy": 0.6631578947368421,
78
+ "balanced_accuracy": 0.6597985347985349,
79
+ "invalid_reason": null,
80
+ "macro_f1": 0.6567299006323397,
81
+ "reward": 0.6631578947368421
82
+ }
83
+ },
84
+ "package": "/workspace/research/dual-summary-subcellular1-replay/candidate/package",
85
+ "report": "/workspace/research/dual-summary-subcellular1-replay/candidate/report.json",
86
+ "model_sha256": "1b5b390aae06941e5a43cfd8ea681df090499e916750d08604e32963da54a1da",
87
+ "inference_assets_sha256": {
88
+ "model.pt": "1b5b390aae06941e5a43cfd8ea681df090499e916750d08604e32963da54a1da",
89
+ "config.json": "9a737008935673cd4bbfc6df460d7805737a9eabfd77bae76dfaa6e72ac26d9f",
90
+ "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9",
91
+ "unified.py": "c5d22277c0153f0e83cf73324ac87bc0f89160e7a082fd7e8b9eca7ca2639bf3",
92
+ "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85",
93
+ "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468"
94
+ },
95
+ "parameters": 138135449,
96
+ "score_kind": "fit_only_development_tune_selection",
97
+ "decision": "/workspace/research/dual-summary-subcellular1-replay/decision.json"
98
+ },
99
+ "new_fit_only_selection_evidence": {
100
+ "kind": "fit_only_complete_native_tune_replay",
101
+ "task": "subcellular_localization",
102
+ "before": 0.7538242618285308,
103
+ "after": 0.7908217716115261,
104
+ "delta": 0.03699750978299532,
105
+ "conditional95": [
106
+ 0.024181785841337605,
107
+ 0.05052472429740305
108
+ ],
109
+ "mean_delta": 0.0033634099802724027,
110
+ "conditional_mean95": [
111
+ 0.0021983441673943276,
112
+ 0.004593156754309368
113
+ ],
114
+ "case_gain": 104,
115
+ "examples": 2811,
116
+ "matched_controls": {
117
+ "full_minus_parent": {
118
+ "delta": 0.036997509782995375,
119
+ "conditional95": [
120
+ 0.024181785841337605,
121
+ 0.05052472429740305
122
+ ]
123
+ },
124
+ "full_minus_primary": {
125
+ "delta": 0.03948772678762007,
126
+ "conditional95": [
127
+ 0.026680896478121666,
128
+ 0.05407328352899324
129
+ ]
130
+ },
131
+ "full_minus_auxiliary": {
132
+ "delta": 0.013162575595873355,
133
+ "conditional95": [
134
+ 0.002845962290999644,
135
+ 0.022767698327997153
136
+ ]
137
+ }
138
+ },
139
+ "native_dependency": {
140
+ "native_accuracy": 0.7908217716115261,
141
+ "normal_replay_bit_exact": true,
142
+ "primary_ablated": {
143
+ "accuracy": 0.736392742796158,
144
+ "accuracy_drop": 0.054429028815368194,
145
+ "conditional95_drop": [
146
+ 0.04054606901458555,
147
+ 0.06794734969761651
148
+ ],
149
+ "prediction_changes": 464
150
+ },
151
+ "auxiliary_ablated": {
152
+ "accuracy": 0.5990750622554251,
153
+ "accuracy_drop": 0.19174670935610102,
154
+ "conditional95_drop": [
155
+ 0.17467093561010316,
156
+ 0.20988971896122377
157
+ ],
158
+ "prediction_changes": 899
159
+ }
160
+ },
161
+ "task_deltas": {
162
+ "beta_lactamase": 0.0,
163
+ "binary_localization": 0.0,
164
+ "fluorescence": 0.0,
165
+ "fold": 0.0,
166
+ "human_ppi": 0.0,
167
+ "ppi_affinity": 0.0,
168
+ "secondary_structure": 0.0,
169
+ "solubility": 0.0,
170
+ "stability": 0.0,
171
+ "subcellular_localization": 0.03699750978299532,
172
+ "yeast_ppi": 0.0
173
+ },
174
+ "ten_other_prediction_files_byte_exact": true,
175
+ "limitations": "Conditional paired-example bootstrap after repeated Tune selection; not corrected for protein-family dependence. Feature removal is a dependence diagnostic, not an in-distribution intervention."
176
+ },
177
+ "production_replay_pending": false,
178
+ "all11_native_valid": true,
179
+ "all11_prediction_references_exact": true
180
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S055/unified.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class ResidualSequenceConvHead(nn.Module):
117
+ """Learn local sequence motifs alongside the retained summary classifier."""
118
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
119
+ super().__init__()
120
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
121
+ self.register_buffer('mean', torch.zeros(dim))
122
+ self.register_buffer('scale', torch.ones(dim))
123
+ self.project = nn.Linear(dim, channels)
124
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
125
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
126
+ self.output = nn.Linear(4 * channels, outputs)
127
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
128
+ self.dropout = dropout
129
+
130
+ def forward(self, features):
131
+ valid = features['valid'].bool().unsqueeze(-1)
132
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
133
+ summaries = []
134
+ for conv,norm in zip(self.convs,self.norms):
135
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
136
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
137
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
138
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
139
+ summaries.extend([center,maximum])
140
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
141
+ logits=self.output(pooled)
142
+ return self.base(features['summary']) + logits if self.base is not None else logits
143
+
144
+
145
+ class TokenLogMeanExpHead(nn.Module):
146
+ """Class-specific local evidence, pooled without sequence-length bias."""
147
+ def __init__(self, dim, outputs):
148
+ super().__init__()
149
+ self.register_buffer('mean', torch.zeros(dim))
150
+ self.register_buffer('scale', torch.ones(dim))
151
+ self.linear = nn.Linear(dim, outputs)
152
+
153
+ def forward(self, representation):
154
+ values, valid = representation['hidden'].float(), representation['valid']
155
+ logits = self.linear((values-self.mean)/self.scale)
156
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
157
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
158
+
159
+ def packed(self, values, lengths):
160
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
161
+ logits = self.linear((values.float()-self.mean)/self.scale)
162
+ # The stabilizing maximum cancels in the derivative; detach avoids
163
+ # retaining another large token-by-class gradient path.
164
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
165
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
166
+ output_size=len(values))
167
+ exponent = (logits-maximum[index]).exp()
168
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
169
+ return maximum+total.log()-lengths.float().log()[:, None]
170
+
171
+
172
+ class SharedPairResidueInteraction(nn.Module):
173
+ """A shared nonlinear comparison of local states from both protein chains."""
174
+ def __init__(self, dim, settings, classes):
175
+ super().__init__()
176
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
177
+ self.register_buffer('mean', torch.zeros(dim))
178
+ self.register_buffer('scale', torch.ones(dim))
179
+ self.project = nn.Linear(dim, width)
180
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
181
+ nn.Linear(hidden, channels), nn.GELU())
182
+ self.dropout = settings['dropout']
183
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
184
+ for task in sorted(esm2.Model.PAIR)})
185
+ for head in self.heads.values():
186
+ nn.init.zeros_(head.weight)
187
+ nn.init.zeros_(head.bias)
188
+
189
+ def forward(self, task, first, second):
190
+ first = F.gelu(self.project((first-self.mean)/self.scale))
191
+ second = F.gelu(self.project((second-self.mean)/self.scale))
192
+ first = F.dropout(first, self.dropout, self.training)
193
+ second = F.dropout(second, self.dropout, self.training)
194
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
195
+ first[:, :, None]*second[:, None, :]], dim=-1)
196
+ local = self.compare(pair)
197
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
198
+ return self.heads[task](summary)
199
+
200
+
201
+ class SSChainDecoder(nn.Module):
202
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
203
+ def __init__(self):
204
+ super().__init__()
205
+ self.transition = nn.Parameter(torch.empty(3, 3))
206
+ self.start = nn.Parameter(torch.empty(3))
207
+ self.end = nn.Parameter(torch.empty(3))
208
+ for parameter in self.parameters():
209
+ nn.init.normal_(parameter, std=.01)
210
+
211
+ def decode(self, probabilities):
212
+ from ss_chain import decode_probabilities
213
+ values = [parameter.detach().double().cpu().numpy()
214
+ for parameter in (self.transition, self.start, self.end)]
215
+ return decode_probabilities(probabilities, *values)
216
+
217
+
218
+ class UnifiedModel(esm2.Model):
219
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
220
+ 'subcellular_localization', 'binary_localization', 'fold',
221
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
222
+
223
+ def __init__(self, config):
224
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
225
+ self.config = config
226
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
227
+ dim = config['dim']
228
+ if config.get('extension_layers', 0):
229
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
230
+ before_norm=config.get('extension_before_norm', False))
231
+ if config.get('task_conditioning', False):
232
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
233
+ if config.get('pooling', 'mean') == 'rich':
234
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
235
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
236
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
237
+ self.pool_fuse = nn.Linear(6 * dim, dim)
238
+ nn.init.zeros_(self.pool_fuse.weight)
239
+ nn.init.zeros_(self.pool_fuse.bias)
240
+ if config.get('pair_interaction', False):
241
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
242
+ nn.init.zeros_(self.pair_fuse.weight)
243
+ nn.init.zeros_(self.pair_fuse.bias)
244
+ if config.get('ss_context', False):
245
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
246
+ for task in config.get('linear_heads', []):
247
+ width = dim * 2 if task in self.PAIR else dim
248
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
249
+ for task, settings in config.get('residue_readouts', {}).items():
250
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
251
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
252
+ bins = config['residue_readouts'][task]['bins']
253
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
254
+ for task in config.get('summary_readouts', []):
255
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
256
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
257
+ for task in config.get('sequence_composition_readouts', []):
258
+ from sequence_composition import WIDTH
259
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
260
+ assert all(task not in config.get(key,[]) for key in
261
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
262
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
263
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
264
+ for task, temperature in config.get('cosine_heads', {}).items():
265
+ assert task in config.get('summary_readouts', [])
266
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
267
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
268
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
269
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
270
+ for task in config.get('calibrated_heads', []):
271
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
272
+ assert task not in config.get('linear_heads', [])
273
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
274
+ for task in config.get('expanded_pair_readouts', []):
275
+ assert task in self.PAIR
276
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
277
+ if task in config.get('pair_summary_readouts', []):
278
+ assert config.get('pooling') == 'rich'
279
+ width *= 8
280
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
281
+ if config.get('ss_linear_context'):
282
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
283
+ if config.get('ss_calibrated'):
284
+ assert not config.get('ss_linear_context')
285
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
286
+ for task in config.get('ss_summary_readouts', []):
287
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
288
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
289
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
290
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
291
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
292
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
293
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
294
+ assert all(task not in config.get(key, {}) for key in
295
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
296
+ bins = settings['bins']
297
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
298
+ for key in ['prefix_residues', 'suffix_residues'])
299
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
300
+ if config.get('pair_bilinear_rank', 0):
301
+ rank = config['pair_bilinear_rank']
302
+ assert not config.get('pair_summary_readouts')
303
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
304
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
305
+ with torch.no_grad():
306
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
307
+ self.pair_bilinear_heads = nn.ModuleDict({
308
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
309
+ for task in sorted(self.PAIR)})
310
+ for head in self.pair_bilinear_heads.values():
311
+ nn.init.zeros_(head.weight)
312
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
313
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
314
+ if config.get('pair_residue_interaction'):
315
+ self.pair_residue_interaction = SharedPairResidueInteraction(
316
+ dim, config['pair_residue_interaction'], self.CLASSES)
317
+ for task in config.get('token_logmeanexp_heads', []):
318
+ assert task in self.CLASSES and task not in self.PAIR
319
+ assert task not in config.get('sequence_windows', [])
320
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
321
+ if config.get('ss_chain_decoder', False):
322
+ self.ss_chain_decoder = SSChainDecoder()
323
+ if config.get('shared_summary_residual'):
324
+ settings = config['shared_summary_residual']
325
+ tasks = settings['tasks']
326
+ assert all(task in config.get('summary_readouts', []) and
327
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
328
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
329
+ {task: self.CLASSES[task] for task in tasks})
330
+
331
+ if config.get('dual_summary'):
332
+ settings = config['dual_summary']
333
+ tasks = settings['tasks']
334
+ assert tasks and len(tasks) == len(set(tasks))
335
+ assert config.get('pooling') == 'rich'
336
+ assert all(task in config.get('summary_readouts', []) and task not in self.PAIR for task in tasks)
337
+ assert all(task not in config.get(key, {}) for task in tasks for key in
338
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts',
339
+ 'sequence_conv_readouts', 'terminal_summary_readouts', 'token_logmeanexp_heads',
340
+ 'summary_residual_tasks', 'sequence_composition_readouts'])
341
+ self.auxiliary_summary_encoder = esm2.Encoder(settings['layers'], settings['dim'], settings['heads'])
342
+ self.auxiliary_summary_index = {task: i for i, task in enumerate(tasks)}
343
+ self.auxiliary_pool_query = nn.Parameter(torch.randn(len(tasks), 2, settings['dim']) * .02)
344
+ self.auxiliary_pool_position = nn.Parameter(torch.zeros(len(tasks), 2, 4))
345
+ for task in tasks:
346
+ self.heads[task] = NormalizedLinear(7*(dim+settings['dim']), self.CLASSES[task])
347
+
348
+ def pair_representation(self, task, first, second, base):
349
+ if task in self.config.get('pair_bilinear_tasks', []):
350
+ return {'base': base, 'chain_a': first, 'chain_b': second}
351
+ return base
352
+
353
+ def apply_head(self, task, representation):
354
+ if task in self.config.get('summary_residual_tasks', []):
355
+ head = self.heads[task]
356
+ normalized = (representation-head.mean)/head.scale
357
+ return head(representation) + self.summary_residual(task, normalized)
358
+ if isinstance(representation, dict) and 'residue_a' in representation:
359
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
360
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
361
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
362
+ if isinstance(representation, dict) and 'chain_a' in representation:
363
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
364
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
365
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
366
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
367
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
368
+ return self.heads[task](representation)
369
+
370
+ def encode_residues(self, tokens, task):
371
+ condition = None
372
+ if self.config.get('task_conditioning', False):
373
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
374
+ condition = self.task_condition[ti]
375
+ return self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
376
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
377
+
378
+ def pool(self, tokens, task):
379
+ hidden, pad_mask = self.encode_residues(tokens, task)
380
+ primary = self.summarize(hidden, tokens, pad_mask, task)
381
+ if task in self.config.get('dual_summary', {}).get('tasks', []):
382
+ auxiliary, auxiliary_mask = self.auxiliary_summary_encoder(tokens)
383
+ secondary = self.auxiliary_summarize(auxiliary, tokens, auxiliary_mask, task)
384
+ return torch.cat([primary, secondary], dim=-1)
385
+ return primary
386
+
387
+ def summarize(self, hidden, tokens, pad_mask, task):
388
+ valid = (~pad_mask).unsqueeze(-1)
389
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
390
+ if self.config.get('pooling', 'mean') == 'mean':
391
+ return mean
392
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
393
+ # Empty/nonstandard-only inputs still produce a finite representation.
394
+ residues[:, 0] |= ~residues.any(1)
395
+ keep = residues.unsqueeze(-1)
396
+ count = keep.sum(1).clamp_min(1)
397
+ center = (hidden * keep).sum(1) / count
398
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
399
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
400
+ torch.cos(position * math.pi)], dim=-1)
401
+ ti = self.task_index[task]
402
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
403
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
404
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
405
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
406
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
407
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
408
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
409
+ first = residues & (residues.cumsum(1) <= 32)
410
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
411
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
412
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
413
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
414
+ deviation, maximum, prefix, suffix], dim=-1)
415
+ if task in self.config.get('summary_readouts', []):
416
+ return torch.cat([mean, summary], dim=-1)
417
+ if task in self.config.get('pair_summary_readouts', []):
418
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
419
+ return mean + self.pool_fuse(summary)
420
+
421
+ def auxiliary_summarize(self, hidden, tokens, pad_mask, task):
422
+ valid = (~pad_mask).unsqueeze(-1)
423
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
424
+ if self.config.get('pooling', 'mean') == 'mean':
425
+ return mean
426
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
427
+ # Empty/nonstandard-only inputs still produce a finite representation.
428
+ residues[:, 0] |= ~residues.any(1)
429
+ keep = residues.unsqueeze(-1)
430
+ count = keep.sum(1).clamp_min(1)
431
+ center = (hidden * keep).sum(1) / count
432
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
433
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
434
+ torch.cos(position * math.pi)], dim=-1)
435
+ ti = self.auxiliary_summary_index[task]
436
+ scores = torch.einsum('bld,qd->blq', hidden, self.auxiliary_pool_query[ti]) / math.sqrt(hidden.shape[-1])
437
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.auxiliary_pool_position[ti])
438
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
439
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
440
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
441
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
442
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
443
+ first = residues & (residues.cumsum(1) <= 32)
444
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
445
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
446
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
447
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
448
+ deviation, maximum, prefix, suffix], dim=-1)
449
+ return torch.cat([mean, summary], dim=-1)
450
+
451
+ def pool_sequences(self, sequences, task, device, max_len):
452
+ if self.training and not self.config.get('window_pooling_training', True):
453
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
454
+ return self.pool(tokens,task)
455
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
456
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
457
+ results=[None]*len(sequences)
458
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
459
+ if short:
460
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
461
+ for j,index in enumerate(short):results[index]=pooled[j]
462
+ width=max_len-2;stride=min(768,width)
463
+ if self.training and self.config.get('batch_window_training',False):
464
+ pieces=[];starts_by_index={};encoded={}
465
+ for index,sequence in enumerate(sequences):
466
+ if len(sequence)<=width:continue
467
+ starts=list(range(0,len(sequence)-width+1,stride))
468
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
469
+ starts_by_index[index]=starts
470
+ pieces.extend((index,start) for start in starts)
471
+ count=max(1,16384//max_len)
472
+ for begin in range(0,len(pieces),count):
473
+ part=pieces[begin:begin+count]
474
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
475
+ hidden,_=self.encode_residues(tokens,task)
476
+ for j,key in enumerate(part):encoded[key]=hidden[j]
477
+ positions=torch.arange(width,device=device)
478
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
479
+ for index,starts in starts_by_index.items():
480
+ sequence=sequences[index];length=len(sequence)
481
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
482
+ for start in starts:
483
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
484
+ counts.index_add_(0,positions+start,weight)
485
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
486
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
487
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
488
+ return torch.stack(results)
489
+ for index,sequence in enumerate(sequences):
490
+ length=len(sequence)
491
+ if length<=width:continue
492
+ starts=list(range(0,length-width+1,stride))
493
+ if starts[-1]!=length-width:starts.append(length-width)
494
+ total=torch.zeros(length,self.config['dim'],device=device)
495
+ counts=torch.zeros(length,1,device=device)
496
+ first=last=None
497
+ for begin in range(0,len(starts),max(1,16384//max_len)):
498
+ part=starts[begin:begin+max(1,16384//max_len)]
499
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
500
+ hidden,_=self.encode_residues(tokens,task)
501
+ for j,start in enumerate(part):
502
+ if start==0:first=hidden[j,0:1]
503
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
504
+ positions=torch.arange(width,device=device)
505
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
506
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
507
+ counts.index_add_(0,positions+start,weight)
508
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
509
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
510
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
511
+ return torch.stack(results)
512
+
513
+ def represent(self, task, batch, device, max_len=1024):
514
+ if task in self.config.get('sequence_composition_readouts', []):
515
+ from sequence_composition import composition_features
516
+ sequences=[item['sequence'] for item in batch]
517
+ pooled=self.pool_sequences(sequences,task,device,max_len)
518
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
519
+ if task in self.config.get('token_logmeanexp_heads', []):
520
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
521
+ hidden, _ = self.encode_residues(tokens, task)
522
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
523
+ valid[:, 0] |= ~valid.any(1)
524
+ return {'hidden':hidden, 'valid':valid}
525
+ if task in self.config.get('terminal_summary_readouts', {}):
526
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
527
+ if task in self.config.get('ss_summary_readouts', []):
528
+ sequences=[x['sequence'] for x in batch]
529
+ summary=self.pool_sequences(sequences,task,device,max_len)
530
+ structure=self.secondary_structure_summary(sequences,device,max_len)
531
+ return torch.cat([summary.float(),structure],-1)
532
+ if task in self.config.get('sequence_conv_readouts',{}):
533
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
534
+ hidden,pad_mask=self.encode_residues(tokens,task)
535
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
536
+ width=max(1,int(lengths.max()))
537
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
538
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
539
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
540
+ if task in self.config.get('residue_readouts', {}):
541
+ bins = self.config['residue_readouts'][task]['bins']
542
+ sequences = [x['sequence'] for x in batch]
543
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
544
+ hidden, _ = self.encode_residues(tokens, task)
545
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
546
+ if task in self.PAIR:
547
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
548
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
549
+ if task in self.config.get('expanded_pair_readouts', []):
550
+ if task in self.config.get('symmetric_pair_readouts',[]):
551
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
552
+ else:
553
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
554
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
555
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
556
+ output = torch.cat([a, b], dim=-1)
557
+ if self.config.get('pair_interaction', False):
558
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
559
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
560
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
561
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
562
+
563
+ def add_pair_residues(self, task, batch, device, max_len, base):
564
+ if task not in self.config.get('pair_residue_tasks', []):
565
+ return base
566
+ result = dict(base) if isinstance(base, dict) else {'base': base}
567
+ bins = self.config['pair_residue_interaction']['bins']
568
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
569
+ result['residue_'+role] = self.pool_residue_bins(
570
+ [row[name] for row in batch], task, device, max_len, bins)
571
+ return result
572
+
573
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
574
+ """Average every residue into fixed relative bins, with full-chain context."""
575
+ width = max_len-2
576
+ assert width > 0 and bins > 0
577
+ output = [None]*len(sequences)
578
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
579
+ if short:
580
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
581
+ hidden, _ = self.encode_residues(tokens, task)
582
+ for j, index in enumerate(short):
583
+ length = len(sequences[index])
584
+ values = hidden[j, 1:1+length].float()
585
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
586
+ else torch.zeros(bins, self.config['dim'], device=device))
587
+ for index, sequence in enumerate(sequences):
588
+ if len(sequence) <= width:
589
+ continue
590
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
591
+ if starts[-1] != len(sequence)-width:
592
+ starts.append(len(sequence)-width)
593
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
594
+ count = torch.zeros(len(sequence), 1, device=device)
595
+ position = torch.arange(width, device=device)
596
+ weight = torch.minimum(torch.minimum(position+1, width-position),
597
+ torch.full_like(position, 128)).float()[:, None]
598
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
599
+ part = starts[begin:begin+max(1, 16384//max_len)]
600
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
601
+ hidden, _ = self.encode_residues(tokens, task)
602
+ for j, start in enumerate(part):
603
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
604
+ count.index_add_(0, position+start, weight)
605
+ values = total/count.clamp_min(1)
606
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
607
+ return torch.stack(output)
608
+
609
+ @staticmethod
610
+ def terminal_bins(states, width, bins, align_end=False):
611
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
612
+ assert width > 0 and bins > 0 and width % bins == 0
613
+ states = (states[-width:] if align_end else states[:width]).float()
614
+ count = states.shape[0]
615
+ padded = states.new_zeros(width, states.shape[-1])
616
+ valid = states.new_zeros(width)
617
+ offset = width-count if align_end else 0
618
+ padded[offset:offset+count] = states
619
+ valid[offset:offset+count] = 1
620
+ total = padded.reshape(bins, width//bins, -1).sum(1)
621
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
622
+ return (total/denominator).flatten()
623
+
624
+ def terminal_summary_features(self, task, sequences, device, max_len):
625
+ settings = self.config['terminal_summary_readouts'][task]
626
+ width = max_len-2
627
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
628
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
629
+ hidden, padding = self.encode_residues(tokens, task)
630
+ summary = self.summarize(hidden, tokens, padding, task)
631
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
632
+ tails = {}
633
+ if long_ids:
634
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
635
+ for index in long_ids], device)
636
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
637
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
638
+ terminals = []
639
+ for index, sequence in enumerate(sequences):
640
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
641
+ suffix = tails.get(index, prefix)
642
+ terminals.append(torch.cat([
643
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
644
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
645
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
646
+
647
+ @staticmethod
648
+ def position_features(hidden, lengths, bins):
649
+ features = []
650
+ for index, length in enumerate(lengths):
651
+ if length:
652
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
653
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
654
+ else:
655
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
656
+ return torch.stack(features)
657
+
658
+ def secondary_structure_summary(self, sequences, device, max_len):
659
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
660
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
661
+ with torch.autocast(device_type=device.type,enabled=False):
662
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
663
+ summaries=[]
664
+ for index,sequence in enumerate(sequences):
665
+ length=min(len(sequence),max_len-2)
666
+ if not length:
667
+ summaries.append(probabilities.new_zeros(40));continue
668
+ value=probabilities[index,1:1+length]
669
+ mean=value.mean(0);std=value.std(0,unbiased=False)
670
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
671
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
672
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
673
+ return torch.stack(summaries)
674
+
675
+ def normalize(self, task, values):
676
+ stats = self.config.get('regression_stats', {}).get(task)
677
+ return (values - stats['mean']) / stats['std'] if stats else values
678
+
679
+ def unscale(self, task, values):
680
+ stats = self.config.get('regression_stats', {}).get(task)
681
+ return values * stats['std'] + stats['mean'] if stats else values
682
+
683
+ def transfer(self, state, normalized_source=False):
684
+ """Transfer our own lineage only; retain random init for new parameters."""
685
+ current = self.state_dict()
686
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
687
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
688
+ if not normalized_source:
689
+ with torch.no_grad():
690
+ for task, stats in self.config.get('regression_stats', {}).items():
691
+ # Preserve predictions when moving a trained head to standardized units.
692
+ if f'heads.{task}.3.weight' in fitting:
693
+ self.heads[task][3].weight.div_(stats['std'])
694
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
695
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-shared-fusion8h-ss1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 558590100
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/README.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ Exact total: **138,597,529 parameters**, in one inference state dictionary.
4
+ A jointly learned 12-layer, width-512, 8-head transformer supplies all eleven
5
+ tasks. Its original **37,845,535 parameters** remain common to every task;
6
+ two shared extension blocks serve beta-lactamase and stability.
7
+
8
+ One 12-layer, width-768, 12-head auxiliary encoder (85,079,839 parameters)
9
+ supplies subcellular summaries and secondary-structure fusion. It was also
10
+ jointly trained on all eleven tasks here and is stored once. Subcellular uses
11
+ one normalized linear head over both encoders' seven summaries. SS adds a
12
+ shared 462,080-parameter residue map: LayerNorm(1280), Linear(1280,256), GELU,
13
+ Linear(256,512), with a residual connection to the primary representation.
14
+ This map received 4,000 joint all-task fit updates with frozen encoders and
15
+ heads. Only SS enables it in this package; one final EMA state is used.
16
+
17
+ All weights originated from random initialization and training in this session.
18
+ The primary received one hour of MLM on mounted decontaminated UniRef50
19
+ (1,713,641,682 token presentations), followed by joint fit supervision,
20
+ task conditioning and shared-extension training. The auxiliary received eight
21
+ hours of MLM (10,254,509,402 token presentations) and 8,486 joint supervised
22
+ updates. Only mounted UniRef50, fit and permitted Tune data were used.
23
+
24
+ Heads:
25
+
26
+ - Fluorescence/beta-lactamase: normalized linear heads over interpolated residue
27
+ positions, trained on rank targets.
28
+ - Fold/solubility: normalized linear heads over seven sequence summaries.
29
+ - Subcellular: one fit-normalized combined-summary linear head, ridge 0.01.
30
+ - Binary localization: summary head plus a nonlinear residual jointly trained
31
+ across solubility and both localization tasks.
32
+ - Stability: MLP and normalized final linear head, balanced length-group loss,
33
+ and a fixed 50:50 continuation midpoint.
34
+ - Human PPI: ordered summaries, product and absolute difference. Yeast/affinity
35
+ use symmetric summaries; yeast also uses shared bilinear and residue modules
36
+ jointly trained across all three PPI tasks.
37
+ - Secondary structure: the shared residue fusion followed by a local convolution
38
+ and residue MLP. Its earlier head distillation used an own-session teacher;
39
+ teacher parameters and feature caches are absent.
40
+
41
+ The fit-only development reference scores **0.7214368926** across all eleven
42
+ Tune tasks. Subcellular accuracy is 0.7908217716, versus its previous 0.7538242618.
43
+ The new SS accuracy is 0.7596380880, versus 0.7441316788 (+8,636 valid residues);
44
+ its conditional paired-protein 95% difference interval is [0.01431, 0.01673].
45
+ A matched zero-auxiliary fusion control scored 0.7439539189. Same data, CPU/CUDA
46
+ RNG and optimizer clocks were verified; only final 4,000-update EMA weights
47
+ were eligible. Ten other production prediction files are byte-identical to the
48
+ previous package. Complete offline replay is valid for all eleven tasks.
49
+
50
+ SS substantially uses the common primary backbone: zeroing primary residues
51
+ reduces accuracy to 0.6834275700; zeroing auxiliary residues gives 0.7315897301.
52
+ Subcellular primary-feature removal gives 0.7363927428, and auxiliary-feature
53
+ removal gives 0.5990750623. These are frozen-feature diagnostics, not fitting.
54
+
55
+ Production retains five previously accepted fit+Tune heads: fold, fluorescence,
56
+ beta-lactamase, affinity and stability. Each recipe used positive fixed two-half
57
+ cross-fit evidence before fitting the full permitted pool. Their feature paths
58
+ and parameters are unchanged here. Their production Tune scores and aggregate
59
+ are IN-SAMPLE and excluded from development selection. All other heads and
60
+ shared encoders use fit-only supervised gradients.
61
+
62
+ Repeated Tune selection and protein-family dependence limit the intervals.
63
+ Fold generalization remains weak, and PPI validation sets are small. SS/PPI use
64
+ full-chain windows; other tasks retain a 1,022-residue prefix. Rank outputs are
65
+ not calibrated for absolute error. No held-out test result is available.
66
+
67
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. No live trainer, research
68
+ files, external weights, lookup table or test-time fitting is required.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/config.json ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ],
134
+ "dual_summary": {
135
+ "layers": 12,
136
+ "dim": 768,
137
+ "heads": 12,
138
+ "tasks": [
139
+ "subcellular_localization"
140
+ ]
141
+ },
142
+ "shared_fusion": {
143
+ "layers": 12,
144
+ "dim": 768,
145
+ "heads": 12,
146
+ "hidden": 256,
147
+ "conditioned": false,
148
+ "auxiliary_input": true
149
+ },
150
+ "shared_fusion_tasks": [
151
+ "secondary_structure"
152
+ ]
153
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/replay.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained replay shared by research evaluation and frozen packages."""
3
+ import contextlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ import esm2
12
+
13
+ TASKS = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
14
+ 'subcellular_localization', 'binary_localization', 'fold',
15
+ 'secondary_structure', 'yeast_ppi', 'human_ppi', 'ppi_affinity')
16
+
17
+
18
+ def autocast(device):
19
+ return torch.autocast('cuda', dtype=torch.bfloat16) if device.type == 'cuda' else contextlib.nullcontext()
20
+
21
+
22
+ def head_output(model, task, representation, device, fp32=False):
23
+ apply = model.apply_head if hasattr(model, 'apply_head') else lambda task, value: model.heads[task](value)
24
+ if fp32:
25
+ with torch.autocast(device.type, enabled=False):
26
+ values={k:v.float() if v.is_floating_point() else v for k,v in representation.items()} if isinstance(representation,dict) else representation.float()
27
+ return apply(task, values).float()
28
+ return apply(task, representation).float()
29
+
30
+
31
+ def residue_states(model, tokens, task):
32
+ return model.encode_residues(tokens, task) if hasattr(model, 'encode_residues') else model.encoder(tokens)
33
+
34
+
35
+ def windows(length, width=1022, stride=768):
36
+ if length <= width:
37
+ return [(0, length)]
38
+ starts = list(range(0, length - width + 1, stride))
39
+ if starts[-1] != length - width:
40
+ starts.append(length - width)
41
+ return [(s, min(s + width, length)) for s in starts]
42
+
43
+
44
+ def batches(rows, task, token_budget=16384, max_len=1024, max_batch=128):
45
+ lengths = [min(max(map(len, r['features'].values())) + 2, max_len) for r in rows]
46
+ order = sorted(range(len(rows)), key=lengths.__getitem__)
47
+ current, width = [], 0
48
+ for i in order:
49
+ length = lengths[i]
50
+ # Pair sequences require two separate passes, but the peak tensor size is unchanged.
51
+ if current and (max(width, length) * (len(current) + 1) > token_budget or len(current) >= max_batch):
52
+ yield current
53
+ current, width = [], 0
54
+ current.append(i)
55
+ width = max(width, length)
56
+ if current:
57
+ yield current
58
+
59
+
60
+ @torch.inference_mode()
61
+ def predict_records(model, rows, task, device, config=None, token_budget=16384):
62
+ config = config or {}
63
+ max_len = config.get('task_max_len', {}).get(task, config.get('max_len', 1024))
64
+ full_ss = config.get('full_ss', True)
65
+ fp32_option = config.get('fp32_heads', False)
66
+ fp32_heads = fp32_option is True or (isinstance(fp32_option, list) and task in fp32_option)
67
+ was_training = model.training
68
+ model.eval()
69
+ result = {}
70
+ for ids in batches(rows, task, token_budget, max_len):
71
+ chunk = [rows[i] for i in ids]
72
+ features = [r['features'] for r in chunk]
73
+ if task == 'secondary_structure':
74
+ if full_ss and any(len(f['sequence']) > max_len - 2 for f in features):
75
+ for record in chunk:
76
+ seq = record['features']['sequence']
77
+ pieces = windows(len(seq), max_len - 2, min(768, max_len - 2))
78
+ total = np.zeros((len(seq), 3), dtype=np.float32)
79
+ weight_sum = np.zeros((len(seq), 1), dtype=np.float32)
80
+ for begin in range(0, len(pieces), max(1, token_budget // max_len)):
81
+ part = pieces[begin:begin + max(1, token_budget // max_len)]
82
+ tokens = esm2.pad_batch([esm2.encode(seq[s:e], max_len) for s, e in part], device)
83
+ with autocast(device):
84
+ hidden, _ = residue_states(model, tokens, task)
85
+ logits = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
86
+ for j, (s, e) in enumerate(part):
87
+ size = e - s
88
+ # Smooth boundaries, without discarding any residue.
89
+ weight = np.minimum(np.arange(1, size + 1), np.arange(size, 0, -1))
90
+ weight = np.minimum(weight, 128).astype(np.float32)[:, None]
91
+ total[s:e] += logits[j, 1:1+size] * weight
92
+ weight_sum[s:e] += weight
93
+ scores = total / np.maximum(weight_sum, 1)
94
+ result[record['example_id']] = {'ss3_scores': scores.tolist()}
95
+ else:
96
+ tokens = esm2.pad_batch([esm2.encode(f['sequence'], max_len) for f in features], device)
97
+ with autocast(device):
98
+ hidden, _ = residue_states(model, tokens, task)
99
+ probabilities = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
100
+ for j, record in enumerate(chunk):
101
+ length = len(record['features']['sequence'])
102
+ used = min(length, max_len - 2)
103
+ scores = probabilities[j, 1:1+used].tolist()
104
+ scores.extend([[1.0, 1.0, 1.0] for _ in range(length-used)])
105
+ result[record['example_id']] = {'ss3_scores': scores}
106
+ continue
107
+ with autocast(device):
108
+ representation = model.represent(task, features, device, max_len)
109
+ output = head_output(model, task, representation, device, fp32_heads)
110
+ if task in model.CLASSES:
111
+ output = output.softmax(-1)
112
+ if task in config.get('symmetric_pairs', []):
113
+ swapped = [{'sequence_a': f['sequence_b'], 'sequence_b': f['sequence_a']} for f in features]
114
+ swapped_rep = model.represent(task, swapped, device, max_len)
115
+ second = head_output(model, task, swapped_rep, device, fp32_heads)
116
+ if task in model.CLASSES:
117
+ second = second.softmax(-1)
118
+ output = (output + second) * 0.5
119
+ if task in model.CLASSES:
120
+ output = output.clamp_min(1e-9)
121
+ elif hasattr(model, 'unscale'):
122
+ output = model.unscale(task, output)
123
+ values = output.cpu().tolist()
124
+ for record, value in zip(chunk, values):
125
+ result[record['example_id']] = {'scores': value} if task in model.CLASSES else {'value': value[0]}
126
+ if task == 'secondary_structure' and hasattr(model, 'ss_chain_decoder'):
127
+ # Decode complete chains only after all overlapping-window probabilities
128
+ # have been aggregated. No labels or parameter updates enter replay.
129
+ identifiers = [record['example_id'] for record in rows]
130
+ probabilities = [result[identifier]['ss3_scores'] for identifier in identifiers]
131
+ decoded = model.ss_chain_decoder.decode(probabilities)
132
+ for identifier, scores in zip(identifiers, decoded):
133
+ result[identifier] = {'ss3_scores': scores.tolist()}
134
+ model.train(was_training)
135
+ return result
136
+
137
+
138
+ def load_model(package, device):
139
+ config = json.loads((package / 'config.json').read_text())
140
+ if config.get('architecture') == 'unified':
141
+ from unified import UnifiedModel
142
+ model = UnifiedModel(config)
143
+ else:
144
+ model = esm2.Model(layers=config['layers'], dim=config['dim'], heads=config['heads'])
145
+ model.load_state_dict(torch.load(package / 'model.pt', map_location='cpu', weights_only=True))
146
+ return model.to(device).eval(), config
147
+
148
+
149
+ def main():
150
+ if len(sys.argv) != 3:
151
+ raise SystemExit('usage: replay.py INPUT_ROOT OUTPUT_ROOT')
152
+ torch.set_num_threads(6)
153
+ source, destination = Path(sys.argv[1]), Path(sys.argv[2]) / 'predictions'
154
+ destination.mkdir(parents=True, exist_ok=True)
155
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
+ model, config = load_model(Path(__file__).resolve().parent, device)
157
+ for task in TASKS:
158
+ rows = [json.loads(line) for line in (source / f'{task}.jsonl').open()]
159
+ predictions = predict_records(model, rows, task, device, config)
160
+ with (destination / f'{task}.jsonl').open('w') as sink:
161
+ for row in rows:
162
+ sink.write(json.dumps({'example_id': row['example_id'], 'prediction': predictions[row['example_id']]}, separators=(',', ':')) + '\n')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/selection.json ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_ppi_affinity_and_stability",
3
+ "tasks_reusing_tune_labels": [
4
+ "fold",
5
+ "fluorescence",
6
+ "beta_lactamase",
7
+ "ppi_affinity",
8
+ "stability"
9
+ ],
10
+ "production_aggregate_excluded_from_selection": true,
11
+ "fit_only_development_reference": {
12
+ "reward": 0.7214368925668725,
13
+ "tasks": {
14
+ "beta_lactamase": {
15
+ "invalid_reason": null,
16
+ "reward": 0.8851158090618965,
17
+ "spearman": 0.8851158090618965
18
+ },
19
+ "binary_localization": {
20
+ "accuracy": 0.9462116830537883,
21
+ "balanced_accuracy": 0.9419155998103367,
22
+ "invalid_reason": null,
23
+ "macro_f1": 0.9439947337349208,
24
+ "reward": 0.9462116830537883
25
+ },
26
+ "fluorescence": {
27
+ "invalid_reason": null,
28
+ "reward": 0.826705913429907,
29
+ "spearman": 0.826705913429907
30
+ },
31
+ "fold": {
32
+ "accuracy": 0.24864130434782608,
33
+ "balanced_accuracy": 0.16124022176653757,
34
+ "invalid_reason": null,
35
+ "macro_f1": 0.03846637235687955,
36
+ "reward": 0.24864130434782608
37
+ },
38
+ "human_ppi": {
39
+ "accuracy": 0.7968253968253968,
40
+ "balanced_accuracy": 0.8005952380952381,
41
+ "invalid_reason": null,
42
+ "macro_f1": 0.7968233491897122,
43
+ "reward": 0.7968253968253968
44
+ },
45
+ "ppi_affinity": {
46
+ "invalid_reason": null,
47
+ "reward": 0.5341420012716276,
48
+ "rmse": 1.9334586965956642,
49
+ "spearman": 0.7162121646852028
50
+ },
51
+ "secondary_structure": {
52
+ "accuracy": 0.759638088021676,
53
+ "invalid_reason": null,
54
+ "reward": 0.759638088021676,
55
+ "valid_residues": 556931
56
+ },
57
+ "solubility": {
58
+ "accuracy": 0.7533851915874388,
59
+ "balanced_accuracy": 0.7392508255204544,
60
+ "invalid_reason": null,
61
+ "macro_f1": 0.742264399722415,
62
+ "reward": 0.7533851915874388
63
+ },
64
+ "stability": {
65
+ "invalid_reason": null,
66
+ "reward": 0.7311607642876724,
67
+ "spearman": 0.7311607642876724
68
+ },
69
+ "subcellular_localization": {
70
+ "accuracy": 0.7908217716115261,
71
+ "balanced_accuracy": 0.6999121500389823,
72
+ "invalid_reason": null,
73
+ "macro_f1": 0.7198401417205603,
74
+ "reward": 0.7908217716115261
75
+ },
76
+ "yeast_ppi": {
77
+ "accuracy": 0.6631578947368421,
78
+ "balanced_accuracy": 0.6597985347985349,
79
+ "invalid_reason": null,
80
+ "macro_f1": 0.6567299006323397,
81
+ "reward": 0.6631578947368421
82
+ }
83
+ },
84
+ "package": "/workspace/research/shared-fusion8h-selected-replay/candidate/package",
85
+ "report": "/workspace/research/shared-fusion8h-selected-replay/candidate/report.json",
86
+ "model_sha256": "8ce3336ad317cf13cf739101485bec029683a2a781f11443887372704e75e8f1",
87
+ "inference_assets_sha256": {
88
+ "model.pt": "8ce3336ad317cf13cf739101485bec029683a2a781f11443887372704e75e8f1",
89
+ "config.json": "b70e96d927ab3daeac46fbb18f190b04ac05d070fe40850c9f8872b7d5e796b0",
90
+ "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9",
91
+ "unified.py": "adbd895246362ab23497425b9f906685c1a95560116563fefa07bfff75bfe45b",
92
+ "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85",
93
+ "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468"
94
+ },
95
+ "parameters": 138597529,
96
+ "score_kind": "fit_only_development_tune_selection",
97
+ "decision": "/workspace/research/shared-fusion8h-selected-replay/decision.json"
98
+ },
99
+ "pending_independent_replay": false,
100
+ "evidence": {
101
+ "full_original_study": {
102
+ "status": "selected_pending_assembly_ablations_and_native_review",
103
+ "chosen_arm": "full",
104
+ "candidates": {
105
+ "zero": {
106
+ "enabled_tasks": [],
107
+ "routed_mean": 0.7166638090200526,
108
+ "mean_gain": 0.0,
109
+ "conditional95": [
110
+ 0.0,
111
+ 0.0
112
+ ],
113
+ "eligible": false
114
+ },
115
+ "full": {
116
+ "enabled_tasks": [
117
+ "secondary_structure",
118
+ "subcellular_localization"
119
+ ],
120
+ "routed_mean": 0.7188819946010887,
121
+ "mean_gain": 0.002218185581036117,
122
+ "conditional95": [
123
+ 0.0015618427916501052,
124
+ 0.0029223180172046797
125
+ ],
126
+ "eligible": true,
127
+ "same_routes_control_comparison": {
128
+ "mean_delta": 0.002266686052709703,
129
+ "conditional95": [
130
+ 0.00163301878385431,
131
+ 0.0028783273901904533
132
+ ],
133
+ "definition": "Treatment-enabled routes only; all other task deltas zero. Both states are final4000EMA."
134
+ }
135
+ }
136
+ },
137
+ "tasks": {
138
+ "beta_lactamase": {
139
+ "examples": 520,
140
+ "parent": 0.8851158090618965,
141
+ "zero": 0.8848969852420536,
142
+ "full": 0.8845439568759146,
143
+ "comparisons": {
144
+ "zero_minus_parent": {
145
+ "delta": -0.00021882381984283938,
146
+ "conditional95": [
147
+ -0.0019190809982984557,
148
+ 0.001469238318171373
149
+ ]
150
+ },
151
+ "full_minus_parent": {
152
+ "delta": -0.0005718521859818804,
153
+ "conditional95": [
154
+ -0.002610170059700731,
155
+ 0.0012711578290376243
156
+ ]
157
+ },
158
+ "full_minus_zero": {
159
+ "delta": -0.000353028366139041,
160
+ "conditional95": [
161
+ -0.001745614993564945,
162
+ 0.0009405445898092214
163
+ ]
164
+ }
165
+ }
166
+ },
167
+ "binary_localization": {
168
+ "examples": 1729,
169
+ "parent": 0.9462116830537883,
170
+ "zero": 0.945054945054945,
171
+ "full": 0.945054945054945,
172
+ "comparisons": {
173
+ "zero_minus_parent": {
174
+ "delta": -0.0011567379988433046,
175
+ "conditional95": [
176
+ -0.0046269519953731075,
177
+ 0.002313475997686501
178
+ ]
179
+ },
180
+ "full_minus_parent": {
181
+ "delta": -0.0011567379988433046,
182
+ "conditional95": [
183
+ -0.0063620589936379535,
184
+ 0.003470213996529803
185
+ ]
186
+ },
187
+ "full_minus_zero": {
188
+ "delta": 0.0,
189
+ "conditional95": [
190
+ -0.004048582995951344,
191
+ 0.004048582995951344
192
+ ]
193
+ }
194
+ }
195
+ },
196
+ "fluorescence": {
197
+ "examples": 5362,
198
+ "parent": 0.826705913429907,
199
+ "zero": 0.8261891093573827,
200
+ "full": 0.8261173562838637,
201
+ "comparisons": {
202
+ "zero_minus_parent": {
203
+ "delta": -0.0005168040725243017,
204
+ "conditional95": [
205
+ -0.0009074676903033013,
206
+ -0.00010004212525541478
207
+ ]
208
+ },
209
+ "full_minus_parent": {
210
+ "delta": -0.0005885571460432226,
211
+ "conditional95": [
212
+ -0.001125277545181083,
213
+ -5.1938701607648406e-05
214
+ ]
215
+ },
216
+ "full_minus_zero": {
217
+ "delta": -7.175307351892091e-05,
218
+ "conditional95": [
219
+ -0.0005318636811548316,
220
+ 0.0003805983773495475
221
+ ]
222
+ }
223
+ }
224
+ },
225
+ "fold": {
226
+ "examples": 736,
227
+ "parent": 0.24864130434782608,
228
+ "zero": 0.24320652173913043,
229
+ "full": 0.24592391304347827,
230
+ "comparisons": {
231
+ "zero_minus_parent": {
232
+ "delta": -0.0054347826086956486,
233
+ "conditional95": [
234
+ -0.014945652173913027,
235
+ 0.002717391304347838
236
+ ]
237
+ },
238
+ "full_minus_parent": {
239
+ "delta": -0.0027173913043478104,
240
+ "conditional95": [
241
+ -0.012228260869565244,
242
+ 0.008152173913043459
243
+ ]
244
+ },
245
+ "full_minus_zero": {
246
+ "delta": 0.002717391304347838,
247
+ "conditional95": [
248
+ -0.005434782608695676,
249
+ 0.012228260869565216
250
+ ]
251
+ }
252
+ }
253
+ },
254
+ "human_ppi": {
255
+ "examples": 315,
256
+ "parent": 0.7968253968253968,
257
+ "zero": 0.7841269841269841,
258
+ "full": 0.780952380952381,
259
+ "comparisons": {
260
+ "zero_minus_parent": {
261
+ "delta": -0.012698412698412653,
262
+ "conditional95": [
263
+ -0.03492063492063491,
264
+ 0.009523809523809493
265
+ ]
266
+ },
267
+ "full_minus_parent": {
268
+ "delta": -0.015873015873015817,
269
+ "conditional95": [
270
+ -0.0444444444444444,
271
+ 0.012698412698412764
272
+ ]
273
+ },
274
+ "full_minus_zero": {
275
+ "delta": -0.0031746031746031633,
276
+ "conditional95": [
277
+ -0.022222222222222254,
278
+ 0.015873015873015817
279
+ ]
280
+ }
281
+ }
282
+ },
283
+ "ppi_affinity": {
284
+ "examples": 203,
285
+ "parent": 0.5341420012716276,
286
+ "zero": 0.5189355347334772,
287
+ "full": 0.5250420716238517,
288
+ "comparisons": {
289
+ "zero_minus_parent": {
290
+ "delta": -0.015206466538150387,
291
+ "conditional95": [
292
+ -0.027845041079411027,
293
+ -0.004519207693363675
294
+ ]
295
+ },
296
+ "full_minus_parent": {
297
+ "delta": -0.00909992964777584,
298
+ "conditional95": [
299
+ -0.01808313521817929,
300
+ -0.0005967466520302408
301
+ ]
302
+ },
303
+ "full_minus_zero": {
304
+ "delta": 0.006106536890374548,
305
+ "conditional95": [
306
+ 0.0007892307088291708,
307
+ 0.012730268854570593
308
+ ]
309
+ }
310
+ }
311
+ },
312
+ "secondary_structure": {
313
+ "examples": 2170,
314
+ "parent": 0.7441316787896526,
315
+ "zero": 0.7439539188876181,
316
+ "full": 0.759638088021676,
317
+ "comparisons": {
318
+ "zero_minus_parent": {
319
+ "delta": -0.0001777599020345022,
320
+ "conditional95": [
321
+ -0.0004337054552560532,
322
+ 8.817027773533869e-05
323
+ ]
324
+ },
325
+ "full_minus_parent": {
326
+ "delta": 0.0155064092320234,
327
+ "conditional95": [
328
+ 0.014309663742752683,
329
+ 0.016726396557557775
330
+ ]
331
+ },
332
+ "full_minus_zero": {
333
+ "delta": 0.0156841691340579,
334
+ "conditional95": [
335
+ 0.014499037971929394,
336
+ 0.01689329854300642
337
+ ]
338
+ }
339
+ }
340
+ },
341
+ "solubility": {
342
+ "examples": 6942,
343
+ "parent": 0.7533851915874388,
344
+ "zero": 0.7492077211178335,
345
+ "full": 0.7539613944108327,
346
+ "comparisons": {
347
+ "zero_minus_parent": {
348
+ "delta": -0.00417747046960526,
349
+ "conditional95": [
350
+ -0.007202535292422985,
351
+ -0.0008643042350907626
352
+ ]
353
+ },
354
+ "full_minus_parent": {
355
+ "delta": 0.0005762028233938787,
356
+ "conditional95": [
357
+ -0.003892970325554695,
358
+ 0.005189426678190781
359
+ ]
360
+ },
361
+ "full_minus_zero": {
362
+ "delta": 0.004753673292999139,
363
+ "conditional95": [
364
+ 0.0004321521175453258,
365
+ 0.00907519446845284
366
+ ]
367
+ }
368
+ }
369
+ },
370
+ "stability": {
371
+ "examples": 2512,
372
+ "parent": 0.7311607642876724,
373
+ "zero": 0.730056227683189,
374
+ "full": 0.7329317436395436,
375
+ "comparisons": {
376
+ "zero_minus_parent": {
377
+ "delta": -0.001104536604483397,
378
+ "conditional95": [
379
+ -0.0028202937870095784,
380
+ 0.0005720436213680235
381
+ ]
382
+ },
383
+ "full_minus_parent": {
384
+ "delta": 0.0017709793518712047,
385
+ "conditional95": [
386
+ -0.0009297756963640934,
387
+ 0.004598901782002785
388
+ ]
389
+ },
390
+ "full_minus_zero": {
391
+ "delta": 0.0028755159563546018,
392
+ "conditional95": [
393
+ 0.0007289400154873922,
394
+ 0.005253062278283147
395
+ ]
396
+ }
397
+ }
398
+ },
399
+ "subcellular_localization": {
400
+ "examples": 2811,
401
+ "parent": 0.7538242618285308,
402
+ "zero": 0.7534685165421559,
403
+ "full": 0.7627178939879047,
404
+ "comparisons": {
405
+ "zero_minus_parent": {
406
+ "delta": -0.0003557452863749422,
407
+ "conditional95": [
408
+ -0.00570081821415867,
409
+ 0.004980434009249302
410
+ ]
411
+ },
412
+ "full_minus_parent": {
413
+ "delta": 0.008893632159373888,
414
+ "conditional95": [
415
+ 0.0010672358591249376,
416
+ 0.016364283173248007
417
+ ]
418
+ },
419
+ "full_minus_zero": {
420
+ "delta": 0.00924937744574883,
421
+ "conditional95": [
422
+ 0.0024902170046247063,
423
+ 0.015652792600498015
424
+ ]
425
+ }
426
+ }
427
+ },
428
+ "yeast_ppi": {
429
+ "examples": 95,
430
+ "parent": 0.6631578947368421,
431
+ "zero": 0.6421052631578947,
432
+ "full": 0.6421052631578947,
433
+ "comparisons": {
434
+ "zero_minus_parent": {
435
+ "delta": -0.021052631578947323,
436
+ "conditional95": [
437
+ -0.0736842105263158,
438
+ 0.03157894736842104
439
+ ]
440
+ },
441
+ "full_minus_parent": {
442
+ "delta": -0.021052631578947323,
443
+ "conditional95": [
444
+ -0.0736842105263158,
445
+ 0.021315789473684035
446
+ ]
447
+ },
448
+ "full_minus_zero": {
449
+ "delta": 0.0,
450
+ "conditional95": [
451
+ -0.03157894736842104,
452
+ 0.03157894736842104
453
+ ]
454
+ }
455
+ }
456
+ }
457
+ },
458
+ "one_final_EMA_state_per_arm": true,
459
+ "mixed_shared_weights": false,
460
+ "bootstrap_draws": 1000,
461
+ "bootstrap_seed": 20261111,
462
+ "sampling": "Paired examples per task; SS by protein. Same resamples for all three predictions.",
463
+ "limitations": "Repeated tune selection; conditional intervals do not correct selection or protein-family dependence. Zero auxiliary changes joint LayerNorm input distribution.",
464
+ "published": false,
465
+ "next": "If eligible, use one complete shared state, prove primary dependency, prune unused auxiliary for zero, native replay and compare current selected. Renew extra-label evidence on changed feature routes."
466
+ },
467
+ "retained_dual_tasks": [
468
+ "subcellular_localization"
469
+ ],
470
+ "active_fusion_tasks": [
471
+ "secondary_structure"
472
+ ],
473
+ "remaining_full_minus_zero_conditional95": [
474
+ 0.014499037971929394,
475
+ 0.01689329854300642
476
+ ],
477
+ "SS_gain": {
478
+ "delta": 0.0155064092320234,
479
+ "conditional95": [
480
+ 0.014309663742752683,
481
+ 0.016726396557557775
482
+ ]
483
+ },
484
+ "production_extra_label_feature_paths_unchanged": true,
485
+ "limitations": "Conditional paired protein intervals after repeated Tune selection; not corrected for protein-family dependence."
486
+ },
487
+ "all11_native_valid": true,
488
+ "all11_prediction_references_exact": true
489
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S056/unified.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class ResidualSequenceConvHead(nn.Module):
117
+ """Learn local sequence motifs alongside the retained summary classifier."""
118
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
119
+ super().__init__()
120
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
121
+ self.register_buffer('mean', torch.zeros(dim))
122
+ self.register_buffer('scale', torch.ones(dim))
123
+ self.project = nn.Linear(dim, channels)
124
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
125
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
126
+ self.output = nn.Linear(4 * channels, outputs)
127
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
128
+ self.dropout = dropout
129
+
130
+ def forward(self, features):
131
+ valid = features['valid'].bool().unsqueeze(-1)
132
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
133
+ summaries = []
134
+ for conv,norm in zip(self.convs,self.norms):
135
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
136
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
137
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
138
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
139
+ summaries.extend([center,maximum])
140
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
141
+ logits=self.output(pooled)
142
+ return self.base(features['summary']) + logits if self.base is not None else logits
143
+
144
+
145
+ class TokenLogMeanExpHead(nn.Module):
146
+ """Class-specific local evidence, pooled without sequence-length bias."""
147
+ def __init__(self, dim, outputs):
148
+ super().__init__()
149
+ self.register_buffer('mean', torch.zeros(dim))
150
+ self.register_buffer('scale', torch.ones(dim))
151
+ self.linear = nn.Linear(dim, outputs)
152
+
153
+ def forward(self, representation):
154
+ values, valid = representation['hidden'].float(), representation['valid']
155
+ logits = self.linear((values-self.mean)/self.scale)
156
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
157
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
158
+
159
+ def packed(self, values, lengths):
160
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
161
+ logits = self.linear((values.float()-self.mean)/self.scale)
162
+ # The stabilizing maximum cancels in the derivative; detach avoids
163
+ # retaining another large token-by-class gradient path.
164
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
165
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
166
+ output_size=len(values))
167
+ exponent = (logits-maximum[index]).exp()
168
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
169
+ return maximum+total.log()-lengths.float().log()[:, None]
170
+
171
+
172
+ class SharedPairResidueInteraction(nn.Module):
173
+ """A shared nonlinear comparison of local states from both protein chains."""
174
+ def __init__(self, dim, settings, classes):
175
+ super().__init__()
176
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
177
+ self.register_buffer('mean', torch.zeros(dim))
178
+ self.register_buffer('scale', torch.ones(dim))
179
+ self.project = nn.Linear(dim, width)
180
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
181
+ nn.Linear(hidden, channels), nn.GELU())
182
+ self.dropout = settings['dropout']
183
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
184
+ for task in sorted(esm2.Model.PAIR)})
185
+ for head in self.heads.values():
186
+ nn.init.zeros_(head.weight)
187
+ nn.init.zeros_(head.bias)
188
+
189
+ def forward(self, task, first, second):
190
+ first = F.gelu(self.project((first-self.mean)/self.scale))
191
+ second = F.gelu(self.project((second-self.mean)/self.scale))
192
+ first = F.dropout(first, self.dropout, self.training)
193
+ second = F.dropout(second, self.dropout, self.training)
194
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
195
+ first[:, :, None]*second[:, None, :]], dim=-1)
196
+ local = self.compare(pair)
197
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
198
+ return self.heads[task](summary)
199
+
200
+
201
+ class SSChainDecoder(nn.Module):
202
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
203
+ def __init__(self):
204
+ super().__init__()
205
+ self.transition = nn.Parameter(torch.empty(3, 3))
206
+ self.start = nn.Parameter(torch.empty(3))
207
+ self.end = nn.Parameter(torch.empty(3))
208
+ for parameter in self.parameters():
209
+ nn.init.normal_(parameter, std=.01)
210
+
211
+ def decode(self, probabilities):
212
+ from ss_chain import decode_probabilities
213
+ values = [parameter.detach().double().cpu().numpy()
214
+ for parameter in (self.transition, self.start, self.end)]
215
+ return decode_probabilities(probabilities, *values)
216
+
217
+
218
+ class UnifiedModel(esm2.Model):
219
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
220
+ 'subcellular_localization', 'binary_localization', 'fold',
221
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
222
+
223
+ def __init__(self, config):
224
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
225
+ self.config = config
226
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
227
+ dim = config['dim']
228
+ if config.get('extension_layers', 0):
229
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
230
+ before_norm=config.get('extension_before_norm', False))
231
+ if config.get('task_conditioning', False):
232
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
233
+ if config.get('pooling', 'mean') == 'rich':
234
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
235
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
236
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
237
+ self.pool_fuse = nn.Linear(6 * dim, dim)
238
+ nn.init.zeros_(self.pool_fuse.weight)
239
+ nn.init.zeros_(self.pool_fuse.bias)
240
+ if config.get('pair_interaction', False):
241
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
242
+ nn.init.zeros_(self.pair_fuse.weight)
243
+ nn.init.zeros_(self.pair_fuse.bias)
244
+ if config.get('ss_context', False):
245
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
246
+ for task in config.get('linear_heads', []):
247
+ width = dim * 2 if task in self.PAIR else dim
248
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
249
+ for task, settings in config.get('residue_readouts', {}).items():
250
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
251
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
252
+ bins = config['residue_readouts'][task]['bins']
253
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
254
+ for task in config.get('summary_readouts', []):
255
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
256
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
257
+ for task in config.get('sequence_composition_readouts', []):
258
+ from sequence_composition import WIDTH
259
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
260
+ assert all(task not in config.get(key,[]) for key in
261
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
262
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
263
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
264
+ for task, temperature in config.get('cosine_heads', {}).items():
265
+ assert task in config.get('summary_readouts', [])
266
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
267
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
268
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
269
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
270
+ for task in config.get('calibrated_heads', []):
271
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
272
+ assert task not in config.get('linear_heads', [])
273
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
274
+ for task in config.get('expanded_pair_readouts', []):
275
+ assert task in self.PAIR
276
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
277
+ if task in config.get('pair_summary_readouts', []):
278
+ assert config.get('pooling') == 'rich'
279
+ width *= 8
280
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
281
+ if config.get('ss_linear_context'):
282
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
283
+ if config.get('ss_calibrated'):
284
+ assert not config.get('ss_linear_context')
285
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
286
+ for task in config.get('ss_summary_readouts', []):
287
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
288
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
289
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
290
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
291
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
292
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
293
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
294
+ assert all(task not in config.get(key, {}) for key in
295
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
296
+ bins = settings['bins']
297
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
298
+ for key in ['prefix_residues', 'suffix_residues'])
299
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
300
+ if config.get('pair_bilinear_rank', 0):
301
+ rank = config['pair_bilinear_rank']
302
+ assert not config.get('pair_summary_readouts')
303
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
304
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
305
+ with torch.no_grad():
306
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
307
+ self.pair_bilinear_heads = nn.ModuleDict({
308
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
309
+ for task in sorted(self.PAIR)})
310
+ for head in self.pair_bilinear_heads.values():
311
+ nn.init.zeros_(head.weight)
312
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
313
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
314
+ if config.get('pair_residue_interaction'):
315
+ self.pair_residue_interaction = SharedPairResidueInteraction(
316
+ dim, config['pair_residue_interaction'], self.CLASSES)
317
+ for task in config.get('token_logmeanexp_heads', []):
318
+ assert task in self.CLASSES and task not in self.PAIR
319
+ assert task not in config.get('sequence_windows', [])
320
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
321
+ if config.get('ss_chain_decoder', False):
322
+ self.ss_chain_decoder = SSChainDecoder()
323
+ if config.get('shared_summary_residual'):
324
+ settings = config['shared_summary_residual']
325
+ tasks = settings['tasks']
326
+ assert all(task in config.get('summary_readouts', []) and
327
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
328
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
329
+ {task: self.CLASSES[task] for task in tasks})
330
+
331
+ if config.get('dual_summary'):
332
+ settings = config['dual_summary']
333
+ tasks = settings['tasks']
334
+ assert tasks and len(tasks) == len(set(tasks))
335
+ assert config.get('pooling') == 'rich'
336
+ assert all(task in config.get('summary_readouts', []) and task not in self.PAIR for task in tasks)
337
+ assert all(task not in config.get(key, {}) for task in tasks for key in
338
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts',
339
+ 'sequence_conv_readouts', 'terminal_summary_readouts', 'token_logmeanexp_heads',
340
+ 'summary_residual_tasks', 'sequence_composition_readouts'])
341
+ self.auxiliary_summary_encoder = esm2.Encoder(settings['layers'], settings['dim'], settings['heads'])
342
+ self.auxiliary_summary_index = {task: i for i, task in enumerate(tasks)}
343
+ self.auxiliary_pool_query = nn.Parameter(torch.randn(len(tasks), 2, settings['dim']) * .02)
344
+ self.auxiliary_pool_position = nn.Parameter(torch.zeros(len(tasks), 2, 4))
345
+ for task in tasks:
346
+ self.heads[task] = NormalizedLinear(7*(dim+settings['dim']), self.CLASSES[task])
347
+
348
+ if config.get('shared_fusion'):
349
+ settings = config['shared_fusion']
350
+ dual = config['dual_summary']
351
+ assert not settings.get('conditioned', True)
352
+ assert all(settings[k] == dual[k] for k in ['layers', 'dim', 'heads'])
353
+ active = config['shared_fusion_tasks']
354
+ assert active and not set(active).intersection(dual['tasks'])
355
+ # One auxiliary module supplies both uses; never register a duplicate alias.
356
+ width = dim + settings['dim']
357
+ self.shared_fusion = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, settings['hidden']),
358
+ nn.GELU(), nn.Linear(settings['hidden'], dim))
359
+ nn.init.normal_(self.shared_fusion[1].weight, std=.02)
360
+ nn.init.zeros_(self.shared_fusion[1].bias)
361
+ nn.init.zeros_(self.shared_fusion[3].weight)
362
+ nn.init.zeros_(self.shared_fusion[3].bias)
363
+
364
+ def pair_representation(self, task, first, second, base):
365
+ if task in self.config.get('pair_bilinear_tasks', []):
366
+ return {'base': base, 'chain_a': first, 'chain_b': second}
367
+ return base
368
+
369
+ def apply_head(self, task, representation):
370
+ if task in self.config.get('summary_residual_tasks', []):
371
+ head = self.heads[task]
372
+ normalized = (representation-head.mean)/head.scale
373
+ return head(representation) + self.summary_residual(task, normalized)
374
+ if isinstance(representation, dict) and 'residue_a' in representation:
375
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
376
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
377
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
378
+ if isinstance(representation, dict) and 'chain_a' in representation:
379
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
380
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
381
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
382
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
383
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
384
+ return self.heads[task](representation)
385
+
386
+ def encode_residues(self, tokens, task):
387
+ condition = None
388
+ if self.config.get('task_conditioning', False):
389
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
390
+ condition = self.task_condition[ti]
391
+ hidden, padding = self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
392
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
393
+ if self.config.get('shared_fusion') and task in self.config['shared_fusion_tasks']:
394
+ auxiliary, auxiliary_padding = self.auxiliary_summary_encoder(tokens)
395
+ if not self.config['shared_fusion'].get('auxiliary_input', True):
396
+ auxiliary = torch.zeros_like(auxiliary)
397
+ correction = self.shared_fusion(torch.cat([hidden, auxiliary], -1))
398
+ hidden = (hidden + correction).masked_fill(padding.unsqueeze(-1), 0)
399
+ return hidden, padding
400
+
401
+ def pool(self, tokens, task):
402
+ hidden, pad_mask = self.encode_residues(tokens, task)
403
+ primary = self.summarize(hidden, tokens, pad_mask, task)
404
+ if task in self.config.get('dual_summary', {}).get('tasks', []):
405
+ auxiliary, auxiliary_mask = self.auxiliary_summary_encoder(tokens)
406
+ secondary = self.auxiliary_summarize(auxiliary, tokens, auxiliary_mask, task)
407
+ return torch.cat([primary, secondary], dim=-1)
408
+ return primary
409
+
410
+ def summarize(self, hidden, tokens, pad_mask, task):
411
+ valid = (~pad_mask).unsqueeze(-1)
412
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
413
+ if self.config.get('pooling', 'mean') == 'mean':
414
+ return mean
415
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
416
+ # Empty/nonstandard-only inputs still produce a finite representation.
417
+ residues[:, 0] |= ~residues.any(1)
418
+ keep = residues.unsqueeze(-1)
419
+ count = keep.sum(1).clamp_min(1)
420
+ center = (hidden * keep).sum(1) / count
421
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
422
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
423
+ torch.cos(position * math.pi)], dim=-1)
424
+ ti = self.task_index[task]
425
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
426
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
427
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
428
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
429
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
430
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
431
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
432
+ first = residues & (residues.cumsum(1) <= 32)
433
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
434
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
435
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
436
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
437
+ deviation, maximum, prefix, suffix], dim=-1)
438
+ if task in self.config.get('summary_readouts', []):
439
+ return torch.cat([mean, summary], dim=-1)
440
+ if task in self.config.get('pair_summary_readouts', []):
441
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
442
+ return mean + self.pool_fuse(summary)
443
+
444
+ def auxiliary_summarize(self, hidden, tokens, pad_mask, task):
445
+ valid = (~pad_mask).unsqueeze(-1)
446
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
447
+ if self.config.get('pooling', 'mean') == 'mean':
448
+ return mean
449
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
450
+ # Empty/nonstandard-only inputs still produce a finite representation.
451
+ residues[:, 0] |= ~residues.any(1)
452
+ keep = residues.unsqueeze(-1)
453
+ count = keep.sum(1).clamp_min(1)
454
+ center = (hidden * keep).sum(1) / count
455
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
456
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
457
+ torch.cos(position * math.pi)], dim=-1)
458
+ ti = self.auxiliary_summary_index[task]
459
+ scores = torch.einsum('bld,qd->blq', hidden, self.auxiliary_pool_query[ti]) / math.sqrt(hidden.shape[-1])
460
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.auxiliary_pool_position[ti])
461
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
462
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
463
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
464
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
465
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
466
+ first = residues & (residues.cumsum(1) <= 32)
467
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
468
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
469
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
470
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
471
+ deviation, maximum, prefix, suffix], dim=-1)
472
+ return torch.cat([mean, summary], dim=-1)
473
+
474
+ def pool_sequences(self, sequences, task, device, max_len):
475
+ if self.training and not self.config.get('window_pooling_training', True):
476
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
477
+ return self.pool(tokens,task)
478
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
479
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
480
+ results=[None]*len(sequences)
481
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
482
+ if short:
483
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
484
+ for j,index in enumerate(short):results[index]=pooled[j]
485
+ width=max_len-2;stride=min(768,width)
486
+ if self.training and self.config.get('batch_window_training',False):
487
+ pieces=[];starts_by_index={};encoded={}
488
+ for index,sequence in enumerate(sequences):
489
+ if len(sequence)<=width:continue
490
+ starts=list(range(0,len(sequence)-width+1,stride))
491
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
492
+ starts_by_index[index]=starts
493
+ pieces.extend((index,start) for start in starts)
494
+ count=max(1,16384//max_len)
495
+ for begin in range(0,len(pieces),count):
496
+ part=pieces[begin:begin+count]
497
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
498
+ hidden,_=self.encode_residues(tokens,task)
499
+ for j,key in enumerate(part):encoded[key]=hidden[j]
500
+ positions=torch.arange(width,device=device)
501
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
502
+ for index,starts in starts_by_index.items():
503
+ sequence=sequences[index];length=len(sequence)
504
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
505
+ for start in starts:
506
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
507
+ counts.index_add_(0,positions+start,weight)
508
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
509
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
510
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
511
+ return torch.stack(results)
512
+ for index,sequence in enumerate(sequences):
513
+ length=len(sequence)
514
+ if length<=width:continue
515
+ starts=list(range(0,length-width+1,stride))
516
+ if starts[-1]!=length-width:starts.append(length-width)
517
+ total=torch.zeros(length,self.config['dim'],device=device)
518
+ counts=torch.zeros(length,1,device=device)
519
+ first=last=None
520
+ for begin in range(0,len(starts),max(1,16384//max_len)):
521
+ part=starts[begin:begin+max(1,16384//max_len)]
522
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
523
+ hidden,_=self.encode_residues(tokens,task)
524
+ for j,start in enumerate(part):
525
+ if start==0:first=hidden[j,0:1]
526
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
527
+ positions=torch.arange(width,device=device)
528
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
529
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
530
+ counts.index_add_(0,positions+start,weight)
531
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
532
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
533
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
534
+ return torch.stack(results)
535
+
536
+ def represent(self, task, batch, device, max_len=1024):
537
+ if task in self.config.get('sequence_composition_readouts', []):
538
+ from sequence_composition import composition_features
539
+ sequences=[item['sequence'] for item in batch]
540
+ pooled=self.pool_sequences(sequences,task,device,max_len)
541
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
542
+ if task in self.config.get('token_logmeanexp_heads', []):
543
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
544
+ hidden, _ = self.encode_residues(tokens, task)
545
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
546
+ valid[:, 0] |= ~valid.any(1)
547
+ return {'hidden':hidden, 'valid':valid}
548
+ if task in self.config.get('terminal_summary_readouts', {}):
549
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
550
+ if task in self.config.get('ss_summary_readouts', []):
551
+ sequences=[x['sequence'] for x in batch]
552
+ summary=self.pool_sequences(sequences,task,device,max_len)
553
+ structure=self.secondary_structure_summary(sequences,device,max_len)
554
+ return torch.cat([summary.float(),structure],-1)
555
+ if task in self.config.get('sequence_conv_readouts',{}):
556
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
557
+ hidden,pad_mask=self.encode_residues(tokens,task)
558
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
559
+ width=max(1,int(lengths.max()))
560
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
561
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
562
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
563
+ if task in self.config.get('residue_readouts', {}):
564
+ bins = self.config['residue_readouts'][task]['bins']
565
+ sequences = [x['sequence'] for x in batch]
566
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
567
+ hidden, _ = self.encode_residues(tokens, task)
568
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
569
+ if task in self.PAIR:
570
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
571
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
572
+ if task in self.config.get('expanded_pair_readouts', []):
573
+ if task in self.config.get('symmetric_pair_readouts',[]):
574
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
575
+ else:
576
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
577
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
578
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
579
+ output = torch.cat([a, b], dim=-1)
580
+ if self.config.get('pair_interaction', False):
581
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
582
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
583
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
584
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
585
+
586
+ def add_pair_residues(self, task, batch, device, max_len, base):
587
+ if task not in self.config.get('pair_residue_tasks', []):
588
+ return base
589
+ result = dict(base) if isinstance(base, dict) else {'base': base}
590
+ bins = self.config['pair_residue_interaction']['bins']
591
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
592
+ result['residue_'+role] = self.pool_residue_bins(
593
+ [row[name] for row in batch], task, device, max_len, bins)
594
+ return result
595
+
596
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
597
+ """Average every residue into fixed relative bins, with full-chain context."""
598
+ width = max_len-2
599
+ assert width > 0 and bins > 0
600
+ output = [None]*len(sequences)
601
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
602
+ if short:
603
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
604
+ hidden, _ = self.encode_residues(tokens, task)
605
+ for j, index in enumerate(short):
606
+ length = len(sequences[index])
607
+ values = hidden[j, 1:1+length].float()
608
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
609
+ else torch.zeros(bins, self.config['dim'], device=device))
610
+ for index, sequence in enumerate(sequences):
611
+ if len(sequence) <= width:
612
+ continue
613
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
614
+ if starts[-1] != len(sequence)-width:
615
+ starts.append(len(sequence)-width)
616
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
617
+ count = torch.zeros(len(sequence), 1, device=device)
618
+ position = torch.arange(width, device=device)
619
+ weight = torch.minimum(torch.minimum(position+1, width-position),
620
+ torch.full_like(position, 128)).float()[:, None]
621
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
622
+ part = starts[begin:begin+max(1, 16384//max_len)]
623
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
624
+ hidden, _ = self.encode_residues(tokens, task)
625
+ for j, start in enumerate(part):
626
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
627
+ count.index_add_(0, position+start, weight)
628
+ values = total/count.clamp_min(1)
629
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
630
+ return torch.stack(output)
631
+
632
+ @staticmethod
633
+ def terminal_bins(states, width, bins, align_end=False):
634
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
635
+ assert width > 0 and bins > 0 and width % bins == 0
636
+ states = (states[-width:] if align_end else states[:width]).float()
637
+ count = states.shape[0]
638
+ padded = states.new_zeros(width, states.shape[-1])
639
+ valid = states.new_zeros(width)
640
+ offset = width-count if align_end else 0
641
+ padded[offset:offset+count] = states
642
+ valid[offset:offset+count] = 1
643
+ total = padded.reshape(bins, width//bins, -1).sum(1)
644
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
645
+ return (total/denominator).flatten()
646
+
647
+ def terminal_summary_features(self, task, sequences, device, max_len):
648
+ settings = self.config['terminal_summary_readouts'][task]
649
+ width = max_len-2
650
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
651
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
652
+ hidden, padding = self.encode_residues(tokens, task)
653
+ summary = self.summarize(hidden, tokens, padding, task)
654
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
655
+ tails = {}
656
+ if long_ids:
657
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
658
+ for index in long_ids], device)
659
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
660
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
661
+ terminals = []
662
+ for index, sequence in enumerate(sequences):
663
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
664
+ suffix = tails.get(index, prefix)
665
+ terminals.append(torch.cat([
666
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
667
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
668
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
669
+
670
+ @staticmethod
671
+ def position_features(hidden, lengths, bins):
672
+ features = []
673
+ for index, length in enumerate(lengths):
674
+ if length:
675
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
676
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
677
+ else:
678
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
679
+ return torch.stack(features)
680
+
681
+ def secondary_structure_summary(self, sequences, device, max_len):
682
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
683
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
684
+ with torch.autocast(device_type=device.type,enabled=False):
685
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
686
+ summaries=[]
687
+ for index,sequence in enumerate(sequences):
688
+ length=min(len(sequence),max_len-2)
689
+ if not length:
690
+ summaries.append(probabilities.new_zeros(40));continue
691
+ value=probabilities[index,1:1+length]
692
+ mean=value.mean(0);std=value.std(0,unbiased=False)
693
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
694
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
695
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
696
+ return torch.stack(summaries)
697
+
698
+ def normalize(self, task, values):
699
+ stats = self.config.get('regression_stats', {}).get(task)
700
+ return (values - stats['mean']) / stats['std'] if stats else values
701
+
702
+ def unscale(self, task, values):
703
+ stats = self.config.get('regression_stats', {}).get(task)
704
+ return values * stats['std'] + stats['mean'] if stats else values
705
+
706
+ def transfer(self, state, normalized_source=False):
707
+ """Transfer our own lineage only; retain random init for new parameters."""
708
+ current = self.state_dict()
709
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
710
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
711
+ if not normalized_source:
712
+ with torch.no_grad():
713
+ for task, stats in self.config.get('regression_stats', {}).items():
714
+ # Preserve predictions when moving a trained head to standardized units.
715
+ if f'heads.{task}.3.weight' in fitting:
716
+ self.heads[task][3].weight.div_(stats['std'])
717
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
718
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-dual-residue-ss1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 561974415
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ Exact total: **139,328,153 parameters** in one state dictionary. The same jointly
4
+ learned 12-layer, width-512, 8-head primary transformer supplies all eleven
5
+ tasks; its original **37,845,535 parameters** remain common to every task.
6
+ Two shared extension blocks serve beta-lactamase and stability. One 12-layer,
7
+ width-768, 12-head auxiliary encoder supplies subcellular summaries and SS
8
+ residue features. It was also jointly trained on all eleven tasks here and is
9
+ stored once.
10
+
11
+ SS concatenates frozen local convolution/MLP features from the primary and
12
+ auxiliary residues, followed by one fit-normalized 1280-to-3 linear readout.
13
+ Subcellular retains the accepted combined seven-summary head. Remaining heads
14
+ retain their existing paths: rank-target position readouts for fluorescence
15
+ and beta-lactamase; summary heads for fold/solubility/binary localization;
16
+ the stability MLP; and paired summary heads with retained shared interaction
17
+ modules for PPI. Binary retains its shared summary residual. The SS local
18
+ prefixes remain fixed; the previous optional SS residue-fusion map is absent.
19
+
20
+ Every parameter originated from random initialization and training in this
21
+ session. The primary received one hour of mounted UniRef50 MLM followed by
22
+ joint fit supervision, conditioning and extension training. The auxiliary
23
+ received eight hours of MLM (10,254,509,402 token presentations) and 8,486 joint
24
+ fit updates. The primary SS prefix includes earlier own-teacher distillation.
25
+ No external weights, embeddings or data were used.
26
+
27
+ The new head compares three same-width primary-only, auxiliary-only and full
28
+ readouts on the same fixed 500,000 valid fit residues, including each native
29
+ overlapping-window view. Fixed seed 20270212, ridge 0.01, fit mean/std, FP32
30
+ LBFGS, and 12 blocks of at most 10 iterations are used. Only final endpoints
31
+ were eligible. All three CUDA interrupted/resumed checks passed. Native source
32
+ feature caches reproduce valid Tune argmax exactly and are absent here.
33
+
34
+ Native SS accuracy is 0.7674307948 versus 0.7596380880 for the previous fusion
35
+ reference and 0.7654377293 for the matched auxiliary-only control. The paired
36
+ protein 95% improvement intervals are [0.00698,0.00868] and [0.00139,0.00262].
37
+ Primary-feature removal reduces accuracy to 0.7548798684; auxiliary removal
38
+ gives 0.6333926465. Complete consolidated native replay and every readout/dependence gate passed.
39
+ The fit-only development mean is **0.7221453205**. Ten other production
40
+ prediction files are byte-identical to the previous package; SS matches the
41
+ accepted development candidate exactly. Both encoders remain shared, with
42
+ one auxiliary copy and one trained SS readout.
43
+
44
+ The five existing production fit+Tune heads (fold, fluorescence, beta-lactamase, affinity and stability) and their feature paths remain exact. Their production Tune scores and aggregate are in-sample and excluded from selection.
45
+
46
+ Repeated Tune selection and protein-family dependence limit the intervals.
47
+ Fold remains weak, PPI validation sets are small, and feature ablation is an
48
+ out-of-distribution diagnostic. SS and PPI use full-chain windows; remaining
49
+ tasks retain a 1022-residue prefix. Rank outputs lack absolute calibration.
50
+ No held-out test measurement is available.
51
+
52
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. No live trainer, cached
53
+ features, sequence lookup, external weights or test-time fitting are needed.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/config.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ],
134
+ "dual_summary": {
135
+ "layers": 12,
136
+ "dim": 768,
137
+ "heads": 12,
138
+ "tasks": [
139
+ "subcellular_localization"
140
+ ]
141
+ },
142
+ "dual_residue": {
143
+ "task": "secondary_structure",
144
+ "features": "two_frozen_local_prefixes"
145
+ }
146
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/replay.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained replay shared by research evaluation and frozen packages."""
3
+ import contextlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ import esm2
12
+
13
+ TASKS = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
14
+ 'subcellular_localization', 'binary_localization', 'fold',
15
+ 'secondary_structure', 'yeast_ppi', 'human_ppi', 'ppi_affinity')
16
+
17
+
18
+ def autocast(device):
19
+ return torch.autocast('cuda', dtype=torch.bfloat16) if device.type == 'cuda' else contextlib.nullcontext()
20
+
21
+
22
+ def head_output(model, task, representation, device, fp32=False):
23
+ apply = model.apply_head if hasattr(model, 'apply_head') else lambda task, value: model.heads[task](value)
24
+ if fp32:
25
+ with torch.autocast(device.type, enabled=False):
26
+ values={k:v.float() if v.is_floating_point() else v for k,v in representation.items()} if isinstance(representation,dict) else representation.float()
27
+ return apply(task, values).float()
28
+ return apply(task, representation).float()
29
+
30
+
31
+ def residue_states(model, tokens, task):
32
+ return model.encode_residues(tokens, task) if hasattr(model, 'encode_residues') else model.encoder(tokens)
33
+
34
+
35
+ def windows(length, width=1022, stride=768):
36
+ if length <= width:
37
+ return [(0, length)]
38
+ starts = list(range(0, length - width + 1, stride))
39
+ if starts[-1] != length - width:
40
+ starts.append(length - width)
41
+ return [(s, min(s + width, length)) for s in starts]
42
+
43
+
44
+ def batches(rows, task, token_budget=16384, max_len=1024, max_batch=128):
45
+ lengths = [min(max(map(len, r['features'].values())) + 2, max_len) for r in rows]
46
+ order = sorted(range(len(rows)), key=lengths.__getitem__)
47
+ current, width = [], 0
48
+ for i in order:
49
+ length = lengths[i]
50
+ # Pair sequences require two separate passes, but the peak tensor size is unchanged.
51
+ if current and (max(width, length) * (len(current) + 1) > token_budget or len(current) >= max_batch):
52
+ yield current
53
+ current, width = [], 0
54
+ current.append(i)
55
+ width = max(width, length)
56
+ if current:
57
+ yield current
58
+
59
+
60
+ @torch.inference_mode()
61
+ def predict_records(model, rows, task, device, config=None, token_budget=16384):
62
+ config = config or {}
63
+ max_len = config.get('task_max_len', {}).get(task, config.get('max_len', 1024))
64
+ full_ss = config.get('full_ss', True)
65
+ fp32_option = config.get('fp32_heads', False)
66
+ fp32_heads = fp32_option is True or (isinstance(fp32_option, list) and task in fp32_option)
67
+ was_training = model.training
68
+ model.eval()
69
+ result = {}
70
+ for ids in batches(rows, task, token_budget, max_len):
71
+ chunk = [rows[i] for i in ids]
72
+ features = [r['features'] for r in chunk]
73
+ if task == 'secondary_structure':
74
+ if full_ss and any(len(f['sequence']) > max_len - 2 for f in features):
75
+ for record in chunk:
76
+ seq = record['features']['sequence']
77
+ pieces = windows(len(seq), max_len - 2, min(768, max_len - 2))
78
+ total = np.zeros((len(seq), 3), dtype=np.float32)
79
+ weight_sum = np.zeros((len(seq), 1), dtype=np.float32)
80
+ for begin in range(0, len(pieces), max(1, token_budget // max_len)):
81
+ part = pieces[begin:begin + max(1, token_budget // max_len)]
82
+ tokens = esm2.pad_batch([esm2.encode(seq[s:e], max_len) for s, e in part], device)
83
+ with autocast(device):
84
+ hidden, _ = residue_states(model, tokens, task)
85
+ logits = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
86
+ for j, (s, e) in enumerate(part):
87
+ size = e - s
88
+ # Smooth boundaries, without discarding any residue.
89
+ weight = np.minimum(np.arange(1, size + 1), np.arange(size, 0, -1))
90
+ weight = np.minimum(weight, 128).astype(np.float32)[:, None]
91
+ total[s:e] += logits[j, 1:1+size] * weight
92
+ weight_sum[s:e] += weight
93
+ scores = total / np.maximum(weight_sum, 1)
94
+ result[record['example_id']] = {'ss3_scores': scores.tolist()}
95
+ else:
96
+ tokens = esm2.pad_batch([esm2.encode(f['sequence'], max_len) for f in features], device)
97
+ with autocast(device):
98
+ hidden, _ = residue_states(model, tokens, task)
99
+ probabilities = head_output(model, task, hidden, device, fp32_heads).softmax(-1).cpu().numpy()
100
+ for j, record in enumerate(chunk):
101
+ length = len(record['features']['sequence'])
102
+ used = min(length, max_len - 2)
103
+ scores = probabilities[j, 1:1+used].tolist()
104
+ scores.extend([[1.0, 1.0, 1.0] for _ in range(length-used)])
105
+ result[record['example_id']] = {'ss3_scores': scores}
106
+ continue
107
+ with autocast(device):
108
+ representation = model.represent(task, features, device, max_len)
109
+ output = head_output(model, task, representation, device, fp32_heads)
110
+ if task in model.CLASSES:
111
+ output = output.softmax(-1)
112
+ if task in config.get('symmetric_pairs', []):
113
+ swapped = [{'sequence_a': f['sequence_b'], 'sequence_b': f['sequence_a']} for f in features]
114
+ swapped_rep = model.represent(task, swapped, device, max_len)
115
+ second = head_output(model, task, swapped_rep, device, fp32_heads)
116
+ if task in model.CLASSES:
117
+ second = second.softmax(-1)
118
+ output = (output + second) * 0.5
119
+ if task in model.CLASSES:
120
+ output = output.clamp_min(1e-9)
121
+ elif hasattr(model, 'unscale'):
122
+ output = model.unscale(task, output)
123
+ values = output.cpu().tolist()
124
+ for record, value in zip(chunk, values):
125
+ result[record['example_id']] = {'scores': value} if task in model.CLASSES else {'value': value[0]}
126
+ if task == 'secondary_structure' and hasattr(model, 'ss_chain_decoder'):
127
+ # Decode complete chains only after all overlapping-window probabilities
128
+ # have been aggregated. No labels or parameter updates enter replay.
129
+ identifiers = [record['example_id'] for record in rows]
130
+ probabilities = [result[identifier]['ss3_scores'] for identifier in identifiers]
131
+ decoded = model.ss_chain_decoder.decode(probabilities)
132
+ for identifier, scores in zip(identifiers, decoded):
133
+ result[identifier] = {'ss3_scores': scores.tolist()}
134
+ model.train(was_training)
135
+ return result
136
+
137
+
138
+ def load_model(package, device):
139
+ config = json.loads((package / 'config.json').read_text())
140
+ if config.get('architecture') == 'unified':
141
+ from unified import UnifiedModel
142
+ model = UnifiedModel(config)
143
+ else:
144
+ model = esm2.Model(layers=config['layers'], dim=config['dim'], heads=config['heads'])
145
+ model.load_state_dict(torch.load(package / 'model.pt', map_location='cpu', weights_only=True))
146
+ return model.to(device).eval(), config
147
+
148
+
149
+ def main():
150
+ if len(sys.argv) != 3:
151
+ raise SystemExit('usage: replay.py INPUT_ROOT OUTPUT_ROOT')
152
+ torch.set_num_threads(6)
153
+ source, destination = Path(sys.argv[1]), Path(sys.argv[2]) / 'predictions'
154
+ destination.mkdir(parents=True, exist_ok=True)
155
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
+ model, config = load_model(Path(__file__).resolve().parent, device)
157
+ for task in TASKS:
158
+ rows = [json.loads(line) for line in (source / f'{task}.jsonl').open()]
159
+ predictions = predict_records(model, rows, task, device, config)
160
+ with (destination / f'{task}.jsonl').open('w') as sink:
161
+ for row in rows:
162
+ sink.write(json.dumps({'example_id': row['example_id'], 'prediction': predictions[row['example_id']]}, separators=(',', ':')) + '\n')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/selection.json ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "score_kind": "tune_labels_used_for_fold_fluorescence_beta_lactamase_ppi_affinity_and_stability",
3
+ "tasks_reusing_tune_labels": [
4
+ "fold",
5
+ "fluorescence",
6
+ "beta_lactamase",
7
+ "ppi_affinity",
8
+ "stability"
9
+ ],
10
+ "production_aggregate_excluded_from_selection": true,
11
+ "fit_only_development_reference": {
12
+ "reward": 0.7221453204592783,
13
+ "tasks": {
14
+ "beta_lactamase": {
15
+ "invalid_reason": null,
16
+ "reward": 0.8851158090618965,
17
+ "spearman": 0.8851158090618965
18
+ },
19
+ "binary_localization": {
20
+ "accuracy": 0.9462116830537883,
21
+ "balanced_accuracy": 0.9419155998103367,
22
+ "invalid_reason": null,
23
+ "macro_f1": 0.9439947337349208,
24
+ "reward": 0.9462116830537883
25
+ },
26
+ "fluorescence": {
27
+ "invalid_reason": null,
28
+ "reward": 0.826705913429907,
29
+ "spearman": 0.826705913429907
30
+ },
31
+ "fold": {
32
+ "accuracy": 0.24864130434782608,
33
+ "balanced_accuracy": 0.16124022176653757,
34
+ "invalid_reason": null,
35
+ "macro_f1": 0.03846637235687955,
36
+ "reward": 0.24864130434782608
37
+ },
38
+ "human_ppi": {
39
+ "accuracy": 0.7968253968253968,
40
+ "balanced_accuracy": 0.8005952380952381,
41
+ "invalid_reason": null,
42
+ "macro_f1": 0.7968233491897122,
43
+ "reward": 0.7968253968253968
44
+ },
45
+ "ppi_affinity": {
46
+ "invalid_reason": null,
47
+ "reward": 0.5341420012716276,
48
+ "rmse": 1.9334586965956642,
49
+ "spearman": 0.7162121646852028
50
+ },
51
+ "secondary_structure": {
52
+ "accuracy": 0.7674307948381397,
53
+ "invalid_reason": null,
54
+ "reward": 0.7674307948381397,
55
+ "valid_residues": 556931
56
+ },
57
+ "solubility": {
58
+ "accuracy": 0.7533851915874388,
59
+ "balanced_accuracy": 0.7392508255204544,
60
+ "invalid_reason": null,
61
+ "macro_f1": 0.742264399722415,
62
+ "reward": 0.7533851915874388
63
+ },
64
+ "stability": {
65
+ "invalid_reason": null,
66
+ "reward": 0.7311607642876724,
67
+ "spearman": 0.7311607642876724
68
+ },
69
+ "subcellular_localization": {
70
+ "accuracy": 0.7908217716115261,
71
+ "balanced_accuracy": 0.6999121500389823,
72
+ "invalid_reason": null,
73
+ "macro_f1": 0.7198401417205603,
74
+ "reward": 0.7908217716115261
75
+ },
76
+ "yeast_ppi": {
77
+ "accuracy": 0.6631578947368421,
78
+ "balanced_accuracy": 0.6597985347985349,
79
+ "invalid_reason": null,
80
+ "macro_f1": 0.6567299006323397,
81
+ "reward": 0.6631578947368421
82
+ }
83
+ },
84
+ "package": "/workspace/research/dual-residue-readout1-replay/candidate/package",
85
+ "report": "/workspace/research/dual-residue-readout1-replay/candidate/report.json",
86
+ "model_sha256": "bd9bdcc7561bc61d64523b9e99cff98df05ddceebd211a740b07ee8b94abb18e",
87
+ "inference_assets_sha256": {
88
+ "model.pt": "bd9bdcc7561bc61d64523b9e99cff98df05ddceebd211a740b07ee8b94abb18e",
89
+ "config.json": "fa516bd8637412d039d46cc25ceeb318e8da206b892fae9a8fc84540dc68e943",
90
+ "esm2.py": "d4d512296047ebbd0f9a26dc1390107f72762cb5de011eefc9fecb18118a9be9",
91
+ "unified.py": "00753e674e1360601f204e445f15714cae02514bfe455d594a4d3f8433018dca",
92
+ "replay.py": "9c5add2d3fb117470241cf63f621e4797a16962cddadbaad6de2cfb481e7fa85",
93
+ "infer.sh": "60f55b73f5b39a35a61df84026abed9a127b1cc035d650c9e1ca62f54fc2b468"
94
+ },
95
+ "parameters": 139328153,
96
+ "score_kind": "fit_only_development_tune_selection",
97
+ "decision": "/workspace/research/dual-residue-readout1-replay/decision.json"
98
+ },
99
+ "pending_independent_replay": false,
100
+ "dual_residue_evidence": {
101
+ "status": "eligible_for_native_all11_review",
102
+ "eligible": true,
103
+ "results": {
104
+ "primary": {
105
+ "accuracy": 0.7436379012840011,
106
+ "blocks": 12,
107
+ "active_seconds": 0.7173126210400369,
108
+ "LBFGS_iterations": 76,
109
+ "closure_evaluations": 129
110
+ },
111
+ "auxiliary": {
112
+ "accuracy": 0.7654377292698736,
113
+ "blocks": 12,
114
+ "active_seconds": 0.5298353870166466,
115
+ "LBFGS_iterations": 98,
116
+ "closure_evaluations": 119
117
+ },
118
+ "full": {
119
+ "accuracy": 0.7674307948381397,
120
+ "blocks": 12,
121
+ "active_seconds": 0.5488360379531514,
122
+ "LBFGS_iterations": 107,
123
+ "closure_evaluations": 122,
124
+ "primary_zeroed_accuracy": 0.7548798684217614,
125
+ "auxiliary_zeroed_accuracy": 0.6333926464858304
126
+ }
127
+ },
128
+ "comparisons": {
129
+ "full_minus_primary": {
130
+ "delta": 0.023792893554138664,
131
+ "conditional95": [
132
+ 0.02227601983558547,
133
+ 0.025405620421006168
134
+ ]
135
+ },
136
+ "full_minus_auxiliary": {
137
+ "delta": 0.001993065568266087,
138
+ "conditional95": [
139
+ 0.0013915113450666237,
140
+ 0.00262078806389141
141
+ ]
142
+ },
143
+ "full_minus_primary_ablated": {
144
+ "delta": 0.01255092641637833,
145
+ "conditional95": [
146
+ 0.01141412252412414,
147
+ 0.01367599499083551
148
+ ]
149
+ },
150
+ "full_minus_auxiliary_ablated": {
151
+ "delta": 0.13403814835230934,
152
+ "conditional95": [
153
+ 0.13069689870620071,
154
+ 0.13760283893506345
155
+ ]
156
+ },
157
+ "full_minus_native_primary": {
158
+ "delta": 0.023299116048487157,
159
+ "conditional95": [
160
+ 0.021785460201619564,
161
+ 0.024879231525420348
162
+ ]
163
+ },
164
+ "full_minus_native_auxiliary": {
165
+ "delta": 0.002027181105020191,
166
+ "conditional95": [
167
+ 0.0014295698320689104,
168
+ 0.0026466899667084306
169
+ ]
170
+ },
171
+ "full_minus_native_fusion": {
172
+ "delta": 0.007792706816463799,
173
+ "conditional95": [
174
+ 0.0069797076175643485,
175
+ 0.00868359254180614
176
+ ]
177
+ }
178
+ },
179
+ "fit_unique_residues": 500000,
180
+ "fit_rows_including_overlap": 505584,
181
+ "tune_valid_residues": 556931,
182
+ "tune_proteins": 2170,
183
+ "published": false,
184
+ "exported": false,
185
+ "limitations": "One fixed fit-only recipe; repeated Tune selection and protein-family dependence are not corrected by conditional protein bootstrap. Feature removal is an out-of-distribution diagnostic. Native all11 review still required."
186
+ },
187
+ "all11_native_valid": true,
188
+ "all11_prediction_references_exact": true
189
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S057/unified.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One jointly learned protein encoder, shared pooling, and eleven small heads."""
2
+ import math
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import esm2
9
+
10
+
11
+ class NormalizedLinear(nn.Module):
12
+ def __init__(self, width, outputs=1):
13
+ super().__init__()
14
+ self.register_buffer('mean', torch.zeros(width))
15
+ self.register_buffer('scale', torch.ones(width))
16
+ self.linear = nn.Linear(width, outputs)
17
+
18
+ def forward(self, values):
19
+ return self.linear((values - self.mean) / self.scale)
20
+
21
+
22
+ class LowRankPositionHead(nn.Module):
23
+ """A shared residue projection followed by an ordered position readout."""
24
+ def __init__(self, dim, bins, rank, outputs=1):
25
+ super().__init__()
26
+ assert 0 < rank <= min(dim, bins)
27
+ self.dim = dim
28
+ self.project = nn.Linear(dim, rank, bias=False)
29
+ self.output = nn.Linear(bins * rank, outputs)
30
+
31
+ def forward(self, values):
32
+ residues = values.reshape(values.shape[0], -1, self.dim)
33
+ return self.output(self.project(residues).flatten(1))
34
+
35
+
36
+ class NormalizedCosine(nn.Module):
37
+ def __init__(self, width, outputs, temperature=20.):
38
+ super().__init__()
39
+ self.register_buffer('mean', torch.zeros(width))
40
+ self.register_buffer('scale', torch.ones(width))
41
+ self.linear = nn.Linear(width, outputs, bias=False)
42
+ self.temperature = temperature
43
+
44
+ def forward(self, values):
45
+ features = F.normalize((values-self.mean)/self.scale, dim=-1)
46
+ return F.linear(features, F.normalize(self.linear.weight, dim=-1))*self.temperature
47
+
48
+
49
+ class NormalizedMLP(nn.Module):
50
+ def __init__(self, width, outputs, hidden=128, dropout=.1):
51
+ super().__init__()
52
+ self.register_buffer('mean', torch.zeros(width))
53
+ self.register_buffer('scale', torch.ones(width))
54
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(), nn.LayerNorm(hidden),
55
+ nn.Dropout(dropout), nn.Linear(hidden, outputs))
56
+
57
+ def forward(self, values):
58
+ return self.network((values-self.mean)/self.scale)
59
+
60
+
61
+ class SharedSummaryResidual(nn.Module):
62
+ """One nonlinear summary map jointly used by several classification heads."""
63
+ def __init__(self, width, hidden, dropout, classes):
64
+ super().__init__()
65
+ self.network = nn.Sequential(nn.Linear(width, hidden), nn.GELU(),
66
+ nn.LayerNorm(hidden), nn.Dropout(dropout),
67
+ nn.Linear(hidden, hidden), nn.GELU(), nn.Dropout(dropout))
68
+ self.heads = nn.ModuleDict({task: nn.Linear(hidden, outputs)
69
+ for task, outputs in sorted(classes.items())})
70
+ for head in self.heads.values():
71
+ nn.init.zeros_(head.weight)
72
+ nn.init.zeros_(head.bias)
73
+
74
+ def forward(self, task, normalized_summary):
75
+ return self.heads[task](self.network(normalized_summary))
76
+
77
+
78
+ class NormalizedResidueLinear(nn.Module):
79
+ def __init__(self, dim, kernel=9):
80
+ super().__init__()
81
+ assert kernel > 0 and kernel % 2 == 1
82
+ self.kernel = kernel
83
+ self.readout = NormalizedLinear(dim * kernel, 3)
84
+
85
+ @staticmethod
86
+ def features(hidden, kernel):
87
+ padded = F.pad(hidden.float().transpose(1, 2), (kernel // 2, kernel // 2))
88
+ return padded.unfold(-1, kernel, 1).transpose(1, 2).flatten(2)
89
+
90
+ def forward(self, hidden):
91
+ return self.readout(self.features(hidden, self.kernel))
92
+
93
+
94
+ class LocalResidueHead(nn.Sequential):
95
+ """Preserve the original four head parameter names; add a local residual."""
96
+ def __init__(self, dim):
97
+ super().__init__(nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
98
+ self.context = nn.Sequential(nn.Conv1d(dim, dim, 9, padding=4, groups=dim),
99
+ nn.GELU(), nn.Conv1d(dim, dim, 1))
100
+ nn.init.zeros_(self.context[-1].weight)
101
+ nn.init.zeros_(self.context[-1].bias)
102
+
103
+ def forward(self, x):
104
+ x = x + self.context(x.transpose(1, 2)).transpose(1, 2)
105
+ for i in range(4):
106
+ x = self[i](x)
107
+ return x
108
+
109
+
110
+ class CalibratedLocalResidueHead(LocalResidueHead):
111
+ def __init__(self, dim):
112
+ super().__init__(dim)
113
+ self[3] = NormalizedLinear(dim, 3)
114
+
115
+
116
+ class DualLocalResidueHead(nn.Module):
117
+ """Two frozen local feature prefixes followed by one joint residue readout."""
118
+ def __init__(self, primary_dim, auxiliary_dim):
119
+ super().__init__()
120
+ self.primary_dim = primary_dim
121
+ self.primary = CalibratedLocalResidueHead(primary_dim)
122
+ self.auxiliary = CalibratedLocalResidueHead(auxiliary_dim)
123
+ self.primary[3] = nn.Identity()
124
+ self.auxiliary[3] = nn.Identity()
125
+ self.readout = NormalizedLinear(primary_dim + auxiliary_dim, 3)
126
+
127
+ def features(self, hidden):
128
+ return torch.cat([self.primary(hidden[..., :self.primary_dim]),
129
+ self.auxiliary(hidden[..., self.primary_dim:])], dim=-1)
130
+
131
+ def forward(self, hidden):
132
+ return self.readout(self.features(hidden))
133
+
134
+
135
+ class ResidualSequenceConvHead(nn.Module):
136
+ """Learn local sequence motifs alongside the retained summary classifier."""
137
+ def __init__(self, dim, outputs, channels=128, dropout=.2, retain_summary=True):
138
+ super().__init__()
139
+ self.base = NormalizedLinear(7 * dim, outputs) if retain_summary else None
140
+ self.register_buffer('mean', torch.zeros(dim))
141
+ self.register_buffer('scale', torch.ones(dim))
142
+ self.project = nn.Linear(dim, channels)
143
+ self.convs = nn.ModuleList([nn.Conv1d(channels, channels, k, padding=k//2) for k in (3,9)])
144
+ self.norms = nn.ModuleList([nn.LayerNorm(channels) for _ in self.convs])
145
+ self.output = nn.Linear(4 * channels, outputs)
146
+ nn.init.zeros_(self.output.weight);nn.init.zeros_(self.output.bias)
147
+ self.dropout = dropout
148
+
149
+ def forward(self, features):
150
+ valid = features['valid'].bool().unsqueeze(-1)
151
+ x = F.gelu(self.project((features['hidden']-self.mean)/self.scale)) * valid
152
+ summaries = []
153
+ for conv,norm in zip(self.convs,self.norms):
154
+ y = norm(F.gelu(conv(x.transpose(1,2)).transpose(1,2)))
155
+ center = (y*valid).sum(1)/valid.sum(1).clamp_min(1)
156
+ maximum = y.masked_fill(~valid,-1e4).amax(1)
157
+ maximum = torch.where(valid.any(1),maximum,torch.zeros_like(maximum))
158
+ summaries.extend([center,maximum])
159
+ pooled = F.dropout(torch.cat(summaries,dim=-1),self.dropout,self.training)
160
+ logits=self.output(pooled)
161
+ return self.base(features['summary']) + logits if self.base is not None else logits
162
+
163
+
164
+ class TokenLogMeanExpHead(nn.Module):
165
+ """Class-specific local evidence, pooled without sequence-length bias."""
166
+ def __init__(self, dim, outputs):
167
+ super().__init__()
168
+ self.register_buffer('mean', torch.zeros(dim))
169
+ self.register_buffer('scale', torch.ones(dim))
170
+ self.linear = nn.Linear(dim, outputs)
171
+
172
+ def forward(self, representation):
173
+ values, valid = representation['hidden'].float(), representation['valid']
174
+ logits = self.linear((values-self.mean)/self.scale)
175
+ logits = logits.masked_fill(~valid.unsqueeze(-1), -torch.inf)
176
+ return torch.logsumexp(logits, 1)-valid.sum(1).clamp_min(1).float().log()[:, None]
177
+
178
+ def packed(self, values, lengths):
179
+ """Equivalent unpadded computation for frozen-feature readout fitting."""
180
+ logits = self.linear((values.float()-self.mean)/self.scale)
181
+ # The stabilizing maximum cancels in the derivative; detach avoids
182
+ # retaining another large token-by-class gradient path.
183
+ maximum = torch.segment_reduce(logits.detach(), 'max', lengths=lengths)
184
+ index = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths,
185
+ output_size=len(values))
186
+ exponent = (logits-maximum[index]).exp()
187
+ total = torch.segment_reduce(exponent, 'sum', lengths=lengths)
188
+ return maximum+total.log()-lengths.float().log()[:, None]
189
+
190
+
191
+ class SharedPairResidueInteraction(nn.Module):
192
+ """A shared nonlinear comparison of local states from both protein chains."""
193
+ def __init__(self, dim, settings, classes):
194
+ super().__init__()
195
+ width, hidden, channels = (settings[k] for k in ['projection_dim', 'pair_hidden', 'pair_channels'])
196
+ self.register_buffer('mean', torch.zeros(dim))
197
+ self.register_buffer('scale', torch.ones(dim))
198
+ self.project = nn.Linear(dim, width)
199
+ self.compare = nn.Sequential(nn.Linear(2*width, hidden), nn.GELU(),
200
+ nn.Linear(hidden, channels), nn.GELU())
201
+ self.dropout = settings['dropout']
202
+ self.heads = nn.ModuleDict({task: nn.Linear(2*channels, classes.get(task, 1))
203
+ for task in sorted(esm2.Model.PAIR)})
204
+ for head in self.heads.values():
205
+ nn.init.zeros_(head.weight)
206
+ nn.init.zeros_(head.bias)
207
+
208
+ def forward(self, task, first, second):
209
+ first = F.gelu(self.project((first-self.mean)/self.scale))
210
+ second = F.gelu(self.project((second-self.mean)/self.scale))
211
+ first = F.dropout(first, self.dropout, self.training)
212
+ second = F.dropout(second, self.dropout, self.training)
213
+ pair = torch.cat([(first[:, :, None]-second[:, None, :]).abs(),
214
+ first[:, :, None]*second[:, None, :]], dim=-1)
215
+ local = self.compare(pair)
216
+ summary = torch.cat([local.mean((1, 2)), local.amax((1, 2))], dim=-1)
217
+ return self.heads[task](summary)
218
+
219
+
220
+ class SSChainDecoder(nn.Module):
221
+ """Small learned label-compatibility model, applied to frozen residue unaries."""
222
+ def __init__(self):
223
+ super().__init__()
224
+ self.transition = nn.Parameter(torch.empty(3, 3))
225
+ self.start = nn.Parameter(torch.empty(3))
226
+ self.end = nn.Parameter(torch.empty(3))
227
+ for parameter in self.parameters():
228
+ nn.init.normal_(parameter, std=.01)
229
+
230
+ def decode(self, probabilities):
231
+ from ss_chain import decode_probabilities
232
+ values = [parameter.detach().double().cpu().numpy()
233
+ for parameter in (self.transition, self.start, self.end)]
234
+ return decode_probabilities(probabilities, *values)
235
+
236
+
237
+ class UnifiedModel(esm2.Model):
238
+ TASK_ORDER = ('fluorescence', 'stability', 'beta_lactamase', 'solubility',
239
+ 'subcellular_localization', 'binary_localization', 'fold',
240
+ 'yeast_ppi', 'human_ppi', 'ppi_affinity')
241
+
242
+ def __init__(self, config):
243
+ super().__init__(layers=config['layers'], dim=config['dim'], heads=config['heads'])
244
+ self.config = config
245
+ self.task_index = {t: i for i, t in enumerate(self.TASK_ORDER)}
246
+ dim = config['dim']
247
+ if config.get('extension_layers', 0):
248
+ self.encoder.add_extension(config['extension_layers'], config['heads'],
249
+ before_norm=config.get('extension_before_norm', False))
250
+ if config.get('task_conditioning', False):
251
+ self.task_condition = nn.Parameter(torch.zeros(11, config['layers'], 4, dim))
252
+ if config.get('pooling', 'mean') == 'rich':
253
+ self.pool_query = nn.Parameter(torch.randn(len(self.TASK_ORDER), 2, dim) * 0.02)
254
+ self.pool_position = nn.Parameter(torch.zeros(len(self.TASK_ORDER), 2, 4))
255
+ # Shared across tasks, with a zero initial residual for safe lineage transfer.
256
+ self.pool_fuse = nn.Linear(6 * dim, dim)
257
+ nn.init.zeros_(self.pool_fuse.weight)
258
+ nn.init.zeros_(self.pool_fuse.bias)
259
+ if config.get('pair_interaction', False):
260
+ self.pair_fuse = nn.Linear(2 * dim, 2 * dim)
261
+ nn.init.zeros_(self.pair_fuse.weight)
262
+ nn.init.zeros_(self.pair_fuse.bias)
263
+ if config.get('ss_context', False):
264
+ self.heads['secondary_structure'] = LocalResidueHead(dim)
265
+ for task in config.get('linear_heads', []):
266
+ width = dim * 2 if task in self.PAIR else dim
267
+ self.heads[task] = nn.Sequential(nn.Linear(width, self.CLASSES.get(task, 1)))
268
+ for task, settings in config.get('residue_readouts', {}).items():
269
+ self.heads[task] = NormalizedLinear(settings['bins'] * dim, self.CLASSES.get(task, 1))
270
+ for task, rank in config.get('residue_lowrank_heads', {}).items():
271
+ bins = config['residue_readouts'][task]['bins']
272
+ self.heads[task] = LowRankPositionHead(dim, bins, rank, self.CLASSES.get(task, 1))
273
+ for task in config.get('summary_readouts', []):
274
+ assert task not in self.PAIR and config.get('pooling') == 'rich'
275
+ self.heads[task] = NormalizedLinear(7 * dim, self.CLASSES.get(task, 1))
276
+ for task in config.get('sequence_composition_readouts', []):
277
+ from sequence_composition import WIDTH
278
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES
279
+ assert all(task not in config.get(key,[]) for key in
280
+ ['cosine_heads','nonlinear_summary_heads','ss_summary_readouts',
281
+ 'sequence_conv_readouts','terminal_summary_readouts','token_logmeanexp_heads'])
282
+ self.heads[task] = NormalizedLinear(7 * dim + WIDTH, self.CLASSES[task])
283
+ for task, temperature in config.get('cosine_heads', {}).items():
284
+ assert task in config.get('summary_readouts', [])
285
+ self.heads[task] = NormalizedCosine(7*dim, self.CLASSES[task], temperature)
286
+ for task, settings in config.get('nonlinear_summary_heads', {}).items():
287
+ assert task in config.get('summary_readouts', []) and task not in config.get('cosine_heads', {})
288
+ self.heads[task] = NormalizedMLP(7*dim, self.CLASSES.get(task,1), settings['hidden'], settings['dropout'])
289
+ for task in config.get('calibrated_heads', []):
290
+ assert task not in config.get('summary_readouts', []) and task not in config.get('residue_readouts', {})
291
+ assert task not in config.get('linear_heads', [])
292
+ self.heads[task][3] = NormalizedLinear(dim, self.CLASSES.get(task,1))
293
+ for task in config.get('expanded_pair_readouts', []):
294
+ assert task in self.PAIR
295
+ width=3 if task in config.get('symmetric_pair_readouts',[]) else 4
296
+ if task in config.get('pair_summary_readouts', []):
297
+ assert config.get('pooling') == 'rich'
298
+ width *= 8
299
+ self.heads[task] = NormalizedLinear(width*dim, self.CLASSES.get(task,1))
300
+ if config.get('ss_linear_context'):
301
+ self.heads['secondary_structure'] = NormalizedResidueLinear(dim, config['ss_linear_context'])
302
+ if config.get('ss_calibrated'):
303
+ assert not config.get('ss_linear_context')
304
+ self.heads['secondary_structure'] = CalibratedLocalResidueHead(dim)
305
+ for task in config.get('ss_summary_readouts', []):
306
+ assert task in config.get('summary_readouts', []) and task not in self.PAIR
307
+ self.heads[task] = NormalizedLinear(7*dim+40, self.CLASSES[task])
308
+ for task,settings in config.get('sequence_conv_readouts',{}).items():
309
+ assert task in config.get('summary_readouts',[]) and task in self.CLASSES and task not in self.PAIR
310
+ self.heads[task] = ResidualSequenceConvHead(dim,self.CLASSES[task],settings['channels'],settings['dropout'],settings.get('retain_summary',True))
311
+ for task, settings in config.get('terminal_summary_readouts', {}).items():
312
+ assert task in config.get('summary_readouts', []) and task in self.CLASSES and task not in self.PAIR
313
+ assert all(task not in config.get(key, {}) for key in
314
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts', 'sequence_conv_readouts'])
315
+ bins = settings['bins']
316
+ assert bins > 0 and all(settings[key] > 0 and settings[key] % bins == 0
317
+ for key in ['prefix_residues', 'suffix_residues'])
318
+ self.heads[task] = NormalizedLinear((7+2*bins)*dim, self.CLASSES[task])
319
+ if config.get('pair_bilinear_rank', 0):
320
+ rank = config['pair_bilinear_rank']
321
+ assert not config.get('pair_summary_readouts')
322
+ self.pair_bilinear_projection = nn.Linear(dim, rank, bias=False)
323
+ nn.init.normal_(self.pair_bilinear_projection.weight, std=dim ** -.5)
324
+ with torch.no_grad():
325
+ self.pair_bilinear_projection.weight.copy_(F.normalize(self.pair_bilinear_projection.weight, dim=1))
326
+ self.pair_bilinear_heads = nn.ModuleDict({
327
+ task: nn.Linear(rank, self.CLASSES.get(task, 1), bias=False)
328
+ for task in sorted(self.PAIR)})
329
+ for head in self.pair_bilinear_heads.values():
330
+ nn.init.zeros_(head.weight)
331
+ self.register_buffer('pair_bilinear_mean', torch.zeros(dim))
332
+ self.register_buffer('pair_bilinear_scale', torch.ones(dim))
333
+ if config.get('pair_residue_interaction'):
334
+ self.pair_residue_interaction = SharedPairResidueInteraction(
335
+ dim, config['pair_residue_interaction'], self.CLASSES)
336
+ for task in config.get('token_logmeanexp_heads', []):
337
+ assert task in self.CLASSES and task not in self.PAIR
338
+ assert task not in config.get('sequence_windows', [])
339
+ self.heads[task] = TokenLogMeanExpHead(dim, self.CLASSES[task])
340
+ if config.get('ss_chain_decoder', False):
341
+ self.ss_chain_decoder = SSChainDecoder()
342
+ if config.get('shared_summary_residual'):
343
+ settings = config['shared_summary_residual']
344
+ tasks = settings['tasks']
345
+ assert all(task in config.get('summary_readouts', []) and
346
+ isinstance(self.heads[task], NormalizedLinear) for task in tasks)
347
+ self.summary_residual = SharedSummaryResidual(7*dim, settings['hidden'], settings['dropout'],
348
+ {task: self.CLASSES[task] for task in tasks})
349
+
350
+ if config.get('dual_summary'):
351
+ settings = config['dual_summary']
352
+ tasks = settings['tasks']
353
+ assert tasks and len(tasks) == len(set(tasks))
354
+ assert config.get('pooling') == 'rich'
355
+ assert all(task in config.get('summary_readouts', []) and task not in self.PAIR for task in tasks)
356
+ assert all(task not in config.get(key, {}) for task in tasks for key in
357
+ ['cosine_heads', 'nonlinear_summary_heads', 'ss_summary_readouts',
358
+ 'sequence_conv_readouts', 'terminal_summary_readouts', 'token_logmeanexp_heads',
359
+ 'summary_residual_tasks', 'sequence_composition_readouts'])
360
+ self.auxiliary_summary_encoder = esm2.Encoder(settings['layers'], settings['dim'], settings['heads'])
361
+ self.auxiliary_summary_index = {task: i for i, task in enumerate(tasks)}
362
+ self.auxiliary_pool_query = nn.Parameter(torch.randn(len(tasks), 2, settings['dim']) * .02)
363
+ self.auxiliary_pool_position = nn.Parameter(torch.zeros(len(tasks), 2, 4))
364
+ for task in tasks:
365
+ self.heads[task] = NormalizedLinear(7*(dim+settings['dim']), self.CLASSES[task])
366
+
367
+ if config.get('shared_fusion'):
368
+ settings = config['shared_fusion']
369
+ dual = config['dual_summary']
370
+ assert not settings.get('conditioned', True)
371
+ assert all(settings[k] == dual[k] for k in ['layers', 'dim', 'heads'])
372
+ active = config['shared_fusion_tasks']
373
+ assert active and not set(active).intersection(dual['tasks'])
374
+ # One auxiliary module supplies both uses; never register a duplicate alias.
375
+ width = dim + settings['dim']
376
+ self.shared_fusion = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, settings['hidden']),
377
+ nn.GELU(), nn.Linear(settings['hidden'], dim))
378
+ nn.init.normal_(self.shared_fusion[1].weight, std=.02)
379
+ nn.init.zeros_(self.shared_fusion[1].bias)
380
+ nn.init.zeros_(self.shared_fusion[3].weight)
381
+ nn.init.zeros_(self.shared_fusion[3].bias)
382
+
383
+ if config.get('dual_residue'):
384
+ assert config.get('ss_calibrated') and config.get('dual_summary')
385
+ assert 'secondary_structure' not in config.get('shared_fusion_tasks', [])
386
+ auxiliary_dim = config['dual_summary']['dim']
387
+ self.heads['secondary_structure'] = DualLocalResidueHead(dim, auxiliary_dim)
388
+
389
+ def pair_representation(self, task, first, second, base):
390
+ if task in self.config.get('pair_bilinear_tasks', []):
391
+ return {'base': base, 'chain_a': first, 'chain_b': second}
392
+ return base
393
+
394
+ def apply_head(self, task, representation):
395
+ if task in self.config.get('summary_residual_tasks', []):
396
+ head = self.heads[task]
397
+ normalized = (representation-head.mean)/head.scale
398
+ return head(representation) + self.summary_residual(task, normalized)
399
+ if isinstance(representation, dict) and 'residue_a' in representation:
400
+ base = {k:v for k,v in representation.items() if k not in ['residue_a', 'residue_b']}
401
+ original = self.apply_head(task, base if 'chain_a' in base else base['base'])
402
+ return original + self.pair_residue_interaction(task, representation['residue_a'], representation['residue_b'])
403
+ if isinstance(representation, dict) and 'chain_a' in representation:
404
+ first = (representation['chain_a'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
405
+ second = (representation['chain_b'] - self.pair_bilinear_mean) / self.pair_bilinear_scale
406
+ interaction = self.pair_bilinear_projection(first) * self.pair_bilinear_projection(second)
407
+ interaction = interaction / math.sqrt(self.config['pair_bilinear_rank'])
408
+ return self.heads[task](representation['base']) + self.pair_bilinear_heads[task](interaction)
409
+ return self.heads[task](representation)
410
+
411
+ def encode_residues(self, tokens, task):
412
+ condition = None
413
+ if self.config.get('task_conditioning', False):
414
+ ti = 10 if task == 'secondary_structure' else self.task_index[task]
415
+ condition = self.task_condition[ti]
416
+ hidden, padding = self.encoder(tokens, condition=condition, depth=self.config.get('task_encoder_layers',{}).get(task),
417
+ extension_depth=self.config.get('task_extension_depths',{}).get(task))
418
+ if self.config.get('shared_fusion') and task in self.config['shared_fusion_tasks']:
419
+ auxiliary, auxiliary_padding = self.auxiliary_summary_encoder(tokens)
420
+ if not self.config['shared_fusion'].get('auxiliary_input', True):
421
+ auxiliary = torch.zeros_like(auxiliary)
422
+ correction = self.shared_fusion(torch.cat([hidden, auxiliary], -1))
423
+ hidden = (hidden + correction).masked_fill(padding.unsqueeze(-1), 0)
424
+ if task == 'secondary_structure' and self.config.get('dual_residue'):
425
+ auxiliary, auxiliary_padding = self.auxiliary_summary_encoder(tokens)
426
+ hidden = torch.cat([hidden, auxiliary], dim=-1)
427
+ return hidden, padding
428
+
429
+ def pool(self, tokens, task):
430
+ hidden, pad_mask = self.encode_residues(tokens, task)
431
+ primary = self.summarize(hidden, tokens, pad_mask, task)
432
+ if task in self.config.get('dual_summary', {}).get('tasks', []):
433
+ auxiliary, auxiliary_mask = self.auxiliary_summary_encoder(tokens)
434
+ secondary = self.auxiliary_summarize(auxiliary, tokens, auxiliary_mask, task)
435
+ return torch.cat([primary, secondary], dim=-1)
436
+ return primary
437
+
438
+ def summarize(self, hidden, tokens, pad_mask, task):
439
+ valid = (~pad_mask).unsqueeze(-1)
440
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
441
+ if self.config.get('pooling', 'mean') == 'mean':
442
+ return mean
443
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
444
+ # Empty/nonstandard-only inputs still produce a finite representation.
445
+ residues[:, 0] |= ~residues.any(1)
446
+ keep = residues.unsqueeze(-1)
447
+ count = keep.sum(1).clamp_min(1)
448
+ center = (hidden * keep).sum(1) / count
449
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
450
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
451
+ torch.cos(position * math.pi)], dim=-1)
452
+ ti = self.task_index[task]
453
+ scores = torch.einsum('bld,qd->blq', hidden, self.pool_query[ti]) / math.sqrt(hidden.shape[-1])
454
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.pool_position[ti])
455
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
456
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
457
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
458
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
459
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
460
+ first = residues & (residues.cumsum(1) <= 32)
461
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
462
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
463
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
464
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
465
+ deviation, maximum, prefix, suffix], dim=-1)
466
+ if task in self.config.get('summary_readouts', []):
467
+ return torch.cat([mean, summary], dim=-1)
468
+ if task in self.config.get('pair_summary_readouts', []):
469
+ return torch.cat([mean + self.pool_fuse(summary), mean, summary], dim=-1)
470
+ return mean + self.pool_fuse(summary)
471
+
472
+ def auxiliary_summarize(self, hidden, tokens, pad_mask, task):
473
+ valid = (~pad_mask).unsqueeze(-1)
474
+ mean = (hidden * valid).sum(1) / valid.sum(1).clamp_min(1)
475
+ if self.config.get('pooling', 'mean') == 'mean':
476
+ return mean
477
+ residues = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
478
+ # Empty/nonstandard-only inputs still produce a finite representation.
479
+ residues[:, 0] |= ~residues.any(1)
480
+ keep = residues.unsqueeze(-1)
481
+ count = keep.sum(1).clamp_min(1)
482
+ center = (hidden * keep).sum(1) / count
483
+ position = residues.cumsum(1).to(hidden.dtype) / count.to(hidden.dtype)
484
+ basis = torch.stack([position, position.square(), torch.sin(position * math.pi),
485
+ torch.cos(position * math.pi)], dim=-1)
486
+ ti = self.auxiliary_summary_index[task]
487
+ scores = torch.einsum('bld,qd->blq', hidden, self.auxiliary_pool_query[ti]) / math.sqrt(hidden.shape[-1])
488
+ scores = scores + torch.einsum('blp,qp->blq', basis, self.auxiliary_pool_position[ti])
489
+ scores = scores.masked_fill(~residues.unsqueeze(-1), -1e4)
490
+ attention = torch.einsum('blq,bld->bqd', scores.softmax(1), hidden)
491
+ variance = ((hidden - center[:, None]).float().square() * keep).sum(1) / count
492
+ deviation = (variance + 1e-5).sqrt().to(hidden.dtype)
493
+ maximum = hidden.masked_fill(~keep, -1e4).amax(1) - center
494
+ first = residues & (residues.cumsum(1) <= 32)
495
+ last = residues & ((residues.sum(1, keepdim=True) - residues.cumsum(1)) < 32)
496
+ prefix = (hidden * first.unsqueeze(-1)).sum(1) / first.sum(1, keepdim=True).clamp_min(1) - center
497
+ suffix = (hidden * last.unsqueeze(-1)).sum(1) / last.sum(1, keepdim=True).clamp_min(1) - center
498
+ summary = torch.cat([attention[:, 0] - center, attention[:, 1] - center,
499
+ deviation, maximum, prefix, suffix], dim=-1)
500
+ return torch.cat([mean, summary], dim=-1)
501
+
502
+ def pool_sequences(self, sequences, task, device, max_len):
503
+ if self.training and not self.config.get('window_pooling_training', True):
504
+ tokens=esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device)
505
+ return self.pool(tokens,task)
506
+ if task not in self.config.get('sequence_windows', []) or not any(len(s)>max_len-2 for s in sequences):
507
+ return self.pool(esm2.pad_batch([esm2.encode(s,max_len) for s in sequences],device),task)
508
+ results=[None]*len(sequences)
509
+ short=[i for i,s in enumerate(sequences) if len(s)<=max_len-2]
510
+ if short:
511
+ pooled=self.pool(esm2.pad_batch([esm2.encode(sequences[i],max_len) for i in short],device),task)
512
+ for j,index in enumerate(short):results[index]=pooled[j]
513
+ width=max_len-2;stride=min(768,width)
514
+ if self.training and self.config.get('batch_window_training',False):
515
+ pieces=[];starts_by_index={};encoded={}
516
+ for index,sequence in enumerate(sequences):
517
+ if len(sequence)<=width:continue
518
+ starts=list(range(0,len(sequence)-width+1,stride))
519
+ if starts[-1]!=len(sequence)-width:starts.append(len(sequence)-width)
520
+ starts_by_index[index]=starts
521
+ pieces.extend((index,start) for start in starts)
522
+ count=max(1,16384//max_len)
523
+ for begin in range(0,len(pieces),count):
524
+ part=pieces[begin:begin+count]
525
+ tokens=esm2.pad_batch([esm2.encode(sequences[i][s:s+width],max_len) for i,s in part],device)
526
+ hidden,_=self.encode_residues(tokens,task)
527
+ for j,key in enumerate(part):encoded[key]=hidden[j]
528
+ positions=torch.arange(width,device=device)
529
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
530
+ for index,starts in starts_by_index.items():
531
+ sequence=sequences[index];length=len(sequence)
532
+ total=torch.zeros(length,self.config['dim'],device=device);counts=torch.zeros(length,1,device=device)
533
+ for start in starts:
534
+ total.index_add_(0,positions+start,encoded[index,start][1:width+1].float()*weight)
535
+ counts.index_add_(0,positions+start,weight)
536
+ assembled=torch.cat([encoded[index,starts[0]][0:1],total/counts.clamp_min(1),encoded[index,starts[-1]][width+1:width+2]],dim=0)[None]
537
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
538
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
539
+ return torch.stack(results)
540
+ for index,sequence in enumerate(sequences):
541
+ length=len(sequence)
542
+ if length<=width:continue
543
+ starts=list(range(0,length-width+1,stride))
544
+ if starts[-1]!=length-width:starts.append(length-width)
545
+ total=torch.zeros(length,self.config['dim'],device=device)
546
+ counts=torch.zeros(length,1,device=device)
547
+ first=last=None
548
+ for begin in range(0,len(starts),max(1,16384//max_len)):
549
+ part=starts[begin:begin+max(1,16384//max_len)]
550
+ tokens=esm2.pad_batch([esm2.encode(sequence[s:s+width],max_len) for s in part],device)
551
+ hidden,_=self.encode_residues(tokens,task)
552
+ for j,start in enumerate(part):
553
+ if start==0:first=hidden[j,0:1]
554
+ if start==starts[-1]:last=hidden[j,width+1:width+2]
555
+ positions=torch.arange(width,device=device)
556
+ weight=torch.minimum(torch.minimum(positions+1,width-positions),torch.full_like(positions,128)).float()[:,None]
557
+ total.index_add_(0,positions+start,hidden[j,1:width+1].float()*weight)
558
+ counts.index_add_(0,positions+start,weight)
559
+ assembled=torch.cat([first,total/counts.clamp_min(1),last],dim=0)[None]
560
+ tokens=esm2.pad_batch([esm2.encode(sequence,length+2)],device)
561
+ results[index]=self.summarize(assembled,tokens,tokens.eq(esm2.PAD),task)[0]
562
+ return torch.stack(results)
563
+
564
+ def represent(self, task, batch, device, max_len=1024):
565
+ if task in self.config.get('sequence_composition_readouts', []):
566
+ from sequence_composition import composition_features
567
+ sequences=[item['sequence'] for item in batch]
568
+ pooled=self.pool_sequences(sequences,task,device,max_len)
569
+ return torch.cat([pooled.float(),composition_features(sequences,device)],-1)
570
+ if task in self.config.get('token_logmeanexp_heads', []):
571
+ tokens = esm2.pad_batch([esm2.encode(row['sequence'], max_len) for row in batch], device)
572
+ hidden, _ = self.encode_residues(tokens, task)
573
+ valid = (tokens >= esm2.FIRST_RESIDUE) & (tokens <= esm2.LAST_RESIDUE)
574
+ valid[:, 0] |= ~valid.any(1)
575
+ return {'hidden':hidden, 'valid':valid}
576
+ if task in self.config.get('terminal_summary_readouts', {}):
577
+ return self.terminal_summary_features(task, [item['sequence'] for item in batch], device, max_len)
578
+ if task in self.config.get('ss_summary_readouts', []):
579
+ sequences=[x['sequence'] for x in batch]
580
+ summary=self.pool_sequences(sequences,task,device,max_len)
581
+ structure=self.secondary_structure_summary(sequences,device,max_len)
582
+ return torch.cat([summary.float(),structure],-1)
583
+ if task in self.config.get('sequence_conv_readouts',{}):
584
+ tokens=esm2.pad_batch([esm2.encode(x['sequence'],max_len) for x in batch],device)
585
+ hidden,pad_mask=self.encode_residues(tokens,task)
586
+ lengths=torch.tensor([min(len(x['sequence']),max_len-2) for x in batch],device=device)
587
+ width=max(1,int(lengths.max()))
588
+ valid=torch.arange(width,device=device)[None,:]<lengths[:,None]
589
+ return {'hidden':hidden[:,1:1+width], 'valid':valid,
590
+ 'summary':self.summarize(hidden,tokens,pad_mask,task)}
591
+ if task in self.config.get('residue_readouts', {}):
592
+ bins = self.config['residue_readouts'][task]['bins']
593
+ sequences = [x['sequence'] for x in batch]
594
+ tokens = esm2.pad_batch([esm2.encode(s, max_len) for s in sequences], device)
595
+ hidden, _ = self.encode_residues(tokens, task)
596
+ return self.position_features(hidden, [min(len(s), max_len-2) for s in sequences], bins)
597
+ if task in self.PAIR:
598
+ a = self.pool_sequences([x['sequence_a'] for x in batch],task,device,max_len)
599
+ b = self.pool_sequences([x['sequence_b'] for x in batch],task,device,max_len)
600
+ if task in self.config.get('expanded_pair_readouts', []):
601
+ if task in self.config.get('symmetric_pair_readouts',[]):
602
+ features=torch.cat([(a.float()+b.float())*.5,a*b,(a-b).abs()],dim=-1)
603
+ else:
604
+ features=torch.cat([a,b,a*b,(a-b).abs()],dim=-1)
605
+ base = F.dropout(features,p=self.config.get('pair_dropout',0.),training=self.training)
606
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
607
+ output = torch.cat([a, b], dim=-1)
608
+ if self.config.get('pair_interaction', False):
609
+ output = output + self.pair_fuse(torch.cat([a * b, (a - b).abs()], dim=-1))
610
+ base = F.dropout(output, p=self.config.get('pair_dropout', 0.0), training=self.training)
611
+ return self.add_pair_residues(task, batch, device, max_len, self.pair_representation(task, a, b, base))
612
+ return self.pool_sequences([x['sequence'] for x in batch],task,device,max_len)
613
+
614
+ def add_pair_residues(self, task, batch, device, max_len, base):
615
+ if task not in self.config.get('pair_residue_tasks', []):
616
+ return base
617
+ result = dict(base) if isinstance(base, dict) else {'base': base}
618
+ bins = self.config['pair_residue_interaction']['bins']
619
+ for role, name in [('a', 'sequence_a'), ('b', 'sequence_b')]:
620
+ result['residue_'+role] = self.pool_residue_bins(
621
+ [row[name] for row in batch], task, device, max_len, bins)
622
+ return result
623
+
624
+ def pool_residue_bins(self, sequences, task, device, max_len, bins):
625
+ """Average every residue into fixed relative bins, with full-chain context."""
626
+ width = max_len-2
627
+ assert width > 0 and bins > 0
628
+ output = [None]*len(sequences)
629
+ short = [i for i, sequence in enumerate(sequences) if len(sequence) <= width]
630
+ if short:
631
+ tokens = esm2.pad_batch([esm2.encode(sequences[i], max_len) for i in short], device)
632
+ hidden, _ = self.encode_residues(tokens, task)
633
+ for j, index in enumerate(short):
634
+ length = len(sequences[index])
635
+ values = hidden[j, 1:1+length].float()
636
+ output[index] = (F.adaptive_avg_pool1d(values.T[None], bins)[0].T if length
637
+ else torch.zeros(bins, self.config['dim'], device=device))
638
+ for index, sequence in enumerate(sequences):
639
+ if len(sequence) <= width:
640
+ continue
641
+ starts = list(range(0, len(sequence)-width+1, min(768, width)))
642
+ if starts[-1] != len(sequence)-width:
643
+ starts.append(len(sequence)-width)
644
+ total = torch.zeros(len(sequence), self.config['dim'], device=device)
645
+ count = torch.zeros(len(sequence), 1, device=device)
646
+ position = torch.arange(width, device=device)
647
+ weight = torch.minimum(torch.minimum(position+1, width-position),
648
+ torch.full_like(position, 128)).float()[:, None]
649
+ for begin in range(0, len(starts), max(1, 16384//max_len)):
650
+ part = starts[begin:begin+max(1, 16384//max_len)]
651
+ tokens = esm2.pad_batch([esm2.encode(sequence[s:s+width], max_len) for s in part], device)
652
+ hidden, _ = self.encode_residues(tokens, task)
653
+ for j, start in enumerate(part):
654
+ total.index_add_(0, position+start, hidden[j, 1:1+width].float()*weight)
655
+ count.index_add_(0, position+start, weight)
656
+ values = total/count.clamp_min(1)
657
+ output[index] = F.adaptive_avg_pool1d(values.T[None], bins)[0].T
658
+ return torch.stack(output)
659
+
660
+ @staticmethod
661
+ def terminal_bins(states, width, bins, align_end=False):
662
+ """Fixed absolute residue bins; exclude padding from partial-bin means."""
663
+ assert width > 0 and bins > 0 and width % bins == 0
664
+ states = (states[-width:] if align_end else states[:width]).float()
665
+ count = states.shape[0]
666
+ padded = states.new_zeros(width, states.shape[-1])
667
+ valid = states.new_zeros(width)
668
+ offset = width-count if align_end else 0
669
+ padded[offset:offset+count] = states
670
+ valid[offset:offset+count] = 1
671
+ total = padded.reshape(bins, width//bins, -1).sum(1)
672
+ denominator = valid.reshape(bins, width//bins).sum(1).clamp_min(1)[:, None]
673
+ return (total/denominator).flatten()
674
+
675
+ def terminal_summary_features(self, task, sequences, device, max_len):
676
+ settings = self.config['terminal_summary_readouts'][task]
677
+ width = max_len-2
678
+ assert width >= max(settings['prefix_residues'], settings['suffix_residues'])
679
+ tokens = esm2.pad_batch([esm2.encode(sequence, max_len) for sequence in sequences], device)
680
+ hidden, padding = self.encode_residues(tokens, task)
681
+ summary = self.summarize(hidden, tokens, padding, task)
682
+ long_ids = [index for index, sequence in enumerate(sequences) if len(sequence) > width]
683
+ tails = {}
684
+ if long_ids:
685
+ tail_tokens = esm2.pad_batch([esm2.encode(sequences[index][-width:], max_len)
686
+ for index in long_ids], device)
687
+ tail_hidden, _ = self.encode_residues(tail_tokens, task)
688
+ tails = {index: tail_hidden[local, 1:width+1] for local, index in enumerate(long_ids)}
689
+ terminals = []
690
+ for index, sequence in enumerate(sequences):
691
+ prefix = hidden[index, 1:1+min(len(sequence), width)]
692
+ suffix = tails.get(index, prefix)
693
+ terminals.append(torch.cat([
694
+ self.terminal_bins(prefix, settings['prefix_residues'], settings['bins']),
695
+ self.terminal_bins(suffix, settings['suffix_residues'], settings['bins'], align_end=True)]))
696
+ return torch.cat([summary.float(), torch.stack(terminals)], dim=-1)
697
+
698
+ @staticmethod
699
+ def position_features(hidden, lengths, bins):
700
+ features = []
701
+ for index, length in enumerate(lengths):
702
+ if length:
703
+ states = hidden[index:index+1, 1:1+length].float().transpose(1, 2)
704
+ features.append(F.interpolate(states, size=bins, mode='linear', align_corners=True).flatten())
705
+ else:
706
+ features.append(hidden.new_zeros(hidden.shape[-1] * bins).float())
707
+ return torch.stack(features)
708
+
709
+ def secondary_structure_summary(self, sequences, device, max_len):
710
+ tokens=esm2.pad_batch([esm2.encode(sequence,max_len) for sequence in sequences],device)
711
+ hidden,_=self.encode_residues(tokens,'secondary_structure')
712
+ with torch.autocast(device_type=device.type,enabled=False):
713
+ probabilities=self.heads['secondary_structure'](hidden.float()).softmax(-1)
714
+ summaries=[]
715
+ for index,sequence in enumerate(sequences):
716
+ length=min(len(sequence),max_len-2)
717
+ if not length:
718
+ summaries.append(probabilities.new_zeros(40));continue
719
+ value=probabilities[index,1:1+length]
720
+ mean=value.mean(0);std=value.std(0,unbiased=False)
721
+ transition=(value[:-1,:,None]*value[1:,None,:]).mean(0).flatten() if length>1 else value.new_zeros(9)
722
+ positions=F.adaptive_avg_pool1d(value.T[None],8).flatten()
723
+ summaries.append(torch.cat([mean,std,transition,positions,value.new_tensor([math.log1p(length)])]))
724
+ return torch.stack(summaries)
725
+
726
+ def normalize(self, task, values):
727
+ stats = self.config.get('regression_stats', {}).get(task)
728
+ return (values - stats['mean']) / stats['std'] if stats else values
729
+
730
+ def unscale(self, task, values):
731
+ stats = self.config.get('regression_stats', {}).get(task)
732
+ return values * stats['std'] + stats['mean'] if stats else values
733
+
734
+ def transfer(self, state, normalized_source=False):
735
+ """Transfer our own lineage only; retain random init for new parameters."""
736
+ current = self.state_dict()
737
+ fitting = {k: v for k, v in state.items() if k in current and v.shape == current[k].shape}
738
+ missing, unexpected = self.load_state_dict(fitting, strict=False)
739
+ if not normalized_source:
740
+ with torch.no_grad():
741
+ for task, stats in self.config.get('regression_stats', {}).items():
742
+ # Preserve predictions when moving a trained head to standardized units.
743
+ if f'heads.{task}.3.weight' in fitting:
744
+ self.heads[task][3].weight.div_(stats['std'])
745
+ self.heads[task][3].bias.sub_(stats['mean']).div_(stats['std'])
746
+ return {'transferred': len(fitting), 'new_tensors': missing, 'unexpected': unexpected}
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/PUBLISHED.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "source": "/run-state/workspace/research/production-allfit-ss1/candidate/package",
3
+ "files": 9,
4
+ "bytes": 562063804
5
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified PEER protein model
2
+
3
+ Exactly **139,328,153 learned parameters** in one state dictionary. The original
4
+ 37,845,535-parameter,12-layer,width-512 primary encoder was jointly trained on
5
+ all eleven tasks and supplies every task. Two shared extension blocks serve
6
+ beta-lactamase/stability. One jointly trained12-layer,width-768 auxiliary
7
+ encoder is stored once and supplies SS and subcellular features.
8
+
9
+ SS concatenates both frozen local convolution/MLP prefixes and uses one
10
+ normalized1280-to-3 linear readout. Subcellular uses both seven-summary
11
+ features. Other heads retain rank-target positional GFP/beta readouts,
12
+ summary fold/solubility/binary heads (binary with shared residual), a stability
13
+ MLP, and pair readouts with retained shared yeast interaction modules.
14
+
15
+ All parameters originated from random initialization and training here.
16
+ Primary provenance: one hour mounted UniRef50 MLM, joint all11 fit training,
17
+ conditioning/extensions and own-teacher SS distillation. Auxiliary: eight
18
+ hours MLM (10,254,509,402 tokens),8,486 joint all11 fit updates. Only mounted
19
+ fit/Tune/UniRef50 were used; no external weights or embeddings.
20
+
21
+ SS now fits all2,221,507 valid fit residues (including2,245,710 window views),
22
+ with the same seed20270212,ridge.01,fit mean/std and final12 LBFGS blocks as
23
+ the500k-residue predecessor. Every previous sampled feature/label/window
24
+ weight matches exactly. CUDA optimizer resume checks passed. Cached SS rises
25
+ from.7674307948 to.7678563413; paired protein95 interval for the increase is
26
+ [.00015318,.00070488]. The original minimum-effect threshold.0005 was missed.
27
+ A separately recorded, retrospective publication review uses positive native
28
+ gain and interval, complete all11 replay and shared-parameter dependence.
29
+ It does not claim the original experimental eligibility rule passed.
30
+ Independent native all11 review passed; all ten unaffected production prediction files match exactly, and SS matches the accepted fit-only development output. Native primary feature removal lowers SS accuracy by .01279153; auxiliary removal lowers it by .13247602. The fit-only development mean is .7221840065.
31
+
32
+ Five existing fit+Tune heads (fold, fluorescence, beta-lactamase, affinity, stability) remain exact. Their Tune scores and aggregate are in-sample and excluded from selection.
33
+
34
+ Limits: repeated Tune selection and protein-family dependence; the intervals
35
+ are conditional. Feature removal is out of distribution. Fold remains weak,
36
+ PPI validation sets are small, rank outputs lack absolute calibration. SS and
37
+ PPI use full-chain windows; other tasks retain their1022-residue prefix.
38
+ No held-out test score is available.
39
+
40
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT` offline. No trainer, feature cache,
41
+ sequence lookup, external model or test-time fitting is accessed.
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/config.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "layers": 12,
3
+ "dim": 512,
4
+ "heads": 8,
5
+ "pooling": "rich",
6
+ "pair_interaction": true,
7
+ "ss_context": true,
8
+ "max_len": 1024,
9
+ "pair_dropout": 0.0,
10
+ "architecture": "unified",
11
+ "full_ss": true,
12
+ "regression_stats": {
13
+ "fluorescence": {
14
+ "mean": 3.180586883940159,
15
+ "std": 0.8339910288860748
16
+ },
17
+ "stability": {
18
+ "mean": 0.1790524860555312,
19
+ "std": 0.5662245232305059
20
+ },
21
+ "beta_lactamase": {
22
+ "mean": 0.7383112351980983,
23
+ "std": 0.31642946622284734
24
+ },
25
+ "ppi_affinity": {
26
+ "mean": -11.654589870742203,
27
+ "std": 3.0832061340498944
28
+ }
29
+ },
30
+ "residue_readouts": {
31
+ "fluorescence": {
32
+ "bins": 256
33
+ },
34
+ "beta_lactamase": {
35
+ "bins": 320
36
+ }
37
+ },
38
+ "fp32_heads": [
39
+ "beta_lactamase",
40
+ "binary_localization",
41
+ "fluorescence",
42
+ "fold",
43
+ "human_ppi",
44
+ "ppi_affinity",
45
+ "secondary_structure",
46
+ "solubility",
47
+ "stability",
48
+ "subcellular_localization",
49
+ "yeast_ppi"
50
+ ],
51
+ "ss_linear_context": 0,
52
+ "ss_calibrated": true,
53
+ "linear_heads": [],
54
+ "summary_readouts": [
55
+ "solubility",
56
+ "subcellular_localization",
57
+ "binary_localization",
58
+ "fold"
59
+ ],
60
+ "cosine_heads": {},
61
+ "nonlinear_summary_heads": {},
62
+ "calibrated_heads": [
63
+ "stability"
64
+ ],
65
+ "sequence_windows": [
66
+ "yeast_ppi",
67
+ "human_ppi"
68
+ ],
69
+ "expanded_pair_readouts": [
70
+ "yeast_ppi",
71
+ "human_ppi",
72
+ "ppi_affinity"
73
+ ],
74
+ "symmetric_pair_readouts": [
75
+ "yeast_ppi",
76
+ "ppi_affinity"
77
+ ],
78
+ "task_encoder_layers": {},
79
+ "task_conditioning": true,
80
+ "pair_summary_readouts": [],
81
+ "extension_layers": 2,
82
+ "window_pooling_training": true,
83
+ "batch_window_training": true,
84
+ "class_weight_power": {
85
+ "fold": 0.5
86
+ },
87
+ "task_extension_depths": {
88
+ "beta_lactamase": 2,
89
+ "binary_localization": 0,
90
+ "fluorescence": 0,
91
+ "fold": 0,
92
+ "human_ppi": 0,
93
+ "ppi_affinity": 0,
94
+ "secondary_structure": 0,
95
+ "solubility": 0,
96
+ "stability": 2,
97
+ "subcellular_localization": 0,
98
+ "yeast_ppi": 0
99
+ },
100
+ "task_max_len": {
101
+ "human_ppi": 1536
102
+ },
103
+ "pair_bilinear_rank": 32,
104
+ "pair_bilinear_tasks": [
105
+ "yeast_ppi"
106
+ ],
107
+ "pair_residue_interaction": {
108
+ "bins": 64,
109
+ "projection_dim": 32,
110
+ "pair_hidden": 32,
111
+ "pair_channels": 8,
112
+ "dropout": 0.1
113
+ },
114
+ "pair_residue_tasks": [
115
+ "yeast_ppi"
116
+ ],
117
+ "rank_target_tasks": [
118
+ "fluorescence",
119
+ "beta_lactamase"
120
+ ],
121
+ "ss_summary_readouts": [],
122
+ "terminal_summary_readouts": {},
123
+ "residue_lowrank_heads": {},
124
+ "shared_summary_residual": {
125
+ "tasks": [
126
+ "binary_localization"
127
+ ],
128
+ "hidden": 128,
129
+ "dropout": 0.2
130
+ },
131
+ "summary_residual_tasks": [
132
+ "binary_localization"
133
+ ],
134
+ "dual_summary": {
135
+ "layers": 12,
136
+ "dim": 768,
137
+ "heads": 12,
138
+ "tasks": [
139
+ "subcellular_localization"
140
+ ]
141
+ },
142
+ "dual_residue": {
143
+ "task": "secondary_structure",
144
+ "features": "two_frozen_local_prefixes"
145
+ }
146
+ }
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/esm2.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """An ESM-2 architecture, trained from scratch, as the reference baseline.
3
+
4
+ Follows Lin et al. (Science 2023) / facebookresearch/esm in the ways that
5
+ matter for a like-for-like architecture claim:
6
+
7
+ * rotary position embeddings, not learned positional embeddings -- this is
8
+ the defining architectural change from ESM-1b to ESM-2
9
+ * pre-LayerNorm blocks, GELU feed-forward at 4x expansion
10
+ * final LayerNorm before the LM head, and the LM head's projection weight
11
+ tied to the token embedding
12
+ * the ESM alphabet's special tokens (<cls>/<pad>/<eos>/<mask>) and the same
13
+ 20 standard + rare amino-acid symbols
14
+
15
+ The published size ladder is reproduced in CONFIGS so the baseline can be named
16
+ by its ESM-2 counterpart rather than by an arbitrary width.
17
+ """
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # ESM-2's alphabet, in its canonical order.
25
+ SPECIALS = ["<cls>", "<pad>", "<eos>", "<unk>"]
26
+ RESIDUES = list("LAGVSERTIDPKQNFYMHWCXBUZO")
27
+ EXTRA = ["<null_1>", "<mask>"]
28
+ ALPHABET = SPECIALS + RESIDUES + EXTRA
29
+ TOKEN = {symbol: index for index, symbol in enumerate(ALPHABET)}
30
+ CLS, PAD, EOS, UNK = TOKEN["<cls>"], TOKEN["<pad>"], TOKEN["<eos>"], TOKEN["<unk>"]
31
+ MASK = TOKEN["<mask>"]
32
+ VOCAB_SIZE = len(ALPHABET)
33
+ FIRST_RESIDUE, LAST_RESIDUE = TOKEN["L"], TOKEN["O"]
34
+
35
+ # name -> (layers, embed_dim, attention_heads), from the ESM-2 release table.
36
+ CONFIGS = {
37
+ "esm2_t6_8M": (6, 320, 20),
38
+ "esm2_t12_35M": (12, 480, 20),
39
+ "esm2_t30_150M": (30, 640, 20),
40
+ "esm2_t33_650M": (33, 1280, 20),
41
+ }
42
+
43
+
44
+ def encode(sequence, max_len=1024):
45
+ body = [TOKEN.get(c, UNK) for c in sequence[:max_len - 2]]
46
+ return [CLS] + body + [EOS]
47
+
48
+
49
+ def pad_batch(sequences, device):
50
+ width = max(len(s) for s in sequences)
51
+ out = torch.full((len(sequences), width), PAD, dtype=torch.long)
52
+ for row, ids in enumerate(sequences):
53
+ out[row, :len(ids)] = torch.tensor(ids, dtype=torch.long)
54
+ return out.to(device, non_blocking=True)
55
+
56
+
57
+ class Rotary(nn.Module):
58
+ """Rotary position embedding, as ESM-2 applies it to q and k."""
59
+
60
+ def __init__(self, dim, base=10000):
61
+ super().__init__()
62
+ inverse = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
63
+ self.register_buffer("inverse", inverse, persistent=False)
64
+ self._cached_length = 0
65
+
66
+ def _tables(self, length, device, dtype):
67
+ if length != self._cached_length or self._cos.device != device:
68
+ position = torch.arange(length, device=device, dtype=torch.float)
69
+ angles = torch.outer(position, self.inverse.to(device))
70
+ table = torch.cat([angles, angles], dim=-1)
71
+ self._cos = table.cos()[None, None]
72
+ self._sin = table.sin()[None, None]
73
+ self._cached_length = length
74
+ return self._cos.to(dtype), self._sin.to(dtype)
75
+
76
+ @staticmethod
77
+ def _rotate_half(x):
78
+ half = x.shape[-1] // 2
79
+ return torch.cat([-x[..., half:], x[..., :half]], dim=-1)
80
+
81
+ def forward(self, q, k):
82
+ cos, sin = self._tables(q.shape[-2], q.device, q.dtype)
83
+ return (q * cos + self._rotate_half(q) * sin,
84
+ k * cos + self._rotate_half(k) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ def __init__(self, dim, heads):
89
+ super().__init__()
90
+ self.heads = heads
91
+ self.head_dim = dim // heads
92
+ self.q = nn.Linear(dim, dim)
93
+ self.k = nn.Linear(dim, dim)
94
+ self.v = nn.Linear(dim, dim)
95
+ self.out = nn.Linear(dim, dim)
96
+ self.rotary = Rotary(self.head_dim)
97
+
98
+ def forward(self, x, pad_mask):
99
+ batch, length, _ = x.shape
100
+ shape = (batch, length, self.heads, self.head_dim)
101
+ q = self.q(x).view(shape).transpose(1, 2)
102
+ k = self.k(x).view(shape).transpose(1, 2)
103
+ v = self.v(x).view(shape).transpose(1, 2)
104
+ q, k = self.rotary(q, k)
105
+ attention_mask = None
106
+ if pad_mask is not None:
107
+ attention_mask = (~pad_mask)[:, None, None, :]
108
+ hidden = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask)
109
+ hidden = hidden.transpose(1, 2).reshape(batch, length, -1)
110
+ return self.out(hidden)
111
+
112
+
113
+ class Block(nn.Module):
114
+ def __init__(self, dim, heads, ffn):
115
+ super().__init__()
116
+ self.norm1 = nn.LayerNorm(dim)
117
+ self.attention = Attention(dim, heads)
118
+ self.norm2 = nn.LayerNorm(dim)
119
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn), nn.GELU(), nn.Linear(ffn, dim))
120
+
121
+ def forward(self, x, pad_mask, condition=None):
122
+ first = self.norm1(x)
123
+ if condition is not None:
124
+ first = first * (1 + condition[0]) + condition[1]
125
+ x = x + self.attention(first, pad_mask)
126
+ second = self.norm2(x)
127
+ if condition is not None:
128
+ second = second * (1 + condition[2]) + condition[3]
129
+ return x + self.ffn(second)
130
+
131
+
132
+ class Encoder(nn.Module):
133
+ """The shared backbone. Every task reads from this one parameter set."""
134
+
135
+ def __init__(self, layers=12, dim=480, heads=20):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.embed = nn.Embedding(VOCAB_SIZE, dim, padding_idx=PAD)
139
+ self.blocks = nn.ModuleList([Block(dim, heads, dim * 4) for _ in range(layers)])
140
+ self.norm = nn.LayerNorm(dim)
141
+ self.lm_bias = nn.Parameter(torch.zeros(VOCAB_SIZE))
142
+ self.apply(self._init)
143
+
144
+ @staticmethod
145
+ def _init(module):
146
+ if isinstance(module, nn.Linear):
147
+ nn.init.normal_(module.weight, std=0.02)
148
+ if module.bias is not None:
149
+ nn.init.zeros_(module.bias)
150
+ elif isinstance(module, nn.Embedding):
151
+ nn.init.normal_(module.weight, std=0.02)
152
+
153
+ def add_extension(self, layers, heads, before_norm=False):
154
+ """Append shared residual blocks after the original normalized representation."""
155
+ assert layers > 0 and not hasattr(self, 'extension')
156
+ self.extension_before_norm = bool(before_norm)
157
+ self.extension = nn.ModuleList([Block(self.dim, heads, 4*self.dim) for _ in range(layers)])
158
+ self.extension.apply(self._init)
159
+ # Identity at initialization preserves every existing readout exactly.
160
+ for block in self.extension:
161
+ nn.init.zeros_(block.attention.out.weight)
162
+ nn.init.zeros_(block.attention.out.bias)
163
+ nn.init.zeros_(block.ffn[2].weight)
164
+ nn.init.zeros_(block.ffn[2].bias)
165
+
166
+ def forward(self, tokens, condition=None, depth=None, extension_depth=None):
167
+ pad_mask = tokens.eq(PAD)
168
+ hidden = self.embed(tokens)
169
+ depth=len(self.blocks) if depth is None else int(depth)
170
+ if not 1<=depth<=len(self.blocks):
171
+ raise ValueError(f'Encoder depth {depth} is outside 1..{len(self.blocks)}')
172
+ for index, block in enumerate(self.blocks):
173
+ if index>=depth:
174
+ break
175
+ hidden = block(hidden, pad_mask, condition[index] if condition is not None else None)
176
+ # Local residue heads must not observe artificial states at padded
177
+ # positions; otherwise predictions near the C terminus depend on which
178
+ # other sequences share the batch. Valid transformer states are unchanged.
179
+ before_norm = getattr(self, 'extension_before_norm', False)
180
+ if not before_norm:
181
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
182
+ extension = getattr(self, 'extension', ())
183
+ extension_depth = len(extension) if extension_depth is None else int(extension_depth)
184
+ if not 0 <= extension_depth <= len(extension):
185
+ raise ValueError(f'Extension depth {extension_depth} is outside 0..{len(extension)}')
186
+ for index, block in enumerate(extension):
187
+ if index >= extension_depth:
188
+ break
189
+ hidden = block(hidden, pad_mask).masked_fill(pad_mask.unsqueeze(-1), 0)
190
+ if before_norm:
191
+ hidden = self.norm(hidden).masked_fill(pad_mask.unsqueeze(-1), 0)
192
+ return hidden, pad_mask
193
+
194
+ def lm_logits(self, hidden):
195
+ # Weight tying, as in ESM-2's RobertaLMHead.
196
+ return F.linear(hidden, self.embed.weight) + self.lm_bias
197
+
198
+ def pool(self, tokens):
199
+ hidden, pad_mask = self.forward(tokens)
200
+ keep = (~pad_mask).to(hidden.dtype).unsqueeze(-1)
201
+ return (hidden * keep).sum(1) / keep.sum(1).clamp(min=1)
202
+
203
+
204
+ class Model(nn.Module):
205
+ """ESM-2 backbone plus the eleven PEER task heads."""
206
+
207
+ CLASSES = {"solubility": 2, "subcellular_localization": 10,
208
+ "binary_localization": 2, "fold": 1195,
209
+ "yeast_ppi": 2, "human_ppi": 2}
210
+ REGRESSION = ("fluorescence", "stability", "beta_lactamase", "ppi_affinity")
211
+ PAIR = {"yeast_ppi", "human_ppi", "ppi_affinity"}
212
+
213
+ def __init__(self, layers=12, dim=480, heads=20):
214
+ super().__init__()
215
+ self.encoder = Encoder(layers=layers, dim=dim, heads=heads)
216
+ self.heads = nn.ModuleDict()
217
+ for task, n in self.CLASSES.items():
218
+ width = dim * 2 if task in self.PAIR else dim
219
+ self.heads[task] = nn.Sequential(
220
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, n))
221
+ for task in self.REGRESSION:
222
+ width = dim * 2 if task in self.PAIR else dim
223
+ self.heads[task] = nn.Sequential(
224
+ nn.Linear(width, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 1))
225
+ self.heads["secondary_structure"] = nn.Sequential(
226
+ nn.Linear(dim, dim), nn.GELU(), nn.LayerNorm(dim), nn.Linear(dim, 3))
227
+
228
+ def represent(self, task, batch, device, max_len=1024):
229
+ if task in self.PAIR:
230
+ a = self.encoder.pool(pad_batch(
231
+ [encode(x["sequence_a"], max_len) for x in batch], device))
232
+ b = self.encoder.pool(pad_batch(
233
+ [encode(x["sequence_b"], max_len) for x in batch], device))
234
+ return torch.cat([a, b], dim=-1)
235
+ return self.encoder.pool(pad_batch(
236
+ [encode(x["sequence"], max_len) for x in batch], device))
237
+
238
+
239
+ def build(name="esm2_t12_35M"):
240
+ layers, dim, heads = CONFIGS[name]
241
+ model = Model(layers=layers, dim=dim, heads=heads)
242
+ return model, {"name": name, "layers": layers, "dim": dim, "heads": heads}
243
+
244
+
245
+ if __name__ == "__main__":
246
+ for name in CONFIGS:
247
+ model, config = build(name)
248
+ backbone = sum(p.numel() for p in model.encoder.parameters())
249
+ total = sum(p.numel() for p in model.parameters())
250
+ print(f"{name:16s} backbone {backbone/1e6:7.2f}M with heads {total/1e6:7.2f}M")
tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/submissions/S058/infer.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ export PYTHONDONTWRITEBYTECODE=1
4
+ exec python3 "$(dirname "$0")/replay.py" "$1" "$2"