import argparse
import torch
from openmind import is_torch_npu_available, AutoTokenizer, AutoModelForCausalLM,AutoModel
import time
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] # model_output的第一个元素包含所有token嵌入
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 parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to model",
default='gbert-large-paraphrase-euclidean',
)
args = parser.parse_args()
return args
def main():
start_time = time.time() # 记录开始时间
args = parse_args()
if args.model_name_or_path:
model_path = args.model_name_or_path
else:
model_path = ""
if is_torch_npu_available():
device = "npu:0"
else:
device='cpu'
# device='cpu'
sentences = ['This is an example sentence', 'Each sentence is converted']
# 从openmind_hub加载模型
tokenizer = AutoTokenizer.from_pretrained(model_path)
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
model = AutoModel.from_pretrained(model_path).to(device)
# 对句子进行分词
encoded_input = tokenizer(sentences,return_tensors='pt',padding=True).to(device)
# 计算token嵌入
with torch.no_grad():
model_output = model(**encoded_input)
# 执行池化
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask']).to(device)
# 归一化嵌入
# sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)
end_time = time.time() # 记录结束时间
elapsed_time = end_time - start_time # 计算差值
print(f"{device}:Program finished in {elapsed_time:.2f} seconds.") # 打印运行时间
if __name__ == "__main__":
main()This is a sentence-transformers model. It maps sentences & paragraphs (text) into a 1024 dimensional dense vector space. The model is intended to be used together with SetFit to improve German few-shot text classification. It has a sibling model called deutsche-telekom/gbert-large-paraphrase-cosine.
This model is based on deepset/gbert-large. Many thanks to deepset!
Loss Function
We have used BatchHardSoftMarginTripletLoss with eucledian distance as the loss function:
train_loss = losses.BatchHardSoftMarginTripletLoss(
model=model,
distance_metric=BatchHardTripletLossDistanceFunction.eucledian_distance,
)Training Data
The model is trained on a carefully filtered dataset of
deutsche-telekom/ger-backtrans-paraphrase.
We deleted the following pairs of sentences:
min_char_len less than 15jaccard_similarity greater than 0.3de_token_count greater than 30en_de_token_count greater than 30cos_sim less than 0.85Hyperparameters
We use the NLU Few-shot Benchmark - English and German dataset to evaluate this model in a German few-shot scenario.
Qualitative results
Copyright (c) 2023 Philip May, Deutsche Telekom AG
Copyright (c) 2022 deepset GmbH
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License by reviewing the file LICENSE in the repository.