-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
405 lines (321 loc) · 12.5 KB
/
models.py
File metadata and controls
405 lines (321 loc) · 12.5 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
""" models
This module defines the classes of each model used in the API.
To add a new model:
1. Add Models_names
2. Add ML_task
3. Create new class:
def class NewModel(Model):
4. Create schema in schemas
5. Add endpoint in api
ToDo:
- Add max_new_tokens parameter
"""
# External
from codecarbon import track_emissions
from enum import Enum
# Required to run CNN model
#import tensorflow as tf
#import tensorflow.keras as keras
import numpy as np
import matplotlib.pyplot as plt
import random
# ---
from torch.nn import functional as F
import torch
# [bert]
from transformers import BertTokenizer, BertForMaskedLM
# [t5, codet5p_220m]
from transformers import T5Tokenizer, T5ForConditionalGeneration
# [codegen]
from transformers import AutoModelForCausalLM, AutoTokenizer
# [pythia-70m]
from transformers import GPTNeoXForCausalLM, AutoTokenizer
from transformers import T5ForConditionalGeneration, AutoTokenizer
# metrics
# Constants
RESULTS_DIR = 'results/'
class ML_task(Enum):
MLM = 1 # Masked Language Modeling
TRANSLATION = 2
CV = 3 # Computer Vision
CODE = 4
class models_names(Enum):
BERT = 1
T5 = 2
CodeGen = 3
CNN = 4
Pythia_70m = 5
Codet5p_220m = 6
class Model:
"""
Creates a default model
"""
def __init__(self, model_name : models_names = None, ml_task : ML_task = None):
self.name = model_name.name
# Masked Language Modeling - MLM
self.ml_task = ml_task.name
def predict(self, user_input : str) -> dict:
# Do prediction
prediction = "Not defined yet "
response = {
"prediction" : prediction
}
return response
def infer(self, text : str, model, tokenizer) -> str:
"""_summary_ Infer function to track
Args:
text (str): _description_
model (_type_): _description_
tokenizer (_type_): _description_
Returns:
str: _description_
"""
#input_ids = tokenizer(text, return_tensors="pt").input_ids
#outputs = model.generate(input_ids)
#return tokenizer.decode(outputs[0], skip_special_tokens=True)
response = None
return response
class LMBERTModel(Model):
"""
Creates a LM Bert model. Inherits from Model()
"""
def __init__(self):
super().__init__(models_names.BERT, ML_task.MLM)
def predict(self, user_input: str, n = 5):
#user_text = input('Enter text with [MASK]: ')
tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path = 'bert-base-uncased') # ./bert-base-uncased
# bert model for masked language modelling
model = BertForMaskedLM.from_pretrained(pretrained_model_name_or_path = 'bert-base-uncased', return_dict = True) # ./bert-base-uncased
# return_dict True to use mask token
response = {
"prediction" : self.infer(user_input, model, tokenizer)
}
return response
@track_emissions(project_name = "bert", output_file = RESULTS_DIR + "emissions_bert.csv")
def infer(self, text: str, model, tokenizer) -> str:
# tokenize
input_token = tokenizer.encode_plus(text, return_tensors = "pt")
mask_index = torch.where(input_token["input_ids"][0] == tokenizer.mask_token_id)
# generate
output = model(**input_token)
#tokens = model.generate(**inputs)
# decode
logits = output.logits
#print(logits)
softmax = F.softmax(logits, dim = -1)
#print(softmax)
#print(f"softmax shape:{softmax.shape}")
mask_word = softmax[0, mask_index, :]
#print(f"mask_word softmax function result {mask_word}")
# Get first n words
top_n = torch.topk(mask_word, 5, dim = 1)[1][0]
print(top_n)
# problem with decode
list_results = tokenizer.convert_ids_to_tokens(top_n)
prediction = str(list_results)
return prediction
class T5Model(Model):
"""
Creates a T5 model. Inherits from Model()
"""
def __init__(self):
super().__init__(models_names.T5, ML_task.TRANSLATION)
def predict(self, user_input: str):
#user_text = input('Enter text with [MASK]: ')
tokenizer = T5Tokenizer.from_pretrained("t5-small")
model = T5ForConditionalGeneration.from_pretrained("t5-small", low_cpu_mem_usage=True)
response = {
"prediction" : self.infer(user_input, model, tokenizer)
}
return response
@track_emissions(project_name = "t5", output_file = RESULTS_DIR + "emissions_t5.csv")
def infer(self, text: str, model, tokenizer) -> str:
# tokenize
input_ids = tokenizer(text, return_tensors="pt").input_ids
#inputs = tokenizer(text, return_tensors="pt")
# generate
outputs = model.generate(input_ids)
#tokens = model.generate(**inputs)
# decode
prediction = tokenizer.decode(outputs[0], skip_special_tokens=True)
return prediction
class CodeGenModel(Model):
"""_summary_ Creates a CodeGen model. Inherits from Model()
Args:
Model (_type_): _description_
"""
def __init__(self):
super().__init__(models_names.CodeGen, ML_task.CODE)
def predict(self, user_input: str):
checkpoint = "Salesforce/codegen-350M-mono"
model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map = 'auto', torch_dtype = 'auto')
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
#text = "def get_random_element(dictionary):"
#completion = model.generate(**tokenizer(text, return_tensors="pt"))
#completion = model.generate(**tokenizer(text, return_tensors="pt"),max_new_tokens =25)
response = {
"prediction" : self.infer(user_input,model,tokenizer),
}
return response
@track_emissions(project_name = "codegen", output_file = RESULTS_DIR + "emissions_codegen.csv")
def infer(self, text: str, model, tokenizer) -> str:
# tokenize
inputs = tokenizer(text, return_tensors="pt")
# generate
tokens = model.generate(**inputs)
# decode
prediction = tokenizer.decode(tokens[0])
return prediction
class Pythia_70mModel(Model):
"""_summary_ Creates a Pythia model. Inherits from Model()
Args:
Model (_type_): _description_
"""
def __init__(self):
super().__init__(models_names.Pythia_70m, ML_task.CODE)
def predict(self, user_input: str):
model = GPTNeoXForCausalLM.from_pretrained(
"EleutherAI/pythia-70m",
revision="step3000",
cache_dir="./pythia-70m/step3000",
)
tokenizer = AutoTokenizer.from_pretrained(
"EleutherAI/pythia-70m",
revision="step3000",
cache_dir="./pythia-70m/step3000",
)
#text = "def get_random_element(dictionary):"
#text = user_input
#inputs = tokenizer(text, return_tensors="pt")
#tokens = model.generate(**inputs)
response = {
"prediction" : self.infer(user_input,model,tokenizer),
}
return response
@track_emissions(project_name = "pythia", output_file = RESULTS_DIR + "emissions_pythia.csv")
def infer(self, text: str, model, tokenizer) -> str:
# tokenize
inputs = tokenizer(text, return_tensors="pt")
# generate
tokens = model.generate(**inputs)
# decode
prediction = tokenizer.decode(tokens[0])
return prediction
class Codet5p_220mModel(Model):
"""_summary_ Creates a Codet5p_220m model. Inherits from Model()
Args:
Model (_type_): _description_
"""
def __init__(self):
super().__init__(models_names.Codet5p_220m, ML_task.CODE)
def predict(self, user_input: str):
checkpoint = "Salesforce/codet5p-220m"
#device = "cpu" # for GPU usage or "cpu" for CPU usage
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
# torch_dtype = 'auto' not implemented
model = T5ForConditionalGeneration.from_pretrained(checkpoint, device_map = 'auto')
#text = "def get_random_element(my_dictionary):<extra_id_0>"
#text = user_input
# inputs = tokenizer.encode(text, return_tensors="pt").to(device)
# #outputs = model.generate(inputs, max_length=10,max_new_tokens = 30)
# outputs = model.generate(inputs, max_new_tokens = 30)
# prediction = tokenizer.decode(outputs[0], skip_special_tokens=True)
response = {
"prediction" : self.infer(user_input,model,tokenizer),
}
return response
@track_emissions(project_name = "codet5p", output_file = RESULTS_DIR + "emissions_codet5p.csv")
def infer(self, text: str, model, tokenizer) -> str:
inputs = tokenizer.encode(text, return_tensors="pt").to('cpu')
#outputs = model.generate(inputs, max_length=10,max_new_tokens = 30)
outputs = model.generate(inputs, max_new_tokens = 30)
prediction = tokenizer.decode(outputs[0], skip_special_tokens=True)
return prediction
class CNNModel(Model):
"""
Creates a LM Bert model. Inherits from Model()
"""
def __init__(self):
super().__init__(models_names.CNN, ML_task.CV)
def predict(self, user_input: str, n = 5):
dataset = "fashion"
label_names = {
0: "T-shirt/top",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle boot"
}
saved_model_dir = f"models/model_{dataset}.h5"
# Get test set
fashion_mnist=keras.datasets.fashion_mnist
(_, _), (x_test, y_test) = fashion_mnist.load_data()
# load model
try:
print(saved_model_dir)
model = keras.models.load_model(saved_model_dir)
print("Model loaded correctly")
except:
print("There is a problem with the file path")
def see_x_image(x,y,name=None,caption=True, save_dir="."):
'''
See image
'''
plt.figure()
plt.imshow((x.reshape((28,28))).astype("uint8"))
title=str(y)
if name:
title += " "+name
plt.title(title)
if caption:
plt.title(title)
print(save_dir)
plt.savefig(save_dir+"/"+dataset+"_image"+ ".png")
plt.axis("off")
if int(user_input) <= len(x_test):
ran = int(user_input)
print(" User entered ",user_input)
else:
# Get random number between 0 and len(x_test)
ran = random.randint(0, len(y_test))
print("Using random")
print(ran)
print(f"label of selected input: {y_test[ran]}")
#print(list(y_test[ran]).index(max(y_test[ran])))
label_name = label_names[y_test[ran]]
see_x_image(x_test[ran],y_test[ran],label_name,save_dir="./")
# Inference
# predict with that random
x_test = x_test.reshape(-1, 28, 28, 1)
print(x_test[ran:ran+1].shape)
#model_predict = model.predict(x_test[ran:ran+1])
#print(f"model_predict: {model_predict}")
#cat_pred = np.argmax(model_predict)
cat_pred = self.infer(x_test[ran:ran+1], model)
print(f"argmax: {cat_pred}")
label = f"{cat_pred} : {label_names[cat_pred]}"
is_correct = False
if y_test[ran] == cat_pred:
is_correct = True
print("Prediction: ",cat_pred)
print("Prediction clothes: ", label_names[cat_pred])
print("Correct label: ",y_test[ran])
print(f"is_correct: ", is_correct)
response = {
"prediction": label,
"is_correct": is_correct,
#"inference": self.infer(x_test[ran:ran+1], model),
}
return response
@track_emissions(project_name = "cnn", output_file = RESULTS_DIR + "emissions_cnn.csv")
def infer(self, user_input, model):
model_predict = model.predict(user_input)
#print(f"model_predict: {model_predict}")
#cat_pred = np.argmax(model_predict)
#print(f"argmax: {cat_pred}")
return np.argmax(model_predict)