File size: 9,300 Bytes
e369cb0
 
96d7c96
e369cb0
 
fd49958
 
0473071
 
e369cb0
 
fd49958
0473071
 
96d7c96
 
458c097
 
0473071
458c097
9be73ed
0473071
96d7c96
f74421e
96d7c96
e369cb0
5d26793
b7302f3
 
3854d90
e369cb0
 
05a2e2d
 
 
 
e369cb0
 
96d7c96
 
 
 
 
 
 
 
 
 
 
 
 
0473071
69ae466
0473071
 
 
 
 
 
 
 
 
05a2e2d
dc0c8b8
bfc9cbd
 
fd49958
0473071
bfc9cbd
413574b
bfc9cbd
7a2e05d
fd49958
 
0473071
96d7c96
 
 
69ae466
96d7c96
69ae466
fd49958
96d7c96
fd49958
96d7c96
f4440c5
5503f0a
 
 
 
 
 
 
 
 
20042af
 
 
 
 
 
 
 
 
 
 
 
 
0473071
20042af
5503f0a
20042af
f4440c5
20042af
f4440c5
20042af
 
 
 
 
f4440c5
20042af
 
 
 
 
f4440c5
20042af
 
 
 
 
 
 
 
 
 
 
fd49958
247c86d
0473071
4dec182
 
fd94d05
fd49958
940deb0
2c3c9f7
bfc9cbd
0473071
e369cb0
fd49958
7a2e05d
 
 
0473071
7a2e05d
0473071
 
 
 
fe56f10
fd49958
4dec182
 
fd49958
0473071
9be73ed
7495c36
9be73ed
0473071
 
fd49958
0473071
fd49958
 
 
 
 
 
 
0473071
fd49958
0473071
05a2e2d
e369cb0
0473071
05a2e2d
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
fd49958
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
e369cb0
05a2e2d
 
2c3c9f7
0473071
 
e369cb0
 
 
 
3854d90
b7302f3
 
34d084e
cfd2220
 
 
f47dc44
cfd2220
ba7e072
cfd2220
ba7e072
cfd2220
e369cb0
05a2e2d
ba7e072
 
 
b7302f3
ba7e072
e22b7aa
ba7e072
2c3c9f7
 
5d26793
ba7e072
 
 
3ed7c05
 
ba7e072
 
a87b166
2c3c9f7
 
 
 
a87b166
ba7e072
05a2e2d
7a2e05d
2c3c9f7
05a2e2d
e369cb0
 
05a2e2d
 
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
import gradio as gr
import math
import spacy
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from sentence_transformers import InputExample
from sentence_transformers import losses
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
from transformers import TrainingArguments, Trainer
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import numpy as np
import evaluate
import nltk
from nltk.corpus import stopwords
import subprocess
import sys

# !pip install https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
# subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl'])
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
nltk.download('stopwords')
nlp = spacy.load("en_core_web_sm")
stops = stopwords.words("english")

# answer = "Pizza"
guesses = []
answer = "Pizza"


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


def normalize(comment, lowercase, remove_stopwords):
    if lowercase:
        comment = comment.lower()
    comment = nlp(comment)
    lemmatized = list()
    for word in comment:
        lemma = word.lemma_.strip()
        if lemma:
            if not remove_stopwords or (remove_stopwords and lemma not in stops):
                lemmatized.append(lemma)
    return " ".join(lemmatized)


def tokenize_function(examples):
    return tokenizer(examples["text"])


def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=-1)
    metric = evaluate.load("accuracy")
    return metric.compute(predictions=predictions, references=labels)


