File size: 25,998 Bytes
46cc63a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Phase 5: Expert Aggressive β€” Toxic-BERT + Hybrid\n",
    "\n",
    "**Expert Adaptation** strategy to break the F1 plateau:\n",
    "\n",
    "| Change | Setting |\n",
    "|--------|--------|\n",
    "| Base model | `unitary/toxic-bert` (head-only fine-tune) |\n",
    "| LR bottleneck | TF-IDF `max_features=250` |\n",
    "| Threshold | Val-set search maximizing **F1-toxic** |\n",
    "| Hybrid weights | **0.7** Toxic-BERT + **0.3** LR |\n",
    "| Augmentation | EN→**DE**→EN back-translation (higher diversity) |\n",
    "\n",
    "Run from repo root (long-running β€” augmentation + fine-tune):\n",
    "\n",
    "```bash\n",
    "uv sync --extra hf --extra train\n",
    "uv run python -m src.pipeline.run_expert_pipeline\n",
    "```\n",
    "\n",
    "Or execute the pipeline cell below inside this notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Config: expert_training.yaml\n",
      "Pivot lang: de\n",
      "Model: unitary/toxic-bert (head_only)\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import pandas as pd\n",
    "import yaml\n",
    "\n",
    "PROJECT_ROOT = Path.cwd().resolve()\n",
    "if not (PROJECT_ROOT / \"configs\").exists() and (PROJECT_ROOT.parent / \"configs\").exists():\n",
    "    PROJECT_ROOT = PROJECT_ROOT.parent\n",
    "\n",
    "if str(PROJECT_ROOT) not in sys.path:\n",
    "    sys.path.insert(0, str(PROJECT_ROOT))\n",
    "\n",
    "cfg_path = PROJECT_ROOT / \"configs\" / \"expert_training.yaml\"\n",
    "cfg = yaml.safe_load(open(cfg_path))\n",
    "reports_dir = PROJECT_ROOT / \"reports\" / \"expert\"\n",
    "print(f\"Config: {cfg_path.name}\")\n",
    "print(f\"Pivot lang: {cfg['augmentation']['pivot_lang']}\")\n",
    "print(f\"Model: {cfg['transformer']['model_id']} ({cfg['transformer']['freeze_mode']})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Run Phase 5 pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:39:47 | INFO     | src.pipeline.run_expert_pipeline | ============================================================\n",
      "2026-05-24 19:39:47 | INFO     | src.pipeline.run_expert_pipeline | EXPERT PIPELINE (Phase 5) β€” run=20260524_193947\n",
      "2026-05-24 19:39:47 | INFO     | src.pipeline.run_expert_pipeline | ============================================================\n",
      "2026-05-24 19:39:47 | INFO     | src.data.loader | Cargando dataset: /Users/miraekang/proyectos/ai-nlp/data/raw/youtoxic_english_1000.csv\n",
      "2026-05-24 19:39:47 | INFO     | src.data.loader |   Shape: (1000, 15)\n",
      "2026-05-24 19:39:47 | INFO     | src.data.loader |   Columnas validadas βœ…\n",
      "2026-05-24 19:39:47 | WARNING  | src.data.loader |   3 duplicados eliminados\n",
      "2026-05-24 19:39:47 | INFO     | src.data.loader |   Toxicos: 459 (46.0%)\n",
      "2026-05-24 19:39:47 | INFO     | src.pipeline.run_expert_pipeline | Augmentation EN→DE→EN (toxic only)\n",
      "2026-05-24 19:39:47 | INFO     | src.features.augmentation | Back-translation: 312 toxic samples\n",
      "2026-05-24 19:42:02 | INFO     | src.features.augmentation | Back-translation produced 295 samples\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.\n",
      "Loading weights: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 103/103 [00:00<00:00, 9092.34it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:42:08 | INFO     | src.features.augmentation | Dedup: kept 209/295 (dropped 86 with cosine > 0.95)\n",
      "2026-05-24 19:42:08 | INFO     | src.features.augmentation | Train size after augmentation: 886 (+209)\n",
      "2026-05-24 19:42:08 | INFO     | src.pipeline.run_expert_pipeline | LR-TFIDF (max_features=250) + gap search\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Training stable LR β€” C=0.05\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | LR gap search β€” C=0.05 max_features=250 min_df=3 train_f1=0.7703 test_f1=0.6563 gap=0.1139\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Training stable LR β€” C=0.03\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | LR gap search β€” C=0.03 max_features=250 min_df=5 train_f1=0.7572 test_f1=0.6563 gap=0.1008\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Training stable LR β€” C=0.02\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | LR gap search β€” C=0.02 max_features=250 min_df=5 train_f1=0.7572 test_f1=0.6563 gap=0.1008\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Training stable LR β€” C=0.01\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | LR gap search β€” C=0.01 max_features=250 min_df=8 train_f1=0.7570 test_f1=0.6563 gap=0.1006\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Training stable LR β€” C=0.005\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | LR gap search β€” C=0.005 max_features=250 min_df=10 train_f1=0.7511 test_f1=0.6509 gap=0.1003\n",
      "2026-05-24 19:42:08 | WARNING  | src.models.hybrid_ensemble | LR gap still 0.1003 after grid search; using best gap C=0.005\n",
      "2026-05-24 19:42:08 | INFO     | src.models.hybrid_ensemble | Stable LR saved: /Users/miraekang/proyectos/ai-nlp/models/expert_lr_tfidf.joblib\n",
      "2026-05-24 19:42:08 | INFO     | src.pipeline.run_expert_pipeline | Toxic-BERT β€” head-only fine-tune + val threshold tuning\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 886/886 [00:00<00:00, 22618.23 examples/s]\n",
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 120/120 [00:00<00:00, 17820.93 examples/s]\n",
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 200/200 [00:00<00:00, 23323.72 examples/s]\n",
      "[transformers] You passed `num_labels=2` which is incompatible to the `id2label` map of length `6`.\n",
      "Loading weights: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 201/201 [00:00<00:00, 8948.39it/s]\n",
      "[transformers] \u001b[1mBertForSequenceClassification LOAD REPORT\u001b[0m from: unitary/toxic-bert\n",
      "Key               | Status   |                                                                                       \n",
      "------------------+----------+---------------------------------------------------------------------------------------\n",
      "classifier.weight | MISMATCH | Reinit due to size mismatch - ckpt: torch.Size([6, 768]) vs model:torch.Size([2, 768])\n",
      "classifier.bias   | MISMATCH | Reinit due to size mismatch - ckpt: torch.Size([6]) vs model:torch.Size([2])          \n",
      "\n",
      "Notes:\n",
      "- MISMATCH:\tckpt weights were loaded, but they did not match the original empty weight shapes.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:42:09 | INFO     | src.models.transformer_trainer | Head-only freeze β€” trainable 592,130/109,483,778 (0.54%)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[transformers] warmup_ratio is deprecated and will be removed in v5.2. Use `warmup_steps` instead.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:42:10 | INFO     | src.models.transformer_trainer | Training unitary/toxic-bert (head_only freeze)...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='444' max='1110' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [ 444/1110 01:19 < 01:59, 5.56 it/s, Epoch 4/10]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Epoch</th>\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "      <th>F1 Toxic</th>\n",
       "      <th>F1 Weighted</th>\n",
       "      <th>Precision</th>\n",
       "      <th>Recall</th>\n",
       "      <th>Roc Auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>0.554757</td>\n",
       "      <td>0.559579</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.716667</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.814545</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>0.507270</td>\n",
       "      <td>0.560950</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.716667</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.690909</td>\n",
       "      <td>0.810350</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>3</td>\n",
       "      <td>0.558299</td>\n",
       "      <td>0.558404</td>\n",
       "      <td>0.673077</td>\n",
       "      <td>0.714744</td>\n",
       "      <td>0.714286</td>\n",
       "      <td>0.636364</td>\n",
       "      <td>0.812028</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>4</td>\n",
       "      <td>0.503684</td>\n",
       "      <td>0.564421</td>\n",
       "      <td>0.685185</td>\n",
       "      <td>0.716190</td>\n",
       "      <td>0.698113</td>\n",
       "      <td>0.672727</td>\n",
       "      <td>0.812308</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:42:31 | INFO     | src.models.transformer_trainer | Gap monitor β€” train_f1=0.7925 val_f1=0.6909 gap=0.1016\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Writing model shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00,  3.64it/s]\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:42:49 | INFO     | src.models.transformer_trainer | Gap monitor β€” train_f1=0.7949 val_f1=0.6909 gap=0.1040\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Writing model shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00,  3.87it/s]\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:43:09 | INFO     | src.models.transformer_trainer | Gap monitor β€” train_f1=0.7952 val_f1=0.6731 gap=0.1221\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Writing model shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00,  2.57it/s]\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:43:29 | INFO     | src.models.transformer_trainer | Gap monitor β€” train_f1=0.7965 val_f1=0.6852 gap=0.1113\n",
      "2026-05-24 19:43:29 | INFO     | src.models.transformer_trainer | Early stop: no f1_toxic improvement for 3 epochs\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Writing model shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00,  3.03it/s]\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:43:31 | INFO     | src.models.transformer_trainer | Val threshold tuning β€” best_t=0.33 val_f1_toxic=0.7313\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Writing model shards: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00,  2.89it/s]\n",
      "Map: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 886/886 [00:00<00:00, 27925.88 examples/s]\n",
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py:752: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used.\n",
      "  super().__init__(loader)\n"
     ]
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/miraekang/proyectos/ai-nlp/.venv/lib/python3.12/site-packages/sklearn/metrics/_ranking.py:442: UndefinedMetricWarning: Only one class is present in y_true. ROC AUC score is not defined in that case.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | Expert report: /Users/miraekang/proyectos/ai-nlp/reports/expert/integrated_report_20260524_193947.md\n",
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | ============================================================\n",
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | Toxic-BERT-expert: F1-toxic=0.7489 ⚠️ | toxic gap=0.0418 βœ… | threshold=0.33\n",
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | LR-TFIDF-expert: F1-toxic=0.6301 ⚠️ | toxic gap=0.0008 βœ… | threshold=0.05\n",
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | Hybrid-ToxicBERT+LR: F1-toxic=0.7489 ⚠️ | toxic gap=0.0428 βœ… | threshold=0.38\n",
      "2026-05-24 19:43:51 | INFO     | src.pipeline.run_expert_pipeline | ============================================================\n",
      "Completed run_id=20260524_193947\n"
     ]
    }
   ],
   "source": [
    "from src.pipeline.run_expert_pipeline import run_expert_pipeline\n",
    "\n",
    "metrics = run_expert_pipeline(config_path=cfg_path)\n",
    "run_id = metrics[\"run_id\"]\n",
    "print(f\"Completed run_id={run_id}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Holdout test β€” F1-toxic and gap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>model</th>\n",
       "      <th>f1_toxic_test</th>\n",
       "      <th>f1_toxic_train</th>\n",
       "      <th>toxic_gap_pp</th>\n",
       "      <th>gap_ok_&lt;5pp</th>\n",
       "      <th>f1_target_&gt;0.75</th>\n",
       "      <th>threshold</th>\n",
       "      <th>roc_auc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Toxic-BERT</td>\n",
       "      <td>0.7489</td>\n",
       "      <td>0.7907</td>\n",
       "      <td>4.18</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>0.33</td>\n",
       "      <td>0.8768</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>LR-TFIDF-250</td>\n",
       "      <td>0.6301</td>\n",
       "      <td>0.6309</td>\n",
       "      <td>0.08</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>0.05</td>\n",
       "      <td>0.7056</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Hybrid 0.7/0.3</td>\n",
       "      <td>0.7489</td>\n",
       "      <td>0.7917</td>\n",
       "      <td>4.28</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>0.38</td>\n",
       "      <td>0.8773</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            model  f1_toxic_test  f1_toxic_train  toxic_gap_pp  gap_ok_<5pp  \\\n",
       "0      Toxic-BERT         0.7489          0.7907          4.18         True   \n",
       "1    LR-TFIDF-250         0.6301          0.6309          0.08         True   \n",
       "2  Hybrid 0.7/0.3         0.7489          0.7917          4.28         True   \n",
       "\n",
       "   f1_target_>0.75  threshold  roc_auc  \n",
       "0            False       0.33   0.8768  \n",
       "1            False       0.05   0.7056  \n",
       "2            False       0.38   0.8773  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def _row(key, label):\n",
    "    m = metrics.get(key, {})\n",
    "    if not m:\n",
    "        return None\n",
    "    return {\n",
    "        \"model\": label,\n",
    "        \"f1_toxic_test\": m.get(\"f1_toxic\"),\n",
    "        \"f1_toxic_train\": m.get(\"f1_toxic_train\"),\n",
    "        \"toxic_gap_pp\": m.get(\"train_test_gap_toxic_pp\"),\n",
    "        \"gap_ok_<5pp\": m.get(\"gap_toxic_ok\", False),\n",
    "        \"f1_target_>0.75\": (m.get(\"f1_toxic\") or 0) > 0.75,\n",
    "        \"threshold\": m.get(\"threshold\"),\n",
    "        \"roc_auc\": m.get(\"roc_auc\"),\n",
    "    }\n",
    "\n",
    "summary = pd.DataFrame(\n",
    "    [\n",
    "        r\n",
    "        for r in [\n",
    "            _row(\"transformer\", \"Toxic-BERT\"),\n",
    "            _row(\"logistic_regression\", \"LR-TFIDF-250\"),\n",
    "            _row(\"ensemble\", \"Hybrid 0.7/0.3\"),\n",
    "        ]\n",
    "        if r\n",
    "    ]\n",
    ")\n",
    "summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Integrated report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Phase 5 Expert Adaptation β€” 20260524_193947\n",
       "\n",
       "## Targets\n",
       "- Test **F1-toxic** > 0.75\n",
       "- |Train F1-toxic βˆ’ Test F1-toxic| < 5 pp (0.05)\n",
       "\n",
       "## Holdout test (tuned thresholds on validation)\n",
       "\n",
       "| Model | F1-toxic (test) | F1-toxic (train) | Toxic gap (pp) | Threshold | Gap OK |\n",
       "|-------|-------------------|--------------------|----------------|-----------|--------|\n",
       "| Toxic-BERT | 0.7489 | 0.7907 | 4.18 | 0.33 | βœ… |\n",
       "| LR-TFIDF (250 feat) | 0.6301 | 0.6309 | 0.08 | 0.05 | βœ… |\n",
       "| Hybrid 0.7/0.3 | 0.7489 | 0.7917 | 4.28 | 0.38 | βœ… |\n",
       "\n",
       "## Augmentation\n",
       "- Pivot language: de\n",
       "- Train size: 677 β†’ 886 (+209)\n",
       "\n",
       "## Verdict\n",
       "**Toxic-BERT** toxic gap < 5 pp βœ…; **Hybrid** toxic gap < 5 pp βœ…\n",
       "\n",
       "- JSON: `reports/expert/expert_run_20260524_193947.json`\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "\n",
    "md_path = reports_dir / f\"integrated_report_{run_id}.md\"\n",
    "if md_path.exists():\n",
    "    display(Markdown(md_path.read_text()))\n",
    "else:\n",
    "    print(\"Report not found\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "Phase 5 applies **Toxic-BERT** with a frozen backbone, a **250-feature** LR safety net, **validation threshold tuning** on F1-toxic, and a **0.7/0.3** hybrid.\n",
    "Augmentation uses a **German** pivot for more diverse toxic paraphrases.\n",
    "\n",
    "Success criteria:\n",
    "- **F1-toxic (test) > 0.75**\n",
    "- **|F1-toxic train βˆ’ F1-toxic test| < 5 pp** (`gap_toxic_ok`)\n",
    "\n",
    "Artifacts: `models/expert_toxic_bert/`, `models/expert_lr_tfidf.joblib`, `reports/expert/expert_run_{run_id}.json`."
   ]
  }
 ],
 "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.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}