File size: 13,748 Bytes
cb63983
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "18562384",
   "metadata": {},
   "source": [
    "# HaUI Olympic AI 2025 — NLP Colab Template\n",
    "\n",
    "**Mục tiêu:** Khung notebook end-to-end, *tuân thủ quy chế*: (1) **không** dùng dữ liệu ngoài, (2) **chỉ** fine-tune **checkpoint tiền huấn luyện tổng quát** (chưa fine-tune đúng tác vụ), (3) **không** đụng `test` cho huấn luyện/tuning, (4) tái lập hoàn toàn trên Colab/Kaggle.\n",
    "\n",
    "> **TODO trước khi chạy**: Đặt dữ liệu vào `/content/data/` theo tên file bạn dùng bên dưới (vd. `train.csv`, `dev.csv`, `test.csv`). Điều chỉnh `CFG` cho phù hợp.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "077202e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %%capture\n",
    "# If running on fresh Colab, uncomment to install core libs\n",
    "# !pip install --upgrade pip\n",
    "# !pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121\n",
    "# !pip install transformers==4.43.4 datasets==2.19.0 accelerate==0.33.0 evaluate==0.4.2\n",
    "# !pip install scikit-learn==1.4.2 pandas==2.2.2 numpy==1.26.4 tqdm==4.66.4 nltk==3.8.1\n",
    "\n",
    "import os, sys, platform, random, time, math, json\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "import torch\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "import transformers\n",
    "from transformers import (\n",
    "    AutoConfig, AutoTokenizer, AutoModelForSequenceClassification,\n",
    "    DataCollatorWithPadding, Trainer, TrainingArguments, set_seed\n",
    ")\n",
    "\n",
    "from sklearn.metrics import accuracy_score, f1_score, classification_report\n",
    "\n",
    "print('Python:', sys.version)\n",
    "print('PyTorch:', torch.__version__)\n",
    "print('Transformers:', transformers.__version__)\n",
    "print('CUDA available:', torch.cuda.is_available())\n",
    "if torch.cuda.is_available():\n",
    "    print('GPU:', torch.cuda.get_device_name(0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b86b5c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class CFG:\n",
    "    model_name: str = 'xlm-roberta-base'   # base LM, pretrain tổng quát\n",
    "    num_labels: int = 2                     # <-- TODO: chỉnh theo số lớp\n",
    "    max_length: int = 256\n",
    "    train_path: str = '/content/data/train.csv'  # TODO: chỉnh đường dẫn\n",
    "    dev_path: str = '/content/data/dev.csv'      # hoặc None nếu dùng CV\n",
    "    test_path: str = '/content/data/test.csv'\n",
    "    text_col: str = 'text'                  # TODO: tên cột văn bản\n",
    "    label_col: str = 'label'                # TODO: tên cột nhãn (int 0..K-1)\n",
    "\n",
    "    seed: int = 42\n",
    "    epochs: int = 3\n",
    "    train_bs: int = 16\n",
    "    eval_bs: int = 32\n",
    "    lr: float = 2e-5\n",
    "    wd: float = 0.01\n",
    "    grad_accum: int = 1\n",
    "    fp16: bool = True\n",
    "    warmup_ratio: float = 0.06\n",
    "    logging_steps: int = 50\n",
    "    save_total_limit: int = 2\n",
    "    output_dir: str = '/content/outputs'\n",
    "    push_to_hub: bool = False  # phải tắt nếu internet whitelist hạn chế\n",
    "\n",
    "os.makedirs(CFG.output_dir, exist_ok=True)\n",
    "\n",
    "def seed_everything(seed: int):\n",
    "    set_seed(seed)\n",
    "    random.seed(seed)\n",
    "    np.random.seed(seed)\n",
    "    torch.manual_seed(seed)\n",
    "    torch.cuda.manual_seed_all(seed)\n",
    "    print(f'Seeded with {seed}')\n",
    "\n",
    "seed_everything(CFG.seed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b0c3d70",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Expect CSV with at least [text_col, label_col] for train/dev; test has [text_col] (no labels).\n",
    "def read_df(path, required_cols=None):\n",
    "    df = pd.read_csv(path)\n",
    "    if required_cols:\n",
    "        for c in required_cols:\n",
    "            if c not in df.columns:\n",
    "                raise ValueError(f'Missing column {c} in {path}. Columns: {df.columns.tolist()}')\n",
    "    return df\n",
    "\n",
    "train_df = read_df(CFG.train_path, [CFG.text_col, CFG.label_col])\n",
    "dev_df = read_df(CFG.dev_path, [CFG.text_col, CFG.label_col]) if os.path.exists(CFG.dev_path) else None\n",
    "test_df = read_df(CFG.test_path, [CFG.text_col]) if os.path.exists(CFG.test_path) else None\n",
    "\n",
    "print('Train shape:', train_df.shape)\n",
    "if dev_df is not None: print('Dev shape:', dev_df.shape)\n",
    "if test_df is not None: print('Test shape:', test_df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32c6e1f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import unicodedata\n",
    "\n",
    "# Simple normalization — adjust to match task/language\n",
    "CONTRACTIONS = {\n",
    "    \"it's\": \"it is\", \"don't\": \"do not\", \"I'm\": \"I am\", \"can't\": \"cannot\",\n",
    "    \"that's\": \"that is\", \"there's\": \"there is\", \"he's\": \"he is\", \"she's\": \"she is\",\n",
    "}\n",
    "\n",
    "def normalize_text(s: str):\n",
    "    if not isinstance(s, str):\n",
    "        return ''\n",
    "    # NFKC normalize\n",
    "    s = unicodedata.normalize('NFKC', s)\n",
    "    # expand contractions (lower-level example; consider multilingual handling)\n",
    "    tmp = []\n",
    "    for tok in s.split():\n",
    "        key = tok.lower()\n",
    "        tmp.append(CONTRACTIONS.get(key, tok))\n",
    "    s = ' '.join(tmp)\n",
    "    # collapse spaces\n",
    "    s = re.sub(r'\\s+', ' ', s).strip()\n",
    "    return s\n",
    "\n",
    "# Apply preview (do NOT overwrite original; create a processed column for tokenization)\n",
    "train_df['proc_text'] = train_df[CFG.text_col].astype(str).map(normalize_text)\n",
    "if dev_df is not None:\n",
    "    dev_df['proc_text'] = dev_df[CFG.text_col].astype(str).map(normalize_text)\n",
    "if test_df is not None:\n",
    "    test_df['proc_text'] = test_df[CFG.text_col].astype(str).map(normalize_text)\n",
    "\n",
    "train_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5b0a5c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(CFG.model_name, use_fast=True)\n",
    "\n",
    "class NLPDataset(Dataset):\n",
    "    def __init__(self, df, has_labels=True):\n",
    "        self.df = df.reset_index(drop=True)\n",
    "        self.has_labels = has_labels\n",
    "    def __len__(self):\n",
    "        return len(self.df)\n",
    "    def __getitem__(self, idx):\n",
    "        row = self.df.iloc[idx]\n",
    "        text = row['proc_text']\n",
    "        enc = tokenizer(\n",
    "            text,\n",
    "            max_length=CFG.max_length,\n",
    "            truncation=True,\n",
    "            padding=False\n",
    "        )\n",
    "        if self.has_labels:\n",
    "            enc['labels'] = int(row[CFG.label_col])\n",
    "        return {k: torch.tensor(v) for k, v in enc.items()}\n",
    "\n",
    "train_ds = NLPDataset(train_df, has_labels=True)\n",
    "dev_ds = NLPDataset(dev_df, has_labels=True) if dev_df is not None else None\n",
    "test_ds = NLPDataset(test_df, has_labels=False) if test_df is not None else None\n",
    "\n",
    "collator = DataCollatorWithPadding(tokenizer=tokenizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0343b24",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = AutoConfig.from_pretrained(CFG.model_name, num_labels=CFG.num_labels)\n",
    "model = AutoModelForSequenceClassification.from_pretrained(\n",
    "    CFG.model_name,\n",
    "    config=config\n",
    ")\n",
    "\n",
    "def compute_metrics(eval_pred):\n",
    "    logits, labels = eval_pred\n",
    "    preds = logits.argmax(axis=-1)\n",
    "    acc = accuracy_score(labels, preds)\n",
    "    f1m = f1_score(labels, preds, average='macro')\n",
    "    f1w = f1_score(labels, preds, average='weighted')\n",
    "    return {'accuracy': acc, 'f1_macro': f1m, 'f1_weighted': f1w}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a8e57d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "training_args = TrainingArguments(\n",
    "    output_dir=CFG.output_dir,\n",
    "    per_device_train_batch_size=CFG.train_bs,\n",
    "    per_device_eval_batch_size=CFG.eval_bs,\n",
    "    gradient_accumulation_steps=CFG.grad_accum,\n",
    "    num_train_epochs=CFG.epochs,\n",
    "    learning_rate=CFG.lr,\n",
    "    weight_decay=CFG.wd,\n",
    "    warmup_ratio=CFG.warmup_ratio,\n",
    "    evaluation_strategy='steps' if dev_df is not None else 'no',\n",
    "    save_strategy='steps' if dev_df is not None else 'epoch',\n",
    "    logging_steps=CFG.logging_steps,\n",
    "    save_total_limit=CFG.save_total_limit,\n",
    "    load_best_model_at_end=True if dev_df is not None else False,\n",
    "    metric_for_best_model='f1_macro',\n",
    "    fp16=CFG.fp16,\n",
    "    report_to=[]  # avoid online reporting\n",
    ")\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=training_args,\n",
    "    train_dataset=train_ds,\n",
    "    eval_dataset=dev_ds if dev_ds is not None else None,\n",
    "    tokenizer=tokenizer,\n",
    "    data_collator=collator,\n",
    "    compute_metrics=compute_metrics if dev_ds is not None else None\n",
    ")\n",
    "\n",
    "if dev_df is not None:\n",
    "    print('Starting training with eval...')\n",
    "else:\n",
    "    print('Starting training (no eval set provided; consider internal CV).')\n",
    "\n",
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63964aac",
   "metadata": {},
   "outputs": [],
   "source": [
    "if dev_df is not None:\n",
    "    eval_res = trainer.evaluate()\n",
    "    print('Evaluation:', eval_res)\n",
    "    # Detailed report\n",
    "    preds = trainer.predict(dev_ds)\n",
    "    y_true = preds.label_ids\n",
    "    y_pred = preds.predictions.argmax(-1)\n",
    "    print(classification_report(y_true, y_pred, digits=4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "790ceec6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create submission: id + prediction (adjust column names as your platform requires)\n",
    "if test_df is not None:\n",
    "    test_pred = trainer.predict(test_ds)\n",
    "    test_labels = test_pred.predictions.argmax(-1)\n",
    "    sub = pd.DataFrame({\n",
    "        'id': np.arange(len(test_labels)),\n",
    "        'prediction': test_labels\n",
    "    })\n",
    "    sub_path = os.path.join(CFG.output_dir, 'submission.csv')\n",
    "    sub.to_csv(sub_path, index=False)\n",
    "    print('Saved:', sub_path)\n",
    "    display(sub.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09ccd875",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %% Optional: Stratified K-Fold CV (skeleton)\n",
    "# from sklearn.model_selection import StratifiedKFold\n",
    "# skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=CFG.seed)\n",
    "# oof_preds = np.zeros((len(train_df), CFG.num_labels))\n",
    "# for fold, (trn_idx, val_idx) in enumerate(skf.split(train_df, train_df[CFG.label_col])):\n",
    "#     print(f'Fold {fold+1}')\n",
    "#     trn_df = train_df.iloc[trn_idx].reset_index(drop=True)\n",
    "#     val_df = train_df.iloc[val_idx].reset_index(drop=True)\n",
    "#     # Rebuild datasets, model, trainer per fold ...\n",
    "#     # Aggregate oof_preds and evaluate macro-F1 for model selection.\n",
    "# pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e0338f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import importlib, pkgutil\n",
    "def pkg_version(name):\n",
    "    try:\n",
    "        mod = importlib.import_module(name)\n",
    "        return getattr(mod, '__version__', 'unknown')\n",
    "    except Exception:\n",
    "        return 'not-installed'\n",
    "\n",
    "print({\n",
    "    'python': sys.version,\n",
    "    'torch': pkg_version('torch'),\n",
    "    'transformers': pkg_version('transformers'),\n",
    "    'datasets': pkg_version('datasets'),\n",
    "    'accelerate': pkg_version('accelerate'),\n",
    "    'evaluate': pkg_version('evaluate'),\n",
    "    'sklearn': pkg_version('sklearn'),\n",
    "    'pandas': pkg_version('pandas'),\n",
    "    'numpy': pkg_version('numpy'),\n",
    "    'nltk': pkg_version('nltk'),\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "558db3d6",
   "metadata": {},
   "source": [
    "## ✅ Submission Checklist\n",
    "\n",
    "- [ ] **Không** dùng dữ liệu ngoài BTC.\n",
    "- [ ] Checkpoint **tổng quát** (chưa fine-tune đúng tác vụ).\n",
    "- [ ] Tách `train/dev` đúng; **không** đụng `test` cho tuning.\n",
    "- [ ] Notebook chạy **end-to-end** từ đầu, tạo `submission.csv` trong `CFG.output_dir`.\n",
    "- [ ] Ghi rõ `CFG`, seed, siêu tham số, phiên bản thư viện (cell Reproducibility).\n",
    "- [ ] Thời gian chạy & VRAM phù hợp Colab/Kaggle.\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}