def training():
    dataset_id = "ag_news"
    dataset = load_dataset(dataset_id)
    # dataset = dataset["train"]
    # tokenized_datasets = dataset.map(tokenize_function, batched=True)
    
    print(f"- The {dataset_id} dataset has {dataset['train'].num_rows} examples.")
    print(f"- Each example is a {type(dataset['train'][0])} with a {type(dataset['train'][0]['text'])} as value.")
    print(f"- Examples look like this: {dataset['train'][0]}")
    
    # small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
    # small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
    
    # dataset = dataset["train"].map(tokenize_function, batched=True)
    # dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"])
    # dataset.format['type']
    
    # print(dataset)
    
    train_examples = []
    train_data = dataset["train"]
    # For agility we only 1/2 of our available data
    n_examples = dataset["train"].num_rows // 2
    # n_remaining = dataset["train"].num_rows - n_examples
    # dataset_clean = {}
    # # dataset_0 = []
    # # dataset_1 = []
    # # dataset_2 = []
    # # dataset_3 = []
    # for i in range(n_examples):
    #     dataset_clean[i] = {}
    #     dataset_clean[i]["text"] = normalize(train_data[i]["text"], lowercase=True, remove_stopwords=True)
    #     dataset_clean[i]["label"] = train_data[i]["label"]
        # if train_data[i]["label"] == 0:
        #     dataset_0.append(dataset_clean[i])
        # elif train_data[i]["label"] == 1:
        #     dataset_1.append(dataset_clean[i])
        # elif train_data[i]["label"] == 2:
        #     dataset_2.append(dataset_clean[i])
        # elif train_data[i]["label"] == 3:
        #     dataset_3.append(dataset_clean[i])
    # n_0 = len(dataset_0) // 2
    # n_1 = len(dataset_1) // 2
    # n_2 = len(dataset_2) // 2
    # n_3 = len(dataset_3) // 2
    # print("Label lengths:", len(dataset_0), len(dataset_1), len(dataset_2), len(dataset_3))
    
    for i in range(n_examples):
        example = train_data[i]
        # example_opposite = dataset_clean[-(i)]
        # print(example["text"])
        train_examples.append(InputExample(texts=[example['text']], label=example['label']))
        
    # for i in range(n_0):
    #     example = dataset_0[i]
    #     # example_opposite = dataset_0[-(i)]
    #     # print(example["text"])
    #     train_examples.append(InputExample(texts=[example['text']], label=0))
        
    # for i in range(n_1):
    #     example = dataset_1[i]
    #     # example_opposite = dataset_1[-(i)]
    #     # print(example["text"])
    #     train_examples.append(InputExample(texts=[example['text']], label=1))
        
    # for i in range(n_2):
    #     example = dataset_2[i]
    #     # example_opposite = dataset_2[-(i)]
    #     # print(example["text"])
    #     train_examples.append(InputExample(texts=[example['text']], label=2))
        
    # for i in range(n_3):
    #     example = dataset_3[i]
    #     # example_opposite = dataset_3[-(i)]
    #     # print(example["text"])
    #     train_examples.append(InputExample(texts=[example['text']], label=3))
        
    train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=25)
    
    print("END DATALOADER")
    
    # print(train_examples)
        
    embeddings = finetune(train_dataloader)
    
    return (dataset['train'].num_rows, type(dataset['train'][0]), type(dataset['train'][0]['text']), dataset['train'][0], embeddings)


def finetune(train_dataloader):
    # model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
    model_id = "sentence-transformers/all-MiniLM-L6-v2"
    model = SentenceTransformer(model_id)
    
    # training_args = TrainingArguments(output_dir="test_trainer")
    
    # USE THIS LINK
    # https://huggingface.co/blog/how-to-train-sentence-transformers
    
    train_loss = losses.BatchHardSoftMarginTripletLoss(model=model)
    
    print("BEGIN FIT")
    
    model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=10)
    
    model.save("ag_news_model")
    
    model.save_to_hub("smhavens/all-MiniLM-agNews")
    # accuracy = compute_metrics(eval, metric)
    
    # training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
    
    # trainer = Trainer(
    #     model=model,
    #     args=training_args,
    #     train_dataset=train,
    #     eval_dataset=eval,
    #     compute_metrics=compute_metrics,
    # )
    
    # trainer.train()
    
    sentences = ["This is an example sentence", "Each sentence is converted"]

    # model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
    embeddings = model.encode(sentences)
    print(embeddings)
    
    # Sentences we want sentence embeddings for
    sentences = ['This is an example sentence', 'Each sentence is converted']

    # Load model from HuggingFace Hub
    # tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
    # model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')

    # Tokenize sentences
    encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

    # Compute token embeddings
    with torch.no_grad():
        model_output = model(**encoded_input)

    # Perform pooling
    sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

    # Normalize embeddings
    sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)

    print("Sentence embeddings:")
    print(sentence_embeddings)
    return sentence_embeddings

 

def greet(name):
    return "Hello " + name + "!!"

def check_answer(guess:str):
    global guesses
    global answer
    guesses.append(guess)
    output = ""
    for guess in guesses:
        output += ("- " + guess + "\n")
    output = output[:-1]
    
    if guess.lower() == answer.lower():
        return "Correct!", output
    else:
        return "Try again!", output

def main():
    word1 = "Black"
    word2 = "White"
    word3 = "Sun"
    global answer
    answer = "Moon"
    global guesses
    
    num_rows, data_type, value, example, embeddings = training()
    
    prompt = f"{word1} is to {word2} as {word3} is to ____"
    with gr.Blocks() as iface:
        gr.Markdown(prompt)
        with gr.Tab("Guess"):
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Submit")
        with gr.Accordion("Open for previous guesses"):
            text_guesses = gr.Textbox()
        with gr.Tab("Testing"):
            gr.Markdown(f"""Number of rows in dataset is {num_rows}, with each having type {data_type} and value {value}.
                        An example is {example}.
                        The Embeddings are {embeddings}.""")
        text_button.click(check_answer, inputs=[text_input], outputs=[text_output, text_guesses])
    # iface = gr.Interface(fn=greet, inputs="text", outputs="text")
    iface.launch()
    
    


    
if __name__ == "__main__":
    main()