Spaces:
Sleeping
Sleeping
smhavens
commited on
Commit
•
949bc1b
1
Parent(s):
d5bca77
Training and fine-tuning embeddings complete!
Browse filesRuns without errors.
Next must generate two random words for analogies.
- ag_news_model/1_Pooling/config.json +7 -0
- ag_news_model/README.md +88 -0
- ag_news_model/config.json +26 -0
- ag_news_model/config_sentence_transformers.json +7 -0
- ag_news_model/model.safetensors +3 -0
- ag_news_model/modules.json +20 -0
- ag_news_model/sentence_bert_config.json +4 -0
- ag_news_model/special_tokens_map.json +7 -0
- ag_news_model/tokenizer.json +0 -0
- ag_news_model/tokenizer_config.json +64 -0
- ag_news_model/vocab.txt +0 -0
- app.py +38 -11
- train.py +36 -24
ag_news_model/1_Pooling/config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"word_embedding_dimension": 384,
|
3 |
+
"pooling_mode_cls_token": false,
|
4 |
+
"pooling_mode_mean_tokens": true,
|
5 |
+
"pooling_mode_max_tokens": false,
|
6 |
+
"pooling_mode_mean_sqrt_len_tokens": false
|
7 |
+
}
|
ag_news_model/README.md
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
pipeline_tag: sentence-similarity
|
3 |
+
tags:
|
4 |
+
- sentence-transformers
|
5 |
+
- feature-extraction
|
6 |
+
- sentence-similarity
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
# {MODEL_NAME}
|
11 |
+
|
12 |
+
This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 384 dimensional dense vector space and can be used for tasks like clustering or semantic search.
|
13 |
+
|
14 |
+
<!--- Describe your model here -->
|
15 |
+
|
16 |
+
## Usage (Sentence-Transformers)
|
17 |
+
|
18 |
+
Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:
|
19 |
+
|
20 |
+
```
|
21 |
+
pip install -U sentence-transformers
|
22 |
+
```
|
23 |
+
|
24 |
+
Then you can use the model like this:
|
25 |
+
|
26 |
+
```python
|
27 |
+
from sentence_transformers import SentenceTransformer
|
28 |
+
sentences = ["This is an example sentence", "Each sentence is converted"]
|
29 |
+
|
30 |
+
model = SentenceTransformer('{MODEL_NAME}')
|
31 |
+
embeddings = model.encode(sentences)
|
32 |
+
print(embeddings)
|
33 |
+
```
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
## Evaluation Results
|
38 |
+
|
39 |
+
<!--- Describe how your model was evaluated -->
|
40 |
+
|
41 |
+
For an automated evaluation of this model, see the *Sentence Embeddings Benchmark*: [https://seb.sbert.net](https://seb.sbert.net?model_name={MODEL_NAME})
|
42 |
+
|
43 |
+
|
44 |
+
## Training
|
45 |
+
The model was trained with the parameters:
|
46 |
+
|
47 |
+
**DataLoader**:
|
48 |
+
|
49 |
+
`torch.utils.data.dataloader.DataLoader` of length 2400 with parameters:
|
50 |
+
```
|
51 |
+
{'batch_size': 25, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}
|
52 |
+
```
|
53 |
+
|
54 |
+
**Loss**:
|
55 |
+
|
56 |
+
`sentence_transformers.losses.BatchHardSoftMarginTripletLoss.BatchHardSoftMarginTripletLoss`
|
57 |
+
|
58 |
+
Parameters of the fit()-Method:
|
59 |
+
```
|
60 |
+
{
|
61 |
+
"epochs": 10,
|
62 |
+
"evaluation_steps": 0,
|
63 |
+
"evaluator": "NoneType",
|
64 |
+
"max_grad_norm": 1,
|
65 |
+
"optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
|
66 |
+
"optimizer_params": {
|
67 |
+
"lr": 2e-05
|
68 |
+
},
|
69 |
+
"scheduler": "WarmupLinear",
|
70 |
+
"steps_per_epoch": null,
|
71 |
+
"warmup_steps": 10000,
|
72 |
+
"weight_decay": 0.01
|
73 |
+
}
|
74 |
+
```
|
75 |
+
|
76 |
+
|
77 |
+
## Full Model Architecture
|
78 |
+
```
|
79 |
+
SentenceTransformer(
|
80 |
+
(0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: BertModel
|
81 |
+
(1): Pooling({'word_embedding_dimension': 384, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
|
82 |
+
(2): Normalize()
|
83 |
+
)
|
84 |
+
```
|
85 |
+
|
86 |
+
## Citing & Authors
|
87 |
+
|
88 |
+
<!--- Describe where people can find more information -->
|
ag_news_model/config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/home/smhavens/.cache/torch/sentence_transformers/sentence-transformers_all-MiniLM-L6-v2/",
|
3 |
+
"architectures": [
|
4 |
+
"BertModel"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"classifier_dropout": null,
|
8 |
+
"gradient_checkpointing": false,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 384,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 1536,
|
14 |
+
"layer_norm_eps": 1e-12,
|
15 |
+
"max_position_embeddings": 512,
|
16 |
+
"model_type": "bert",
|
17 |
+
"num_attention_heads": 12,
|
18 |
+
"num_hidden_layers": 6,
|
19 |
+
"pad_token_id": 0,
|
20 |
+
"position_embedding_type": "absolute",
|
21 |
+
"torch_dtype": "float32",
|
22 |
+
"transformers_version": "4.35.2",
|
23 |
+
"type_vocab_size": 2,
|
24 |
+
"use_cache": true,
|
25 |
+
"vocab_size": 30522
|
26 |
+
}
|
ag_news_model/config_sentence_transformers.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"__version__": {
|
3 |
+
"sentence_transformers": "2.0.0",
|
4 |
+
"transformers": "4.6.1",
|
5 |
+
"pytorch": "1.8.1"
|
6 |
+
}
|
7 |
+
}
|
ag_news_model/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f1167225afc7fa8d939844ba7a4715244880742fc1c279ef49127fe2dd36a796
|
3 |
+
size 90864192
|
ag_news_model/modules.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"idx": 0,
|
4 |
+
"name": "0",
|
5 |
+
"path": "",
|
6 |
+
"type": "sentence_transformers.models.Transformer"
|
7 |
+
},
|
8 |
+
{
|
9 |
+
"idx": 1,
|
10 |
+
"name": "1",
|
11 |
+
"path": "1_Pooling",
|
12 |
+
"type": "sentence_transformers.models.Pooling"
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"idx": 2,
|
16 |
+
"name": "2",
|
17 |
+
"path": "2_Normalize",
|
18 |
+
"type": "sentence_transformers.models.Normalize"
|
19 |
+
}
|
20 |
+
]
|
ag_news_model/sentence_bert_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"max_seq_length": 256,
|
3 |
+
"do_lower_case": false
|
4 |
+
}
|
ag_news_model/special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cls_token": "[CLS]",
|
3 |
+
"mask_token": "[MASK]",
|
4 |
+
"pad_token": "[PAD]",
|
5 |
+
"sep_token": "[SEP]",
|
6 |
+
"unk_token": "[UNK]"
|
7 |
+
}
|
ag_news_model/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ag_news_model/tokenizer_config.json
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "[PAD]",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"100": {
|
12 |
+
"content": "[UNK]",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"101": {
|
20 |
+
"content": "[CLS]",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"102": {
|
28 |
+
"content": "[SEP]",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"103": {
|
36 |
+
"content": "[MASK]",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
}
|
43 |
+
},
|
44 |
+
"clean_up_tokenization_spaces": true,
|
45 |
+
"cls_token": "[CLS]",
|
46 |
+
"do_basic_tokenize": true,
|
47 |
+
"do_lower_case": true,
|
48 |
+
"mask_token": "[MASK]",
|
49 |
+
"max_length": 128,
|
50 |
+
"model_max_length": 512,
|
51 |
+
"never_split": null,
|
52 |
+
"pad_to_multiple_of": null,
|
53 |
+
"pad_token": "[PAD]",
|
54 |
+
"pad_token_type_id": 0,
|
55 |
+
"padding_side": "right",
|
56 |
+
"sep_token": "[SEP]",
|
57 |
+
"stride": 0,
|
58 |
+
"strip_accents": null,
|
59 |
+
"tokenize_chinese_chars": true,
|
60 |
+
"tokenizer_class": "BertTokenizer",
|
61 |
+
"truncation_side": "right",
|
62 |
+
"truncation_strategy": "longest_first",
|
63 |
+
"unk_token": "[UNK]"
|
64 |
+
}
|
ag_news_model/vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
app.py
CHANGED
@@ -19,7 +19,7 @@ import sys
|
|
19 |
|
20 |
# !pip install https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
|
21 |
# 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'])
|
22 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
23 |
nltk.download('stopwords')
|
24 |
nlp = spacy.load("en_core_web_sm")
|
25 |
stops = stopwords.words("english")
|
@@ -31,7 +31,7 @@ answer = "Pizza"
|
|
31 |
|
32 |
#Mean Pooling - Take attention mask into account for correct averaging
|
33 |
def mean_pooling(model_output, attention_mask):
|
34 |
-
token_embeddings = model_output[
|
35 |
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
36 |
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
37 |
|
@@ -49,8 +49,8 @@ def normalize(comment, lowercase, remove_stopwords):
|
|
49 |
return " ".join(lemmatized)
|
50 |
|
51 |
|
52 |
-
def tokenize_function(examples):
|
53 |
-
|
54 |
|
55 |
|
56 |
def compute_metrics(eval_pred):
|
@@ -181,28 +181,56 @@ def finetune(train_dataloader):
|
|
181 |
|
182 |
# trainer.train()
|
183 |
|
|
|
|
|
|
|
|
|
184 |
sentences = ["This is an example sentence", "Each sentence is converted"]
|
185 |
|
186 |
# model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
187 |
embeddings = model.encode(sentences)
|
188 |
-
print(embeddings)
|
189 |
|
190 |
# Sentences we want sentence embeddings for
|
191 |
sentences = ['This is an example sentence', 'Each sentence is converted']
|
192 |
|
193 |
# Load model from HuggingFace Hub
|
194 |
-
|
195 |
# model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
196 |
|
197 |
# Tokenize sentences
|
198 |
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
# Compute token embeddings
|
201 |
with torch.no_grad():
|
202 |
model_output = model(**encoded_input)
|
203 |
|
|
|
204 |
# Perform pooling
|
205 |
-
sentence_embeddings = mean_pooling(model_output, encoded_input['
|
206 |
|
207 |
# Normalize embeddings
|
208 |
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
|
@@ -238,7 +266,8 @@ def main():
|
|
238 |
answer = "Moon"
|
239 |
global guesses
|
240 |
|
241 |
-
num_rows, data_type, value, example, embeddings = training()
|
|
|
242 |
|
243 |
prompt = f"{word1} is to {word2} as {word3} is to ____"
|
244 |
with gr.Blocks() as iface:
|
@@ -250,9 +279,7 @@ def main():
|
|
250 |
with gr.Accordion("Open for previous guesses"):
|
251 |
text_guesses = gr.Textbox()
|
252 |
with gr.Tab("Testing"):
|
253 |
-
gr.Markdown(f"""
|
254 |
-
An example is {example}.
|
255 |
-
The Embeddings are {embeddings}.""")
|
256 |
text_button.click(check_answer, inputs=[text_input], outputs=[text_output, text_guesses])
|
257 |
# iface = gr.Interface(fn=greet, inputs="text", outputs="text")
|
258 |
iface.launch()
|
|
|
19 |
|
20 |
# !pip install https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
|
21 |
# 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'])
|
22 |
+
# tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
23 |
nltk.download('stopwords')
|
24 |
nlp = spacy.load("en_core_web_sm")
|
25 |
stops = stopwords.words("english")
|
|
|
31 |
|
32 |
#Mean Pooling - Take attention mask into account for correct averaging
|
33 |
def mean_pooling(model_output, attention_mask):
|
34 |
+
token_embeddings = model_output['token_embeddings'] #First element of model_output contains all token embeddings
|
35 |
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
36 |
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
37 |
|
|
|
49 |
return " ".join(lemmatized)
|
50 |
|
51 |
|
52 |
+
# def tokenize_function(examples):
|
53 |
+
# return tokenizer(examples["text"])
|
54 |
|
55 |
|
56 |
def compute_metrics(eval_pred):
|
|
|
181 |
|
182 |
# trainer.train()
|
183 |
|
184 |
+
def embeddings():
|
185 |
+
model = SentenceTransformer("ag_news_model")
|
186 |
+
device = torch.device('cuda:0')
|
187 |
+
model = model.to(device)
|
188 |
sentences = ["This is an example sentence", "Each sentence is converted"]
|
189 |
|
190 |
# model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
191 |
embeddings = model.encode(sentences)
|
192 |
+
# print(embeddings)
|
193 |
|
194 |
# Sentences we want sentence embeddings for
|
195 |
sentences = ['This is an example sentence', 'Each sentence is converted']
|
196 |
|
197 |
# Load model from HuggingFace Hub
|
198 |
+
tokenizer = AutoTokenizer.from_pretrained('ag_news_model')
|
199 |
# model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
200 |
|
201 |
# Tokenize sentences
|
202 |
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
203 |
|
204 |
+
# print(model.device)
|
205 |
+
# print(encoded_input["input_ids"].device)
|
206 |
+
# print(encoded_input["attention_mask"].device)
|
207 |
+
# print(encoded_input["token_type_ids"].device)
|
208 |
+
encoded_input["input_ids"] = encoded_input["input_ids"].to(device)
|
209 |
+
encoded_input["attention_mask"] = encoded_input["attention_mask"].to(device)
|
210 |
+
encoded_input['token_type_ids'] = encoded_input['token_type_ids'].to(device)
|
211 |
+
# print(encoded_input)
|
212 |
+
|
213 |
+
# print(encoded_input["input_ids"].device)
|
214 |
+
# print(encoded_input["attention_mask"].device)
|
215 |
+
# print(encoded_input["token_type_ids"].device)
|
216 |
+
|
217 |
+
encoded_input['input'] = {'input_ids':encoded_input['input_ids'], 'attention_mask':encoded_input['attention_mask']}
|
218 |
+
|
219 |
+
# + encoded_input['token_type_ids'] + encoded_input['attention_mask']
|
220 |
+
del encoded_input['input_ids']
|
221 |
+
del encoded_input['token_type_ids']
|
222 |
+
del encoded_input['attention_mask']
|
223 |
+
|
224 |
+
# print(encoded_input)
|
225 |
+
|
226 |
+
# encoded_input.to(device)
|
227 |
# Compute token embeddings
|
228 |
with torch.no_grad():
|
229 |
model_output = model(**encoded_input)
|
230 |
|
231 |
+
print(model_output)
|
232 |
# Perform pooling
|
233 |
+
sentence_embeddings = mean_pooling(model_output, encoded_input['input']["attention_mask"])
|
234 |
|
235 |
# Normalize embeddings
|
236 |
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
|
|
|
266 |
answer = "Moon"
|
267 |
global guesses
|
268 |
|
269 |
+
# num_rows, data_type, value, example, embeddings = training()
|
270 |
+
sent_embeddings = embeddings()
|
271 |
|
272 |
prompt = f"{word1} is to {word2} as {word3} is to ____"
|
273 |
with gr.Blocks() as iface:
|
|
|
279 |
with gr.Accordion("Open for previous guesses"):
|
280 |
text_guesses = gr.Textbox()
|
281 |
with gr.Tab("Testing"):
|
282 |
+
gr.Markdown(f"""The Embeddings are {sent_embeddings}.""")
|
|
|
|
|
283 |
text_button.click(check_answer, inputs=[text_input], outputs=[text_output, text_guesses])
|
284 |
# iface = gr.Interface(fn=greet, inputs="text", outputs="text")
|
285 |
iface.launch()
|
train.py
CHANGED
@@ -16,10 +16,13 @@ import nltk
|
|
16 |
from nltk.corpus import stopwords
|
17 |
import subprocess
|
18 |
import sys
|
|
|
|
|
19 |
|
20 |
# !pip install https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
|
21 |
# 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'])
|
22 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
|
|
23 |
# nltk.download('stopwords')
|
24 |
# nlp = spacy.load("en_core_web_sm")
|
25 |
# stops = stopwords.words("english")
|
@@ -49,8 +52,8 @@ def mean_pooling(model_output, attention_mask):
|
|
49 |
# return " ".join(lemmatized)
|
50 |
|
51 |
|
52 |
-
def tokenize_function(examples):
|
53 |
-
|
54 |
|
55 |
|
56 |
def compute_metrics(eval_pred):
|
@@ -62,6 +65,8 @@ def compute_metrics(eval_pred):
|
|
62 |
|
63 |
def training():
|
64 |
dataset_id = "ag_news"
|
|
|
|
|
65 |
dataset = load_dataset(dataset_id)
|
66 |
# dataset = dataset["train"]
|
67 |
# tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
@@ -77,6 +82,10 @@ def training():
|
|
77 |
# dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"])
|
78 |
# dataset.format['type']
|
79 |
|
|
|
|
|
|
|
|
|
80 |
# print(dataset)
|
81 |
|
82 |
train_examples = []
|
@@ -152,6 +161,8 @@ def finetune(train_dataloader):
|
|
152 |
# model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
|
153 |
model_id = "sentence-transformers/all-MiniLM-L6-v2"
|
154 |
model = SentenceTransformer(model_id)
|
|
|
|
|
155 |
|
156 |
# training_args = TrainingArguments(output_dir="test_trainer")
|
157 |
|
@@ -181,35 +192,35 @@ def finetune(train_dataloader):
|
|
181 |
|
182 |
# trainer.train()
|
183 |
|
184 |
-
sentences = ["This is an example sentence", "Each sentence is converted"]
|
185 |
|
186 |
-
# model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
187 |
-
embeddings = model.encode(sentences)
|
188 |
-
print(embeddings)
|
189 |
|
190 |
-
# Sentences we want sentence embeddings for
|
191 |
-
sentences = ['This is an example sentence', 'Each sentence is converted']
|
192 |
|
193 |
-
# Load model from HuggingFace Hub
|
194 |
-
# tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
195 |
-
# model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
196 |
|
197 |
-
# Tokenize sentences
|
198 |
-
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
199 |
|
200 |
-
# Compute token embeddings
|
201 |
-
with torch.no_grad():
|
202 |
-
|
203 |
|
204 |
-
# Perform pooling
|
205 |
-
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
206 |
|
207 |
-
# Normalize embeddings
|
208 |
-
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
|
209 |
|
210 |
-
print("Sentence embeddings:")
|
211 |
-
print(sentence_embeddings)
|
212 |
-
return
|
213 |
|
214 |
|
215 |
|
@@ -231,6 +242,7 @@ def check_answer(guess:str):
|
|
231 |
return "Try again!", output
|
232 |
|
233 |
def main():
|
|
|
234 |
word1 = "Black"
|
235 |
word2 = "White"
|
236 |
word3 = "Sun"
|
|
|
16 |
from nltk.corpus import stopwords
|
17 |
import subprocess
|
18 |
import sys
|
19 |
+
from transformers import DataCollatorWithPadding
|
20 |
+
|
21 |
|
22 |
# !pip install https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
|
23 |
# 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'])
|
24 |
+
# tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
25 |
+
# data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
26 |
# nltk.download('stopwords')
|
27 |
# nlp = spacy.load("en_core_web_sm")
|
28 |
# stops = stopwords.words("english")
|
|
|
52 |
# return " ".join(lemmatized)
|
53 |
|
54 |
|
55 |
+
# def tokenize_function(examples):
|
56 |
+
# return tokenizer(examples["text"], truncation=True)
|
57 |
|
58 |
|
59 |
def compute_metrics(eval_pred):
|
|
|
65 |
|
66 |
def training():
|
67 |
dataset_id = "ag_news"
|
68 |
+
|
69 |
+
print("GETTING DATASET")
|
70 |
dataset = load_dataset(dataset_id)
|
71 |
# dataset = dataset["train"]
|
72 |
# tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
|
|
82 |
# dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"])
|
83 |
# dataset.format['type']
|
84 |
|
85 |
+
# tokenized_news = dataset.map(tokenize_function, batched=True)
|
86 |
+
|
87 |
+
# model = AutoModelForSequenceClassification.from_pretrained("sentence-transformers/all-MiniLM-L6-v2", num_labels=2)
|
88 |
+
|
89 |
# print(dataset)
|
90 |
|
91 |
train_examples = []
|
|
|
161 |
# model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
|
162 |
model_id = "sentence-transformers/all-MiniLM-L6-v2"
|
163 |
model = SentenceTransformer(model_id)
|
164 |
+
device = torch.device('cuda:0')
|
165 |
+
model = model.to(device)
|
166 |
|
167 |
# training_args = TrainingArguments(output_dir="test_trainer")
|
168 |
|
|
|
192 |
|
193 |
# trainer.train()
|
194 |
|
195 |
+
# sentences = ["This is an example sentence", "Each sentence is converted"]
|
196 |
|
197 |
+
# # model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
198 |
+
# embeddings = model.encode(sentences)
|
199 |
+
# print(embeddings)
|
200 |
|
201 |
+
# # Sentences we want sentence embeddings for
|
202 |
+
# sentences = ['This is an example sentence', 'Each sentence is converted']
|
203 |
|
204 |
+
# # Load model from HuggingFace Hub
|
205 |
+
# # tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
206 |
+
# # model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
207 |
|
208 |
+
# # Tokenize sentences
|
209 |
+
# encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
210 |
|
211 |
+
# # Compute token embeddings
|
212 |
+
# with torch.no_grad():
|
213 |
+
# model_output = model(**encoded_input)
|
214 |
|
215 |
+
# # Perform pooling
|
216 |
+
# sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
217 |
|
218 |
+
# # Normalize embeddings
|
219 |
+
# sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
|
220 |
|
221 |
+
# print("Sentence embeddings:")
|
222 |
+
# print(sentence_embeddings)
|
223 |
+
return 0
|
224 |
|
225 |
|
226 |
|
|
|
242 |
return "Try again!", output
|
243 |
|
244 |
def main():
|
245 |
+
print("BEGIN")
|
246 |
word1 = "Black"
|
247 |
word2 = "White"
|
248 |
word3 = "Sun"
|