File size: 8,806 Bytes
162232a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ca08817",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install seqeval"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5958200",
   "metadata": {},
   "outputs": [],
   "source": [
    "# import torch\n",
    "# torch.cuda.is_available(), torch.cuda.device_count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "590c3f48",
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "import pickle\n",
    "import numpy as np\n",
    "import transformers\n",
    "from transformers import Trainer\n",
    "from datasets import load_metric\n",
    "from datasets import load_dataset\n",
    "from transformers import AutoTokenizer\n",
    "from transformers import TrainingArguments\n",
    "from transformers import AutoModelForTokenClassification\n",
    "from transformers import DataCollatorForTokenClassification"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44d7c35c",
   "metadata": {},
   "source": [
    "## Helpful funcs "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c9e36d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def align_labels_with_tokens(labels: list, word_ids: list) -> list:\n",
    "    \"\"\"\n",
    "    Repeat label for each splitted token\n",
    "\n",
    "    :param labels: list of entities token\n",
    "    :type labels: list\n",
    "    :param word_ids: list of word ids (repeadted if word was splitted)\n",
    "    :type word_ids: list\n",
    "    :return: list of aligned labels for tokenized sequence\n",
    "    :rtype: list\n",
    "    \"\"\"\n",
    "    return [-100 if i is None else labels[i] for i in word_ids]\n",
    "\n",
    "def tokenize_and_align_labels(examples):\n",
    "    \"\"\"\n",
    "    Tokenizing input sequence with corresponding labels\n",
    "\n",
    "    :param examples: DatasetDict object with sequences and label ids\n",
    "    :type examples: DatasetDict\n",
    "    :return: DatasetDict with tokenizer output\n",
    "    :rtype: DatasetDict\n",
    "    \"\"\"\n",
    "    tokenized_inputs = tokenizer(\n",
    "        examples[\"sequences\"], truncation=True, is_split_into_words=True\n",
    "    )\n",
    "    all_labels = examples[\"ids\"]\n",
    "    new_labels = []\n",
    "    for i, labels in enumerate(all_labels):\n",
    "        word_ids = tokenized_inputs.word_ids(i)\n",
    "        new_labels.append(align_labels_with_tokens(labels, word_ids))\n",
    "\n",
    "    tokenized_inputs[\"labels\"] = new_labels\n",
    "    return tokenized_inputs\n",
    "\n",
    "def compute_metrics(eval_preds):\n",
    "    \"\"\"\n",
    "    Function for evaluate model\n",
    "    \n",
    "    :param eval_preds: model output\n",
    "    :type eval_preds: \n",
    "    \"\"\"\n",
    "    logits, labels = eval_preds\n",
    "    predictions = np.argmax(logits, axis=-1)\n",
    "\n",
    "    # Remove ignored index (special tokens) and convert to labels\n",
    "    true_labels = [[label_names[l] for l in label if l != -100] for label in labels]\n",
    "    true_predictions = [[label_names[p] for (p, l) in zip(prediction, label) if l != -100]\n",
    "                        for prediction, label in zip(predictions, labels)\n",
    "                        ]\n",
    "    all_metrics = metric.compute(predictions=true_predictions, references=true_labels)\n",
    "    return {\n",
    "        \"precision\": all_metrics[\"overall_precision\"],\n",
    "        \"recall\": all_metrics[\"overall_recall\"],\n",
    "        \"f1\": all_metrics[\"overall_f1\"],\n",
    "        \"accuracy\": all_metrics[\"overall_accuracy\"],\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8760e709",
   "metadata": {},
   "source": [
    "## Load Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8c723f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_datasets = load_dataset(\"surdan/nerel_short\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e540a898",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a4947d1",
   "metadata": {},
   "source": [
    "## Preprocess data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8829557e",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_checkpoint = \"cointegrated/LaBSE-en-ru\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6c13ad1",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea2c1a9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenized_datasets = raw_datasets.map(\n",
    "    tokenize_and_align_labels,\n",
    "    batched=True,\n",
    "    remove_columns=raw_datasets[\"train\"].column_names,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b15c3cf1",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenized_datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9b5b9b1",
   "metadata": {},
   "source": [
    "## Init Training pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b24d86e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('id_to_label_map.pickle', 'rb') as f:\n",
    "    map_id_to_label = pickle.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d90a6d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d890df2",
   "metadata": {},
   "outputs": [],
   "source": [
    "id2label = {str(k): v for k, v in map_id_to_label.items()}\n",
    "label2id = {v: k for k, v in id2label.items()}\n",
    "label_names = list(id2label.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31bcfd6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForTokenClassification.from_pretrained(\n",
    "    model_checkpoint,\n",
    "    id2label=id2label,\n",
    "    label2id=label2id,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84497580",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.config.num_labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ccfbf74",
   "metadata": {},
   "outputs": [],
   "source": [
    "args = TrainingArguments(\n",
    "    \"LaBSE_ner_nerel\",\n",
    "    evaluation_strategy=\"epoch\",\n",
    "    save_strategy=\"no\",\n",
    "    learning_rate=2e-5,\n",
    "    num_train_epochs=25,\n",
    "    weight_decay=0.01,\n",
    "    push_to_hub=False,\n",
    "    per_device_train_batch_size = 4 ## depending on the total volume of memory of your GPU\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c798d567",
   "metadata": {},
   "source": [
    "## Train model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1348d188",
   "metadata": {},
   "outputs": [],
   "source": [
    "## for compute_metrics function\n",
    "metric = load_metric(\"seqeval\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cff0367",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    train_dataset=tokenized_datasets[\"train\"],\n",
    "    eval_dataset=tokenized_datasets[\"dev\"],\n",
    "    data_collator=data_collator,\n",
    "    compute_metrics=compute_metrics,\n",
    "    tokenizer=tokenizer,\n",
    ")\n",
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "576a10f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer.save_model(\"LaBSE_nerel_last_checkpoint\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "451d6db1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hf_env",
   "language": "python",
   "name": "hf_env"
  },
  "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.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}