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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""model.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1R4jublO4svjd6q5L02m88OG-LlcPyDsM
|
8 |
+
"""
|
9 |
+
|
10 |
+
import pandas as pd
|
11 |
+
|
12 |
+
data = {'Question': ['What is the story about?',
|
13 |
+
'Who is the Phantom Thief Kid?',
|
14 |
+
'What did the police deduce about Kid\'s next target?',
|
15 |
+
'What happened during the heist?',
|
16 |
+
'Who did Conan and Heiji suspect to be the person who shot Kid?',
|
17 |
+
'Who was murdered after the heist and how did it happen?',
|
18 |
+
'Who did the police initially suspect for the murder and who did Conan conclude was the culprit?',
|
19 |
+
'What did Conan deduce about Scorpion\'s next target?',
|
20 |
+
'Who did Conan suspect to be Scorpion and why?',
|
21 |
+
'How did Conan prevent Seiran from killing him?',
|
22 |
+
'Who did Conan suspect Shiratori to be?',
|
23 |
+
'What happened at the end of the story?'],
|
24 |
+
'Answer': ['The story is about the Phantom Thief Kid\'s heist of the Fabergé egg from the Suzuki Modern Art Museum, his apparent death after being shot, and the subsequent investigation to find his killer and recover the stolen egg.',
|
25 |
+
'The Phantom Thief Kid is a notorious thief who specializes in stealing high-profile objects and has a signature calling card left at the scene of the crime.',
|
26 |
+
'The police deduced that Kid\'s next target would be the recently discovered Fabergé egg, which would be displayed at the Suzuki Modern Art Museum in Osaka on August 22.',
|
27 |
+
'Kid successfully stole the egg and fled with Conan and Heiji in pursuit. However, an unknown assailant shot Kid in the right eye, causing him to fall into the sea and apparently die. The police recovered the egg but could not find Kid\'s body.',
|
28 |
+
'Conan and Heiji initially suspected Sonoko\'s father\'s servant, Mr. Nishino, to be the person who shot Kid.',
|
29 |
+
'Ryu Sagawa, a freelance photographer covering the press with news of the egg, was murdered after the heist. He was shot in the right eye in the same fashion as Kid.',
|
30 |
+
'The police initially suspected Sonoko\'s father\'s servant, Mr. Nishino, for the murder, but Conan concluded that the culprit was Scorpion - a mysterious killer who always shoots his victims in the right eye.',
|
31 |
+
'Conan deduced that Scorpion\'s next target was the second egg, which was located at Yokosuka Castle.',
|
32 |
+
'Conan suspected Scorpion to be Seiran the historian because she had a personal vendetta against Kid and had access to information about the second egg.',
|
33 |
+
'Conan prevented Seiran from killing him by wearing bulletproof glass on his glasses, which caused the bullet to ricochet off.',
|
34 |
+
'Conan suspected Shiratori to be Kid in disguise.',
|
35 |
+
'At the end of the story, Kid appeared disguised as Shinichi and distracted Ran while Conan was about to confess to her. Kid then disappeared in a flurry of pigeons.']
|
36 |
+
}
|
37 |
+
|
38 |
+
df = pd.DataFrame(data)
|
39 |
+
|
40 |
+
# ! pip -q install transformers
|
41 |
+
|
42 |
+
from transformers import AutoModelWithLMHead, AutoTokenizer
|
43 |
+
import torch
|
44 |
+
import os
|
45 |
+
|
46 |
+
|
47 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
|
48 |
+
model = AutoModelWithLMHead.from_pretrained("microsoft/DialoGPT-small")
|
49 |
+
|
50 |
+
"""
|
51 |
+
Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).
|
52 |
+
GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned
|
53 |
+
using a masked language modeling (MLM) loss.
|
54 |
+
"""
|
55 |
+
|
56 |
+
import glob
|
57 |
+
import logging
|
58 |
+
import os
|
59 |
+
import pickle
|
60 |
+
import random
|
61 |
+
import re
|
62 |
+
import shutil
|
63 |
+
from typing import Dict, List, Tuple
|
64 |
+
import json
|
65 |
+
|
66 |
+
import pandas as pd
|
67 |
+
import numpy as np
|
68 |
+
import torch
|
69 |
+
|
70 |
+
from sklearn.model_selection import train_test_split
|
71 |
+
|
72 |
+
from torch.nn.utils.rnn import pad_sequence
|
73 |
+
from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler
|
74 |
+
from torch.utils.data.distributed import DistributedSampler
|
75 |
+
from tqdm.notebook import tqdm, trange
|
76 |
+
|
77 |
+
from pathlib import Path
|
78 |
+
|
79 |
+
from transformers import (
|
80 |
+
MODEL_WITH_LM_HEAD_MAPPING,
|
81 |
+
WEIGHTS_NAME,
|
82 |
+
AdamW,
|
83 |
+
AutoConfig,
|
84 |
+
AutoModelWithLMHead,
|
85 |
+
AutoTokenizer,
|
86 |
+
PreTrainedModel,
|
87 |
+
PreTrainedTokenizer,
|
88 |
+
get_linear_schedule_with_warmup,
|
89 |
+
)
|
90 |
+
|
91 |
+
|
92 |
+
try:
|
93 |
+
from torch.utils.tensorboard import SummaryWriter
|
94 |
+
except ImportError:
|
95 |
+
from tensorboardX import SummaryWriter
|
96 |
+
|
97 |
+
# Configs
|
98 |
+
logger = logging.getLogger(__name__)
|
99 |
+
|
100 |
+
MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
|
101 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
102 |
+
|
103 |
+
# Args to allow for easy convertion of python script to notebook
|
104 |
+
class Args():
|
105 |
+
def __init__(self):
|
106 |
+
self.output_dir = 'output-small-save'
|
107 |
+
self.model_type = 'gpt2'
|
108 |
+
self.model_name_or_path = 'microsoft/DialoGPT-small'
|
109 |
+
self.config_name = 'microsoft/DialoGPT-small'
|
110 |
+
self.tokenizer_name = 'microsoft/DialoGPT-small'
|
111 |
+
self.cache_dir = 'cached'
|
112 |
+
self.block_size = 512
|
113 |
+
self.do_train = True
|
114 |
+
self.do_eval = True
|
115 |
+
self.evaluate_during_training = False
|
116 |
+
self.per_gpu_train_batch_size = 4
|
117 |
+
self.per_gpu_eval_batch_size = 4
|
118 |
+
self.gradient_accumulation_steps = 1
|
119 |
+
self.learning_rate = 5e-5
|
120 |
+
self.weight_decay = 0.0
|
121 |
+
self.adam_epsilon = 1e-8
|
122 |
+
self.max_grad_norm = 1.0
|
123 |
+
self.num_train_epochs = 3
|
124 |
+
self.max_steps = -1
|
125 |
+
self.warmup_steps = 0
|
126 |
+
self.logging_steps = 1000
|
127 |
+
self.save_steps = 3500
|
128 |
+
self.save_total_limit = None
|
129 |
+
self.eval_all_checkpoints = False
|
130 |
+
self.no_cuda = False
|
131 |
+
self.overwrite_output_dir = True
|
132 |
+
self.overwrite_cache = True
|
133 |
+
self.should_continue = False
|
134 |
+
self.seed = 42
|
135 |
+
self.local_rank = -1
|
136 |
+
self.fp16 = False
|
137 |
+
self.fp16_opt_level = 'O1'
|
138 |
+
|
139 |
+
args = Args()
|
140 |
+
|
141 |
+
df.head()
|
142 |
+
|
143 |
+
def construct_conv(row, tokenizer, eos = True):
|
144 |
+
flatten = lambda l: [item for sublist in l for item in sublist]
|
145 |
+
conv = list(reversed([tokenizer.encode(x) + [tokenizer.eos_token_id] for x in row]))
|
146 |
+
conv = flatten(conv)
|
147 |
+
return conv
|
148 |
+
|
149 |
+
class ConversationDataset(Dataset):
|
150 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, args, df, block_size=512):
|
151 |
+
|
152 |
+
block_size = block_size - (tokenizer.model_max_length - tokenizer.max_len_single_sentence)
|
153 |
+
|
154 |
+
directory = args.cache_dir
|
155 |
+
cached_features_file = os.path.join(
|
156 |
+
directory, args.model_type + "_cached_lm_" + str(block_size)
|
157 |
+
)
|
158 |
+
|
159 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
160 |
+
logger.info("Loading features from cached file %s", cached_features_file)
|
161 |
+
with open(cached_features_file, "rb") as handle:
|
162 |
+
self.examples = pickle.load(handle)
|
163 |
+
else:
|
164 |
+
logger.info("Creating features from dataset file at %s", directory)
|
165 |
+
|
166 |
+
self.examples = []
|
167 |
+
for _, row in df.iterrows():
|
168 |
+
conv = construct_conv(row, tokenizer)
|
169 |
+
self.examples.append(conv)
|
170 |
+
|
171 |
+
logger.info("Saving features into cached file %s", cached_features_file)
|
172 |
+
with open(cached_features_file, "wb") as handle:
|
173 |
+
pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
174 |
+
|
175 |
+
def __len__(self):
|
176 |
+
return len(self.examples)
|
177 |
+
|
178 |
+
def __getitem__(self, item):
|
179 |
+
return torch.tensor(self.examples[item], dtype=torch.long)
|
180 |
+
|
181 |
+
# Cacheing and storing of data/checkpoints
|
182 |
+
|
183 |
+
def load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=False):
|
184 |
+
return ConversationDataset(tokenizer, args, df_val if evaluate else df_trn)
|
185 |
+
|
186 |
+
|
187 |
+
def set_seed(args):
|
188 |
+
random.seed(args.seed)
|
189 |
+
np.random.seed(args.seed)
|
190 |
+
torch.manual_seed(args.seed)
|
191 |
+
if args.n_gpu > 0:
|
192 |
+
torch.cuda.manual_seed_all(args.seed)
|
193 |
+
|
194 |
+
|
195 |
+
def _sorted_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]:
|
196 |
+
ordering_and_checkpoint_path = []
|
197 |
+
|
198 |
+
glob_checkpoints = glob.glob(os.path.join(args.output_dir, "{}-*".format(checkpoint_prefix)))
|
199 |
+
|
200 |
+
for path in glob_checkpoints:
|
201 |
+
if use_mtime:
|
202 |
+
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
|
203 |
+
else:
|
204 |
+
regex_match = re.match(".*{}-([0-9]+)".format(checkpoint_prefix), path)
|
205 |
+
if regex_match and regex_match.groups():
|
206 |
+
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
|
207 |
+
|
208 |
+
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
|
209 |
+
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
|
210 |
+
return checkpoints_sorted
|
211 |
+
|
212 |
+
|
213 |
+
def _rotate_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> None:
|
214 |
+
if not args.save_total_limit:
|
215 |
+
return
|
216 |
+
if args.save_total_limit <= 0:
|
217 |
+
return
|
218 |
+
|
219 |
+
# Check if we should delete older checkpoint(s)
|
220 |
+
checkpoints_sorted = _sorted_checkpoints(args, checkpoint_prefix, use_mtime)
|
221 |
+
if len(checkpoints_sorted) <= args.save_total_limit:
|
222 |
+
return
|
223 |
+
|
224 |
+
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)
|
225 |
+
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
|
226 |
+
for checkpoint in checkpoints_to_be_deleted:
|
227 |
+
logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
|
228 |
+
shutil.rmtree(checkpoint)
|
229 |
+
|
230 |
+
def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[int, float]:
|
231 |
+
""" Train the model """
|
232 |
+
if args.local_rank in [-1, 0]:
|
233 |
+
tb_writer = SummaryWriter()
|
234 |
+
|
235 |
+
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
|
236 |
+
|
237 |
+
def collate(examples: List[torch.Tensor]):
|
238 |
+
if tokenizer._pad_token is None:
|
239 |
+
return pad_sequence(examples, batch_first=True)
|
240 |
+
return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
|
241 |
+
|
242 |
+
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
|
243 |
+
train_dataloader = DataLoader(
|
244 |
+
train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=collate, drop_last = True
|
245 |
+
)
|
246 |
+
|
247 |
+
if args.max_steps > 0:
|
248 |
+
t_total = args.max_steps
|
249 |
+
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
|
250 |
+
else:
|
251 |
+
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
|
252 |
+
|
253 |
+
model = model.module if hasattr(model, "module") else model # Take care of distributed/parallel training
|
254 |
+
model.resize_token_embeddings(len(tokenizer))
|
255 |
+
# add_special_tokens_(model, tokenizer)
|
256 |
+
|
257 |
+
|
258 |
+
# Prepare optimizer and schedule (linear warmup and decay)
|
259 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
260 |
+
optimizer_grouped_parameters = [
|
261 |
+
{
|
262 |
+
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
|
263 |
+
"weight_decay": args.weight_decay,
|
264 |
+
},
|
265 |
+
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
|
266 |
+
]
|
267 |
+
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
|
268 |
+
scheduler = get_linear_schedule_with_warmup(
|
269 |
+
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
|
270 |
+
)
|
271 |
+
|
272 |
+
# Check if saved optimizer or scheduler states exist
|
273 |
+
if (
|
274 |
+
args.model_name_or_path
|
275 |
+
and os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt"))
|
276 |
+
and os.path.isfile(os.path.join(args.model_name_or_path, "scheduler.pt"))
|
277 |
+
):
|
278 |
+
# Load in optimizer and scheduler states
|
279 |
+
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
|
280 |
+
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
|
281 |
+
|
282 |
+
if args.fp16:
|
283 |
+
try:
|
284 |
+
from apex import amp
|
285 |
+
except ImportError:
|
286 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
|
287 |
+
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
|
288 |
+
|
289 |
+
# multi-gpu training (should be after apex fp16 initialization)
|
290 |
+
if args.n_gpu > 1:
|
291 |
+
model = torch.nn.DataParallel(model)
|
292 |
+
|
293 |
+
# Distributed training (should be after apex fp16 initialization)
|
294 |
+
if args.local_rank != -1:
|
295 |
+
model = torch.nn.parallel.DistributedDataParallel(
|
296 |
+
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
|
297 |
+
)
|
298 |
+
|
299 |
+
# Train!
|
300 |
+
logger.info("***** Running training *****")
|
301 |
+
logger.info(" Num examples = %d", len(train_dataset))
|
302 |
+
logger.info(" Num Epochs = %d", args.num_train_epochs)
|
303 |
+
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
|
304 |
+
logger.info(
|
305 |
+
" Total train batch size (w. parallel, distributed & accumulation) = %d",
|
306 |
+
args.train_batch_size
|
307 |
+
* args.gradient_accumulation_steps
|
308 |
+
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
|
309 |
+
)
|
310 |
+
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
|
311 |
+
logger.info(" Total optimization steps = %d", t_total)
|
312 |
+
|
313 |
+
global_step = 0
|
314 |
+
epochs_trained = 0
|
315 |
+
steps_trained_in_current_epoch = 0
|
316 |
+
# Check if continuing training from a checkpoint
|
317 |
+
if args.model_name_or_path and os.path.exists(args.model_name_or_path):
|
318 |
+
try:
|
319 |
+
# set global_step to gobal_step of last saved checkpoint from model path
|
320 |
+
checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
|
321 |
+
global_step = int(checkpoint_suffix)
|
322 |
+
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
|
323 |
+
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
|
324 |
+
|
325 |
+
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
|
326 |
+
logger.info(" Continuing training from epoch %d", epochs_trained)
|
327 |
+
logger.info(" Continuing training from global step %d", global_step)
|
328 |
+
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
|
329 |
+
except ValueError:
|
330 |
+
logger.info(" Starting fine-tuning.")
|
331 |
+
|
332 |
+
tr_loss, logging_loss = 0.0, 0.0
|
333 |
+
|
334 |
+
model.zero_grad()
|
335 |
+
train_iterator = trange(
|
336 |
+
epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
|
337 |
+
)
|
338 |
+
set_seed(args) # Added here for reproducibility
|
339 |
+
for _ in train_iterator:
|
340 |
+
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
|
341 |
+
for step, batch in enumerate(epoch_iterator):
|
342 |
+
|
343 |
+
# Skip past any already trained steps if resuming training
|
344 |
+
if steps_trained_in_current_epoch > 0:
|
345 |
+
steps_trained_in_current_epoch -= 1
|
346 |
+
continue
|
347 |
+
|
348 |
+
inputs, labels = (batch, batch)
|
349 |
+
if inputs.shape[1] > 1024: continue
|
350 |
+
inputs = inputs.to(args.device)
|
351 |
+
labels = labels.to(args.device)
|
352 |
+
model.train()
|
353 |
+
outputs = model(inputs, labels=labels)
|
354 |
+
loss = outputs[0] # model outputs are always tuple in transformers (see doc)
|
355 |
+
|
356 |
+
if args.n_gpu > 1:
|
357 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
358 |
+
if args.gradient_accumulation_steps > 1:
|
359 |
+
loss = loss / args.gradient_accumulation_steps
|
360 |
+
|
361 |
+
if args.fp16:
|
362 |
+
with amp.scale_loss(loss, optimizer) as scaled_loss:
|
363 |
+
scaled_loss.backward()
|
364 |
+
else:
|
365 |
+
loss.backward()
|
366 |
+
|
367 |
+
tr_loss += loss.item()
|
368 |
+
if (step + 1) % args.gradient_accumulation_steps == 0:
|
369 |
+
if args.fp16:
|
370 |
+
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
|
371 |
+
else:
|
372 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
|
373 |
+
optimizer.step()
|
374 |
+
scheduler.step() # Update learning rate schedule
|
375 |
+
model.zero_grad()
|
376 |
+
global_step += 1
|
377 |
+
|
378 |
+
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
|
379 |
+
# Log metrics
|
380 |
+
if (
|
381 |
+
args.local_rank == -1 and args.evaluate_during_training
|
382 |
+
): # Only evaluate when single GPU otherwise metrics may not average well
|
383 |
+
results = evaluate(args, model, tokenizer)
|
384 |
+
for key, value in results.items():
|
385 |
+
tb_writer.add_scalar("eval_{}".format(key), value, global_step)
|
386 |
+
tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
|
387 |
+
tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
|
388 |
+
logging_loss = tr_loss
|
389 |
+
|
390 |
+
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
|
391 |
+
checkpoint_prefix = "checkpoint"
|
392 |
+
# Save model checkpoint
|
393 |
+
output_dir = os.path.join(args.output_dir, "{}-{}".format(checkpoint_prefix, global_step))
|
394 |
+
os.makedirs(output_dir, exist_ok=True)
|
395 |
+
model_to_save = (
|
396 |
+
model.module if hasattr(model, "module") else model
|
397 |
+
) # Take care of distributed/parallel training
|
398 |
+
model_to_save.save_pretrained(output_dir)
|
399 |
+
tokenizer.save_pretrained(output_dir)
|
400 |
+
|
401 |
+
torch.save(args, os.path.join(output_dir, "training_args.bin"))
|
402 |
+
logger.info("Saving model checkpoint to %s", output_dir)
|
403 |
+
|
404 |
+
_rotate_checkpoints(args, checkpoint_prefix)
|
405 |
+
|
406 |
+
torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
|
407 |
+
torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
|
408 |
+
logger.info("Saving optimizer and scheduler states to %s", output_dir)
|
409 |
+
|
410 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
411 |
+
epoch_iterator.close()
|
412 |
+
break
|
413 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
414 |
+
train_iterator.close()
|
415 |
+
break
|
416 |
+
|
417 |
+
if args.local_rank in [-1, 0]:
|
418 |
+
tb_writer.close()
|
419 |
+
|
420 |
+
return global_step, tr_loss / global_step
|
421 |
+
|
422 |
+
# Evaluation of some model
|
423 |
+
|
424 |
+
def evaluate(args, model: PreTrainedModel, tokenizer: PreTrainedTokenizer, df_trn, df_val, prefix="") -> Dict:
|
425 |
+
# Loop to handle MNLI double evaluation (matched, mis-matched)
|
426 |
+
eval_output_dir = args.output_dir
|
427 |
+
|
428 |
+
eval_dataset = load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=True)
|
429 |
+
os.makedirs(eval_output_dir, exist_ok=True)
|
430 |
+
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
|
431 |
+
# Note that DistributedSampler samples randomly
|
432 |
+
|
433 |
+
def collate(examples: List[torch.Tensor]):
|
434 |
+
if tokenizer._pad_token is None:
|
435 |
+
return pad_sequence(examples, batch_first=True)
|
436 |
+
return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
|
437 |
+
|
438 |
+
eval_sampler = SequentialSampler(eval_dataset)
|
439 |
+
eval_dataloader = DataLoader(
|
440 |
+
eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size, collate_fn=collate, drop_last = True
|
441 |
+
)
|
442 |
+
|
443 |
+
# multi-gpu evaluate
|
444 |
+
if args.n_gpu > 1:
|
445 |
+
model = torch.nn.DataParallel(model)
|
446 |
+
|
447 |
+
# Eval!
|
448 |
+
logger.info("***** Running evaluation {} *****".format(prefix))
|
449 |
+
logger.info(" Num examples = %d", len(eval_dataset))
|
450 |
+
logger.info(" Batch size = %d", args.eval_batch_size)
|
451 |
+
eval_loss = 0.0
|
452 |
+
nb_eval_steps = 0
|
453 |
+
model.eval()
|
454 |
+
|
455 |
+
for batch in tqdm(eval_dataloader, desc="Evaluating"):
|
456 |
+
inputs, labels = (batch, batch)
|
457 |
+
inputs = inputs.to(args.device)
|
458 |
+
labels = labels.to(args.device)
|
459 |
+
|
460 |
+
with torch.no_grad():
|
461 |
+
outputs = model(inputs, labels=labels)
|
462 |
+
lm_loss = outputs[0]
|
463 |
+
eval_loss += lm_loss.mean().item()
|
464 |
+
nb_eval_steps += 1
|
465 |
+
|
466 |
+
eval_loss = eval_loss / nb_eval_steps
|
467 |
+
perplexity = torch.exp(torch.tensor(eval_loss))
|
468 |
+
|
469 |
+
result = {"perplexity": perplexity}
|
470 |
+
|
471 |
+
output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
|
472 |
+
with open(output_eval_file, "w") as writer:
|
473 |
+
logger.info("***** Eval results {} *****".format(prefix))
|
474 |
+
for key in sorted(result.keys()):
|
475 |
+
logger.info(" %s = %s", key, str(result[key]))
|
476 |
+
writer.write("%s = %s\n" % (key, str(result[key])))
|
477 |
+
|
478 |
+
return result
|
479 |
+
|
480 |
+
def main(df_trn, df_val):
|
481 |
+
args = Args()
|
482 |
+
|
483 |
+
if args.should_continue:
|
484 |
+
sorted_checkpoints = _sorted_checkpoints(args)
|
485 |
+
if len(sorted_checkpoints) == 0:
|
486 |
+
raise ValueError("Used --should_continue but no checkpoint was found in --output_dir.")
|
487 |
+
else:
|
488 |
+
args.model_name_or_path = sorted_checkpoints[-1]
|
489 |
+
|
490 |
+
if (
|
491 |
+
os.path.exists(args.output_dir)
|
492 |
+
and os.listdir(args.output_dir)
|
493 |
+
and args.do_train
|
494 |
+
and not args.overwrite_output_dir
|
495 |
+
and not args.should_continue
|
496 |
+
):
|
497 |
+
raise ValueError(
|
498 |
+
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
|
499 |
+
args.output_dir
|
500 |
+
)
|
501 |
+
)
|
502 |
+
|
503 |
+
# Setup CUDA, GPU & distributed training
|
504 |
+
device = torch.device("cuda")
|
505 |
+
args.n_gpu = torch.cuda.device_count()
|
506 |
+
args.device = device
|
507 |
+
|
508 |
+
# Setup logging
|
509 |
+
logging.basicConfig(
|
510 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
511 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
512 |
+
level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
|
513 |
+
)
|
514 |
+
logger.warning(
|
515 |
+
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
516 |
+
args.local_rank,
|
517 |
+
device,
|
518 |
+
args.n_gpu,
|
519 |
+
bool(args.local_rank != -1),
|
520 |
+
args.fp16,
|
521 |
+
)
|
522 |
+
|
523 |
+
# Set seed
|
524 |
+
set_seed(args)
|
525 |
+
|
526 |
+
config = AutoConfig.from_pretrained(args.config_name, cache_dir=args.cache_dir)
|
527 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, cache_dir=args.cache_dir)
|
528 |
+
model = AutoModelWithLMHead.from_pretrained(
|
529 |
+
args.model_name_or_path,
|
530 |
+
from_tf=False,
|
531 |
+
config=config,
|
532 |
+
cache_dir=args.cache_dir,
|
533 |
+
)
|
534 |
+
model.to(args.device)
|
535 |
+
|
536 |
+
logger.info("Training/evaluation parameters %s", args)
|
537 |
+
|
538 |
+
# Training
|
539 |
+
if args.do_train:
|
540 |
+
train_dataset = load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=False)
|
541 |
+
|
542 |
+
global_step, tr_loss = train(args, train_dataset, model, tokenizer)
|
543 |
+
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
|
544 |
+
|
545 |
+
# Saving best-practices: if you use save_pretrained for the model and tokenizer, you can reload them using from_pretrained()
|
546 |
+
if args.do_train:
|
547 |
+
# Create output directory if needed
|
548 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
549 |
+
|
550 |
+
logger.info("Saving model checkpoint to %s", args.output_dir)
|
551 |
+
# Save a trained model, configuration and tokenizer using `save_pretrained()`.
|
552 |
+
# They can then be reloaded using `from_pretrained()`
|
553 |
+
model_to_save = (
|
554 |
+
model.module if hasattr(model, "module") else model
|
555 |
+
) # Take care of distributed/parallel training
|
556 |
+
model_to_save.save_pretrained(args.output_dir)
|
557 |
+
tokenizer.save_pretrained(args.output_dir)
|
558 |
+
|
559 |
+
# Good practice: save your training arguments together with the trained model
|
560 |
+
torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
|
561 |
+
|
562 |
+
# Load a trained model and vocabulary that you have fine-tuned
|
563 |
+
model = AutoModelWithLMHead.from_pretrained(args.output_dir)
|
564 |
+
tokenizer = AutoTokenizer.from_pretrained(args.output_dir)
|
565 |
+
model.to(args.device)
|
566 |
+
|
567 |
+
# Evaluation
|
568 |
+
results = {}
|
569 |
+
if args.do_eval and args.local_rank in [-1, 0]:
|
570 |
+
checkpoints = [args.output_dir]
|
571 |
+
if args.eval_all_checkpoints:
|
572 |
+
checkpoints = list(
|
573 |
+
os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
|
574 |
+
)
|
575 |
+
logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging
|
576 |
+
logger.info("Evaluate the following checkpoints: %s", checkpoints)
|
577 |
+
for checkpoint in checkpoints:
|
578 |
+
global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
|
579 |
+
prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
|
580 |
+
|
581 |
+
model = AutoModelWithLMHead.from_pretrained(checkpoint)
|
582 |
+
model.to(args.device)
|
583 |
+
result = evaluate(args, model, tokenizer, df_trn, df_val, prefix=prefix)
|
584 |
+
result = dict((k + "_{}".format(global_step), v) for k, v in result.items())
|
585 |
+
results.update(result)
|
586 |
+
|
587 |
+
return results
|
588 |
+
|
589 |
+
df = df.rename(columns={'Answer': 'response'})
|
590 |
+
df = df.rename(columns={'Question': 'context'})
|
591 |
+
|
592 |
+
df
|
593 |
+
|
594 |
+
main(df,df)
|
595 |
+
|
596 |
+
test_chatbot = []
|
597 |
+
text = str(input())
|
598 |
+
# for i in range(len(test_query)):
|
599 |
+
tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')
|
600 |
+
model = AutoModelWithLMHead.from_pretrained('output-small-save')
|
601 |
+
# append the new user input tokens to the chat history
|
602 |
+
bot_input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors='pt')
|
603 |
+
print("Patient: {} \n".format(text))
|
604 |
+
print("Reference: {} \n".format(text))
|
605 |
+
|
606 |
+
|
607 |
+
# generated a response while limiting the total chat history to 1000 tokens,
|
608 |
+
chat_history_ids = model.generate(
|
609 |
+
bot_input_ids, max_length=100,
|
610 |
+
pad_token_id=tokenizer.eos_token_id,
|
611 |
+
no_repeat_ngram_size=3,
|
612 |
+
do_sample=True,
|
613 |
+
top_k=10,
|
614 |
+
top_p=0.7,
|
615 |
+
temperature = 0.8
|
616 |
+
)
|
617 |
+
|
618 |
+
# pretty print last ouput tokens from bot
|
619 |
+
print("Predict: {} \n\n".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))
|
620 |
+
test_chatbot.append(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True))
|
621 |
+
|
622 |
+
print(len(test_chatbot))
|
623 |
+
|