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\n",
15
+ "if str(ROOT) not in sys.path:\n",
16
+ " sys.path.append(str(ROOT))"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": null,
22
+ "id": "977db8b5",
23
+ "metadata": {},
24
+ "outputs": [],
25
+ "source": [
26
+ "import ast, re, os, joblib\n",
27
+ "from pathlib import Path\n",
28
+ "import numpy as np\n",
29
+ "import pandas as pd\n",
30
+ "import matplotlib.pyplot as plt \n",
31
+ "from sklearn.model_selection import train_test_split\n",
32
+ "from sklearn.preprocessing import MultiLabelBinarizer\n",
33
+ "from sklearn.feature_extraction.text import TfidfVectorizer\n",
34
+ "from sklearn.multiclass import OneVsRestClassifier\n",
35
+ "from sklearn.pipeline import Pipeline\n",
36
+ "from sklearn.base import BaseEstimator, TransformerMixin\n",
37
+ "from sklearn.metrics import (classification_report,hamming_loss,f1_score)\n",
38
+ "from scipy.sparse import hstack, csr_matrix\n",
39
+ "from catboost import CatBoostClassifier\n",
40
+ "\n",
41
+ "from app.ml.features import (CombinedFeatures,structural_features,FEATURE_NAMES,)\n",
42
+ "pd.set_option('display.max_columns', 200)"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "id": "69bdcc5e",
49
+ "metadata": {},
50
+ "outputs": [
51
+ {
52
+ "name": "stdout",
53
+ "output_type": "stream",
54
+ "text": [
55
+ "Dataset shape: (2321, 2)\n",
56
+ "Total Samples: 2321\n"
57
+ ]
58
+ }
59
+ ],
60
+ "source": [
61
+ "df1=pd.read_csv('../data/datasets/clean.csv')\n",
62
+ "df2=pd.read_csv('../data/datasets/noisy.csv')\n",
63
+ "df3=pd.read_csv('../data/datasets/real.csv')\n",
64
+ "df4=pd.read_csv('../data/datasets/balance.csv')\n",
65
+ "df5=pd.read_csv('../data/datasets/augment.csv')\n",
66
+ "\n",
67
+ "df = pd.concat([df1, df2, df3, df4, df5], ignore_index=True)\n",
68
+ "\n",
69
+ "print(\"Dataset shape:\", df.shape)\n",
70
+ "print(\"Total Samples:\", len(df))"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 4,
76
+ "id": "3fee4af2",
77
+ "metadata": {},
78
+ "outputs": [
79
+ {
80
+ "name": "stdout",
81
+ "output_type": "stream",
82
+ "text": [
83
+ "Index(['prompt', 'labels'], dtype='str')\n"
84
+ ]
85
+ }
86
+ ],
87
+ "source": [
88
+ "print(df.columns)"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": 5,
94
+ "id": "d7708521",
95
+ "metadata": {},
96
+ "outputs": [
97
+ {
98
+ "data": {
99
+ "application/vnd.microsoft.datawrangler.viewer.v0+json": {
100
+ "columns": [
101
+ {
102
+ "name": "index",
103
+ "rawType": "str",
104
+ "type": "string"
105
+ },
106
+ {
107
+ "name": "0",
108
+ "rawType": "int64",
109
+ "type": "integer"
110
+ }
111
+ ],
112
+ "ref": "458585f5-8854-4b93-9546-69c5b143b71a",
113
+ "rows": [
114
+ [
115
+ "prompt",
116
+ "0"
117
+ ],
118
+ [
119
+ "labels",
120
+ "0"
121
+ ]
122
+ ],
123
+ "shape": {
124
+ "columns": 1,
125
+ "rows": 2
126
+ }
127
+ },
128
+ "text/plain": [
129
+ "prompt 0\n",
130
+ "labels 0\n",
131
+ "dtype: int64"
132
+ ]
133
+ },
134
+ "execution_count": 5,
135
+ "metadata": {},
136
+ "output_type": "execute_result"
137
+ }
138
+ ],
139
+ "source": [
140
+ "df.isnull().sum()"
141
+ ]
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "execution_count": null,
146
+ "id": "1e901c63",
147
+ "metadata": {},
148
+ "outputs": [
149
+ {
150
+ "name": "stdout",
151
+ "output_type": "stream",
152
+ "text": [
153
+ "Write a Java script to connect to a PostgreSQL database.\n",
154
+ "----------------------------------------------------------------------------------------------------\n",
155
+ "[\"coding\", \"realtime\", \"reasoning-light\", \"short-output\", \"easy\", \"cheap\"]\n",
156
+ "Create an end-to-end MLOps deployment pipeline using Weights & Biases to reliably serve a distributed database.\n",
157
+ "----------------------------------------------------------------------------------------------------\n",
158
+ "[\"premium\", \"background\", \"long-output\", \"mlops\", \"hard\", \"reasoning-intensive\"]\n",
159
+ "Analyze the performance implications, cost, and developer velocity of using Terraform and AWS ECS for high-throughput enterprise systems.\n",
160
+ "----------------------------------------------------------------------------------------------------\n",
161
+ "[\"interactive\", \"reasoning-moderate\", \"balanced\", \"analysis\", \"medium-output\", \"moderate\"]\n",
162
+ "Write Pulumi code to provision a secure AWS VPC with private subnets, a NAT gateway, and restrictive security groups.\n",
163
+ "----------------------------------------------------------------------------------------------------\n",
164
+ "[\"interactive\", \"reasoning-moderate\", \"balanced\", \"infrastructure\", \"medium-output\", \"moderate\"]\n",
165
+ "Write a Go script to sort an array using merge sort.\n",
166
+ "----------------------------------------------------------------------------------------------------\n",
167
+ "[\"coding\", \"realtime\", \"reasoning-light\", \"short-output\", \"easy\", \"cheap\"]\n"
168
+ ]
169
+ }
170
+ ],
171
+ "source": [
172
+ "for i in range(5):\n",
173
+ " print(df.iloc[i]['prompt'])\n",
174
+ " print(\"-\" * 100)\n",
175
+ " print(df.iloc[i]['labels'])"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": 7,
181
+ "id": "14953727",
182
+ "metadata": {},
183
+ "outputs": [
184
+ {
185
+ "name": "stdout",
186
+ "output_type": "stream",
187
+ "text": [
188
+ "After Deduplication: 1859\n"
189
+ ]
190
+ }
191
+ ],
192
+ "source": [
193
+ "df = df.drop_duplicates(subset=[\"prompt\"])\n",
194
+ "\n",
195
+ "print(\"After Deduplication:\", len(df))"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": 8,
201
+ "id": "08fa0d67",
202
+ "metadata": {},
203
+ "outputs": [],
204
+ "source": [
205
+ "df = df.sample(frac=1, random_state=42).reset_index(drop=True)"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "id": "c0bd9ed9",
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "print(\"Current Working Directory:\", os.getcwd())\n",
216
+ "print(\"Does the target folder exist?\", os.path.exists(\"../data\"))"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": null,
222
+ "id": "ede80918",
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "base_dir = Path(os.getcwd())\n",
227
+ "target_file = base_dir.parent / \"data\" / \"master_dataset.csv\"\n",
228
+ "print(f\"Saving to: {target_file.resolve()}\")\n",
229
+ "target_file.parent.mkdir(parents=True, exist_ok=True)\n",
230
+ "df.to_csv(target_file, index=False)"
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "execution_count": null,
236
+ "id": "59c21d7d",
237
+ "metadata": {},
238
+ "outputs": [],
239
+ "source": [
240
+ "df[\"labels\"] = df[\"labels\"].apply(ast.literal_eval)\n",
241
+ "\n",
242
+ "mlb = MultiLabelBinarizer()\n",
243
+ "\n",
244
+ "y = mlb.fit_transform(df[\"labels\"])\n",
245
+ "\n",
246
+ "label_counts = pd.DataFrame(y,columns=mlb.classes_).sum().sort_values()\n",
247
+ "\n",
248
+ "plt.figure(figsize=(10,8))\n",
249
+ "label_counts.plot(kind=\"barh\")\n",
250
+ "plt.title(\"Master Dataset Label Distribution\")\n",
251
+ "plt.tight_layout()\n",
252
+ "plt.show()"
253
+ ]
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "execution_count": null,
258
+ "id": "0b94ca7e",
259
+ "metadata": {},
260
+ "outputs": [],
261
+ "source": [
262
+ "print(type(df[\"labels\"].iloc[4]))\n",
263
+ "print(df[\"labels\"].iloc[4])"
264
+ ]
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "execution_count": 13,
269
+ "id": "1348ea7f",
270
+ "metadata": {},
271
+ "outputs": [
272
+ {
273
+ "name": "stdout",
274
+ "output_type": "stream",
275
+ "text": [
276
+ "Labels (23): ['analysis', 'architecture', 'architecture-heavy', 'background', 'balanced', 'cheap', 'coding', 'debugging', 'easy', 'hard', 'infrastructure', 'interactive', 'long-output', 'medium-output', 'mlops', 'moderate', 'premium', 'realtime', 'reasoning-intensive', 'reasoning-light', 'reasoning-moderate', 'research', 'short-output']\n"
277
+ ]
278
+ }
279
+ ],
280
+ "source": [
281
+ "print(f\"Labels ({len(mlb.classes_)}): {list(mlb.classes_)}\")"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": 14,
287
+ "id": "2d982c5d",
288
+ "metadata": {},
289
+ "outputs": [
290
+ {
291
+ "name": "stdout",
292
+ "output_type": "stream",
293
+ "text": [
294
+ "Train: 1487 Test: 372\n"
295
+ ]
296
+ }
297
+ ],
298
+ "source": [
299
+ "X_train_raw, X_test_raw, y_train, y_test = train_test_split(\n",
300
+ " df[\"prompt\"], y, test_size=0.2, random_state=42\n",
301
+ ")\n",
302
+ "print(f\"Train: {len(X_train_raw)} Test: {len(X_test_raw)}\")"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "execution_count": null,
308
+ "id": "e84086fa",
309
+ "metadata": {},
310
+ "outputs": [],
311
+ "source": [
312
+ "feat_extractor = CombinedFeatures(max_features=5000,ngram_range=(1, 2),)"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "execution_count": null,
318
+ "id": "f707136a",
319
+ "metadata": {},
320
+ "outputs": [
321
+ {
322
+ "name": "stdout",
323
+ "output_type": "stream",
324
+ "text": [
325
+ "Feature extraction complete.\n",
326
+ "\n",
327
+ "Train matrix shape: (1487, 5019)\n",
328
+ "Test matrix shape : (372, 5019)\n"
329
+ ]
330
+ }
331
+ ],
332
+ "source": [
333
+ "X_train = feat_extractor.fit_transform(X_train_raw)\n",
334
+ "X_test = feat_extractor.transform(X_test_raw)\n",
335
+ "\n",
336
+ "print(\"Feature extraction complete.\")\n",
337
+ "print(\"\\nTrain matrix shape:\", X_train.shape)\n",
338
+ "print(\"Test matrix shape :\", X_test.shape)"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "execution_count": null,
344
+ "id": "71bac789",
345
+ "metadata": {},
346
+ "outputs": [],
347
+ "source": [
348
+ "import tempfile\n",
349
+ "\n",
350
+ "def make_catboost():\n",
351
+ "\n",
352
+ " kwargs = dict(\n",
353
+ " iterations=300,\n",
354
+ " learning_rate=0.1,\n",
355
+ " depth=6,\n",
356
+ " loss_function=\"Logloss\",\n",
357
+ " eval_metric=\"F1\",\n",
358
+ " random_seed=42,\n",
359
+ " verbose=0,\n",
360
+ " auto_class_weights=\"Balanced\",\n",
361
+ " train_dir=tempfile.gettempdir(),\n",
362
+ " )\n",
363
+ " return CatBoostClassifier(**kwargs)"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": null,
369
+ "id": "1872329e",
370
+ "metadata": {},
371
+ "outputs": [],
372
+ "source": [
373
+ "base_clf = make_catboost()\n",
374
+ "\n",
375
+ "ovr = OneVsRestClassifier(base_clf,n_jobs=1,)"
376
+ ]
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "execution_count": null,
381
+ "id": "032a46cf",
382
+ "metadata": {},
383
+ "outputs": [],
384
+ "source": [
385
+ "print(\"Training CatBoost OvR classifier…\")\n",
386
+ "ovr.fit(X_train, y_train)\n",
387
+ "print(\"Training complete.\")"
388
+ ]
389
+ },
390
+ {
391
+ "cell_type": "code",
392
+ "execution_count": null,
393
+ "id": "09ac2a0d",
394
+ "metadata": {},
395
+ "outputs": [
396
+ {
397
+ "name": "stdout",
398
+ "output_type": "stream",
399
+ "text": [
400
+ "\n",
401
+ "======================================================================\n",
402
+ "BASELINE CLASSIFICATION REPORT (threshold = 0.50)\n",
403
+ "======================================================================\n",
404
+ " precision recall f1-score support\n",
405
+ "\n",
406
+ " analysis 0.59 0.71 0.64 41\n",
407
+ " architecture 0.53 0.58 0.56 43\n",
408
+ " architecture-heavy 0.87 0.93 0.90 29\n",
409
+ " background 0.90 0.86 0.88 91\n",
410
+ " balanced 0.71 0.86 0.78 122\n",
411
+ " cheap 0.70 0.82 0.76 90\n",
412
+ " coding 0.79 0.86 0.82 105\n",
413
+ " debugging 0.85 0.85 0.85 46\n",
414
+ " easy 0.74 0.86 0.80 96\n",
415
+ " hard 0.92 0.90 0.91 136\n",
416
+ " infrastructure 0.74 0.66 0.70 77\n",
417
+ " interactive 0.93 0.94 0.94 230\n",
418
+ " long-output 0.90 0.87 0.88 104\n",
419
+ " medium-output 0.85 0.88 0.86 177\n",
420
+ " mlops 0.77 0.89 0.83 27\n",
421
+ " moderate 0.71 0.79 0.75 140\n",
422
+ " premium 0.92 0.85 0.88 114\n",
423
+ " realtime 0.88 0.92 0.90 48\n",
424
+ "reasoning-intensive 0.92 0.90 0.91 136\n",
425
+ " reasoning-light 0.75 0.84 0.79 96\n",
426
+ " reasoning-moderate 0.72 0.81 0.76 140\n",
427
+ " research 0.71 0.68 0.70 22\n",
428
+ " short-output 0.80 0.87 0.83 91\n",
429
+ "\n",
430
+ " micro avg 0.81 0.85 0.83 2201\n",
431
+ " macro avg 0.79 0.83 0.81 2201\n",
432
+ " weighted avg 0.81 0.85 0.83 2201\n",
433
+ " samples avg 0.82 0.85 0.83 2201\n",
434
+ "\n",
435
+ "Baseline β†’ Hamming Loss : 0.0907 Micro F1 : 0.8282 Macro F1 : 0.8094 Weighted F1 : 0.8300\n"
436
+ ]
437
+ },
438
+ {
439
+ "data": {
440
+ "text/plain": [
441
+ "0.8094470286424041"
442
+ ]
443
+ },
444
+ "execution_count": 22,
445
+ "metadata": {},
446
+ "output_type": "execute_result"
447
+ }
448
+ ],
449
+ "source": [
450
+ "preds_default = ovr.predict(X_test)\n",
451
+ "print(\"\\n\" + \"=\"*70)\n",
452
+ "print(\"BASELINE CLASSIFICATION REPORT (threshold = 0.50)\")\n",
453
+ "print(\"=\"*70)\n",
454
+ "print(classification_report(y_test, preds_default, target_names=mlb.classes_, zero_division=0))\n",
455
+ " \n",
456
+ "def _metrics(y_true, y_pred, label=\"\"):\n",
457
+ " hl = hamming_loss(y_true, y_pred)\n",
458
+ " mif1 = f1_score(y_true, y_pred, average=\"micro\", zero_division=0)\n",
459
+ " maf1 = f1_score(y_true, y_pred, average=\"macro\", zero_division=0)\n",
460
+ " wf1 = f1_score(y_true, y_pred, average=\"weighted\", zero_division=0)\n",
461
+ " print(f\"{label}Hamming Loss : {hl:.4f} Micro F1 : {mif1:.4f} \"\n",
462
+ " f\"Macro F1 : {maf1:.4f} Weighted F1 : {wf1:.4f}\")\n",
463
+ " return maf1\n",
464
+ " \n",
465
+ "_metrics(y_test, preds_default, \"Baseline β†’ \")"
466
+ ]
467
+ },
468
+ {
469
+ "cell_type": "code",
470
+ "execution_count": null,
471
+ "id": "c39ee384",
472
+ "metadata": {},
473
+ "outputs": [],
474
+ "source": [
475
+ "probas = ovr.predict_proba(X_test) # shape: (n_samples, n_labels)\n",
476
+ "THRESHOLDS = np.full(len(mlb.classes_), 0.5)\n",
477
+ " \n",
478
+ "print(\"\\nTuning per-label thresholds…\")\n",
479
+ "for i, label in enumerate(mlb.classes_):\n",
480
+ " best_t, best_f1 = 0.5, 0.0\n",
481
+ " for t in np.arange(0.10, 0.91, 0.05):\n",
482
+ " col_pred = (probas[:, i] >= t).astype(int)\n",
483
+ " lf1 = f1_score(y_test[:, i], col_pred, zero_division=0)\n",
484
+ " if lf1 > best_f1:\n",
485
+ " best_f1, best_t = lf1, t\n",
486
+ " THRESHOLDS[i] = best_t\n",
487
+ " print(f\" {label:<22} best_threshold={best_t:.2f} F1={best_f1:.3f}\")"
488
+ ]
489
+ },
490
+ {
491
+ "cell_type": "code",
492
+ "execution_count": 24,
493
+ "id": "5cb94f45",
494
+ "metadata": {},
495
+ "outputs": [
496
+ {
497
+ "name": "stdout",
498
+ "output_type": "stream",
499
+ "text": [
500
+ "\n",
501
+ "======================================================================\n",
502
+ "TUNED CLASSIFICATION REPORT (per-label optimal thresholds)\n",
503
+ "======================================================================\n",
504
+ " precision recall f1-score support\n",
505
+ "\n",
506
+ " analysis 0.56 0.85 0.68 41\n",
507
+ " architecture 0.80 0.56 0.66 43\n",
508
+ " architecture-heavy 1.00 0.90 0.95 29\n",
509
+ " background 0.93 0.85 0.89 91\n",
510
+ " balanced 0.75 0.83 0.79 122\n",
511
+ " cheap 0.82 0.79 0.80 90\n",
512
+ " coding 0.77 0.90 0.83 105\n",
513
+ " debugging 0.90 0.80 0.85 46\n",
514
+ " easy 0.88 0.77 0.82 96\n",
515
+ " hard 0.92 0.90 0.91 136\n",
516
+ " infrastructure 0.62 0.83 0.71 77\n",
517
+ " interactive 0.91 0.98 0.94 230\n",
518
+ " long-output 0.94 0.86 0.89 104\n",
519
+ " medium-output 0.85 0.92 0.88 177\n",
520
+ " mlops 1.00 0.85 0.92 27\n",
521
+ " moderate 0.67 0.89 0.77 140\n",
522
+ " premium 0.84 0.93 0.88 114\n",
523
+ " realtime 0.90 0.92 0.91 48\n",
524
+ "reasoning-intensive 0.92 0.90 0.91 136\n",
525
+ " reasoning-light 0.88 0.76 0.82 96\n",
526
+ " reasoning-moderate 0.65 0.92 0.76 140\n",
527
+ " research 0.71 0.77 0.74 22\n",
528
+ " short-output 0.86 0.81 0.84 91\n",
529
+ "\n",
530
+ " micro avg 0.82 0.87 0.84 2201\n",
531
+ " macro avg 0.83 0.85 0.83 2201\n",
532
+ " weighted avg 0.83 0.87 0.84 2201\n",
533
+ " samples avg 0.83 0.87 0.85 2201\n",
534
+ "\n",
535
+ "Tuned β†’ Hamming Loss : 0.0840 Micro F1 : 0.8419 Macro F1 : 0.8320 Weighted F1 : 0.8447\n"
536
+ ]
537
+ },
538
+ {
539
+ "data": {
540
+ "text/plain": [
541
+ "0.8319727417678422"
542
+ ]
543
+ },
544
+ "execution_count": 24,
545
+ "metadata": {},
546
+ "output_type": "execute_result"
547
+ }
548
+ ],
549
+ "source": [
550
+ "preds_tuned = (probas >= THRESHOLDS).astype(int)\n",
551
+ " \n",
552
+ "print(\"\\n\" + \"=\"*70)\n",
553
+ "print(\"TUNED CLASSIFICATION REPORT (per-label optimal thresholds)\")\n",
554
+ "print(\"=\"*70)\n",
555
+ "print(classification_report(y_test, preds_tuned, target_names=mlb.classes_, zero_division=0))\n",
556
+ "_metrics(y_test, preds_tuned, \"Tuned β†’ \")"
557
+ ]
558
+ },
559
+ {
560
+ "cell_type": "code",
561
+ "execution_count": null,
562
+ "id": "662c5972",
563
+ "metadata": {},
564
+ "outputs": [],
565
+ "source": [
566
+ "base_f1 = f1_score(y_test, preds_default, average=None, zero_division=0)\n",
567
+ "tuned_f1 = f1_score(y_test, preds_tuned, average=None, zero_division=0)\n",
568
+ " \n",
569
+ "order = np.argsort(tuned_f1)\n",
570
+ "labels_sorted = np.array(mlb.classes_)[order]\n",
571
+ "base_sorted = base_f1[order]\n",
572
+ "tuned_sorted = tuned_f1[order]\n",
573
+ " \n",
574
+ "y_pos = np.arange(len(labels_sorted))\n",
575
+ "fig, ax = plt.subplots(figsize=(11, 9))\n",
576
+ "ax.barh(y_pos - 0.18, base_sorted, 0.35, label=\"Baseline (t=0.50)\", color=\"#5b9bd5\", alpha=0.85)\n",
577
+ "ax.barh(y_pos + 0.18, tuned_sorted, 0.35, label=\"Tuned thresholds\", color=\"#ed7d31\", alpha=0.90)\n",
578
+ "ax.set_yticks(y_pos)\n",
579
+ "ax.set_yticklabels(labels_sorted)\n",
580
+ "ax.axvline(0.7, color=\"red\", linestyle=\"--\", linewidth=1, label=\"0.70 target\")\n",
581
+ "ax.set_xlabel(\"F1 Score\")\n",
582
+ "ax.set_title(\"Per-Label F1 β€” Baseline vs Tuned Thresholds\")\n",
583
+ "ax.legend(loc=\"lower right\")\n",
584
+ "plt.tight_layout()\n",
585
+ "plt.savefig(\"label_f1_tuned.png\", dpi=150)\n",
586
+ "plt.show()\n",
587
+ "print(\"Chart saved: label_f1_tuned.png\")"
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": null,
593
+ "id": "16a5f592",
594
+ "metadata": {},
595
+ "outputs": [],
596
+ "source": [
597
+ "MODELS_DIR = Path(\"../models\")\n",
598
+ "MODELS_DIR.mkdir(exist_ok=True)\n",
599
+ " \n",
600
+ "joblib.dump(feat_extractor, MODELS_DIR / \"feature_extractor.pkl\")\n",
601
+ "joblib.dump(ovr, MODELS_DIR / \"prompt_router.pkl\")\n",
602
+ "joblib.dump(mlb, MODELS_DIR / \"label_binarizer.pkl\")\n",
603
+ "np.save(MODELS_DIR / \"thresholds.npy\", THRESHOLDS)\n",
604
+ "print(f\"\\nSaved artefacts β†’ {MODELS_DIR.resolve()}\")\n",
605
+ "print(f\" feature_extractor.pkl | prompt_router.pkl | \"\n",
606
+ " f\"label_binarizer.pkl | thresholds.npy\")"
607
+ ]
608
+ },
609
+ {
610
+ "cell_type": "code",
611
+ "execution_count": null,
612
+ "id": "559a32d1",
613
+ "metadata": {},
614
+ "outputs": [],
615
+ "source": [
616
+ "def predict_labels(prompts: list[str], use_tuned: bool = True) -> list[list[str]]:\n",
617
+ " X = feat_extractor.transform(pd.Series(prompts))\n",
618
+ " proba = ovr.predict_proba(X)\n",
619
+ " thresh = THRESHOLDS if use_tuned else np.full(len(mlb.classes_), 0.5)\n",
620
+ " pred = (proba >= thresh).astype(int)\n",
621
+ " return [list(lbl) for lbl in mlb.inverse_transform(pred)]"
622
+ ]
623
+ },
624
+ {
625
+ "cell_type": "code",
626
+ "execution_count": null,
627
+ "id": "dbb8d1a8",
628
+ "metadata": {},
629
+ "outputs": [],
630
+ "source": [
631
+ "def diagnose(prompt: str):\n",
632
+ " feat_names = [\n",
633
+ " \"word_count\", \"sentence_count\", \"punct_count\", \"avg_sent_len\",\n",
634
+ " \"code_blocks\", \"uppercase_ratio\", \"question_count\",\n",
635
+ " \"contains_code\", \"contains_arch\", \"contains_math\",\n",
636
+ " \"contains_debug\", \"contains_research\",\n",
637
+ " \"complexity_verbs\", \"scale_adj\", \"hard_domain_nouns\",\n",
638
+ " \"contains_simple\", \"contains_realtime\", \"contains_long_output\",\n",
639
+ " \"semantic_complexity\",\n",
640
+ " ]\n",
641
+ " struct = structural_features(pd.Series([prompt]))[0]\n",
642
+ " print(f\"\\n{'─'*60}\")\n",
643
+ " print(f\"DIAGNOSE: {prompt}\")\n",
644
+ " print(f\"{'─'*60}\")\n",
645
+ " print(\"Structural features:\")\n",
646
+ " for name, val in zip(feat_names, struct):\n",
647
+ " if val != 0:\n",
648
+ " print(f\" {name:<25} = {val:.2f} β—„\")\n",
649
+ " else:\n",
650
+ " print(f\" {name:<25} = {val:.2f}\")\n",
651
+ " \n",
652
+ " X = feat_extractor.transform(pd.Series([prompt]))\n",
653
+ " proba = ovr.predict_proba(X)[0]\n",
654
+ " print(\"\\nLabel probabilities (sorted):\")\n",
655
+ " label_proba = sorted(zip(mlb.classes_, proba, THRESHOLDS),\n",
656
+ " key=lambda x: x[1], reverse=True)\n",
657
+ " for label, prob, thresh in label_proba:\n",
658
+ " marker = \"βœ“ PREDICTED\" if prob >= thresh else \"\"\n",
659
+ " print(f\" {label:<22} prob={prob:.3f} thresh={thresh:.2f} {marker}\")\n",
660
+ " \n",
661
+ " "
662
+ ]
663
+ },
664
+ {
665
+ "cell_type": "code",
666
+ "execution_count": 30,
667
+ "id": "55c716ee",
668
+ "metadata": {},
669
+ "outputs": [
670
+ {
671
+ "name": "stdout",
672
+ "output_type": "stream",
673
+ "text": [
674
+ "\n",
675
+ "======================================================================\n",
676
+ "FEATURE DIAGNOSIS β€” previously mispredicted prompts\n",
677
+ "======================================================================\n",
678
+ "\n",
679
+ "────────────────────────────────────────────────────────────\n",
680
+ "DIAGNOSE: Build scalable recommendation infrastructure\n",
681
+ "────────────────────────────────────────────────────────────\n",
682
+ "Structural features:\n",
683
+ " word_count = 4.00 β—„\n",
684
+ " sentence_count = 1.00 β—„\n",
685
+ " punct_count = 0.00\n",
686
+ " avg_sent_len = 4.00 β—„\n",
687
+ " code_blocks = 0.00\n",
688
+ " uppercase_ratio = 0.02 β—„\n",
689
+ " question_count = 0.00\n",
690
+ " contains_code = 0.00\n",
691
+ " contains_arch = 1.00 β—„\n",
692
+ " contains_math = 0.00\n",
693
+ " contains_debug = 0.00\n",
694
+ " contains_research = 0.00\n",
695
+ " complexity_verbs = 1.00 β—„\n",
696
+ " scale_adj = 0.00\n",
697
+ " hard_domain_nouns = 2.00 β—„\n",
698
+ " contains_simple = 0.00\n",
699
+ " contains_realtime = 0.00\n",
700
+ " contains_long_output = 0.00\n",
701
+ " semantic_complexity = 3.00 β—„\n",
702
+ "\n",
703
+ "Label probabilities (sorted):\n",
704
+ " infrastructure prob=0.986 thresh=0.30 βœ“ PREDICTED\n",
705
+ " premium prob=0.957 thresh=0.25 βœ“ PREDICTED\n",
706
+ " hard prob=0.956 thresh=0.50 βœ“ PREDICTED\n",
707
+ " reasoning-intensive prob=0.956 thresh=0.50 βœ“ PREDICTED\n",
708
+ " medium-output prob=0.935 thresh=0.45 βœ“ PREDICTED\n",
709
+ " balanced prob=0.751 thresh=0.55 βœ“ PREDICTED\n",
710
+ " mlops prob=0.156 thresh=0.90 \n",
711
+ " background prob=0.079 thresh=0.60 \n",
712
+ " cheap prob=0.066 thresh=0.70 \n",
713
+ " long-output prob=0.065 thresh=0.60 \n",
714
+ " reasoning-light prob=0.060 thresh=0.70 \n",
715
+ " moderate prob=0.050 thresh=0.35 \n",
716
+ " easy prob=0.047 thresh=0.70 \n",
717
+ " short-output prob=0.046 thresh=0.65 \n",
718
+ " realtime prob=0.036 thresh=0.55 \n",
719
+ " reasoning-moderate prob=0.034 thresh=0.30 \n",
720
+ " coding prob=0.031 thresh=0.40 \n",
721
+ " analysis prob=0.019 thresh=0.40 \n",
722
+ " interactive prob=0.013 thresh=0.25 \n",
723
+ " architecture-heavy prob=0.007 thresh=0.90 \n",
724
+ " debugging prob=0.005 thresh=0.65 \n",
725
+ " architecture prob=0.004 thresh=0.75 \n",
726
+ " research prob=0.001 thresh=0.20 \n",
727
+ "\n",
728
+ "────────────────────────────────────────────────────────────\n",
729
+ "DIAGNOSE: Explain TCP handshake simply\n",
730
+ "────────────────────────────────────────────────────────────\n",
731
+ "Structural features:\n",
732
+ " word_count = 4.00 β—„\n",
733
+ " sentence_count = 1.00 β—„\n",
734
+ " punct_count = 0.00\n",
735
+ " avg_sent_len = 4.00 β—„\n",
736
+ " code_blocks = 0.00\n",
737
+ " uppercase_ratio = 0.14 β—„\n",
738
+ " question_count = 0.00\n",
739
+ " contains_code = 0.00\n",
740
+ " contains_arch = 0.00\n",
741
+ " contains_math = 0.00\n",
742
+ " contains_debug = 0.00\n",
743
+ " contains_research = 0.00\n",
744
+ " complexity_verbs = 0.00\n",
745
+ " scale_adj = 0.00\n",
746
+ " hard_domain_nouns = 0.00\n",
747
+ " contains_simple = 1.00 β—„\n",
748
+ " contains_realtime = 0.00\n",
749
+ " contains_long_output = 0.00\n",
750
+ " semantic_complexity = 0.00\n",
751
+ "\n",
752
+ "Label probabilities (sorted):\n",
753
+ " interactive prob=0.985 thresh=0.25 βœ“ PREDICTED\n",
754
+ " reasoning-light prob=0.970 thresh=0.70 βœ“ PREDICTED\n",
755
+ " cheap prob=0.960 thresh=0.70 βœ“ PREDICTED\n",
756
+ " easy prob=0.950 thresh=0.70 βœ“ PREDICTED\n",
757
+ " short-output prob=0.769 thresh=0.65 βœ“ PREDICTED\n",
758
+ " analysis prob=0.367 thresh=0.40 \n",
759
+ " medium-output prob=0.207 thresh=0.45 \n",
760
+ " reasoning-moderate prob=0.181 thresh=0.30 \n",
761
+ " balanced prob=0.118 thresh=0.55 \n",
762
+ " moderate prob=0.117 thresh=0.35 \n",
763
+ " coding prob=0.107 thresh=0.40 \n",
764
+ " infrastructure prob=0.044 thresh=0.30 \n",
765
+ " debugging prob=0.018 thresh=0.65 \n",
766
+ " architecture prob=0.015 thresh=0.75 \n",
767
+ " mlops prob=0.009 thresh=0.90 \n",
768
+ " hard prob=0.008 thresh=0.50 \n",
769
+ " reasoning-intensive prob=0.008 thresh=0.50 \n",
770
+ " research prob=0.007 thresh=0.20 \n",
771
+ " premium prob=0.006 thresh=0.25 \n",
772
+ " realtime prob=0.005 thresh=0.55 \n",
773
+ " background prob=0.004 thresh=0.60 \n",
774
+ " long-output prob=0.002 thresh=0.60 \n",
775
+ " architecture-heavy prob=0.000 thresh=0.90 \n"
776
+ ]
777
+ }
778
+ ],
779
+ "source": [
780
+ "print(\"\\n\" + \"=\"*70)\n",
781
+ "print(\"FEATURE DIAGNOSIS β€” previously mispredicted prompts\")\n",
782
+ "print(\"=\"*70)\n",
783
+ "diagnose(\"Build scalable recommendation infrastructure\")\n",
784
+ "diagnose(\"Explain TCP handshake simply\")"
785
+ ]
786
+ },
787
+ {
788
+ "cell_type": "code",
789
+ "execution_count": 31,
790
+ "id": "728424bc",
791
+ "metadata": {},
792
+ "outputs": [
793
+ {
794
+ "name": "stdout",
795
+ "output_type": "stream",
796
+ "text": [
797
+ "\n",
798
+ "======================================================================\n",
799
+ "POLICY ENGINE ROUTING\n",
800
+ "======================================================================\n",
801
+ "\n",
802
+ "PROMPT : Create a distributed orchestration workflow for ML deployment\n",
803
+ "LABELS : ['hard', 'infrastructure', 'interactive', 'mlops', 'premium', 'reasoning-intensive']\n",
804
+ "β†’ MODEL: nemotron-super-120b\n",
805
+ "\n",
806
+ "PROMPT : Fix segmentation fault in C++ linked list implementation\n",
807
+ "LABELS : ['cheap', 'coding', 'easy', 'interactive', 'moderate', 'reasoning-light', 'reasoning-moderate', 'short-output']\n",
808
+ "β†’ MODEL: nemotron-nano-30b\n",
809
+ "\n",
810
+ "PROMPT : Explain TCP handshake simply\n",
811
+ "LABELS : ['cheap', 'easy', 'interactive', 'reasoning-light', 'short-output']\n",
812
+ "β†’ MODEL: nemotron-nano-30b\n",
813
+ "\n",
814
+ "PROMPT : Build scalable recommendation infrastructure\n",
815
+ "LABELS : ['balanced', 'hard', 'infrastructure', 'medium-output', 'premium', 'reasoning-intensive']\n",
816
+ "β†’ MODEL: nemotron-super-120b\n",
817
+ "\n",
818
+ "PROMPT : Write a quick hello world in Python\n",
819
+ "LABELS : ['cheap', 'coding', 'easy', 'interactive', 'reasoning-light', 'short-output']\n",
820
+ "β†’ MODEL: nemotron-nano-30b\n",
821
+ "\n",
822
+ "PROMPT : Compare transformer architectures for long-context tasks\n",
823
+ "LABELS : ['analysis', 'balanced', 'interactive', 'medium-output', 'moderate', 'reasoning-moderate', 'research']\n",
824
+ "β†’ MODEL: nemotron-nano-30b\n"
825
+ ]
826
+ }
827
+ ],
828
+ "source": [
829
+ "MODEL_POLICY = {\n",
830
+ " \"premium\": \"nemotron-super-120b\",\n",
831
+ " \"background\": \"nemotron-super-120b\",\n",
832
+ " \"hard\": \"nemotron-super-120b\",\n",
833
+ " \"balanced\": \"nemotron-nano-30b\",\n",
834
+ " \"moderate\": \"nemotron-nano-30b\",\n",
835
+ " \"interactive\":\"nemotron-nano-30b\",\n",
836
+ " \"realtime\": \"nemotron-nano-9b\",\n",
837
+ " \"cheap\": \"nemotron-nano-9b\",\n",
838
+ " \"easy\": \"nemotron-nano-9b\",\n",
839
+ "}\n",
840
+ "# Labels checked in descending priority β€” first match wins\n",
841
+ "POLICY_PRIORITY = [\"premium\", \"background\", \"hard\",\n",
842
+ " \"balanced\", \"moderate\", \"interactive\",\n",
843
+ " \"realtime\", \"cheap\", \"easy\"]\n",
844
+ " \n",
845
+ "def route(prompt: str) -> tuple[str, list[str]]:\n",
846
+ " labels = predict_labels([prompt])[0]\n",
847
+ " for priority_label in POLICY_PRIORITY:\n",
848
+ " if priority_label in labels:\n",
849
+ " return MODEL_POLICY[priority_label], labels\n",
850
+ " return \"nemotron-nano-30b\", labels # safe default\n",
851
+ " \n",
852
+ "print(\"\\n\" + \"=\"*70)\n",
853
+ "print(\"POLICY ENGINE ROUTING\")\n",
854
+ "print(\"=\"*70)\n",
855
+ "for p in test_prompts:\n",
856
+ " model, labels = route(p)\n",
857
+ " print(f\"\\nPROMPT : {p}\")\n",
858
+ " print(f\"LABELS : {sorted(labels)}\")\n",
859
+ " print(f\"β†’ MODEL: {model}\")"
860
+ ]
861
+ }
862
+ ],
863
+ "metadata": {
864
+ "kernelspec": {
865
+ "display_name": "Adaptive-Token",
866
+ "language": "python",
867
+ "name": "python3"
868
+ },
869
+ "language_info": {
870
+ "codemirror_mode": {
871
+ "name": "ipython",
872
+ "version": 3
873
+ },
874
+ "file_extension": ".py",
875
+ "mimetype": "text/x-python",
876
+ "name": "python",
877
+ "nbconvert_exporter": "python",
878
+ "pygments_lexer": "ipython3",
879
+ "version": "3.12.12"
880
+ }
881
+ },
882
+ "nbformat": 4,
883
+ "nbformat_minor": 5
884
+ }