hf_mirrors/gbert-large-paraphrase-euclidean
Model Introduction
Files & versions
Analysis
You are visiting the mirror address of https://modelers.cn/Rose/gbert-large-paraphrase-euclidean. The repo is synchronized in real-time and is only for mirror acceleration access.

openmind

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()

German BERT large paraphrase euclidean

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!

Training

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 15
  • jaccard_similarity greater than 0.3
  • de_token_count greater than 30
  • en_de_token_count greater than 30
  • cos_sim less than 0.85

Hyperparameters

  • learning_rate: 5.5512022294147105e-06
  • num_epochs: 7
  • train_batch_size: 68
  • num_gpu: ???

Evaluation Results

We use the NLU Few-shot Benchmark - English and German dataset to evaluate this model in a German few-shot scenario.

Qualitative results

  • multilingual sentence embeddings provide the worst results
  • Electra models also deliver poor results
  • German BERT base size model (deepset/gbert-base) provides good results
  • German BERT large size model (deepset/gbert-large) provides very good results
  • our fine-tuned models (this model and deutsche-telekom/gbert-large-paraphrase-cosine) provide best results

Licensing

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.