nb-sbert-v2-base / README.md
versae's picture
Update README.md
e339220 verified
metadata
tags:
  - sentence-transformers
  - sentence-similarity
  - feature-extraction
  - dense
  - generated_from_trainer
  - dataset_size:527098
  - loss:MultipleNegativesRankingLoss
base_model: NbAiLab/nb-bert-base
datasets: NbAiLab/mnli-norwegian
license: apache-2.0
language:
  - 'no'
widget:
  - source_sentence: The man talked to a girl over the internet camera.
    sentences:
      - A group of elderly people pose around a dining table.
      - A teenager talks to a girl over a webcam.
      - There is no 'still' that is not relative to some other object.
  - source_sentence: A woman is writing something.
    sentences:
      - Two eagles are perched on a branch.
      - >-
        It refers to the maximum f-stop (which is defined as the ratio of focal
        length to effective aperture diameter).
      - A woman is chopping green onions.
  - source_sentence: The player shoots the winning points.
    sentences:
      - Minimum wage laws hurt the least skilled, least productive the most.
      - The basketball player is about to score points for his team.
      - Sheep are grazing in the field in front of a line of trees.
  - source_sentence: >-
      Stars form in star-formation regions, which itself develop from molecular
      clouds.
    sentences:
      - >-
        Although I believe Searle is mistaken, I don't think you have found the
        problem.
      - >-
        It may be possible for a solar system like ours to exist outside of a
        galaxy.
      - >-
        A blond-haired child performing on the trumpet in front of a house while
        his younger brother watches.
  - source_sentence: >-
      While Queen may refer to both Queen regent (sovereign) or Queen consort,
      the King has always been the sovereign.
    sentences:
      - At first, I thought this is a bit of a tricky question.
      - A man sitting on the floor in a room is strumming a guitar.
      - >-
        There is a very good reason not to refer to the Queen's spouse as "King"
        - because they aren't the King.
pipeline_tag: sentence-similarity
library_name: sentence-transformers
metrics:
  - pearson_cosine
  - spearman_cosine
model-index:
  - name: SentenceTransformer based on NbAiLab/nb-bert-base
    results:
      - task:
          type: semantic-similarity
          name: Semantic Similarity
        dataset:
          name: sts dev
          type: sts-dev
        metrics:
          - type: pearson_cosine
            value: 0.8478162865349333
            name: Pearson Cosine
          - type: spearman_cosine
            value: 0.8495062962177747
            name: Spearman Cosine

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

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

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, and negative

  • Approximate 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: MultipleNegativesRankingLoss with these parameters:

    {
        "scale": 20.0,
        "similarity_fct": "cos_sim",
        "gather_across_devices": false
    }
    

Training Hyperparameters

Non-Default Hyperparameters

  • per_device_train_batch_size: 128
  • num_train_epochs: 1
  • learning_rate: 2e-05
  • warmup_steps: 412.0
  • bf16: True
  • eval_strategy: steps
  • per_device_eval_batch_size: 128
  • batch_sampler: no_duplicates

All Hyperparameters

Click to expand
  • per_device_train_batch_size: 128
  • num_train_epochs: 1
  • max_steps: -1
  • learning_rate: 2e-05
  • lr_scheduler_type: linear
  • lr_scheduler_kwargs: None
  • warmup_steps: 412.0
  • optim: adamw_torch_fused
  • optim_args: None
  • weight_decay: 0.0
  • adam_beta1: 0.9
  • adam_beta2: 0.999
  • adam_epsilon: 1e-08
  • optim_target_modules: None
  • gradient_accumulation_steps: 1
  • average_tokens_across_devices: True
  • max_grad_norm: 1.0
  • label_smoothing_factor: 0.0
  • bf16: True
  • fp16: False
  • bf16_full_eval: False
  • fp16_full_eval: False
  • tf32: None
  • gradient_checkpointing: False
  • gradient_checkpointing_kwargs: None
  • torch_compile: False
  • torch_compile_backend: None
  • torch_compile_mode: None
  • use_liger_kernel: False
  • liger_kernel_config: None
  • use_cache: False
  • neftune_noise_alpha: None
  • torch_empty_cache_steps: None
  • auto_find_batch_size: False
  • log_on_each_node: True
  • logging_nan_inf_filter: True
  • include_num_input_tokens_seen: no
  • log_level: passive
  • log_level_replica: warning
  • disable_tqdm: False
  • project: huggingface
  • trackio_space_id: trackio
  • eval_strategy: steps
  • per_device_eval_batch_size: 128
  • prediction_loss_only: True
  • eval_on_start: False
  • eval_do_concat_batches: True
  • eval_use_gather_object: False
  • eval_accumulation_steps: None
  • include_for_metrics: []
  • batch_eval_metrics: False
  • save_only_model: False
  • save_on_each_node: False
  • enable_jit_checkpoint: False
  • push_to_hub: False
  • hub_private_repo: None
  • hub_model_id: None
  • hub_strategy: every_save
  • hub_always_push: False
  • hub_revision: None
  • load_best_model_at_end: False
  • ignore_data_skip: False
  • restore_callback_states_from_checkpoint: False
  • full_determinism: False
  • seed: 42
  • data_seed: None
  • use_cpu: False
  • accelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
  • parallelism_config: None
  • dataloader_drop_last: False
  • dataloader_num_workers: 0
  • dataloader_pin_memory: True
  • dataloader_persistent_workers: False
  • dataloader_prefetch_factor: None
  • remove_unused_columns: True
  • label_names: None
  • train_sampling_strategy: random
  • length_column_name: length
  • ddp_find_unused_parameters: None
  • ddp_bucket_cap_mb: None
  • ddp_broadcast_buffers: False
  • ddp_backend: None
  • ddp_timeout: 1800
  • fsdp: []
  • fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
  • deepspeed: None
  • debug: []
  • skip_memory_metrics: True
  • do_predict: False
  • resume_from_checkpoint: None
  • warmup_ratio: None
  • local_rank: -1
  • prompts: None
  • batch_sampler: no_duplicates
  • multi_dataset_batch_sampler: proportional
  • router_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.