File size: 13,892 Bytes
9270c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Inference @128: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 782/782 [4:10:15<00:00, 19.20s/it]  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Finished inference with batch=128 in 250.25 min\n",
      "Saved probabilities to 100k_probs.npy\n",
      "\n",
      "bottom-100000 metrics: ROC-AUC=0.9123 | PR-AUC=0.6204 (batch=128)\n",
      "Confusion (thr=0.5):\n",
      " [[83418  9395]\n",
      " [ 1097  6090]]\n",
      "Best-F1 thr=0.5832 -> Confusion:\n",
      " [[89911  2902]\n",
      " [ 2323  4864]]\n",
      "Brier score: 0.1676\n",
      "Recall@Top1%: 0.11172951161819951\n",
      "Recall@Top5%: 0.4886600807012661\n",
      "Recall@Top10%: 0.7528871573674689\n",
      "Recall @ FPR=1%: 0.3568 (thr=0.6822442412376404)\n"
     ]
    }
   ],
   "source": [
    "# =============================\n",
    "# RUN: Bottom-100k Evaluation (single cell)\n",
    "# - loads model + feat scalers\n",
    "# - takes the last 100k rows from 900k_test.parquet\n",
    "# - normalizes features exactly like training\n",
    "# - batched tokenization & inference with GPU-safe fallback\n",
    "# - metrics, leaderboard, ROC/PR, calibration, ranking metrics\n",
    "# =============================\n",
    "\n",
    "import os, time, gc, json\n",
    "from tqdm.auto import tqdm\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from safetensors.torch import load_file\n",
    "from transformers import AutoTokenizer, AutoModel\n",
    "from sklearn.metrics import (\n",
    "    roc_auc_score, average_precision_score, roc_curve,\n",
    "    precision_recall_curve, confusion_matrix, brier_score_loss\n",
    ")\n",
    "from sklearn.calibration import calibration_curve\n",
    "\n",
    "# ---------- CONFIG ----------\n",
    "MODEL_DIR = \"PathoPreter_Ready_V1\"\n",
    "PARQUET_900K = \"900k_test.parquet\"\n",
    "BOTTOM_K = 100_000                      # <--- using bottom 100k as requested\n",
    "OUT_PROBS = \"100k_probs.npy\"\n",
    "\n",
    "# feature columns exactly as training\n",
    "feature_cols = [\n",
    "    \"gnomad_af\",\n",
    "    \"GERP++_RS_rankscore\",\n",
    "    \"GERP_91_mammals_rankscore\",\n",
    "    \"phyloP100way_vertebrate_rankscore\",\n",
    "    \"phyloP470way_mammalian_rankscore\",\n",
    "    \"phyloP17way_primate_rankscore\",\n",
    "    \"phastCons100way_vertebrate_rankscore\",\n",
    "    \"phastCons470way_mammalian_rankscore\",\n",
    "    \"phastCons17way_primate_rankscore\",\n",
    "]\n",
    "\n",
    "bench_cols = [\n",
    "    \"CADD_raw_rankscore\",\"REVEL_rankscore\",\"AlphaMissense_rankscore\",\n",
    "    \"ClinPred_rankscore\",\"PrimateAI_rankscore\",\"MPC_rankscore\",\n",
    "    \"BayesDel_addAF_rankscore\",\"EVE_rankscore\",\"ESM1b_rankscore\"\n",
    "]\n",
    "\n",
    "DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "print(\"Device:\", DEVICE)\n",
    "if DEVICE.type == \"cuda\":\n",
    "    print(torch.cuda.get_device_properties(0))\n",
    "\n",
    "# ---------- helpers ----------\n",
    "def map_label_str(x):\n",
    "    if pd.isna(x): return np.nan\n",
    "    s = str(x).lower()\n",
    "    if s.startswith(\"path\"): return 1\n",
    "    if s.startswith(\"ben\"):  return 0\n",
    "    return np.nan\n",
    "\n",
    "class SequenceClassificationWithFeatures(nn.Module):\n",
    "    def __init__(self, encoder, hidden_size, feature_dim, num_labels):\n",
    "        super().__init__()\n",
    "        self.encoder = encoder\n",
    "        self.classifier = nn.Sequential(\n",
    "            nn.Linear(hidden_size + feature_dim, hidden_size),\n",
    "            nn.GELU(),\n",
    "            nn.Dropout(0.1),\n",
    "            nn.Linear(hidden_size, num_labels)\n",
    "        )\n",
    "    def forward(self, input_ids=None, attention_mask=None, features=None):\n",
    "        out = self.encoder(input_ids=input_ids, attention_mask=attention_mask, return_dict=True)\n",
    "        last = out.last_hidden_state\n",
    "        mask = attention_mask.unsqueeze(-1)\n",
    "        pooled = (last * mask).sum(1) / mask.sum(1).clamp(min=1e-9)\n",
    "        features = features.to(pooled.device).to(pooled.dtype)\n",
    "        logits = self.classifier(torch.cat([pooled, features], dim=1))\n",
    "        return logits\n",
    "\n",
    "# ---------- load metadata + scalers + tokenizer ----------\n",
    "print(\"Loading model metadata and scalers...\")\n",
    "meta_path = os.path.join(MODEL_DIR, \"model_metadata.json\")\n",
    "if not os.path.exists(meta_path):\n",
    "    raise FileNotFoundError(\"Missing model metadata: \" + meta_path)\n",
    "with open(meta_path, \"r\") as f:\n",
    "    meta = json.load(f)\n",
    "\n",
    "feat_means_path = os.path.join(MODEL_DIR, \"feat_means.npy\")\n",
    "feat_stds_path  = os.path.join(MODEL_DIR, \"feat_stds.npy\")\n",
    "if not (os.path.exists(feat_means_path) and os.path.exists(feat_stds_path)):\n",
    "    raise FileNotFoundError(\"Missing feat_means.npy or feat_stds.npy in model directory.\")\n",
    "feat_means = np.load(feat_means_path)\n",
    "feat_stds  = np.load(feat_stds_path)\n",
    "\n",
    "# sanity check feature lengths\n",
    "if len(feat_means) != len(feature_cols):\n",
    "    print(\"Warning: feat_means length != feature_cols. Using feature_cols from meta if present.\")\n",
    "    if \"feature_cols\" in meta:\n",
    "        feature_cols = meta[\"feature_cols\"]\n",
    "        print(\"Using meta feature_cols length:\", len(feature_cols))\n",
    "    else:\n",
    "        raise RuntimeError(\"feature_cols mismatch; check model metadata.\")\n",
    "\n",
    "print(\"Loading tokenizer...\")\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"InstaDeepAI/nucleotide-transformer-500m-human-ref\", trust_remote_code=True)\n",
    "\n",
    "# ---------- load model weights safely ----------\n",
    "print(\"Loading encoder and model weights (safetensors)...\")\n",
    "base_encoder = AutoModel.from_pretrained(MODEL_DIR, trust_remote_code=True)\n",
    "hidden_size = base_encoder.config.hidden_size\n",
    "FEATURE_DIM = len(feature_cols)\n",
    "NUM_LABELS = meta.get(\"num_labels\", 2)\n",
    "\n",
    "model = SequenceClassificationWithFeatures(base_encoder, hidden_size, FEATURE_DIM, NUM_LABELS)\n",
    "state_path = os.path.join(MODEL_DIR, \"model.safetensors\")\n",
    "if not os.path.exists(state_path):\n",
    "    raise FileNotFoundError(\"Missing model.safetensors in \" + MODEL_DIR)\n",
    "state = load_file(state_path)\n",
    "state_t = {k: torch.as_tensor(v) for k, v in state.items()}\n",
    "missing, unexpected = model.load_state_dict(state_t, strict=False)\n",
    "print(\"Loaded weights (strict=False). Missing keys:\", len(missing), \"Unexpected keys:\", len(unexpected))\n",
    "model.to(DEVICE).eval()\n",
    "torch.cuda.empty_cache()\n",
    "\n",
    "# ---------- prepare bottom-100k dataframe ----------\n",
    "print(f\"\\nLoading {PARQUET_900K} and slicing last {BOTTOM_K} rows (bottom)...\")\n",
    "if not os.path.exists(PARQUET_900K):\n",
    "    raise FileNotFoundError(\"Missing parquet file: \" + PARQUET_900K)\n",
    "df_all = pd.read_parquet(PARQUET_900K)\n",
    "print(\"Total rows in file:\", len(df_all))\n",
    "df = df_all.tail(BOTTOM_K).reset_index(drop=True)\n",
    "print(\"Sliced rows:\", len(df))\n",
    "del df_all\n",
    "gc.collect()\n",
    "\n",
    "# ensure labels exist and map\n",
    "df[\"labels\"] = df[\"clean_label\"].map(map_label_str)\n",
    "valid_mask = ~df[\"labels\"].isna()\n",
    "print(\"Rows with labels present:\", valid_mask.sum())\n",
    "df = df.loc[valid_mask].reset_index(drop=True)\n",
    "df[\"labels\"] = df[\"labels\"].astype(int)\n",
    "\n",
    "# ---------- inference routine ----------\n",
    "def run_inference_on_df(df, name=\"bottom100k\", batch_candidates=(2048,1536,1024,768,512,256,128)):\n",
    "    print(f\"\\nStarting inference on {name} ({len(df)} rows)\")\n",
    "    # prepare sequences and features\n",
    "    seqs = df[\"raw_sequence\"].astype(str).tolist()\n",
    "    feats = df[feature_cols].copy()\n",
    "    # impute missing with training means\n",
    "    feats = feats.fillna(pd.Series(feat_means, index=feature_cols))\n",
    "    feats_arr = feats.values.astype(np.float32)\n",
    "    feats_norm = (feats_arr - feat_means.reshape(1,-1)) / (feat_stds.reshape(1,-1) + 1e-9)\n",
    "    feats_tensor = torch.from_numpy(feats_norm)\n",
    "\n",
    "    y_true = df[\"labels\"].values\n",
    "\n",
    "    probs = None\n",
    "    chosen_bs = None\n",
    "    for bs in batch_candidates:\n",
    "        try:\n",
    "            print(f\"\\nTrying batch size {bs} ...\")\n",
    "            probs_chunks = []\n",
    "            t0 = time.time()\n",
    "            for i in tqdm(range(0, len(seqs), bs), desc=f\"Inference @{bs}\"):\n",
    "                j = min(len(seqs), i+bs)\n",
    "                batch_seqs = seqs[i:j]\n",
    "                tok = tokenizer(batch_seqs, padding=\"max_length\", truncation=True,\n",
    "                                max_length=tokenizer.model_max_length, return_tensors=\"pt\")\n",
    "                ids = tok[\"input_ids\"].to(DEVICE)\n",
    "                mask = tok[\"attention_mask\"].to(DEVICE)\n",
    "                feats_batch = feats_tensor[i:j].to(DEVICE, non_blocking=True)\n",
    "\n",
    "                with torch.no_grad():\n",
    "                    logits = model(ids, mask, feats_batch)\n",
    "                    probs_batch = torch.softmax(logits, dim=1)[:, 1].cpu()\n",
    "                    probs_chunks.append(probs_batch)\n",
    "\n",
    "                # cleanup\n",
    "                del ids, mask, feats_batch, tok, logits, probs_batch\n",
    "                torch.cuda.empty_cache()\n",
    "\n",
    "            probs = torch.cat(probs_chunks).numpy()\n",
    "            chosen_bs = bs\n",
    "            elapsed = (time.time() - t0) / 60.0\n",
    "            print(f\"Finished inference with batch={bs} in {elapsed:.2f} min\")\n",
    "            break\n",
    "\n",
    "        except RuntimeError as e:\n",
    "            msg = str(e).lower()\n",
    "            print(f\"RuntimeError at bs={bs}: {msg}\")\n",
    "            if \"out of memory\" in msg or \"cuda\" in msg:\n",
    "                print(\" -> OOM, clearing cache and trying next smaller batch\")\n",
    "                torch.cuda.empty_cache(); gc.collect(); time.sleep(2)\n",
    "                continue\n",
    "            else:\n",
    "                raise\n",
    "\n",
    "    if probs is None:\n",
    "        raise RuntimeError(\"All batch sizes failed.\")\n",
    "\n",
    "    # save probs\n",
    "    np.save(OUT_PROBS, probs)\n",
    "    print(\"Saved probabilities to\", OUT_PROBS)\n",
    "\n",
    "    # metrics\n",
    "    roc = roc_auc_score(y_true, probs)\n",
    "    ap = average_precision_score(y_true, probs)\n",
    "    print(f\"\\n{name} metrics: ROC-AUC={roc:.4f} | PR-AUC={ap:.4f} (batch={chosen_bs})\")\n",
    "\n",
    "    # confusion at 0.5\n",
    "    y_pred05 = (probs >= 0.5).astype(int)\n",
    "    cm05 = confusion_matrix(y_true, y_pred05)\n",
    "    print(\"Confusion (thr=0.5):\\n\", cm05)\n",
    "\n",
    "    # best F1 threshold via precision-recall curve\n",
    "    prec, rec, thr = precision_recall_curve(y_true, probs)\n",
    "    f1 = 2 * prec * rec / (prec + rec + 1e-12)\n",
    "    if len(thr) > 0:\n",
    "        best_idx = np.nanargmax(f1[:-1])\n",
    "        best_thr = thr[best_idx]\n",
    "    else:\n",
    "        best_thr = 0.5\n",
    "    y_pred_best = (probs >= best_thr).astype(int)\n",
    "    cm_best = confusion_matrix(y_true, y_pred_best)\n",
    "    print(f\"Best-F1 thr={best_thr:.4f} -> Confusion:\\n\", cm_best)\n",
    "\n",
    "    # calibration\n",
    "    brier = brier_score_loss(y_true, probs)\n",
    "    prob_true, prob_pred = calibration_curve(y_true, probs, n_bins=10, strategy=\"uniform\")\n",
    "    print(f\"Brier score: {brier:.4f}\")\n",
    "\n",
    "    # ranking metrics\n",
    "    def recall_at_top_frac(scores, labels, frac):\n",
    "        k = max(1, int(len(scores) * frac))\n",
    "        idx = np.argsort(scores)[-k:]\n",
    "        return labels[idx].sum() / (labels.sum() + 1e-12)\n",
    "\n",
    "    print(\"Recall@Top1%:\", recall_at_top_frac(probs, y_true, 0.01))\n",
    "    print(\"Recall@Top5%:\", recall_at_top_frac(probs, y_true, 0.05))\n",
    "    print(\"Recall@Top10%:\", recall_at_top_frac(probs, y_true, 0.10))\n",
    "\n",
    "    # recall at fixed FPR=1%\n",
    "    fpr_vals, tpr_vals, t_thresh = roc_curve(y_true, probs)\n",
    "    valid = np.where(fpr_vals <= 0.01)[0]\n",
    "    if len(valid) > 0:\n",
    "        idx = valid[np.argmax(tpr_vals[valid])]\n",
    "        rec_at_1pct, thr_at_1pct = tpr_vals[idx], t_thresh[idx]\n",
    "    else:\n",
    "        rec_at_1pct, thr_at_1pct = 0.0, None\n",
    "    print(f\"Recall @ FPR=1%: {rec_at_1pct:.4f} (thr={thr_at_1pct})\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}