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()这是一个 sentence-transformers 模型。 它能将句子和段落(文本)映射到 1024 维的稠密向量空间中。 该模型旨在与 SetFit 配合使用,以改进德语小样本文本分类。 它有一个姊妹模型,名为 deutsche-telekom/gbert-large-paraphrase-cosine。
此模型基于 deepset/gbert-large 构建。 非常感谢 deepset!
损失函数
我们使用了 BatchHardSoftMarginTripletLoss 作为损失函数,并采用欧氏距离:
train_loss = losses.BatchHardSoftMarginTripletLoss(
model=model,
distance_metric=BatchHardTripletLossDistanceFunction.eucledian_distance,
)训练数据
该模型在经过精心筛选的 deutsche-telekom/ger-backtrans-paraphrase 数据集上训练。我们删除了以下句子对:
min_char_len 小于 15jaccard_similarity 大于 0.3de_token_count 大于 30en_de_token_count 大于 30cos_sim 小于 0.85超参数
我们使用 NLU Few-shot Benchmark - English and German 数据集,在德语少样本场景下对该模型进行评估。
定性结果
Copyright (c) 2023 Philip May、Deutsche Telekom AG
Copyright (c) 2022 deepset GmbH
本模型基于 MIT License(“许可协议”)授权。您必须遵守许可协议的规定才能使用本文件。您可以通过查看仓库中的 LICENSE 文件获取许可协议副本。