Transformers
PyTorch
I-SPIn
Lutech-admin commited on
Commit
572788d
·
1 Parent(s): 8b40e0e

Delete ISPIn/ISPIn.py

Browse files
Files changed (1) hide show
  1. ISPIn/ISPIn.py +0 -128
ISPIn/ISPIn.py DELETED
@@ -1,128 +0,0 @@
1
- # SYS
2
- import gc
3
-
4
- # BASE
5
- import numpy as np
6
-
7
- # TORCH
8
- import torch
9
- from torch import nn
10
-
11
- # TQDM
12
- from tqdm.notebook import tqdm
13
- from tqdm.autonotebook import trange
14
-
15
- # TRANSFORMERS
16
- from transformers import PreTrainedModel, AutoTokenizer, AutoModel
17
-
18
- # CONFIG
19
- from .ISPInConfig import ISPInConfig
20
-
21
- class ISPIn(PreTrainedModel):
22
-
23
- config_class = ISPInConfig
24
-
25
- def __init__(self, config):
26
- super(ISPIn, self).__init__(config=config)
27
-
28
- self.tokenizer = AutoTokenizer.from_pretrained(config.sbert_id)
29
- self.encoder = AutoModel.from_pretrained(config.sbert_id)
30
-
31
- self.layers = nn.ModuleList()
32
-
33
- for index in range(len(config.layers_dimensions) - 1):
34
- self.layers.append(nn.Linear(config.layers_dimensions[index], config.layers_dimensions[index + 1]))
35
-
36
- self.activation = nn.GELU()
37
-
38
- self.local_labels_dict = {'contradiction': 2, 'neutral': 0, 'entailment': 1}
39
-
40
-
41
- def mean_pooling(self, x, attention_mask):
42
- token_embeddings = x[0] #First element of SBERT output contains all token embeddings
43
- input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
44
- return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
45
-
46
-
47
- def forward(self, sentences, batch_size = 32, show_progress_bar = False):
48
-
49
- # cast individual sentence to a list of sentences of length one
50
- if isinstance(sentences, str) or not hasattr(sentences, '__len__'):
51
- sentences = [sentences]
52
-
53
- all_embeddings = []
54
-
55
- for start_index in trange(0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar):
56
- sentences_batch = sentences[start_index : start_index + batch_size]
57
-
58
- tokenized_batch = self.tokenizer(sentences_batch, padding=True, truncation=True, return_tensors='pt')
59
-
60
- with torch.no_grad():
61
- last_layer = self.encoder(**tokenized_batch)
62
- embeddings = self.mean_pooling(last_layer, tokenized_batch['attention_mask'])
63
-
64
- all_embeddings.extend(embeddings)
65
- del embeddings
66
- gc.collect()
67
-
68
- all_embeddings = torch.stack(all_embeddings)
69
-
70
- return all_embeddings
71
-
72
-
73
- def predict(self, embeddings_to_predict, embeddings_ground_truth, one_to_many = False):
74
-
75
- if (one_to_many == False):
76
-
77
- prod = torch.mul(embeddings_to_predict, embeddings_ground_truth)
78
- diff = torch.subtract(embeddings_to_predict, embeddings_ground_truth)
79
-
80
- prod_diff = torch.concat((prod, diff), 1)
81
-
82
- x = prod_diff
83
- del prod_diff
84
-
85
- elif (one_to_many == True):
86
-
87
- number_of_sentences = embeddings_to_predict.size(dim = 0)
88
- number_of_ground_truths = embeddings_ground_truth.size(dim = 0)
89
- embedding_dimension = embeddings_to_predict.size(dim = 1)
90
-
91
- prod_diff = torch.zeros((number_of_sentences * number_of_ground_truths, 2 * embedding_dimension))
92
-
93
- for i in range(number_of_sentences):
94
- start_index = i * number_of_ground_truths
95
- end_index = (i + 1) * number_of_ground_truths
96
-
97
- # shape (1, embedding_dimension)
98
- single_sentence_embeddings = torch.reshape(embeddings_to_predict[i], (1, embedding_dimension))
99
-
100
- prod = torch.mul(single_sentence_embeddings, embeddings_ground_truth)
101
- diff = torch.subtract(single_sentence_embeddings, embeddings_ground_truth)
102
-
103
- prod_diff[start_index : end_index] = torch.concat((prod, diff), axis=1)
104
-
105
- x = prod_diff
106
- del prod_diff
107
-
108
- del prod, diff
109
-
110
- for layer in self.layers:
111
- x = self.activation(layer(x))
112
-
113
- if (one_to_many == False):
114
- probabilities = [torch.softmax(elem, 0) for elem in x]
115
- predictions = [torch.argmax(elem, 0) for elem in x]
116
-
117
- if (one_to_many == True):
118
-
119
- # Reshape as a matrix. predictions[0] are the labels given to sentence[0] with all ground truths
120
- x = [x[i * number_of_ground_truths : (i + 1) * number_of_ground_truths] for i in range(number_of_sentences)]
121
-
122
- probabilities = [torch.softmax(elem, 1) for elem in x]
123
- predictions = [torch.argmax(elem, 1) for elem in x]
124
-
125
- predictions = np.array([prediction.cpu().detach().numpy() for prediction in predictions])
126
- probabilities = np.array([probability.cpu().detach().numpy() for probability in probabilities])
127
-
128
- return predictions