SentenceTransformer based on NorBERT4-large
NorSBERT4-Large is a Sentence Transformer model finetuned from ltg/norbert4-large. The model maps sentences (and paragraphs) to a 960-dimensional dense vector space and can be used for semantic textual similarity, semantic search, text classification, clustering, among other tasks.
Note: While the fine-tuned sentence-transformer model has a max_seq_length of 75 tokens, the base model does not.
This means that the sequence length can be increased to 16384 (which is the max length in the base model).
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. Note that you should load the model with trust_remote_code=True because it needs a custom wrapper (see the base model for more details).
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("Fremtind/norsbert4-large", trust_remote_code=True)
# Run inference
sentences = [
'To personer, en i lyse jeans og en stripete skjorte, spiller biljard.',
'Folk spiller biljard',
'folk løper',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 960]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.7294, 0.1690],
# [0.7294, 1.0000, 0.2412],
# [0.1690, 0.2412, 1.0000]])
Evaluation
To verify the utility of our models, we evaluated them on a selection of classification and clustering tasks for Norwegian from MTEBv2.
The heatmap below shows the results of evaluating five sentence-transformers on ten different tasks; three of the sentence-transformer models we have fine-tuned (Fremtind/norsbert4-large, Fremtind/norsbert4-base, Fremtind/mmBERT-base-norwegian) and the other two are relatively popular (and comparable) sentence similarity models (FFI/SimCSE-NB-BERT-large and NbAiLab/nb-sbert-base).
We ranked the models using Borda count (which is used in MTEB), where each model was assigned a number of points based on its relative performance across all evaluated tasks.
| Rank | Model | Borda Points |
|---|---|---|
| 1 | Fremtind/norsbert4-large | 44 |
| 2 | FFI/SimCSE-NB-BERT-large | 40 |
| 3 | Fremtind/norsbert4-base | 24 |
| 4 | NbAiLab/nb-sbert-base | 15 |
| 5 | Fremtind/mmBERT-base-norwegian | 7 |
Training Details
The model was fine-tuned in two stages.
In the first stage, it was trained in an unsupervised manner following the SimCSE method (Gao et al., 2021). In this setup, the same sentence is encoded twice, and due to dropout (in training mode), the model produces two slightly different embeddings. The training objective is to minimize the distance between these embeddings while maximizing the distance to embeddings of other sentences in the same batch. For this stage, we created sentence pairs in three categories from the NDLA Parallel Paragraphs dataset: (Bokmål, Bokmål), (Nynorsk, Nynorsk), and (Bokmål, Nynorsk). In the (Bokmål, Bokmål) and (Nynorsk, Nynorsk) pairs, each sentence was paired with itself, leveraging dropout to create embedding variation. In the (Bokmål, Nynorsk) category, cross-lingual sentence pairs were used to align the model’s semantic representations across the two language varieties.
In the second stage, the model was further fine-tuned on a natural language inference dataset, namely Fremtind/all-nli-norwegian. The dataset is formatted as triplets (anchor, positive, negative), where the anchor is the premise, the positive is an entailment hypothesis, and the negative is a contradiction hypothesis. The objective is to minimize the distance between the anchor and positive while maximizing it between the anchor and negative. This fine-tuning stage follows the 'standard' supervised fine-tuning strategy introduced in Sentence-BERT.
Training Hyperparameters
Non-Default Hyperparameters
Click to expand
eval_strategy: stepsper_device_train_batch_size: 512per_device_eval_batch_size: 256num_train_epochs: 1warmup_ratio: 0.1batch_sampler: no_duplicates
All Hyperparameters
Click to expand
overwrite_output_dir: Falsedo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 512per_device_eval_batch_size: 256per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 1max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_ratio: 0.1warmup_steps: 0log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Truesave_safetensors: Truesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseno_cuda: Falseuse_cpu: Falseuse_mps_device: Falseseed: 42data_seed: Nonejit_mode_eval: Falseuse_ipex: Falsebf16: Falsefp16: Falsefp16_opt_level: O1half_precision_backend: autobf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: 1ddp_backend: Nonetpu_num_cores: Nonetpu_metrics_debug: Falsedebug: []dataloader_drop_last: Truedataloader_num_workers: 0dataloader_prefetch_factor: Nonepast_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_min_num_params: 0fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedeepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torchoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsehub_revision: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_inputs_for_metrics: Falseinclude_for_metrics: []eval_do_concat_batches: Truefp16_backend: autopush_to_hub_model_id: Nonepush_to_hub_organization: Nonemp_parameters:auto_find_batch_size: Falsefull_determinism: Falsetorchdynamo: Noneray_scope: lastddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_tokens_per_second: Falseinclude_num_input_tokens_seen: Falseneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Trueprompts: Nonebatch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}
Framework Versions
Click to expand
- Python: 3.12.11
- Sentence Transformers: 5.1.1
- Transformers: 4.56.2
- PyTorch: 2.6.0+cu124
- Accelerate: 1.10.1
- Datasets: 4.1.1
- Tokenizers: 0.22.1
- Downloads last month
- 85
Model tree for Fremtind/norsbert4-large
Base model
ltg/norbert4-large