Youssefk commited on
Commit
95f8397
1 Parent(s): e8cee6f
Files changed (1) hide show
  1. app.py +2 -765
app.py CHANGED
@@ -7,770 +7,6 @@ st.set_page_config(
7
  page_icon=":robot:"
8
  )
9
 
10
- #########################
11
- #######################""
12
-
13
- import streamlit as st
14
- #from streamlit_chat import message
15
- import requests
16
- from transformers import AutoModelWithLMHead, AutoTokenizer
17
-
18
-
19
- import streamlit as st
20
- #from streamlit_chat import message
21
- import requests
22
- from transformers import AutoModelWithLMHead, AutoTokenizer
23
-
24
- # st.write("yoyoyo")
25
- import pandas as pd
26
-
27
- data = {'Question': ['What did Conan and Heiji see at the museum?',
28
- 'What did Natsumi Kosaka ask for?',
29
- 'What did Heiji say about the time?',
30
- "What did Conan figure out about Kid's message?",
31
- 'What did Heiji realize about the "Shining Sky chamber"?',
32
- 'What did Kid do at Osaka Castle?',
33
- 'What did Conan ask Nishino?',
34
- 'Where did Nakamori take the egg?',
35
- 'What did Kid do at the Haginochaya electric substation?',
36
- 'How did Kid get to the warehouse?',
37
- 'Who did Conan find in the warehouse?',
38
- 'What did Kid do to escape from the warehouse?',
39
- 'What happened to Kid at the end?','What is the Memories Egg?',
40
- 'How many of the Fabergé eggs have been found so far?',
41
- 'Who currently owns the Memories Egg?',
42
- 'Where is the Suzuki corporation planning to display the Memories Egg?',
43
- 'Who is Kaito Kid?',
44
- 'What do the police believe "between the dusk of the Lion and the dawn of the Virgin" means?',
45
- 'Who did the police ask to help protect the egg?',
46
- 'Where do the Detective Boys go while Kogoro, Ran, and Conan go to Osaka?',
47
- 'What riddle does Professor Agasa give the Detective Boys?',
48
- 'Who is Sergei Ovchinnikov?',
49
- 'Who is Shoichi Inui?',
50
- 'What is the value of the Memories Egg?',
51
- 'What is inside the Memories Egg?',
52
- 'What is the significance of the lock on the front of the Memories Egg?',
53
- 'Why is the Tsarina missing from the Memories Egg?',
54
- 'Who is planning to steal the Memories Egg and what is their message?','Who is the thief?',
55
- 'What is the target of the theft?',
56
- 'Who is the owner of the Imperial Easter Egg?',
57
- 'Where is the Imperial Easter Egg located?',
58
- 'When is the theft planned to take place?',
59
- 'Is there an advanced notice of the theft?',
60
- 'What is the Memories Egg?',
61
- 'Who is Kaitou Kid?',
62
- 'Has Kaitou Kid stolen anything before?',
63
- 'Is there anyone trying to stop Kaitou Kid from stealing the Imperial Easter Egg?','Who is Conan Edogawa?',
64
- 'What happened to Shinichi Kudo?',
65
- "What is Conan's goal?",
66
- 'How does Conan plan to achieve his goal?',
67
- 'Who is Kogoro Mouri?',
68
- 'Who is Ran Mouri?',
69
- 'Who is Juzo Megure?',
70
- 'Who is Ninzaburo Shiratori?',
71
- 'Who is Wataru Takagi?',
72
- 'Who is Hiroshi Agasa?',
73
- 'Who is Sonoko Suzuki?',
74
- 'Who is Ai Haibara?',
75
- 'Who is Ayumi Yoshida?',
76
- 'Who is Mitsuhiko Tsuburaya?',
77
- 'Who is Kaitou Kid?',
78
- 'Who is Heiji Hattori?',
79
- 'Who is Kazuha Toyama?',
80
- 'Who is Ginzo Nakamori?',
81
- 'Who is Shintaro Chaki?',
82
- 'Who is Shiro Suzuki?',
83
- 'What was Ayumi doing when her mother told her to go to bed?',
84
- 'What happened when Ayumi went to bed?',
85
- 'Did Ayumi ask Kaito Kid if he was Dracula?',
86
- 'What did Kaito Kid tell Ayumi?',
87
- 'What did Kaito Kid do before he left Ayumi?',
88
- 'What happened when the police helicopter arrived?',
89
- 'Did Ayumi tell her friends about meeting Kaito Kid?',
90
- 'What did Conan think about Kaito Kid?',
91
- 'What is the Memories Egg?',
92
- 'What did Kaito Kid announce in his cryptic fashion?'],
93
- 'Answer': ["They saw Natsumi Kosaka, the owner of a sweetshop and her family's assistant Kuranosuke Sawabe argue with Nishino.",
94
- 'She asked for an urgent meeting with Chairman Suzuki because she saw the picture of the Imperial Easter egg on the leaflets announcing the exhibition and realized that this egg looked different from the sketch her great-grandfather made.',
95
- 'Heiji said "that\'s interesting. 3 AM looks like a "L" and now we\'ll almost have a "he"."',
96
- 'Conan figured out the second part of Kid\'s message - "he" is the twelfth character of the phrase. Kid didn\'t mean 3 AM, but 7:20 PM.',
97
- 'Heiji realized that "Shining Sky chamber" was meant to refer to the Tsuuten Tower because there is a weather station on top of Tsuuten Tower that "shines".',
98
- 'Kid set off fireworks at Osaka Castle to divert attention away from Tsuuten Tower.',
99
- 'Conan asked Nishino if he knows where the egg is.',
100
- 'Nakamori took the egg to a different secret location.',
101
- 'Kid planted bombs at the station to watch where emergency power is turned back on after the blackout, helping him figure out where the egg actually is.',
102
- 'Kid flew to the warehouse on his hang glider, chased by Conan on his skateboard.',
103
- 'Conan found Kid, who had already taken the egg and had knocked Nakamori and his officers out.',
104
- 'Kid activated his car gun, filling the room with smoke and used the confusion to fly away.',
105
- 'Kid was shot in the right eye and crashed, falling into the sea.','The Memories Egg is a rare Fabergé egg that was originally a gift from the Russian czar to his wife on Easter Sunday.',
106
- 'Fifty Fabergé eggs have been found worldwide, meaning the Memories Egg will be the fifty-first piece.',
107
- 'The Suzuki corporation currently owns the Memories Egg.',
108
- 'The Suzuki corporation plans to display the Memories Egg in the Modern Arts museum in Osaka beginning on August 23rd.',
109
- 'Kaito Kid is a notorious thief who is planning to steal the Memories Egg.',
110
- 'The police believe that "between the dusk of the Lion and the dawn of the Virgin" indicates the day Kaito Kid plans to commit his heist. The astrological sign Leo ends on August 23 and the astrological sign Virgo begins on August 23, meaning Kaito Kid wants to steal the egg between dusk on August 22 and dawn on August 23.',
111
- "Following Director Suzuki's wishes, the police asked Kogoro Mori to help protect the egg.",
112
- 'The Detective Boys visit Professor Agasa.',
113
- 'Professor Agasa\'s riddle is: "I (meaning Agasa) have many grandchildren, how old are they?"',
114
- 'Sergei Ovchinnikov is a high-level representative of the Russian Embassy.',
115
- 'Shoichi Inui is an arts dealer.',
116
- 'The Memories Egg is valued at 600 million yen.',
117
- 'The Memories Egg contains several figures, Tsar Nicholas II and his family crowded together around a book, all made of gold.',
118
- "The lock on the front of the Memories Egg is for a key, and when a key is inserted there, the pages of the golden book on the Tsar's knees begin to turn.",
119
- 'The Tsarina is missing from the Memories Egg, which is odd to Conan as the egg was supposed to be a gift to her. Chairman Suzuki says that the egg was created in a time of great financial hardship for Russia.',
120
- 'Kaito Kid is planning to steal the Memories Egg, and his message includes a reference to the "Shining Sky Chamber," which Heiji and Kazuha try to decipher.','The thief is Kaitou Kid.',
121
- 'The target of the theft is the Imperial Easter Egg.',
122
- 'The owner of the Imperial Easter Egg is the Suzuki Financial Group.',
123
- 'The Imperial Easter Egg is located at the Suzuki Modern Art Museum in Osaka.',
124
- 'The theft is planned to take place on August 22.',
125
- 'Yes, there is an advanced notice of the theft. The notice says, "Between the dusk of the Lion and the dawn of the Virgin, when the second hand on the clock indicates the twelfth symbol, I will take the Memories Egg from Shining Sky Chamber."',
126
- 'The Memories Egg is another name for the Imperial Easter Egg.',
127
- 'Kaitou Kid is a master thief who often targets valuable items and leaves challenging clues for the authorities to solve.',
128
- 'Yes, Kaitou Kid has a reputation for being a skilled and daring thief who has stolen many valuable items in the past.',
129
- 'Yes, there are likely to be security measures in place at the museum to prevent the theft, and the police may also be involved in trying to catch Kaitou Kid.','Conan Edogawa is the alias used by Shinichi Kudo in his shrunken form after being exposed to the poison APTX 4869.',
130
- 'Shinichi Kudo was forced to swallow the poison APTX 4869 by two men in black, which de-aged his body but left his nervous system intact.',
131
- "Conan's goal is to hunt down the Black Organization and have them arrested for their crimes, as well as find an antidote to the APTX 4869.",
132
- 'Conan plans to make the washout detective Kogoro Mouri famous in hopes of attracting cases related to the Black Organization.',
133
- 'Kogoro Mouri is a private detective and the father of Ran Mouri, who is also a childhood friend of Shinichi Kudo.',
134
- 'Ran Mouri is the daughter of Kogoro Mouri and a childhood friend of Shinichi Kudo.',
135
- 'Juzo Megure is a Police Inspector in Division 1 of the Tokyo Metropolitan Police Department.',
136
- 'Ninzaburo Shiratori is the boyfriend of Sumiko Kobayashi.',
137
- "Wataru Takagi is a police sergeant and detective from the Tokyo Metropolitan Police District's Criminal Investigation First Division, and the love interest of Miwako Sato.",
138
- "Hiroshi Agasa is Shinichi Kudo's next door neighbor and family friend.",
139
- "Sonoko Suzuki is Ran Mouri's best friend and the girlfriend of Makoto Kyogoku, with whom she is currently in a long-distance relationship.",
140
- 'Ai Haibara is a former member of the Black Organization, known as Sherry, who is now on the run from them and lives with Professor Agasa.',
141
- 'Ayumi Yoshida is a student in Teitan Elementary School.',
142
- 'Mitsuhiko Tsuburaya is also a student in Teitan Elementary School.',
143
- 'Kaitou Kid is a master thief who first appeared 18 years ago in Paris.',
144
- 'Heiji Hattori is an Osakan high school detective and a childhood friend and romantic interest of Kazuha Toyama.',
145
- 'Kazuha Toyama is a childhood friend and the romantic interest of Heiji Hattori.',
146
- 'Ginzo Nakamori is an inspector for the Tokyo district who is nominally devoted to fraud cases, but spends most of his time and energy capturing Kaitou Kid.',
147
- "Shintaro Chaki is the superintendent of the Tokyo Metropolitan Police 2nd Division and Ginzo Nakamori's direct superior.",
148
- "Shiro Suzuki is the chairman and CEO of the Suzuki family and Sonoko's father, with the second wealthiest family after Renya Karasuma.",
149
- 'Ayumi was watching a vampire movie on TV.',
150
- 'Ayumi saw a strange shadow on her balcony, which turned out to be Kaito Kid, the master thief.',
151
- 'Yes, Ayumi asked Kaito Kid if he was Dracula because she was still impressed by the vampire movie.',
152
- "Kaito Kid told Ayumi that he wasn't Dracula, he just needed a little rest, and that she shouldn't tell anyone she had seen him.",
153
- "Kaito Kid gently pressed a kiss to the back of Ayumi's hand before he left.",
154
- 'The police helicopter arrived, and Inspector Ginzo Nakamori shouted that he had spotted Kaito Kid and they needed to catch him.',
155
- 'Yes, Ayumi excitedly told her friends at school that she had met "handsome" Kaito Kid.',
156
- 'Conan thought that he would catch the master thief one day.',
157
- 'The Memories Egg is a priceless egg made by famous jeweler Fabergé and belonged to the Russian Imperial family, the Romanovs.',
158
- "Kaito Kid recently announced his new heist in his usual cryptic fashion: Between the dusk of the Lion and the dawn of the Virgin, when the second hand on the clock indicates the twelfth symbol, I will take the Memories Egg from Shining Sky chamber. The last wizard of the century, Kaito Kid."]}
159
-
160
-
161
- df = pd.DataFrame(data)
162
-
163
- # ! pip -q install transformers
164
-
165
- import torch
166
- import os
167
-
168
-
169
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-large")
170
- model = AutoModelWithLMHead.from_pretrained("microsoft/DialoGPT-large")
171
-
172
- """
173
- Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).
174
- GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned
175
- using a masked language modeling (MLM) loss.
176
- """
177
-
178
- import glob
179
- import logging
180
- import os
181
- import pickle
182
- import random
183
- import re
184
- import shutil
185
- from typing import Dict, List, Tuple
186
- import json
187
-
188
- import pandas as pd
189
- import numpy as np
190
- import torch
191
-
192
- from sklearn.model_selection import train_test_split
193
-
194
- from torch.nn.utils.rnn import pad_sequence
195
- from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler
196
- from torch.utils.data.distributed import DistributedSampler
197
- from tqdm.notebook import tqdm, trange
198
-
199
- from pathlib import Path
200
-
201
- from transformers import (
202
- MODEL_WITH_LM_HEAD_MAPPING,
203
- WEIGHTS_NAME,
204
- AdamW,
205
- AutoConfig,
206
- AutoModelWithLMHead,
207
- AutoTokenizer,
208
- PreTrainedModel,
209
- PreTrainedTokenizer,
210
- get_linear_schedule_with_warmup,
211
- )
212
-
213
-
214
- try:
215
- from torch.utils.tensorboard import SummaryWriter
216
- except ImportError:
217
- from tensorboardX import SummaryWriter
218
-
219
- # Configs
220
- logger = logging.getLogger(__name__)
221
-
222
- MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
223
- MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
224
-
225
- # Args to allow for easy convertion of python script to notebook
226
- class Args():
227
- def __init__(self):
228
- self.output_dir = 'output-small-save'
229
- self.model_type = 'gpt2'
230
- self.model_name_or_path = 'microsoft/DialoGPT-small'
231
- self.config_name = 'microsoft/DialoGPT-small'
232
- self.tokenizer_name = 'microsoft/DialoGPT-small'
233
- self.cache_dir = 'cached'
234
- self.block_size = 120
235
- self.do_train = True
236
- self.do_eval = True
237
- self.evaluate_during_training = False
238
- self.per_gpu_train_batch_size = 4
239
- self.per_gpu_eval_batch_size = 4
240
- self.gradient_accumulation_steps = 1
241
- self.learning_rate = 5e-5
242
- self.weight_decay = 0.0
243
- self.adam_epsilon = 1e-8
244
- self.max_grad_norm = 1.0
245
- self.num_train_epochs = 5
246
- self.max_steps = -1
247
- self.warmup_steps = 0
248
- self.logging_steps = 1000
249
- self.save_steps = 3500
250
- self.save_total_limit = None
251
- self.eval_all_checkpoints = False
252
- self.no_cuda = False
253
- self.overwrite_output_dir = True
254
- self.overwrite_cache = True
255
- self.should_continue = False
256
- self.seed = 42
257
- self.local_rank = -1
258
- self.fp16 = False
259
- self.fp16_opt_level = 'O1'
260
-
261
- args = Args()
262
-
263
- df.head()
264
-
265
- def construct_conv(row, tokenizer, eos = True):
266
- flatten = lambda l: [item for sublist in l for item in sublist]
267
- conv = list(reversed([tokenizer.encode(x) + [tokenizer.eos_token_id] for x in row]))
268
- conv = flatten(conv)
269
- return conv
270
-
271
- class ConversationDataset(Dataset):
272
- def __init__(self, tokenizer: PreTrainedTokenizer, args, df, block_size=512):
273
-
274
- block_size = block_size - (tokenizer.model_max_length - tokenizer.max_len_single_sentence)
275
-
276
- directory = args.cache_dir
277
- cached_features_file = os.path.join(
278
- directory, args.model_type + "_cached_lm_" + str(block_size)
279
- )
280
-
281
- if os.path.exists(cached_features_file) and not args.overwrite_cache:
282
- logger.info("Loading features from cached file %s", cached_features_file)
283
- with open(cached_features_file, "rb") as handle:
284
- self.examples = pickle.load(handle)
285
- else:
286
- logger.info("Creating features from dataset file at %s", directory)
287
-
288
- self.examples = []
289
- for _, row in df.iterrows():
290
- conv = construct_conv(row, tokenizer)
291
- self.examples.append(conv)
292
-
293
- logger.info("Saving features into cached file %s", cached_features_file)
294
- with open(cached_features_file, "wb") as handle:
295
- pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
296
-
297
- def __len__(self):
298
- return len(self.examples)
299
-
300
- def __getitem__(self, item):
301
- return torch.tensor(self.examples[item], dtype=torch.long)
302
-
303
- # Cacheing and storing of data/checkpoints
304
-
305
- def load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=False):
306
- return ConversationDataset(tokenizer, args, df_val if evaluate else df_trn)
307
-
308
-
309
- def set_seed(args):
310
- random.seed(args.seed)
311
- np.random.seed(args.seed)
312
- torch.manual_seed(args.seed)
313
- if args.n_gpu > 0:
314
- torch.cuda.manual_seed_all(args.seed)
315
-
316
-
317
- def _sorted_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]:
318
- ordering_and_checkpoint_path = []
319
-
320
- glob_checkpoints = glob.glob(os.path.join(args.output_dir, "{}-*".format(checkpoint_prefix)))
321
-
322
- for path in glob_checkpoints:
323
- if use_mtime:
324
- ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
325
- else:
326
- regex_match = re.match(".*{}-([0-9]+)".format(checkpoint_prefix), path)
327
- if regex_match and regex_match.groups():
328
- ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
329
-
330
- checkpoints_sorted = sorted(ordering_and_checkpoint_path)
331
- checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
332
- return checkpoints_sorted
333
-
334
-
335
- def _rotate_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> None:
336
- if not args.save_total_limit:
337
- return
338
- if args.save_total_limit <= 0:
339
- return
340
-
341
- # Check if we should delete older checkpoint(s)
342
- checkpoints_sorted = _sorted_checkpoints(args, checkpoint_prefix, use_mtime)
343
- if len(checkpoints_sorted) <= args.save_total_limit:
344
- return
345
-
346
- number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)
347
- checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
348
- for checkpoint in checkpoints_to_be_deleted:
349
- logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
350
- shutil.rmtree(checkpoint)
351
-
352
- def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[int, float]:
353
- """ Train the model """
354
- if args.local_rank in [-1, 0]:
355
- tb_writer = SummaryWriter()
356
-
357
- args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
358
-
359
- def collate(examples: List[torch.Tensor]):
360
- if tokenizer._pad_token is None:
361
- return pad_sequence(examples, batch_first=True)
362
- return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
363
-
364
- train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
365
- train_dataloader = DataLoader(
366
- train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=collate, drop_last = True
367
- )
368
-
369
- if args.max_steps > 0:
370
- t_total = args.max_steps
371
- args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
372
- else:
373
- t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
374
-
375
- model = model.module if hasattr(model, "module") else model # Take care of distributed/parallel training
376
- model.resize_token_embeddings(len(tokenizer))
377
- # add_special_tokens_(model, tokenizer)
378
-
379
-
380
- # Prepare optimizer and schedule (linear warmup and decay)
381
- no_decay = ["bias", "LayerNorm.weight"]
382
- optimizer_grouped_parameters = [
383
- {
384
- "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
385
- "weight_decay": args.weight_decay,
386
- },
387
- {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
388
- ]
389
- optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
390
- scheduler = get_linear_schedule_with_warmup(
391
- optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
392
- )
393
-
394
- # Check if saved optimizer or scheduler states exist
395
- if (
396
- args.model_name_or_path
397
- and os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt"))
398
- and os.path.isfile(os.path.join(args.model_name_or_path, "scheduler.pt"))
399
- ):
400
- # Load in optimizer and scheduler states
401
- optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
402
- scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
403
-
404
- if args.fp16:
405
- try:
406
- from apex import amp
407
- except ImportError:
408
- raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
409
- model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
410
-
411
- # multi-gpu training (should be after apex fp16 initialization)
412
- if args.n_gpu > 1:
413
- model = torch.nn.DataParallel(model)
414
-
415
- # Distributed training (should be after apex fp16 initialization)
416
- if args.local_rank != -1:
417
- model = torch.nn.parallel.DistributedDataParallel(
418
- model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
419
- )
420
-
421
- # Train!
422
- logger.info("***** Running training *****")
423
- logger.info(" Num examples = %d", len(train_dataset))
424
- logger.info(" Num Epochs = %d", args.num_train_epochs)
425
- logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
426
- logger.info(
427
- " Total train batch size (w. parallel, distributed & accumulation) = %d",
428
- args.train_batch_size
429
- * args.gradient_accumulation_steps
430
- * (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
431
- )
432
- logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
433
- logger.info(" Total optimization steps = %d", t_total)
434
-
435
- global_step = 0
436
- epochs_trained = 0
437
- steps_trained_in_current_epoch = 0
438
- # Check if continuing training from a checkpoint
439
- if args.model_name_or_path and os.path.exists(args.model_name_or_path):
440
- try:
441
- # set global_step to gobal_step of last saved checkpoint from model path
442
- checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
443
- global_step = int(checkpoint_suffix)
444
- epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
445
- steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
446
-
447
- logger.info(" Continuing training from checkpoint, will skip to saved global_step")
448
- logger.info(" Continuing training from epoch %d", epochs_trained)
449
- logger.info(" Continuing training from global step %d", global_step)
450
- logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
451
- except ValueError:
452
- logger.info(" Starting fine-tuning.")
453
-
454
- tr_loss, logging_loss = 0.0, 0.0
455
-
456
- model.zero_grad()
457
- train_iterator = trange(
458
- epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
459
- )
460
- set_seed(args) # Added here for reproducibility
461
- for _ in train_iterator:
462
- epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
463
- for step, batch in enumerate(epoch_iterator):
464
-
465
- # Skip past any already trained steps if resuming training
466
- if steps_trained_in_current_epoch > 0:
467
- steps_trained_in_current_epoch -= 1
468
- continue
469
-
470
- inputs, labels = (batch, batch)
471
- if inputs.shape[1] > 1024: continue
472
- inputs = inputs.to(args.device)
473
- labels = labels.to(args.device)
474
- model.train()
475
- outputs = model(inputs, labels=labels)
476
- loss = outputs[0] # model outputs are always tuple in transformers (see doc)
477
-
478
- if args.n_gpu > 1:
479
- loss = loss.mean() # mean() to average on multi-gpu parallel training
480
- if args.gradient_accumulation_steps > 1:
481
- loss = loss / args.gradient_accumulation_steps
482
-
483
- if args.fp16:
484
- with amp.scale_loss(loss, optimizer) as scaled_loss:
485
- scaled_loss.backward()
486
- else:
487
- loss.backward()
488
-
489
- tr_loss += loss.item()
490
- if (step + 1) % args.gradient_accumulation_steps == 0:
491
- if args.fp16:
492
- torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
493
- else:
494
- torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
495
- optimizer.step()
496
- scheduler.step() # Update learning rate schedule
497
- model.zero_grad()
498
- global_step += 1
499
-
500
- if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
501
- # Log metrics
502
- if (
503
- args.local_rank == -1 and args.evaluate_during_training
504
- ): # Only evaluate when single GPU otherwise metrics may not average well
505
- results = evaluate(args, model, tokenizer)
506
- for key, value in results.items():
507
- tb_writer.add_scalar("eval_{}".format(key), value, global_step)
508
- tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
509
- tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
510
- logging_loss = tr_loss
511
-
512
- if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
513
- checkpoint_prefix = "checkpoint"
514
- # Save model checkpoint
515
- output_dir = os.path.join(args.output_dir, "{}-{}".format(checkpoint_prefix, global_step))
516
- os.makedirs(output_dir, exist_ok=True)
517
- model_to_save = (
518
- model.module if hasattr(model, "module") else model
519
- ) # Take care of distributed/parallel training
520
- model_to_save.save_pretrained(output_dir)
521
- tokenizer.save_pretrained(output_dir)
522
-
523
- torch.save(args, os.path.join(output_dir, "training_args.bin"))
524
- logger.info("Saving model checkpoint to %s", output_dir)
525
-
526
- _rotate_checkpoints(args, checkpoint_prefix)
527
-
528
- torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
529
- torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
530
- logger.info("Saving optimizer and scheduler states to %s", output_dir)
531
-
532
- if args.max_steps > 0 and global_step > args.max_steps:
533
- epoch_iterator.close()
534
- break
535
- if args.max_steps > 0 and global_step > args.max_steps:
536
- train_iterator.close()
537
- break
538
-
539
- if args.local_rank in [-1, 0]:
540
- tb_writer.close()
541
-
542
- return global_step, tr_loss / global_step
543
-
544
- # Evaluation of some model
545
-
546
- def evaluate(args, model: PreTrainedModel, tokenizer: PreTrainedTokenizer, df_trn, df_val, prefix="") -> Dict:
547
- # Loop to handle MNLI double evaluation (matched, mis-matched)
548
- eval_output_dir = args.output_dir
549
-
550
- eval_dataset = load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=True)
551
- os.makedirs(eval_output_dir, exist_ok=True)
552
- args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
553
- # Note that DistributedSampler samples randomly
554
-
555
- def collate(examples: List[torch.Tensor]):
556
- if tokenizer._pad_token is None:
557
- return pad_sequence(examples, batch_first=True)
558
- return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
559
-
560
- eval_sampler = SequentialSampler(eval_dataset)
561
- eval_dataloader = DataLoader(
562
- eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size, collate_fn=collate, drop_last = True
563
- )
564
-
565
- # multi-gpu evaluate
566
- if args.n_gpu > 1:
567
- model = torch.nn.DataParallel(model)
568
-
569
- # Eval!
570
- logger.info("***** Running evaluation {} *****".format(prefix))
571
- logger.info(" Num examples = %d", len(eval_dataset))
572
- logger.info(" Batch size = %d", args.eval_batch_size)
573
- eval_loss = 0.0
574
- nb_eval_steps = 0
575
- model.eval()
576
-
577
- for batch in tqdm(eval_dataloader, desc="Evaluating"):
578
- inputs, labels = (batch, batch)
579
- inputs = inputs.to(args.device)
580
- labels = labels.to(args.device)
581
-
582
- with torch.no_grad():
583
- outputs = model(inputs, labels=labels)
584
- lm_loss = outputs[0]
585
- eval_loss += lm_loss.mean().item()
586
- nb_eval_steps += 1
587
-
588
- eval_loss = eval_loss / nb_eval_steps
589
- perplexity = torch.exp(torch.tensor(eval_loss))
590
-
591
- result = {"perplexity": perplexity}
592
-
593
- output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
594
- with open(output_eval_file, "w") as writer:
595
- logger.info("***** Eval results {} *****".format(prefix))
596
- for key in sorted(result.keys()):
597
- logger.info(" %s = %s", key, str(result[key]))
598
- writer.write("%s = %s\n" % (key, str(result[key])))
599
-
600
- return result
601
-
602
- def main(df_trn, df_val):
603
- args = Args()
604
-
605
- if args.should_continue:
606
- sorted_checkpoints = _sorted_checkpoints(args)
607
- if len(sorted_checkpoints) == 0:
608
- raise ValueError("Used --should_continue but no checkpoint was found in --output_dir.")
609
- else:
610
- args.model_name_or_path = sorted_checkpoints[-1]
611
-
612
- if (
613
- os.path.exists(args.output_dir)
614
- and os.listdir(args.output_dir)
615
- and args.do_train
616
- and not args.overwrite_output_dir
617
- and not args.should_continue
618
- ):
619
- raise ValueError(
620
- "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
621
- args.output_dir
622
- )
623
- )
624
-
625
- # Setup CUDA, GPU & distributed training
626
- device = torch.device("cuda")
627
- args.n_gpu = torch.cuda.device_count()
628
- args.device = device
629
-
630
- # Setup logging
631
- logging.basicConfig(
632
- format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
633
- datefmt="%m/%d/%Y %H:%M:%S",
634
- level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
635
- )
636
- logger.warning(
637
- "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
638
- args.local_rank,
639
- device,
640
- args.n_gpu,
641
- bool(args.local_rank != -1),
642
- args.fp16,
643
- )
644
-
645
- # Set seed
646
- set_seed(args)
647
-
648
- config = AutoConfig.from_pretrained(args.config_name, cache_dir=args.cache_dir)
649
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, cache_dir=args.cache_dir)
650
- model = AutoModelWithLMHead.from_pretrained(
651
- args.model_name_or_path,
652
- from_tf=False,
653
- config=config,
654
- cache_dir=args.cache_dir,
655
- )
656
- model.to(args.device)
657
-
658
- logger.info("Training/evaluation parameters %s", args)
659
-
660
- # Training
661
- if args.do_train:
662
- train_dataset = load_and_cache_examples(args, tokenizer, df_trn, df_val, evaluate=False)
663
-
664
- global_step, tr_loss = train(args, train_dataset, model, tokenizer)
665
- logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
666
-
667
- # Saving best-practices: if you use save_pretrained for the model and tokenizer, you can reload them using from_pretrained()
668
- if args.do_train:
669
- # Create output directory if needed
670
- os.makedirs(args.output_dir, exist_ok=True)
671
-
672
- logger.info("Saving model checkpoint to %s", args.output_dir)
673
- # Save a trained model, configuration and tokenizer using `save_pretrained()`.
674
- # They can then be reloaded using `from_pretrained()`
675
- model_to_save = (
676
- model.module if hasattr(model, "module") else model
677
- ) # Take care of distributed/parallel training
678
- model_to_save.save_pretrained(args.output_dir)
679
- tokenizer.save_pretrained(args.output_dir)
680
-
681
- # Good practice: save your training arguments together with the trained model
682
- torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
683
-
684
- # Load a trained model and vocabulary that you have fine-tuned
685
- model = AutoModelWithLMHead.from_pretrained(args.output_dir)
686
- tokenizer = AutoTokenizer.from_pretrained(args.output_dir)
687
- model.to(args.device)
688
-
689
- # Evaluation
690
- results = {}
691
- if args.do_eval and args.local_rank in [-1, 0]:
692
- checkpoints = [args.output_dir]
693
- if args.eval_all_checkpoints:
694
- checkpoints = list(
695
- os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
696
- )
697
- logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging
698
- logger.info("Evaluate the following checkpoints: %s", checkpoints)
699
- for checkpoint in checkpoints:
700
- global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
701
- prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
702
-
703
- model = AutoModelWithLMHead.from_pretrained(checkpoint)
704
- model.to(args.device)
705
- result = evaluate(args, model, tokenizer, df_trn, df_val, prefix=prefix)
706
- result = dict((k + "_{}".format(global_step), v) for k, v in result.items())
707
- results.update(result)
708
-
709
- return results
710
-
711
- df = df.rename(columns={'Answer': 'response'})
712
- df = df.rename(columns={'Question': 'context'})
713
-
714
- df
715
-
716
- main(df,df)
717
-
718
- test_chatbot = []
719
- text = "Hello"
720
- # for i in range(len(test_query)):
721
- tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')
722
- model = AutoModelWithLMHead.from_pretrained('output-small-save')
723
- # append the new user input tokens to the chat history
724
- bot_input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors='pt')
725
- print("Patient: {} \n".format(text))
726
- print("Reference: {} \n".format(text))
727
-
728
-
729
- # generated a response while limiting the total chat history to 1000 tokens,
730
- chat_history_ids = model.generate(
731
- bot_input_ids, max_length=100,
732
- pad_token_id=tokenizer.eos_token_id,
733
- no_repeat_ngram_size=3,
734
- do_sample=True,
735
- top_k=10,
736
- top_p=0.7,
737
- temperature = 0.8
738
- )
739
-
740
- # pretty print last ouput tokens from bot
741
- st.write("Predict: {} \n\n".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))
742
- test_chatbot.append(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True))
743
-
744
- print(len(test_chatbot))
745
-
746
-
747
-
748
-
749
- text = 'Who is the thief'
750
- # for i in range(len(test_query)):
751
- tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')
752
- model = AutoModelWithLMHead.from_pretrained('output-small-save')
753
- # append the new user input tokens to the chat history
754
- bot_input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors='pt')
755
- print("Patient: {} \n".format(text))
756
- print("Reference: {} \n".format(text))
757
- chat_history_ids = model.generate(
758
- bot_input_ids, max_length=100,
759
- pad_token_id=tokenizer.eos_token_id,
760
- no_repeat_ngram_size=3,
761
- do_sample=True,
762
- top_k=10,
763
- top_p=0.7,
764
- temperature = 0.8
765
- )
766
-
767
- # pretty print last ouput tokens from bot
768
- st.write("Predict: {} \n\n".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))
769
-
770
-
771
-
772
- #######################""
773
- #########################""
774
  st.header("Hello - Welcome to SAI")
