/ Модель

Характеристики

Контекст
512 токенов
Параметры
152 млн
Лицензия
Apache 2.0
Архитектура
bert · dense
Опубликована
10 апр 2026

sentence-bert-swedish-cased

ЭмбеддингиТекст → embedding10 профессий

Производная модели KBLab/sentence-bert-swedish-cased. Двуязычная модель KBLab на базе BERT преобразует шведские и английские предложения в векторы для семантического поиска, сравнения и кластеризации.

104скачиваний за 30 дней0лайковвеса обновлены10 апр 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Эмбеддинги» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Карточка модели PapaMoth/sentence-bert-swedish-cased на Hugging Face совпадает с карточкой KBLab/sentence-bert-swedish-cased, поэтому описание составлено по ней.

KBLab, лаборатория данных Национальной библиотеки Швеции, разработала эту модель на базе BERT для получения плотных векторных представлений шведских и английских предложений и абзацев. Это sentence-transformers bi-encoder размером 151,9 млн параметров; он отображает текст в векторы размерности 768 и поддерживает входную последовательность до 512 токенов.

Модель предназначена для оценки семантического сходства, семантического поиска и кластеризации текстов. Шведская KB-BERT обучалась как student-модель с помощью дистилляции знаний от английской all-mpnet-base-v2. В README приведены результаты оценки на шведских наборах SweParaphrase и SweFAQ; версия v2.0 показала лучшие результаты на задаче поиска ответов в SweFAQ v2.0 среди перечисленных версий.

Модель принимает текст и выдаёт векторы, пригодные для сравнения и поиска. Распространяется по лицензии Apache-2.0. Результаты оценки относятся к указанным шведским бенчмаркам; качество на других языках и типах текстов может отличаться.

Сценарии применения

  • семантический поиск по шведским документам
  • поиск ответов в шведских FAQ по сходству с вопросом
  • сравнение семантической близости предложений на шведском и английском
  • кластеризация шведских текстов по смыслу

Ограничения

Максимальная длина входа составляет 512 токенов. Представленные оценки относятся к шведским бенчмаркам и не гарантируют такое же качество на других данных.

Для каких профессий подходит10

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

KBLab/sentence-bert-swedish-cased

This is a sentence-transformers model: It maps Swedish sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search. This model is a bilingual Swedish-English model trained according to instructions in the paper Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation and the documentation accompanying its companion python package. We have used the strongest available pretrained English Bi-Encoder (all-mpnet-base-v2) as a teacher model, and the pretrained Swedish KB-BERT as the student model.

A more detailed description of the model can be found in an article we published on the KBLab blog here and for the updated model here.

Update: We have released updated versions of the model since the initial release. The original model described in the blog post is v1.0. The current version is v2.0. The newer versions are trained on longer paragraphs, and have a longer max sequence length. v2.0 is trained with a stronger teacher model and is the current default.

Model versionTeacher ModelMax Sequence Length
v1.0paraphrase-mpnet-base-v2256
v1.1paraphrase-mpnet-base-v2384
v2.0all-mpnet-base-v2384

Usage (Sentence-Transformers)

Using this model becomes easy when you have sentence-transformers installed:

pip install -U sentence-transformers

Then you can use the model like this:

from sentence_transformers import SentenceTransformer
sentences = ["Det här är en exempelmening", "Varje exempel blir konverterad"]

model = SentenceTransformer('KBLab/sentence-bert-swedish-cased')
embeddings = model.encode(sentences)
print(embeddings)

Loading an older model version (Sentence-Transformers)

Currently, the easiest way to load an older model version is to clone the model repository and load it from disk. For example, to clone the v1.0 model:

git clone --depth 1 --branch v1.0 https://huggingface.co/KBLab/sentence-bert-swedish-cased

Then you can load the model by pointing to the local folder where you cloned the model:

from sentence_transformers import SentenceTransformer
model = SentenceTransformer("path_to_model_folder/sentence-bert-swedish-cased")

Usage (HuggingFace Transformers)

Without sentence-transformers, 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.

from transformers import AutoTokenizer, AutoModel
import torch


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    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)


# Sentences we want sentence embeddings for
sentences = ['Det här är en exempelmening', 'Varje exempel blir konverterad']

# Load model from HuggingFace Hub
# To load an older version, e.g. v1.0, add the argument revision="v1.0" 
tokenizer = AutoTokenizer.from_pretrained('KBLab/sentence-bert-swedish-cased')
model = AutoModel.from_pretrained('KBLab/sentence-bert-swedish-cased')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, max pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

print("Sentence embeddings:")
print(sentence_embeddings)

Loading an older model (Hugginfface Transformers)

To load an older model specify the version tag with the revision arg. For example, to load the v1.0 model, use the following code:

AutoTokenizer.from_pretrained('KBLab/sentence-bert-swedish-cased', revision="v1.0")
AutoModel.from_pretrained('KBLab/sentence-bert-swedish-cased', revision="v1.0")

Evaluation Results

