Ahmet commited on
Commit
e8f6c47
·
1 Parent(s): e2f69e8

upload files

Browse files
1_Pooling/config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 512,
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
+ }
README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - tr
4
+ pipeline_tag: sentence-similarity
5
+ tags:
6
+ - sentence-transformers
7
+ - feature-extraction
8
+ - sentence-similarity
9
+ - transformers
10
+ datasets:
11
+ - nli_tr
12
+ - emrecan/stsb-mt-turkish
13
+ license: mit
14
+ ---
15
+
16
+ # turkish-small-bert-uncased-mean-nli-stsb-tr
17
+
18
+ This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 512 dimensional dense vector space and can be used for tasks like clustering or semantic search.
19
+
20
+ This model was adapted from [ytu-ce-cosmos/turkish-small-bert-uncased](https://huggingface.co/ytu-ce-cosmos/turkish-small-bert-uncased) and fine-tuned on these datasets:
21
+ - [nli_tr](https://huggingface.co/datasets/nli_tr)
22
+ - [emrecan/stsb-mt-turkish](https://huggingface.co/datasets/emrecan/stsb-mt-turkish)
23
+
24
+ ## Usage (Sentence-Transformers)
25
+
26
+ Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:
27
+
28
+ ```
29
+ pip install -U sentence-transformers
30
+ ```
31
+
32
+ Then you can use the model like this:
33
+
34
+ ```python
35
+ from sentence_transformers import SentenceTransformer
36
+ sentences = ["Bu örnek bir cümle", "Her cümle dönüştürülür"]
37
+
38
+ model = SentenceTransformer('atasoglu/turkish-small-bert-uncased-mean-nli-stsb-tr')
39
+ embeddings = model.encode(sentences)
40
+ print(embeddings)
41
+ ```
42
+
43
+
44
+
45
+ ## Usage (HuggingFace Transformers)
46
+ Without [sentence-transformers](https://www.SBERT.net), you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
47
+
48
+ ```python
49
+ from transformers import AutoTokenizer, AutoModel
50
+ import torch
51
+
52
+
53
+ #Mean Pooling - Take attention mask into account for correct averaging
54
+ def mean_pooling(model_output, attention_mask):
55
+ token_embeddings = model_output[0] #First element of model_output contains all token embeddings
56
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
57
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
58
+
59
+
60
+ # Sentences we want sentence embeddings for
61
+ sentences = ["Bu örnek bir cümle", "Her cümle dönüştürülür"]
62
+
63
+ # Load model from HuggingFace Hub
64
+ tokenizer = AutoTokenizer.from_pretrained('atasoglu/turkish-small-bert-uncased-mean-nli-stsb-tr')
65
+ model = AutoModel.from_pretrained('atasoglu/turkish-small-bert-uncased-mean-nli-stsb-tr')
66
+
67
+ # Tokenize sentences
68
+ encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
69
+
70
+ # Compute token embeddings
71
+ with torch.no_grad():
72
+ model_output = model(**encoded_input)
73
+
74
+ # Perform pooling. In this case, mean pooling.
75
+ sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
76
+
77
+ print("Sentence embeddings:")
78
+ print(sentence_embeddings)
79
+ ```
80
+
81
+
82
+
83
+ ## Evaluation Results
84
+
85
+ Achieved results on the [STS-b](https://huggingface.co/datasets/emrecan/stsb-mt-turkish) test split are given below:
86
+
87
+ ```txt
88
+ Cosine-Similarity : Pearson: 0.7387 Spearman: 0.7244
89
+ Manhattan-Distance: Pearson: 0.7118 Spearman: 0.7156
90
+ Euclidean-Distance: Pearson: 0.7119 Spearman: 0.7155
91
+ Dot-Product-Similarity: Pearson: 0.7164 Spearman: 0.7081
92
+ ```
93
+
94
+ ## Training
95
+ The model was trained with the parameters:
96
+
97
+ **DataLoader**:
98
+
99
+ `torch.utils.data.dataloader.DataLoader` of length 90 with parameters:
100
+ ```
101
+ {'batch_size': 64, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}
102
+ ```
103
+
104
+ **Loss**:
105
+
106
+ `sentence_transformers.losses.CosineSimilarityLoss.CosineSimilarityLoss`
107
+
108
+ Parameters of the fit()-Method:
109
+ ```
110
+ {
111
+ "epochs": 5,
112
+ "evaluation_steps": 45,
113
+ "evaluator": "sentence_transformers.evaluation.EmbeddingSimilarityEvaluator.EmbeddingSimilarityEvaluator",
114
+ "max_grad_norm": 1,
115
+ "optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
116
+ "optimizer_params": {
117
+ "lr": 2e-05
118
+ },
119
+ "scheduler": "WarmupLinear",
120
+ "steps_per_epoch": null,
121
+ "warmup_steps": 45,
122
+ "weight_decay": 0.01
123
+ }
124
+ ```
125
+
126
+
127
+ ## Full Model Architecture
128
+ ```
129
+ SentenceTransformer(
130
+ (0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: BertModel
131
+ (1): Pooling({'word_embedding_dimension': 512, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
132
+ )
133
+ ```
134
+
135
+ ## Citing & Authors
136
+
137
+ <!--- Describe where people can find more information -->
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "e5_b64_turkish_small_bert_uncased-mean-nli/",
3
+ "architectures": [
4
+ "BertModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 512,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 2048,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 8,
17
+ "num_hidden_layers": 4,
18
+ "pad_token_id": 0,
19
+ "position_embedding_type": "absolute",
20
+ "torch_dtype": "float32",
21
+ "transformers_version": "4.28.0",
22
+ "type_vocab_size": 2,
23
+ "use_cache": true,
24
+ "vocab_size": 32000
25
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "2.2.2",
4
+ "transformers": "4.28.0",
5
+ "pytorch": "2.1.0+cu121"
6
+ }
7
+ }
modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f74195b8a9669f7049a5ebf54d48133741be60ce00ceb478e8a08728bb735530
3
+ size 118109958
sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 256,
3
+ "do_lower_case": false
4
+ }
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
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "clean_up_tokenization_spaces": true,
3
+ "cls_token": "[CLS]",
4
+ "do_basic_tokenize": true,
5
+ "do_lower_case": false,
6
+ "mask_token": "[MASK]",
7
+ "max_len": 512,
8
+ "model_max_length": 512,
9
+ "never_split": null,
10
+ "pad_token": "[PAD]",
11
+ "sep_token": "[SEP]",
12
+ "strip_accents": null,
13
+ "tokenize_chinese_chars": true,
14
+ "tokenizer_class": "BertTokenizer",
15
+ "truncation": true,
16
+ "unk_token": "[UNK]"
17
+ }
training.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # -*- coding: utf-8 -*-
2
+ # """turkish-sentence-embedding.ipynb
3
+
4
+ # Automatically generated by Colaboratory.
5
+
6
+ # Original file is located at
7
+ # https://colab.research.google.com/drive/1jvsd0ZRXCjsd5-lH6EI7GaEYIjHN-6d8
8
+ # """
9
+
10
+ # import sys
11
+ # import torch
12
+ # if not torch.cuda.is_available():
13
+ # print("CUDA NOT FOUND!")
14
+ # sys.exit(0)
15
+
16
+ from datasets import load_dataset
17
+ # ds_multinli = load_dataset("nli_tr", "multinli_tr")
18
+ # ds_snli = load_dataset("nli_tr", "snli_tr")
19
+ ds_stsb = load_dataset("emrecan/stsb-mt-turkish")
20
+
21
+ # """# ALLNLI Training"""
22
+
23
+ # import math
24
+ # from sentence_transformers import models, losses, datasets
25
+ from sentence_transformers import LoggingHandler, SentenceTransformer, util, InputExample
26
+ # from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
27
+ import logging
28
+ # from datetime import datetime
29
+ # import sys
30
+ # import os
31
+ # import gzip
32
+ # import csv
33
+ # import random
34
+
35
+ # #### Just some code to print debug information to stdout
36
+ logging.basicConfig(
37
+ format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, handlers=[LoggingHandler()]
38
+ )
39
+ # #### /print debug information to stdout
40
+
41
+ # model_name = "ytu-ce-cosmos/turkish-small-bert-uncased"
42
+ train_batch_size = 64 # The larger you select this, the better the results (usually). But it requires more GPU memory
43
+ max_seq_length = 75
44
+ num_epochs = 5
45
+
46
+ # # Save path of the model
47
+ model_save_path = "e5_b64_turkish_small_bert_uncased-mean-nli"
48
+
49
+ # # Here we define our SentenceTransformer model
50
+ # word_embedding_model = models.Transformer(model_name, max_seq_length=max_seq_length).cuda()
51
+ # pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(), pooling_mode="mean")
52
+ # model = SentenceTransformer(modules=[word_embedding_model, pooling_model])
53
+
54
+ # def add_to_samples(sent1, sent2, label):
55
+ # if sent1 not in train_data:
56
+ # train_data[sent1] = {"contradiction": set(), "entailment": set(), "neutral": set()}
57
+ # train_data[sent1][label].add(sent2)
58
+
59
+ # """
60
+ # 0: neutral
61
+ # 1: entailment
62
+ # 2: contradiction
63
+ # """
64
+ # id_to_label = {0: "entailment", 1: "neutral", 2: "contradiction"}
65
+
66
+ # train_data = {}
67
+
68
+ # nan_count = 0
69
+ # ds_allnli_train = [ds_multinli["train"], ds_snli["train"]]
70
+ # for ds in ds_allnli_train:
71
+ # for row in ds:
72
+ # sent1 = row["premise"].strip()
73
+ # sent2 = row["hypothesis"].strip()
74
+ # label = row["label"]
75
+ # label = id_to_label.get(label)
76
+ # if label:
77
+ # add_to_samples(sent1, sent2, label)
78
+ # add_to_samples(sent2, sent1, label) # Also add the opposite
79
+ # else:
80
+ # nan_count += 1
81
+
82
+ # print("total Nan:", nan_count)
83
+
84
+
85
+ # train_samples = []
86
+ # for sent1, others in train_data.items():
87
+ # if len(others["entailment"]) > 0 and len(others["contradiction"]) > 0:
88
+ # train_samples.append(
89
+ # InputExample(
90
+ # texts=[sent1, random.choice(list(others["entailment"])), random.choice(list(others["contradiction"]))]
91
+ # )
92
+ # )
93
+ # train_samples.append(
94
+ # InputExample(
95
+ # texts=[random.choice(list(others["entailment"])), sent1, random.choice(list(others["contradiction"]))]
96
+ # )
97
+ # )
98
+
99
+ # logging.info("Train samples: {}".format(len(train_samples)))
100
+
101
+ # train_dataloader = datasets.NoDuplicatesDataLoader(train_samples, batch_size=train_batch_size)
102
+
103
+
104
+ # # Our training loss
105
+ # train_loss = losses.MultipleNegativesRankingLoss(model)
106
+
107
+ # logging.info("Read STSbenchmark dev dataset")
108
+ # dev_samples = []
109
+ # for row in ds_stsb["validation"]:
110
+ # score = float(row["score"]) / 5.0 # Normalize score to range 0 ... 1
111
+ # dev_samples.append(InputExample(texts=[row["sentence1"], row["sentence2"]], label=score))
112
+
113
+ # dev_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(
114
+ # dev_samples, batch_size=train_batch_size, name="sts-dev"
115
+ # )
116
+
117
+ # test_samples = []
118
+ # for row in ds_stsb["test"]:
119
+ # score = float(row["score"]) / 5.0 # Normalize score to range 0 ... 1
120
+ # test_samples.append(InputExample(texts=[row["sentence1"], row["sentence2"]], label=score))
121
+
122
+
123
+ # test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(
124
+ # test_samples, batch_size=train_batch_size, name="sts-test"
125
+ # )
126
+
127
+ # # Configure the training
128
+ # warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) # 10% of train data for warm-up
129
+ # logging.info("Warmup-steps: {}".format(warmup_steps))
130
+
131
+ # print(test_evaluator(model))
132
+
133
+ # model.fit(
134
+ # train_objectives=[(train_dataloader, train_loss)],
135
+ # evaluator=dev_evaluator,
136
+ # epochs=num_epochs,
137
+ # evaluation_steps=int(len(train_dataloader) * 0.1),
138
+ # warmup_steps=warmup_steps,
139
+ # output_path=model_save_path,
140
+ # use_amp=False, # Set to True, if your GPU supports FP16 operations
141
+ # )
142
+
143
+ # ft_model = SentenceTransformer(model_save_path)
144
+ # print(test_evaluator(ft_model, output_path=model_save_path))
145
+
146
+ from torch.utils.data import DataLoader
147
+ import math
148
+ from sentence_transformers import SentenceTransformer, LoggingHandler, losses, util, InputExample
149
+ from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
150
+ import logging
151
+ from datetime import datetime
152
+ import os
153
+ import gzip
154
+ import csv
155
+
156
+ #### /print debug information to stdout
157
+
158
+
159
+ # Read the dataset
160
+
161
+ # Load a pre-trained sentence transformer model
162
+ model = SentenceTransformer(model_save_path, device="cuda")
163
+
164
+ model_save_path = "e5_b64_turkish_small_bert_uncased-mean-nli-stsb"
165
+
166
+ # model_save_path = (
167
+ # "output/training_stsbenchmark_continue_training-" + model_name.replace("/", "-") + "-" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
168
+ # )
169
+ # Convert the dataset to a DataLoader ready for training
170
+ logging.info("Read STSbenchmark train dataset")
171
+
172
+ def generate_samples(split):
173
+ samples = []
174
+ for row in ds_stsb[split]:
175
+ score = float(row["score"]) / 5.0 # Normalize score to range 0 ... 1
176
+ samples.append(InputExample(texts=[row["sentence1"], row["sentence2"]], label=score))
177
+ return samples
178
+
179
+ train_samples = generate_samples("train")
180
+ dev_samples = generate_samples("validation")
181
+ test_samples = generate_samples("test")
182
+
183
+ train_dataloader = DataLoader(train_samples, shuffle=True, batch_size=train_batch_size)
184
+ train_loss = losses.CosineSimilarityLoss(model=model)
185
+
186
+
187
+ # Development set: Measure correlation between cosine score and gold labels
188
+ logging.info("Read STSbenchmark dev dataset")
189
+ evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name="sts-dev")
190
+
191
+
192
+ # Configure the training. We skip evaluation in this example
193
+ warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) # 10% of train data for warm-up
194
+ logging.info("Warmup-steps: {}".format(warmup_steps))
195
+
196
+ test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name="sts-test")
197
+ print(test_evaluator(model))
198
+
199
+ model.fit(
200
+ train_objectives=[(train_dataloader, train_loss)],
201
+ evaluator=evaluator,
202
+ epochs=num_epochs,
203
+ evaluation_steps=int(len(train_dataloader) * 0.5),
204
+ # evaluation_steps=1000,
205
+ warmup_steps=warmup_steps,
206
+ output_path=model_save_path,
207
+ )
208
+
209
+ ft_model = SentenceTransformer(model_save_path)
210
+ print(test_evaluator(ft_model, output_path=model_save_path))
vocab.txt ADDED
The diff for this file is too large to render. See raw diff