Ateeb commited on
Commit
60f8cd4
1 Parent(s): 88526e2

First version of the your-model-name model and tokenizer.

Browse files
__init__.py ADDED
File without changes
__pycache__/preprocess.cpython-37.pyc ADDED
Binary file (3.56 kB). View file
 
main.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from preprocess import Model, SquadDataset
2
+ from transformers import DistilBertForQuestionAnswering
3
+ from torch.utils.data import DataLoader
4
+ from transformers import AdamW
5
+ import torch
6
+ import subprocess
7
+
8
+ data = Model()
9
+ train_contexts, train_questions, train_answers = data.ArrangeData("livecheckcontainer")
10
+ val_contexts, val_questions, val_answers = data.ArrangeData("livecheckcontainer")
11
+ print(train_answers)
12
+
13
+ train_answers, train_contexts = data.add_end_idx(train_answers, train_contexts)
14
+ val_answers, val_contexts = data.add_end_idx(val_answers, val_contexts)
15
+
16
+ train_encodings, val_encodings = data.Tokenizer(train_contexts, train_questions, val_contexts, val_questions)
17
+
18
+ train_encodings = data.add_token_positions(train_encodings, train_answers)
19
+ val_encodings = data.add_token_positions(val_encodings, val_answers)
20
+
21
+ train_dataset = SquadDataset(train_encodings)
22
+ val_dataset = SquadDataset(val_encodings)
23
+
24
+
25
+
26
+ model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
27
+
28
+
29
+ device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
30
+
31
+ model.to(device)
32
+ model.train()
33
+
34
+ train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
35
+
36
+ optim = AdamW(model.parameters(), lr=5e-5)
37
+
38
+ for epoch in range(2):
39
+ print(epoch)
40
+ for batch in train_loader:
41
+ optim.zero_grad()
42
+ input_ids = batch['input_ids'].to(device)
43
+ attention_mask = batch['attention_mask'].to(device)
44
+ start_positions = batch['start_positions'].to(device)
45
+ end_positions = batch['end_positions'].to(device)
46
+ outputs = model(input_ids, attention_mask=attention_mask, start_positions=start_positions, end_positions=end_positions)
47
+ loss = outputs[0]
48
+ loss.backward()
49
+ optim.step()
50
+ print("Done")
51
+ model.eval()
52
+ model.save_pretrained("test-squad-trained")
53
+ data.tokenizer.save_pretrained("test-squad-trained")
54
+
55
+
56
+ subprocess.call(["git", "add","--all"])
57
+ subprocess.call(["git", "status"])
58
+ subprocess.call(["git", "commit", "-m", "First version of the your-model-name model and tokenizer."])
59
+ subprocess.call(["git", "push"])
60
+
preprocess.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from os import close
3
+ from pathlib import Path
4
+ from azure.cosmos import CosmosClient, PartitionKey, exceptions
5
+ from transformers import DistilBertTokenizerFast
6
+ import torch
7
+
8
+
9
+ class Model:
10
+
11
+ def __init__(self) -> None:
12
+ self.endPoint = "https://productdevelopmentstorage.documents.azure.com:443/"
13
+ self.primaryKey = "nVds9dPOkPuKu8RyWqigA1DIah4SVZtl1DIM0zDuRKd95an04QC0qv9TQIgrdtgluZo7Z0HXACFQgKgOQEAx1g=="
14
+ self.client = CosmosClient(self.endPoint, self.primaryKey)
15
+ self.tokenizer = None
16
+
17
+ def GetData(self, type):
18
+ database = self.client.get_database_client("squadstorage")
19
+ container = database.get_container_client(type)
20
+ item_list = list(container.read_all_items(max_item_count=10))
21
+ return item_list
22
+
23
+ def ArrangeData(self, type):
24
+ squad_dict = self.GetData(type)
25
+
26
+ contexts = []
27
+ questions = []
28
+ answers = []
29
+
30
+ for i in squad_dict:
31
+ contexts.append(i["context"])
32
+ questions.append(i["question"])
33
+ answers.append(i["answers"])
34
+
35
+ return contexts, questions, answers
36
+
37
+ def add_end_idx(self, answers, contexts):
38
+ for answer, context in zip(answers, contexts):
39
+ gold_text = answer['text'][0]
40
+ start_idx = answer['answer_start'][0]
41
+ end_idx = start_idx + len(gold_text)
42
+
43
+ if context[start_idx:end_idx] == gold_text:
44
+ answer['answer_end'] = end_idx
45
+ elif context[start_idx-1:end_idx-1] == gold_text:
46
+ answer['answer_start'] = start_idx - 1
47
+ answer['answer_end'] = end_idx - 1 # When the gold label is off by one character
48
+ elif context[start_idx-2:end_idx-2] == gold_text:
49
+ answer['answer_start'] = start_idx - 2
50
+ answer['answer_end'] = end_idx - 2 # When the gold label is off by two characters
51
+
52
+ return answers, contexts
53
+
54
+ def Tokenizer(self, train_contexts, train_questions, val_contexts, val_questions):
55
+ self.tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')
56
+
57
+ train_encodings = self.tokenizer(train_contexts, train_questions, truncation=True, padding=True)
58
+ val_encodings = self.tokenizer(val_contexts, val_questions, truncation=True, padding=True)
59
+
60
+ return train_encodings, val_encodings
61
+
62
+
63
+ def add_token_positions(self, encodings, answers):
64
+ start_positions = []
65
+ end_positions = []
66
+ for i in range(len(answers)):
67
+ start_positions.append(encodings.char_to_token(i, answers[i]['answer_start'][0]))
68
+ end_positions.append(encodings.char_to_token(i, answers[i]['answer_end'] - 1))
69
+
70
+ # if start position is None, the answer passage has been truncated
71
+
72
+ if start_positions[-1] is None:
73
+ start_positions[-1] = self.tokenizer.model_max_length
74
+ if end_positions[-1] is None:
75
+ end_positions[-1] = self.tokenizer.model_max_length
76
+
77
+ encodings.update({'start_positions': start_positions, 'end_positions': end_positions})
78
+ return encodings
79
+
80
+ # train_contexts, train_questions, train_answers = read_squad('squad/train-v2.0.json')
81
+ # val_contexts, val_questions, val_answers = read_squad('squad/dev-v2.0.json')
82
+
83
+
84
+
85
+
86
+
87
+ class SquadDataset(torch.utils.data.Dataset):
88
+ def __init__(self, encodings):
89
+ self.encodings = encodings
90
+
91
+ def __getitem__(self, idx):
92
+ return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
93
+
94
+ def __len__(self):
95
+ return len(self.encodings.input_ids)
96
+
test-squad-trained/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "distilbert-base-uncased",
3
+ "activation": "gelu",
4
+ "architectures": [
5
+ "DistilBertForQuestionAnswering"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "dim": 768,
9
+ "dropout": 0.1,
10
+ "hidden_dim": 3072,
11
+ "initializer_range": 0.02,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "distilbert",
14
+ "n_heads": 12,
15
+ "n_layers": 6,
16
+ "pad_token_id": 0,
17
+ "qa_dropout": 0.1,
18
+ "seq_classif_dropout": 0.2,
19
+ "sinusoidal_pos_embds": false,
20
+ "tie_weights_": true,
21
+ "transformers_version": "4.3.2",
22
+ "vocab_size": 30522
23
+ }
test-squad-trained/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:423cba4a34bfc72ad38bc33a07f81fd45f433c8e8f15383b8b35c95be8a1b26e
3
+ size 265498527
test-squad-trained/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
test-squad-trained/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"do_lower_case": true, "unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]", "tokenize_chinese_chars": true, "strip_accents": null, "model_max_length": 512, "name_or_path": "distilbert-base-uncased"}
test-squad-trained/vocab.txt ADDED
The diff for this file is too large to render. See raw diff