775
  st.write("""The Phantom Thief Kid sends a heist notice, warning of another heist. The police deduce that his next target is a recently discovered Fabergé egg, which Suzuki Modern Art Museum in Osaka will display on August 22. The night of the heist, Kid steals the egg and flies off, and Conan and Heiji give chase. However, in the middle of the chase, an unknown assailant shoots Kid in the right eye, and Kid apparently falls into the sea to his death. After recovering the egg, the police fruitlessly search for Kid's body.
776
 
@@ -795,6 +31,7 @@ if st.session_state['generated']:
795
  for i in range(len(st.session_state['generated'])-1, -1, -1):
796
  message(st.session_state["generated"][i], key=str(i))
797
  message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
798
-
799
  message("Tell me what happened?",is_user=True)
 
800
  user_input = get_text()
 
7
  page_icon=":robot:"
8
  )
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  st.header("Hello - Welcome to SAI")
11
  st.write("""The Phantom Thief Kid sends a heist notice, warning of another heist. The police deduce that his next target is a recently discovered Fabergé egg, which Suzuki Modern Art Museum in Osaka will display on August 22. The night of the heist, Kid steals the egg and flies off, and Conan and Heiji give chase. However, in the middle of the chase, an unknown assailant shoots Kid in the right eye, and Kid apparently falls into the sea to his death. After recovering the egg, the police fruitlessly search for Kid's body.
12
 
 
31
  for i in range(len(st.session_state['generated'])-1, -1, -1):
32
  message(st.session_state["generated"][i], key=str(i))
33
  message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
34
+ message("Detective!!")
35
  message("Tell me what happened?",is_user=True)
36
+
37
  user_input = get_text()