cuong1206 commited on
Commit
cb63983
·
verified ·
1 Parent(s): 438a805

Upload NLP_Colab_Template.ipynb

Browse files
Files changed (1) hide show
  1. NLP_Colab_Template.ipynb +372 -0
NLP_Colab_Template.ipynb ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "18562384",
6
+ "metadata": {},
7
+ "source": [
8
+ "# HaUI Olympic AI 2025 — NLP Colab Template\n",
9
+ "\n",
10
+ "**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",
11
+ "\n",
12
+ "> **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"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": null,
18
+ "id": "077202e5",
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "# %%capture\n",
23
+ "# If running on fresh Colab, uncomment to install core libs\n",
24
+ "# !pip install --upgrade pip\n",
25
+ "# !pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121\n",
26
+ "# !pip install transformers==4.43.4 datasets==2.19.0 accelerate==0.33.0 evaluate==0.4.2\n",
27
+ "# !pip install scikit-learn==1.4.2 pandas==2.2.2 numpy==1.26.4 tqdm==4.66.4 nltk==3.8.1\n",
28
+ "\n",
29
+ "import os, sys, platform, random, time, math, json\n",
30
+ "import numpy as np\n",
31
+ "import pandas as pd\n",
32
+ "\n",
33
+ "import torch\n",
34
+ "from torch.utils.data import Dataset, DataLoader\n",
35
+ "\n",
36
+ "import transformers\n",
37
+ "from transformers import (\n",
38
+ " AutoConfig, AutoTokenizer, AutoModelForSequenceClassification,\n",
39
+ " DataCollatorWithPadding, Trainer, TrainingArguments, set_seed\n",
40
+ ")\n",
41
+ "\n",
42
+ "from sklearn.metrics import accuracy_score, f1_score, classification_report\n",
43
+ "\n",
44
+ "print('Python:', sys.version)\n",
45
+ "print('PyTorch:', torch.__version__)\n",
46
+ "print('Transformers:', transformers.__version__)\n",
47
+ "print('CUDA available:', torch.cuda.is_available())\n",
48
+ "if torch.cuda.is_available():\n",
49
+ " print('GPU:', torch.cuda.get_device_name(0))"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "9b86b5c5",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "from dataclasses import dataclass\n",
60
+ "\n",
61
+ "@dataclass\n",
62
+ "class CFG:\n",
63
+ " model_name: str = 'xlm-roberta-base' # base LM, pretrain tổng quát\n",
64
+ " num_labels: int = 2 # <-- TODO: chỉnh theo số lớp\n",
65
+ " max_length: int = 256\n",
66
+ " train_path: str = '/content/data/train.csv' # TODO: chỉnh đường dẫn\n",
67
+ " dev_path: str = '/content/data/dev.csv' # hoặc None nếu dùng CV\n",
68
+ " test_path: str = '/content/data/test.csv'\n",
69
+ " text_col: str = 'text' # TODO: tên cột văn bản\n",
70
+ " label_col: str = 'label' # TODO: tên cột nhãn (int 0..K-1)\n",
71
+ "\n",
72
+ " seed: int = 42\n",
73
+ " epochs: int = 3\n",
74
+ " train_bs: int = 16\n",
75
+ " eval_bs: int = 32\n",
76
+ " lr: float = 2e-5\n",
77
+ " wd: float = 0.01\n",
78
+ " grad_accum: int = 1\n",
79
+ " fp16: bool = True\n",
80
+ " warmup_ratio: float = 0.06\n",
81
+ " logging_steps: int = 50\n",
82
+ " save_total_limit: int = 2\n",
83
+ " output_dir: str = '/content/outputs'\n",
84
+ " push_to_hub: bool = False # phải tắt nếu internet whitelist hạn chế\n",
85
+ "\n",
86
+ "os.makedirs(CFG.output_dir, exist_ok=True)\n",
87
+ "\n",
88
+ "def seed_everything(seed: int):\n",
89
+ " set_seed(seed)\n",
90
+ " random.seed(seed)\n",
91
+ " np.random.seed(seed)\n",
92
+ " torch.manual_seed(seed)\n",
93
+ " torch.cuda.manual_seed_all(seed)\n",
94
+ " print(f'Seeded with {seed}')\n",
95
+ "\n",
96
+ "seed_everything(CFG.seed)"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "execution_count": null,
102
+ "id": "6b0c3d70",
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "# Expect CSV with at least [text_col, label_col] for train/dev; test has [text_col] (no labels).\n",
107
+ "def read_df(path, required_cols=None):\n",
108
+ " df = pd.read_csv(path)\n",
109
+ " if required_cols:\n",
110
+ " for c in required_cols:\n",
111
+ " if c not in df.columns:\n",
112
+ " raise ValueError(f'Missing column {c} in {path}. Columns: {df.columns.tolist()}')\n",
113
+ " return df\n",
114
+ "\n",
115
+ "train_df = read_df(CFG.train_path, [CFG.text_col, CFG.label_col])\n",
116
+ "dev_df = read_df(CFG.dev_path, [CFG.text_col, CFG.label_col]) if os.path.exists(CFG.dev_path) else None\n",
117
+ "test_df = read_df(CFG.test_path, [CFG.text_col]) if os.path.exists(CFG.test_path) else None\n",
118
+ "\n",
119
+ "print('Train shape:', train_df.shape)\n",
120
+ "if dev_df is not None: print('Dev shape:', dev_df.shape)\n",
121
+ "if test_df is not None: print('Test shape:', test_df.shape)"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "32c6e1f5",
128
+ "metadata": {},
129
+ "outputs": [],
130
+ "source": [
131
+ "import re\n",
132
+ "import unicodedata\n",
133
+ "\n",
134
+ "# Simple normalization — adjust to match task/language\n",
135
+ "CONTRACTIONS = {\n",
136
+ " \"it's\": \"it is\", \"don't\": \"do not\", \"I'm\": \"I am\", \"can't\": \"cannot\",\n",
137
+ " \"that's\": \"that is\", \"there's\": \"there is\", \"he's\": \"he is\", \"she's\": \"she is\",\n",
138
+ "}\n",
139
+ "\n",
140
+ "def normalize_text(s: str):\n",
141
+ " if not isinstance(s, str):\n",
142
+ " return ''\n",
143
+ " # NFKC normalize\n",
144
+ " s = unicodedata.normalize('NFKC', s)\n",
145
+ " # expand contractions (lower-level example; consider multilingual handling)\n",
146
+ " tmp = []\n",
147
+ " for tok in s.split():\n",
148
+ " key = tok.lower()\n",
149
+ " tmp.append(CONTRACTIONS.get(key, tok))\n",
150
+ " s = ' '.join(tmp)\n",
151
+ " # collapse spaces\n",
152
+ " s = re.sub(r'\\s+', ' ', s).strip()\n",
153
+ " return s\n",
154
+ "\n",
155
+ "# Apply preview (do NOT overwrite original; create a processed column for tokenization)\n",
156
+ "train_df['proc_text'] = train_df[CFG.text_col].astype(str).map(normalize_text)\n",
157
+ "if dev_df is not None:\n",
158
+ " dev_df['proc_text'] = dev_df[CFG.text_col].astype(str).map(normalize_text)\n",
159
+ "if test_df is not None:\n",
160
+ " test_df['proc_text'] = test_df[CFG.text_col].astype(str).map(normalize_text)\n",
161
+ "\n",
162
+ "train_df.head()"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": null,
168
+ "id": "f5b0a5c4",
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "tokenizer = AutoTokenizer.from_pretrained(CFG.model_name, use_fast=True)\n",
173
+ "\n",
174
+ "class NLPDataset(Dataset):\n",
175
+ " def __init__(self, df, has_labels=True):\n",
176
+ " self.df = df.reset_index(drop=True)\n",
177
+ " self.has_labels = has_labels\n",
178
+ " def __len__(self):\n",
179
+ " return len(self.df)\n",
180
+ " def __getitem__(self, idx):\n",
181
+ " row = self.df.iloc[idx]\n",
182
+ " text = row['proc_text']\n",
183
+ " enc = tokenizer(\n",
184
+ " text,\n",
185
+ " max_length=CFG.max_length,\n",
186
+ " truncation=True,\n",
187
+ " padding=False\n",
188
+ " )\n",
189
+ " if self.has_labels:\n",
190
+ " enc['labels'] = int(row[CFG.label_col])\n",
191
+ " return {k: torch.tensor(v) for k, v in enc.items()}\n",
192
+ "\n",
193
+ "train_ds = NLPDataset(train_df, has_labels=True)\n",
194
+ "dev_ds = NLPDataset(dev_df, has_labels=True) if dev_df is not None else None\n",
195
+ "test_ds = NLPDataset(test_df, has_labels=False) if test_df is not None else None\n",
196
+ "\n",
197
+ "collator = DataCollatorWithPadding(tokenizer=tokenizer)"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": null,
203
+ "id": "c0343b24",
204
+ "metadata": {},
205
+ "outputs": [],
206
+ "source": [
207
+ "config = AutoConfig.from_pretrained(CFG.model_name, num_labels=CFG.num_labels)\n",
208
+ "model = AutoModelForSequenceClassification.from_pretrained(\n",
209
+ " CFG.model_name,\n",
210
+ " config=config\n",
211
+ ")\n",
212
+ "\n",
213
+ "def compute_metrics(eval_pred):\n",
214
+ " logits, labels = eval_pred\n",
215
+ " preds = logits.argmax(axis=-1)\n",
216
+ " acc = accuracy_score(labels, preds)\n",
217
+ " f1m = f1_score(labels, preds, average='macro')\n",
218
+ " f1w = f1_score(labels, preds, average='weighted')\n",
219
+ " return {'accuracy': acc, 'f1_macro': f1m, 'f1_weighted': f1w}"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "execution_count": null,
225
+ "id": "7a8e57d0",
226
+ "metadata": {},
227
+ "outputs": [],
228
+ "source": [
229
+ "training_args = TrainingArguments(\n",
230
+ " output_dir=CFG.output_dir,\n",
231
+ " per_device_train_batch_size=CFG.train_bs,\n",
232
+ " per_device_eval_batch_size=CFG.eval_bs,\n",
233
+ " gradient_accumulation_steps=CFG.grad_accum,\n",
234
+ " num_train_epochs=CFG.epochs,\n",
235
+ " learning_rate=CFG.lr,\n",
236
+ " weight_decay=CFG.wd,\n",
237
+ " warmup_ratio=CFG.warmup_ratio,\n",
238
+ " evaluation_strategy='steps' if dev_df is not None else 'no',\n",
239
+ " save_strategy='steps' if dev_df is not None else 'epoch',\n",
240
+ " logging_steps=CFG.logging_steps,\n",
241
+ " save_total_limit=CFG.save_total_limit,\n",
242
+ " load_best_model_at_end=True if dev_df is not None else False,\n",
243
+ " metric_for_best_model='f1_macro',\n",
244
+ " fp16=CFG.fp16,\n",
245
+ " report_to=[] # avoid online reporting\n",
246
+ ")\n",
247
+ "\n",
248
+ "trainer = Trainer(\n",
249
+ " model=model,\n",
250
+ " args=training_args,\n",
251
+ " train_dataset=train_ds,\n",
252
+ " eval_dataset=dev_ds if dev_ds is not None else None,\n",
253
+ " tokenizer=tokenizer,\n",
254
+ " data_collator=collator,\n",
255
+ " compute_metrics=compute_metrics if dev_ds is not None else None\n",
256
+ ")\n",
257
+ "\n",
258
+ "if dev_df is not None:\n",
259
+ " print('Starting training with eval...')\n",
260
+ "else:\n",
261
+ " print('Starting training (no eval set provided; consider internal CV).')\n",
262
+ "\n",
263
+ "trainer.train()"
264
+ ]
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "execution_count": null,
269
+ "id": "63964aac",
270
+ "metadata": {},
271
+ "outputs": [],
272
+ "source": [
273
+ "if dev_df is not None:\n",
274
+ " eval_res = trainer.evaluate()\n",
275
+ " print('Evaluation:', eval_res)\n",
276
+ " # Detailed report\n",
277
+ " preds = trainer.predict(dev_ds)\n",
278
+ " y_true = preds.label_ids\n",
279
+ " y_pred = preds.predictions.argmax(-1)\n",
280
+ " print(classification_report(y_true, y_pred, digits=4))"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "execution_count": null,
286
+ "id": "790ceec6",
287
+ "metadata": {},
288
+ "outputs": [],
289
+ "source": [
290
+ "# Create submission: id + prediction (adjust column names as your platform requires)\n",
291
+ "if test_df is not None:\n",
292
+ " test_pred = trainer.predict(test_ds)\n",
293
+ " test_labels = test_pred.predictions.argmax(-1)\n",
294
+ " sub = pd.DataFrame({\n",
295
+ " 'id': np.arange(len(test_labels)),\n",
296
+ " 'prediction': test_labels\n",
297
+ " })\n",
298
+ " sub_path = os.path.join(CFG.output_dir, 'submission.csv')\n",
299
+ " sub.to_csv(sub_path, index=False)\n",
300
+ " print('Saved:', sub_path)\n",
301
+ " display(sub.head())"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "code",
306
+ "execution_count": null,
307
+ "id": "09ccd875",
308
+ "metadata": {},
309
+ "outputs": [],
310
+ "source": [
311
+ "# %% Optional: Stratified K-Fold CV (skeleton)\n",
312
+ "# from sklearn.model_selection import StratifiedKFold\n",
313
+ "# skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=CFG.seed)\n",
314
+ "# oof_preds = np.zeros((len(train_df), CFG.num_labels))\n",
315
+ "# for fold, (trn_idx, val_idx) in enumerate(skf.split(train_df, train_df[CFG.label_col])):\n",
316
+ "# print(f'Fold {fold+1}')\n",
317
+ "# trn_df = train_df.iloc[trn_idx].reset_index(drop=True)\n",
318
+ "# val_df = train_df.iloc[val_idx].reset_index(drop=True)\n",
319
+ "# # Rebuild datasets, model, trainer per fold ...\n",
320
+ "# # Aggregate oof_preds and evaluate macro-F1 for model selection.\n",
321
+ "# pass"
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "execution_count": null,
327
+ "id": "0e0338f2",
328
+ "metadata": {},
329
+ "outputs": [],
330
+ "source": [
331
+ "import importlib, pkgutil\n",
332
+ "def pkg_version(name):\n",
333
+ " try:\n",
334
+ " mod = importlib.import_module(name)\n",
335
+ " return getattr(mod, '__version__', 'unknown')\n",
336
+ " except Exception:\n",
337
+ " return 'not-installed'\n",
338
+ "\n",
339
+ "print({\n",
340
+ " 'python': sys.version,\n",
341
+ " 'torch': pkg_version('torch'),\n",
342
+ " 'transformers': pkg_version('transformers'),\n",
343
+ " 'datasets': pkg_version('datasets'),\n",
344
+ " 'accelerate': pkg_version('accelerate'),\n",
345
+ " 'evaluate': pkg_version('evaluate'),\n",
346
+ " 'sklearn': pkg_version('sklearn'),\n",
347
+ " 'pandas': pkg_version('pandas'),\n",
348
+ " 'numpy': pkg_version('numpy'),\n",
349
+ " 'nltk': pkg_version('nltk'),\n",
350
+ "})"
351
+ ]
352
+ },
353
+ {
354
+ "cell_type": "markdown",
355
+ "id": "558db3d6",
356
+ "metadata": {},
357
+ "source": [
358
+ "## ✅ Submission Checklist\n",
359
+ "\n",
360
+ "- [ ] **Không** dùng dữ liệu ngoài BTC.\n",
361
+ "- [ ] Checkpoint **tổng quát** (chưa fine-tune đúng tác vụ).\n",
362
+ "- [ ] Tách `train/dev` đúng; **không** đụng `test` cho tuning.\n",
363
+ "- [ ] Notebook chạy **end-to-end** từ đầu, tạo `submission.csv` trong `CFG.output_dir`.\n",
364
+ "- [ ] Ghi rõ `CFG`, seed, siêu tham số, phiên bản thư viện (cell Reproducibility).\n",
365
+ "- [ ] Thời gian chạy & VRAM phù hợp Colab/Kaggle.\n"
366
+ ]
367
+ }
368
+ ],
369
+ "metadata": {},
370
+ "nbformat": 4,
371
+ "nbformat_minor": 5
372
+ }