Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 18
How to use sjmeis/task-cross-encoder-v1 with sentence-transformers:
from sentence_transformers import CrossEncoder
model = CrossEncoder("sjmeis/task-cross-encoder-v1")
query = "Which planet is known as the Red Planet?"
passages = [
"Venus is often called Earth's twin because of its similar size and proximity.",
"Mars, known for its reddish appearance, is often referred to as the Red Planet.",
"Jupiter, the largest planet in our solar system, has a prominent red spot.",
"Saturn, famous for its rings, is sometimes mistaken for the Red Planet."
]
scores = model.predict([(query, passage) for passage in passages])
print(scores)This is a Cross Encoder model finetuned from cross-encoder/ettin-reranker-68m-v1 using the sentence-transformers library. It computes scores for pairs of texts, which can be used for text reranking and semantic search.
CrossEncoder(
(0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}}, 'module_output_name': 'token_embeddings', 'architecture': 'ModernBertModel'})
(1): Pooling({'embedding_dimension': 512, 'pooling_mode': 'cls', 'include_prompt': True})
(2): Dense({'in_features': 512, 'out_features': 512, 'bias': False, 'activation_function': 'torch.nn.modules.activation.GELU', 'module_input_name': 'sentence_embedding', 'module_output_name': 'sentence_embedding'})
(3): LayerNorm({'dimension': 512})
(4): Dense({'in_features': 512, 'out_features': 1, 'bias': True, 'activation_function': 'torch.nn.modules.linear.Identity', 'module_input_name': 'sentence_embedding', 'module_output_name': 'scores'})
)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import CrossEncoder
# Download from the 🤗 Hub
model = CrossEncoder("cross_encoder_model_id")
# Get scores for pairs of inputs
pairs = [
['Plan, organize, or maintain dental health programs.', 'Turn or reposition bedridden patients.'],
['Maintain required records of work hours, budgets, payrolls, and other information.', 'Process payroll information.'],
['Conduct research to develop or test medications, treatments, or procedures to prevent or control disease or injury.', 'Conduct clinical or basic research.'],
['Prepare and submit reports describing the results of security fixes.', 'Receive patients, schedule appointments, and maintain patient records.'],
['Determine work assignments and procedures.', 'Conduct inventories to maintain stock of clinical supplies.'],
]
scores = model.predict(pairs)
print(scores)
# [-2.6881 1.3212 -0.5072 -2.6118 -2.2695]
# Or rank different texts based on similarity to a single text
ranks = model.rank(
'Plan, organize, or maintain dental health programs.',
[
'Turn or reposition bedridden patients.',
'Process payroll information.',
'Conduct clinical or basic research.',
'Receive patients, schedule appointments, and maintain patient records.',
'Conduct inventories to maintain stock of clinical supplies.',
]
)
# [{'corpus_id': ..., 'score': ...}, {'corpus_id': ..., 'score': ...}, ...]
val_correlationCrossEncoderCorrelationEvaluator| Metric | Value |
|---|---|
| pearson | 0.8442 |
| spearman | 0.8962 |
sentence1, sentence2, and label| sentence1 | sentence2 | label | |
|---|---|---|---|
| type | string | string | float |
| modality | text | text | |
| details |
|
|
|
| sentence1 | sentence2 | label |
|---|---|---|
Monitor customer preferences to determine focus of sales efforts. |
Advise food service managers and organizations on sanitation, safety procedures, menu development, budgeting, and planning to assist with establishment, operation, and evaluation of food service facilities and nutrition programs. |
0.07737485777805486 |
Collaborate with colleagues to address teaching and research issues. |
Collaborate with colleagues to address teaching and research issues. |
0.6937963999029872 |
Keep abreast of developments in the field by reading current literature, talking with colleagues, and participating in professional conferences. |
Keep abreast of developments in the field by reading current literature, talking with colleagues, and participating in professional conferences. |
0.6937963999029872 |
BinaryCrossEntropyLoss with these parameters:{
"activation_fn": "torch.nn.modules.linear.Identity",
"pos_weight": null
}
sentence1, sentence2, and label| sentence1 | sentence2 | label | |
|---|---|---|---|
| type | string | string | float |
| modality | text | text | |
| details |
|
|
|
| sentence1 | sentence2 | label |
|---|---|---|
Plan, organize, or maintain dental health programs. |
Turn or reposition bedridden patients. |
0.056361597787474016 |
Maintain required records of work hours, budgets, payrolls, and other information. |
Process payroll information. |
0.8059258707828006 |
Conduct research to develop or test medications, treatments, or procedures to prevent or control disease or injury. |
Conduct clinical or basic research. |
0.37034095223637237 |
BinaryCrossEntropyLoss with these parameters:{
"activation_fn": "torch.nn.modules.linear.Identity",
"pos_weight": null
}
per_device_train_batch_size: 128learning_rate: 2e-05warmup_steps: 0.1per_device_eval_batch_size: 128load_best_model_at_end: Trueper_device_train_batch_size: 128num_train_epochs: 3max_steps: -1learning_rate: 2e-05lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0.1optim: 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: Falsefp16: 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: Nonetrackio_bucket_id: Nonetrackio_static_space_id: Noneper_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: Trueignore_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: Nonedataloader_multiprocessing_context: Nonedataloader_in_order: Trueremove_unused_columns: Truelabel_names: Nonetrain_sampling_strategy: randomlength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falseddp_static_graph: Noneddp_backend: Noneddp_timeout: 1800fsdp: Nonefsdp_config: Nonedeepspeed: Nonedebug: []skip_memory_metrics: Truedo_predict: Falseresume_from_checkpoint: Nonelocal_rank: -1prompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}warmup_ratio: None| Epoch | Step | Training Loss | Validation Loss | val_correlation_spearman |
|---|---|---|---|---|
| 0.0434 | 100 | 1.6617 | - | - |
| 0.0867 | 200 | 0.4783 | - | - |
| 0.1301 | 300 | 0.4244 | - | - |
| 0.1735 | 400 | 0.4227 | - | - |
| 0.2168 | 500 | 0.4231 | - | - |
| 0.2602 | 600 | 0.4164 | - | - |
| 0.3036 | 700 | 0.4201 | - | - |
| 0.3469 | 800 | 0.4195 | - | - |
| 0.3903 | 900 | 0.4109 | - | - |
| 0.4337 | 1000 | 0.4132 | - | - |
| 0.4770 | 1100 | 0.4145 | - | - |
| 0.5204 | 1200 | 0.4169 | - | - |
| 0.5637 | 1300 | 0.4135 | - | - |
| 0.6071 | 1400 | 0.4179 | - | - |
| 0.6505 | 1500 | 0.4085 | - | - |
| 0.6938 | 1600 | 0.4119 | - | - |
| 0.7372 | 1700 | 0.4125 | - | - |
| 0.7806 | 1800 | 0.4119 | - | - |
| 0.8239 | 1900 | 0.4096 | - | - |
| 0.8673 | 2000 | 0.4123 | - | - |
| 0.9107 | 2100 | 0.4081 | - | - |
| 0.9540 | 2200 | 0.4084 | - | - |
| 0.9974 | 2300 | 0.4100 | - | - |
| 1.0 | 2306 | - | 0.4095 | 0.8917 |
| 1.0408 | 2400 | 0.4077 | - | - |
| 1.0841 | 2500 | 0.4046 | - | - |
| 1.1275 | 2600 | 0.4061 | - | - |
| 1.1709 | 2700 | 0.4052 | - | - |
| 1.2142 | 2800 | 0.4055 | - | - |
| 1.2576 | 2900 | 0.4062 | - | - |
| 1.3010 | 3000 | 0.4026 | - | - |
| 1.3443 | 3100 | 0.4059 | - | - |
| 1.3877 | 3200 | 0.4039 | - | - |
| 1.4310 | 3300 | 0.4050 | - | - |
| 1.4744 | 3400 | 0.4047 | - | - |
| 1.5178 | 3500 | 0.4004 | - | - |
| 1.5611 | 3600 | 0.4053 | - | - |
| 1.6045 | 3700 | 0.4008 | - | - |
| 1.6479 | 3800 | 0.4042 | - | - |
| 1.6912 | 3900 | 0.4015 | - | - |
| 1.7346 | 4000 | 0.4057 | - | - |
| 1.7780 | 4100 | 0.4018 | - | - |
| 1.8213 | 4200 | 0.4048 | - | - |
| 1.8647 | 4300 | 0.4015 | - | - |
| 1.9081 | 4400 | 0.4052 | - | - |
| 1.9514 | 4500 | 0.4026 | - | - |
| 1.9948 | 4600 | 0.4028 | - | - |
| 2.0 | 4612 | - | 0.4062 | 0.8967 |
| 2.0382 | 4700 | 0.3993 | - | - |
| 2.0815 | 4800 | 0.3973 | - | - |
| 2.1249 | 4900 | 0.3982 | - | - |
| 2.1683 | 5000 | 0.3991 | - | - |
| 2.2116 | 5100 | 0.3956 | - | - |
| 2.2550 | 5200 | 0.4006 | - | - |
| 2.2984 | 5300 | 0.3985 | - | - |
| 2.3417 | 5400 | 0.3962 | - | - |
| 2.3851 | 5500 | 0.3964 | - | - |
| 2.4284 | 5600 | 0.4017 | - | - |
| 2.4718 | 5700 | 0.3977 | - | - |
| 2.5152 | 5800 | 0.3981 | - | - |
| 2.5585 | 5900 | 0.3968 | - | - |
| 2.6019 | 6000 | 0.3973 | - | - |
| 2.6453 | 6100 | 0.3993 | - | - |
| 2.6886 | 6200 | 0.4029 | - | - |
| 2.7320 | 6300 | 0.4011 | - | - |
| 2.7754 | 6400 | 0.3980 | - | - |
| 2.8187 | 6500 | 0.3955 | - | - |
| 2.8621 | 6600 | 0.3985 | - | - |
| 2.9055 | 6700 | 0.3952 | - | - |
| 2.9488 | 6800 | 0.3948 | - | - |
| 2.9922 | 6900 | 0.3972 | - | - |
| 3.0 | 6918 | - | 0.4057 | 0.8962 |
@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",
}
Base model
jhu-clsp/ettin-encoder-68m