SentenceTransformer based on NbAiLab/nb-bert-base
This is a sentence-transformers model finetuned from NbAiLab/nb-bert-base. It is the second version of the existing NbAiLab/nb-sbert-base model, providing a larger max sequence length for inputs.
The model maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more. The easiest way is to simply measure the cosine distance between two sentences. Sentences that are close to each other in meaning, will have a small cosine distance and a similarity close to 1. The model is trained in such a way that similar sentences in different languages should also be close to each other. Ideally, an English-Norwegian sentence pair should have high similarity.
Model Details
Model Description
- Model Type: Sentence Transformer
- Base model: NbAiLab/nb-bert-base
- Maximum Sequence Length: 512 tokens
- Output Dimensionality: 768 dimensions
- Similarity Function: Cosine Similarity
- Training Dataset: Subset of NbAiLab/mnli-norwegian
- Language: Norwegian and English
- License: Apache 2.0
EU AI Act
This release is a non-generative encoder model whose outputs are vectors/scores rather than language or media. Its intended functionality is limited to representation, retrieval, ranking, or classification support. On that basis, the release is preliminarily assessed as not falling within the provider obligations for GPAI models under the EU AI Act definitions, subject to legal confirmation if capability scope or marketed generality changes. For more information, see the Model Documentation Form here.
Model Sources
- Documentation: Sentence Transformers Documentation
- Repository: Sentence Transformers on GitHub
- Hugging Face: Sentence Transformers on Hugging Face
Full Model Architecture
SentenceTransformer(
(0): Transformer({'max_seq_length': 512, 'do_lower_case': False, 'architecture': '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, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
)
Usage
Direct Usage (Sentence Transformers)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("NbAiLab/nb-sbert-v2-base")
# Run inference
sentences = [
"This is a Norwegian boy",
"Dette er en norsk gutt"
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# (2, 768)
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.8287],
# [0.8287, 1.0000]])
Direct Usage (Transformers)
Without sentence-transformers, you can still use the model. First, you pass in your input through the transformer model, then you have to apply the right pooling-operation on top of the contextualized word embeddings.
Click to see the direct usage in Transformers
import torch
from sklearn.metrics.pairwise import cosine_similarity
from transformers import AutoTokenizer, AutoModel
#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 = ["This is a Norwegian boy", "Dette er en norsk gutt"]
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('NbAiLab/nb-sbert-v2-base')
model = AutoModel.from_pretrained('NbAiLab/nb-sbert-v2-base')
# 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, mean pooling.
embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
print(embeddings.shape)
# torch.Size([2, 768])
similarity = cosine_similarity(embeddings[0].reshape(1, -1), embeddings[1].reshape(1, -1))
print(similarity)
# This should give 0.8287 in the example above.
Evaluation
Metrics
Semantic Similarity
- Dataset: STS Benchmark
- Evaluated with
EmbeddingSimilarityEvaluator
| Metric | nb-sbert-base | nb-sbert-v2-base |
|---|---|---|
| pearson_cosine | 0.8275 | 0.8478 |
| spearman_cosine | 0.8245 | 0.8495 |
MTEB (Scandinavian)
| Metric | nb-sbert-base | nb-sbert-v2-base |
|---|---|---|
| Mean (Task) | 0.5190 | 0.5496 |
| Mean (TaskType) | 0.5394 | 0.5690 |
| Bitext Mining | 0.7228 | 0.7275 |
| Classification | 0.5708 | 0.5841 |
| Clustering | 0.3798 | 0.4105 |
| Retrieval | 0.4840 | 0.5540 |
Training Details
Training Dataset
Subset of NbAiLab/mnli-norwegian
Size: 527,098 training samples
Columns:
anchor,positive, andnegativeApproximate statistics based on the first 1000 samples:
anchor positive negative type string string string details - min: 5 tokens
- mean: 20.91 tokens
- max: 130 tokens
- min: 5 tokens
- mean: 20.91 tokens
- max: 130 tokens
- min: 5 tokens
- mean: 14.14 tokens
- max: 39 tokens
Samples:
anchor positive negative Det som følger er mindre en glid nedover en glatt skråning enn et profesjonelt skred som resulterer i enten en oppsigelse eller en smal flukt til neste drømmejobb, der, selvfølgelig, syklusen gjentas igjen.Syklusen gjentar seg ved neste jobb.Syklusen gjentar seg sjelden ved neste jobb.Syklusen gjentar seg ved neste jobb.Det som følger er mindre en glid nedover en glatt skråning enn et profesjonelt skred som resulterer i enten en oppsigelse eller en smal flukt til neste drømmejobb, der, selvfølgelig, syklusen gjentas igjen.Syklusen gjentar seg sjelden ved neste jobb.The public areas are spectacular, the rooms a bit less so, but a long-awaited renovation was carried out in 1998.The rooms are nice, but the public area is in a league of it's own.The public area was fine, but the rooms were really something else.Ah, but he had no opportunity.Han hadde ikke sjansen til å gjøre noe.Han hadde mange muligheter.Loss:
MultipleNegativesRankingLosswith these parameters:{ "scale": 20.0, "similarity_fct": "cos_sim", "gather_across_devices": false }
Training Hyperparameters
Non-Default Hyperparameters
per_device_train_batch_size: 128num_train_epochs: 1learning_rate: 2e-05warmup_steps: 412.0bf16: Trueeval_strategy: stepsper_device_eval_batch_size: 128batch_sampler: no_duplicates
All Hyperparameters
Click to expand
per_device_train_batch_size: 128num_train_epochs: 1max_steps: -1learning_rate: 2e-05lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 412.0optim: adamw_torch_fusedoptim_args: Noneweight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08optim_target_modules: Nonegradient_accumulation_steps: 1average_tokens_across_devices: Truemax_grad_norm: 1.0label_smoothing_factor: 0.0bf16: Truefp16: Falsebf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Nonetorch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneuse_liger_kernel: Falseliger_kernel_config: Noneuse_cache: Falseneftune_noise_alpha: Nonetorch_empty_cache_steps: Noneauto_find_batch_size: Falselog_on_each_node: Truelogging_nan_inf_filter: Trueinclude_num_input_tokens_seen: nolog_level: passivelog_level_replica: warningdisable_tqdm: Falseproject: huggingfacetrackio_space_id: trackioeval_strategy: stepsper_device_eval_batch_size: 128prediction_loss_only: Trueeval_on_start: Falseeval_do_concat_batches: Trueeval_use_gather_object: Falseeval_accumulation_steps: Noneinclude_for_metrics: []batch_eval_metrics: Falsesave_only_model: Falsesave_on_each_node: Falseenable_jit_checkpoint: Falsepush_to_hub: Falsehub_private_repo: Nonehub_model_id: Nonehub_strategy: every_savehub_always_push: Falsehub_revision: Noneload_best_model_at_end: Falseignore_data_skip: Falserestore_callback_states_from_checkpoint: Falsefull_determinism: Falseseed: 42data_seed: Noneuse_cpu: Falseaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedataloader_drop_last: Falsedataloader_num_workers: 0dataloader_pin_memory: Truedataloader_persistent_workers: Falsedataloader_prefetch_factor: Noneremove_unused_columns: Truelabel_names: Nonetrain_sampling_strategy: randomlength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falseddp_backend: Noneddp_timeout: 1800fsdp: []fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}deepspeed: Nonedebug: []skip_memory_metrics: Truedo_predict: Falseresume_from_checkpoint: Nonewarmup_ratio: Nonelocal_rank: -1prompts: Nonebatch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}
Training Logs
Click to see expand
| Epoch | Step | Training Loss | sts-dev_spearman_cosine | |:------:|:----:|:-------------:|:-----------------------:| | 0.0243 | 100 | 1.8923 | - | | 0.0486 | 200 | 0.8525 | - | | 0.0729 | 300 | 0.6760 | - | | 0.0971 | 400 | 0.5891 | - | | 0.1000 | 412 | - | 0.8397 | | 0.1214 | 500 | 0.5567 | - | | 0.1457 | 600 | 0.5245 | - | | 0.1700 | 700 | 0.5024 | - | | 0.1943 | 800 | 0.4654 | - | | 0.2001 | 824 | - | 0.8390 | | 0.2186 | 900 | 0.4796 | - | | 0.2428 | 1000 | 0.4528 | - | | 0.2671 | 1100 | 0.4577 | - | | 0.2914 | 1200 | 0.4443 | - | | 0.3001 | 1236 | - | 0.8455 | | 0.3157 | 1300 | 0.4201 | - | | 0.3400 | 1400 | 0.4010 | - | | 0.3643 | 1500 | 0.4063 | - | | 0.3885 | 1600 | 0.3955 | - | | 0.4002 | 1648 | - | 0.8446 | | 0.4128 | 1700 | 0.3798 | - | | 0.4371 | 1800 | 0.3772 | - | | 0.4614 | 1900 | 0.3933 | - | | 0.4857 | 2000 | 0.3793 | - | | 0.5002 | 2060 | - | 0.8499 | | 0.5100 | 2100 | 0.3862 | - | | 0.5342 | 2200 | 0.3730 | - | | 0.5585 | 2300 | 0.3463 | - | | 0.5828 | 2400 | 0.3556 | - | | 0.6003 | 2472 | - | 0.8503 | | 0.6071 | 2500 | 0.3614 | - | | 0.6314 | 2600 | 0.3479 | - | | 0.6557 | 2700 | 0.3508 | - | | 0.6799 | 2800 | 0.3463 | - | | 0.7003 | 2884 | - | 0.8471 | | 0.7042 | 2900 | 0.3453 | - | | 0.7285 | 3000 | 0.3327 | - | | 0.7528 | 3100 | 0.3269 | - | | 0.7771 | 3200 | 0.3333 | - | | 0.8004 | 3296 | - | 0.8493 | | 0.8014 | 3300 | 0.3370 | - | | 0.8256 | 3400 | 0.3254 | - | | 0.8499 | 3500 | 0.3348 | - | | 0.8742 | 3600 | 0.3213 | - | | 0.8985 | 3700 | 0.3376 | - | | 0.9004 | 3708 | - | 0.8495 | | 0.9228 | 3800 | 0.3362 | - | | 0.9471 | 3900 | 0.3246 | - | | 0.9713 | 4000 | 0.3215 | - | | 0.9956 | 4100 | 0.3143 | - |Framework Versions
- Python: 3.14.3
- Sentence Transformers: 5.2.3
- Transformers: 5.3.0
- PyTorch: 2.10.0+cu130
- Accelerate: 1.13.0
- Datasets: 4.6.1
- Tokenizers: 0.22.2
Citation
BibTeX
Sentence Transformers
@inproceedings{reimers-2019-sentence-bert,
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2019",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/1908.10084",
}
MultipleNegativesRankingLoss
@misc{henderson2017efficient,
title={Efficient Natural Language Response Suggestion for Smart Reply},
author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
year={2017},
eprint={1705.00652},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
NbAiLab/nb-bert-base
@inproceedings{kummervold-etal-2021-operationalizing,
title = {Operationalizing a National Digital Library: The Case for a {N}orwegian Transformer Model},
author = {Kummervold, Per E and
De la Rosa, Javier and
Wetjen, Freddy and
Brygfjeld, Svein Arne},
booktitle = {Proceedings of the 23rd Nordic Conference on Computational Linguistics (NoDaLiDa)},
year = {2021},
address = {Reykjavik, Iceland (Online)},
publisher = {Linköping University Electronic Press, Sweden},
url = {https://huggingface.co/papers/2104.09617},
pages = {20--29},
abstract = {In this work, we show the process of building a large-scale training set from digital and digitized collections at a national library. The resulting Bidirectional Encoder Representations from Transformers (BERT)-based language model for Norwegian outperforms multilingual BERT (mBERT) models in several token and sequence classification tasks for both Norwegian Bokmål and Norwegian Nynorsk. Our model also improves the mBERT performance for other languages present in the corpus such as English, Swedish, and Danish. For languages not included in the corpus, the weights degrade moderately while keeping strong multilingual properties. Therefore, we show that building high-quality models within a memory institution using somewhat noisy optical character recognition (OCR) content is feasible, and we hope to pave the way for other memory institutions to follow.},
}
Citing & Authors
The model was trained by Victoria Handford and Lucas Georges Gabriel Charpentier. The documentation was initially autogenerated by the SentenceTransformers library then revised by Victoria Handford, Lucas Georges Gabriel Charpentier, and Javier de la Rosa.
- Downloads last month
- 37
Model tree for NbAiLab/nb-sbert-v2-base
Base model
NbAiLab/nb-bert-baseDataset used to train NbAiLab/nb-sbert-v2-base
Papers for NbAiLab/nb-sbert-v2-base
Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Efficient Natural Language Response Suggestion for Smart Reply
Evaluation results
- Pearson Cosine on sts devself-reported0.848
- Spearman Cosine on sts devself-reported0.850