The model was evaluated on SweParaphrase v1.0 and SweParaphrase v2.0. This test set is part of SuperLim -- a Swedish evaluation suite for natural langage understanding tasks. We calculated Pearson and Spearman correlation between predicted model similarity scores and the human similarity score labels. Results from SweParaphrase v1.0 are displayed below.

Model versionPearsonSpearman
v1.00.91830.9114
v1.10.91830.9114
v2.00.92830.9130

The following code snippet can be used to reproduce the above results:

from sentence_transformers import SentenceTransformer
import pandas as pd

df = pd.read_csv(
    "sweparaphrase-dev-165.csv",
    sep="\t",
    header=None,
    names=[
        "original_id",
        "source",
        "type",
        "sentence_swe1",
        "sentence_swe2",
        "score",
        "sentence1",
        "sentence2",
    ],
)

model = SentenceTransformer("KBLab/sentence-bert-swedish-cased")

sentences1 = df["sentence_swe1"].tolist()
sentences2 = df["sentence_swe2"].tolist()

# Compute embedding for both lists
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
embeddings2 = model.encode(sentences2, convert_to_tensor=True)

# Compute cosine similarity after normalizing
embeddings1 /= embeddings1.norm(dim=-1, keepdim=True)
embeddings2 /= embeddings2.norm(dim=-1, keepdim=True)

cosine_scores = embeddings1 @ embeddings2.t()
sentence_pair_scores = cosine_scores.diag()

df["model_score"] = sentence_pair_scores.cpu().tolist()
print(df[["score", "model_score"]].corr(method="spearman"))
print(df[["score", "model_score"]].corr(method="pearson"))

Sweparaphrase v2.0

In general, v1.1 correlates the most with human assessment of text similarity on SweParaphrase v2.0. Below, we present zero-shot evaluation results on all data splits. They display the model's performance out of the box, without any fine-tuning.

Model versionData splitPearsonSpearman
v1.0train0.83550.8256
v1.1train0.83830.8302
v2.0train0.82090.8059
v1.0dev0.86820.8774
v1.1dev0.87390.8833
v2.0dev0.86380.8668
v1.0test0.83560.8476
v1.1test0.83930.8550
v2.0test0.82320.8213

SweFAQ v2.0

When it comes to retrieval tasks, v2.0 performs the best by quite a substantial margin. It is better at matching the correct answer to a question compared to v1.1 and v1.0.

Model versionData splitAccuracy
v1.0train0.5262
v1.1train0.6236
v2.0train0.7106
v1.0dev0.4636
v1.1dev0.5818
v2.0dev0.6727
v1.0test0.4495
v1.1test0.5229
v2.0test0.5871

Examples how to evaluate the models on some of the test sets of the SuperLim suites can be found on the following links: evaluate_faq.py (Swedish FAQ), evaluate_swesat.py (SweSAT synonyms), evaluate_supersim.py (SuperSim).

Training

An article with more details on data and v1.0 of the model can be found on the KBLab blog.

Around 14.6 million sentences from English-Swedish parallel corpuses were used to train the model. Data was sourced from the Open Parallel Corpus (OPUS) and downloaded via the python package opustools. Datasets used were: JW300, Europarl, DGT-TM, EMEA, ELITR-ECA, TED2020, Tatoeba and OpenSubtitles.

The model was trained with the parameters:

DataLoader:

torch.utils.data.dataloader.DataLoader of length 180513 with parameters:

{'batch_size': 64, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}

Loss:

sentence_transformers.losses.MSELoss.MSELoss

Parameters of the fit()-Method:

{
    "epochs": 2,
    "evaluation_steps": 1000,
    "evaluator": "sentence_transformers.evaluation.SequentialEvaluator.SequentialEvaluator",
    "max_grad_norm": 1,
    "optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
    "optimizer_params": {
        "eps": 1e-06,
        "lr": 8e-06
    },
    "scheduler": "WarmupLinear",
    "steps_per_epoch": null,
    "warmup_steps": 5000,
    "weight_decay": 0.01
}

Full Model Architecture

SentenceTransformer(
  (0): Transformer({'max_seq_length': 384, 'do_lower_case': False}) with Transformer model: BertModel 
  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
)

Citing & Authors

This model was trained by KBLab, a data lab at the National Library of Sweden.

You can cite the article on our blog: https://kb-labb.github.io/posts/2021-08-23-a-swedish-sentence-transformer/ .

@misc{rekathati2021introducing,  
  author = {Rekathati, Faton},  
  title = {The KBLab Blog: Introducing a Swedish Sentence Transformer},  
  url = {https://kb-labb.github.io/posts/2021-08-23-a-swedish-sentence-transformer/},  
  year = {2021}  
}

Acknowledgements

We gratefully acknowledge the HPC RIVR consortium (www.hpc-rivr.si) and EuroHPC JU (eurohpc-ju.europa.eu/) for funding this research by providing computing resources of the HPC system Vega at the Institute of Information Science (www.izum.si).

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Класс архитектуры
BertModel
Ревизия весов
5c8717a

0 моделей