Sentence Similarity
sentence-transformers
Safetensors
English
modernbert
feature-extraction
dense
Generated from Trainer
dataset_size:19963
loss:CachedMultipleNegativesRankingLoss
Eval Results (legacy)
text-embeddings-inference
Instructions to use benjamintli/modernbert-cosqa-hard-negatives with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use benjamintli/modernbert-cosqa-hard-negatives with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("benjamintli/modernbert-cosqa-hard-negatives") sentences = [ "python string to microseconds", "def seconds_to_hms(seconds):\n \"\"\"\n Converts seconds float to 'hh:mm:ss.ssssss' format.\n \"\"\"\n hours = int(seconds / 3600.0)\n minutes = int((seconds / 60.0) % 60.0)\n secs = float(seconds % 60.0)\n return \"{0:02d}:{1:02d}:{2:02.6f}\".format(hours, minutes, secs)", "def align_file_position(f, size):\n \"\"\" Align the position in the file to the next block of specified size \"\"\"\n align = (size - 1) - (f.tell() % size)\n f.seek(align, 1)", "def timestamp_to_microseconds(timestamp):\n \"\"\"Convert a timestamp string into a microseconds value\n :param timestamp\n :return time in microseconds\n \"\"\"\n timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)\n epoch_time_secs = calendar.timegm(timestamp_str.timetuple())\n epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond\n return epoch_time_mus" ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [4, 4] - Notebooks
- Google Colab
- Kaggle
metadata
language:
- en
tags:
- sentence-transformers
- sentence-similarity
- feature-extraction
- dense
- generated_from_trainer
- dataset_size:19963
- loss:CachedMultipleNegativesRankingLoss
base_model: benjamintli/modernbert-cosqa
widget:
- source_sentence: python string to microseconds
sentences:
- |-
def seconds_to_hms(seconds):
"""
Converts seconds float to 'hh:mm:ss.ssssss' format.
"""
hours = int(seconds / 3600.0)
minutes = int((seconds / 60.0) % 60.0)
secs = float(seconds % 60.0)
return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)
- |-
def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1)
- |-
def timestamp_to_microseconds(timestamp):
"""Convert a timestamp string into a microseconds value
:param timestamp
:return time in microseconds
"""
timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)
epoch_time_secs = calendar.timegm(timestamp_str.timetuple())
epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond
return epoch_time_mus
- source_sentence: python remove parenthesis around stringf
sentences:
- |-
def format_screen(strng):
"""Format a string for screen printing.
This removes some latex-type format codes."""
# Paragraph continue
par_re = re.compile(r'\\$',re.MULTILINE)
strng = par_re.sub('',strng)
return strng
- |-
def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(unicode(value)).striptags()
- |-
def _replace_file(path, content):
"""Writes a file if it doesn't already exist with the same content.
This is useful because cargo uses timestamps to decide whether to compile things."""
if os.path.exists(path):
with open(path, 'r') as f:
if content == f.read():
print("Not overwriting {} because it is unchanged".format(path), file=sys.stderr)
return
with open(path, 'w') as f:
f.write(content)
- source_sentence: python out of range float values are not json compliant
sentences:
- |-
def show():
"""Show (print out) current environment variables."""
env = get_environment()
for key, val in sorted(env.env.items(), key=lambda item: item[0]):
click.secho('%s = %s' % (key, val))
- |-
def default_number_converter(number_str):
"""
Converts the string representation of a json number into its python object equivalent, an
int, long, float or whatever type suits.
"""
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()
# FIXME: this handles a wider range of numbers than allowed by the json standard,
# etc.: float('nan') and float('inf'). But is this a problem?
return int(number_str) if is_int else float(number_str)
- |-
def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0)
- source_sentence: python openclipboard access is denied win32clipboard
sentences:
- "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))"
- |-
def paste(cmd=paste_cmd, stdout=PIPE):
"""Returns system clipboard contents.
"""
return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
- |-
def paste(xsel=False):
"""Returns system clipboard contents."""
selection = "primary" if xsel else "clipboard"
try:
return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8")
except OSError as why:
raise XclipNotFound
- source_sentence: python strftime miliseconds fixed width
sentences:
- |-
def fmt_duration(secs):
"""Format a duration in seconds."""
return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
- |-
def check_hash_key(query_on, key):
"""Only allows == against query_on.hash_key"""
return (
isinstance(key, BaseCondition) and
(key.operation == "==") and
(key.column is query_on.hash_key)
)
- |-
def seconds_to_hms(seconds):
"""
Converts seconds float to 'hh:mm:ss.ssssss' format.
"""
hours = int(seconds / 3600.0)
minutes = int((seconds / 60.0) % 60.0)
secs = float(seconds % 60.0)
return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)
datasets:
- benjamintli/cosqa-llm-filtered-hard-negatives
pipeline_tag: sentence-similarity
library_name: sentence-transformers
metrics:
- cosine_accuracy@1
- cosine_accuracy@3
- cosine_accuracy@5
- cosine_accuracy@10
- cosine_precision@1
- cosine_precision@3
- cosine_precision@5
- cosine_precision@10
- cosine_recall@1
- cosine_recall@3
- cosine_recall@5
- cosine_recall@10
- cosine_ndcg@10
- cosine_mrr@10
- cosine_map@100
model-index:
- name: SentenceTransformer based on benjamintli/modernbert-cosqa
results:
- task:
type: information-retrieval
name: Information Retrieval
dataset:
name: eval
type: eval
metrics:
- type: cosine_accuracy@1
value: 0.5520504731861199
name: Cosine Accuracy@1
- type: cosine_accuracy@3
value: 0.8598467778278504
name: Cosine Accuracy@3
- type: cosine_accuracy@5
value: 0.9310500225326723
name: Cosine Accuracy@5
- type: cosine_accuracy@10
value: 0.975214060387562
name: Cosine Accuracy@10
- type: cosine_precision@1
value: 0.5520504731861199
name: Cosine Precision@1
- type: cosine_precision@3
value: 0.2866155926092835
name: Cosine Precision@3
- type: cosine_precision@5
value: 0.18621000450653444
name: Cosine Precision@5
- type: cosine_precision@10
value: 0.09752140603875618
name: Cosine Precision@10
- type: cosine_recall@1
value: 0.5520504731861199
name: Cosine Recall@1
- type: cosine_recall@3
value: 0.8598467778278504
name: Cosine Recall@3
- type: cosine_recall@5
value: 0.9310500225326723
name: Cosine Recall@5
- type: cosine_recall@10
value: 0.975214060387562
name: Cosine Recall@10
- type: cosine_ndcg@10
value: 0.778855811581032
name: Cosine Ndcg@10
- type: cosine_mrr@10
value: 0.7140104937874189
name: Cosine Mrr@10
- type: cosine_map@100
value: 0.7154223269913967
name: Cosine Map@100
SentenceTransformer based on benjamintli/modernbert-cosqa
This is a sentence-transformers model finetuned from benjamintli/modernbert-cosqa on the cosqa-llm-filtered-hard-negatives dataset. It 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.
Model Details
Model Description
- Model Type: Sentence Transformer
- Base model: benjamintli/modernbert-cosqa
- Maximum Sequence Length: 512 tokens
- Output Dimensionality: 768 dimensions
- Similarity Function: Cosine Similarity
- Training Dataset:
- Language: en
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': 'OptimizedModule'})
(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("modernbert-cosqa-hard-negatives")
# Run inference
sentences = [
'python strftime miliseconds fixed width',
'def fmt_duration(secs):\n """Format a duration in seconds."""\n return \' \'.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())',
'def seconds_to_hms(seconds):\n """\n Converts seconds float to \'hh:mm:ss.ssssss\' format.\n """\n hours = int(seconds / 3600.0)\n minutes = int((seconds / 60.0) % 60.0)\n secs = float(seconds % 60.0)\n return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.7076, 0.6960],
# [0.7076, 1.0000, 0.7423],
# [0.6960, 0.7423, 1.0000]])
Evaluation
Metrics
Information Retrieval
- Dataset:
eval - Evaluated with
InformationRetrievalEvaluator
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.5521 |
| cosine_accuracy@3 | 0.8598 |
| cosine_accuracy@5 | 0.9311 |
| cosine_accuracy@10 | 0.9752 |
| cosine_precision@1 | 0.5521 |
| cosine_precision@3 | 0.2866 |
| cosine_precision@5 | 0.1862 |
| cosine_precision@10 | 0.0975 |
| cosine_recall@1 | 0.5521 |
| cosine_recall@3 | 0.8598 |
| cosine_recall@5 | 0.9311 |
| cosine_recall@10 | 0.9752 |
| cosine_ndcg@10 | 0.7789 |
| cosine_mrr@10 | 0.714 |
| cosine_map@100 | 0.7154 |
Training Details
Training Dataset
cosqa-llm-filtered-hard-negatives
- Dataset: cosqa-llm-filtered-hard-negatives at 1585731
- Size: 19,963 training samples
- Columns:
anchor,positive, andnegative - Approximate statistics based on the first 1000 samples:
anchor positive negative type string string string details - min: 6 tokens
- mean: 9.57 tokens
- max: 22 tokens
- min: 37 tokens
- mean: 88.3 tokens
- max: 512 tokens
- min: 36 tokens
- mean: 94.31 tokens
- max: 512 tokens
- Samples:
anchor positive negative python 2d array to dictdef to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist()))def multidict_to_dict(d):
"""
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
list values
:param d: a MultiDict or MultiValueDict instance
:return: a dict instance
"""
return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))how to send dns request message in pythondef _request_modify_dns_record(self, record):
"""Sends Modify_DNS_Record request"""
return self._request_internal("Modify_DNS_Record",
domain=self.domain,
record=record)def request(self, method, url, body=None, headers={}):
"""Send a complete request to the server."""
self._send_request(method, url, body, headers)how to cast string to uint8 in pythondef b2u(string):
""" bytes to unicode """
if (isinstance(string, bytes) or
(PY2 and isinstance(string, str))):
return string.decode('utf-8')
return stringdef to_bytes(s, encoding="utf-8"):
"""Convert a string to bytes."""
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding) - Loss:
CachedMultipleNegativesRankingLosswith these parameters:{ "scale": 20.0, "similarity_fct": "cos_sim", "mini_batch_size": 64, "gather_across_devices": false, "directions": [ "query_to_doc" ], "partition_mode": "joint", "hardness_mode": null, "hardness_strength": 0.0 }
Evaluation Dataset
cosqa-llm-filtered-hard-negatives
- Dataset: cosqa-llm-filtered-hard-negatives at 1585731
- Size: 2,219 evaluation samples
- Columns:
anchor,positive, andnegative - Approximate statistics based on the first 1000 samples:
anchor positive negative type string string string details - min: 6 tokens
- mean: 9.65 tokens
- max: 21 tokens
- min: 35 tokens
- mean: 88.87 tokens
- max: 512 tokens
- min: 37 tokens
- mean: 94.56 tokens
- max: 512 tokens
- Samples:
anchor positive negative way to change the string "python" to have all uppercase lettersdef uppercase_chars(string: any) -> str:
"""Return all (and only) the uppercase chars in the given string."""
return ''.join([c if c.isupper() else '' for c in str(string)])def to_capitalized_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var"
would become "SomeVar".
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.split('_')
return ''.join([i.title() for i in parts])how to make intercept zero in pythondef prox_zero(X, step):
"""Proximal operator to project onto zero
"""
return np.zeros(X.shape, dtype=X.dtype)def _adjust_offset(self, real_wave_mfcc, algo_parameters):
"""
OFFSET
"""
self.log(u"Called _adjust_offset")
self._apply_offset(offset=algo_parameters[0])stop running function and passing to other variable pythondef stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = Nonedef stop(self, dummy_signum=None, dummy_frame=None):
""" Shutdown process (this method is also a signal handler) """
logging.info('Shutting down ...')
self.socket.close()
sys.exit(0) - Loss:
CachedMultipleNegativesRankingLosswith these parameters:{ "scale": 20.0, "similarity_fct": "cos_sim", "mini_batch_size": 64, "gather_across_devices": false, "directions": [ "query_to_doc" ], "partition_mode": "joint", "hardness_mode": null, "hardness_strength": 0.0 }
Training Hyperparameters
Non-Default Hyperparameters
per_device_train_batch_size: 1024num_train_epochs: 10learning_rate: 2e-06warmup_steps: 0.1bf16: Trueeval_strategy: epochper_device_eval_batch_size: 1024push_to_hub: Truehub_model_id: modernbert-cosqa-hard-negativesload_best_model_at_end: Truedataloader_num_workers: 4batch_sampler: no_duplicates
All Hyperparameters
Click to expand
per_device_train_batch_size: 1024num_train_epochs: 10max_steps: -1learning_rate: 2e-06lr_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: 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: epochper_device_eval_batch_size: 1024prediction_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: Truehub_private_repo: Nonehub_model_id: modernbert-cosqa-hard-negativeshub_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: 4dataloader_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
| Epoch | Step | Training Loss | Validation Loss | eval_cosine_ndcg@10 |
|---|---|---|---|---|
| 0.5 | 10 | 1.5380 | - | - |
| 1.0 | 20 | 1.4167 | 0.9702 | 0.7440 |
| 1.5 | 30 | 1.4515 | - | - |
| 2.0 | 40 | 1.3789 | 0.9269 | 0.7499 |
| 2.5 | 50 | 1.3920 | - | - |
| 3.0 | 60 | 1.2849 | 0.8898 | 0.7581 |
| 3.5 | 70 | 1.3585 | - | - |
| 4.0 | 80 | 1.2197 | 0.8572 | 0.7653 |
| 4.5 | 90 | 1.2825 | - | - |
| 5.0 | 100 | 1.2078 | 0.8350 | 0.7686 |
| 5.5 | 110 | 1.2496 | - | - |
| 6.0 | 120 | 1.1569 | 0.8104 | 0.7720 |
| 6.5 | 130 | 1.2119 | - | - |
| 7.0 | 140 | 1.1278 | 0.7952 | 0.7754 |
| 7.5 | 150 | 1.1812 | - | - |
| 8.0 | 160 | 1.1018 | 0.7835 | 0.7770 |
| 8.5 | 170 | 1.1696 | - | - |
| 9.0 | 180 | 1.0972 | 0.7788 | 0.7786 |
| 9.5 | 190 | 1.1655 | - | - |
| 10.0 | 200 | 1.0796 | 0.7755 | 0.7789 |
- The bold row denotes the saved checkpoint.
Framework Versions
- Python: 3.12.12
- Sentence Transformers: 5.3.0
- Transformers: 5.3.0
- PyTorch: 2.10.0+cu128
- Accelerate: 1.13.0
- Datasets: 4.8.2
- 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",
}
CachedMultipleNegativesRankingLoss
@misc{gao2021scaling,
title={Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup},
author={Luyu Gao and Yunyi Zhang and Jiawei Han and Jamie Callan},
year={2021},
eprint={2101.06983},
archivePrefix={arXiv},
primaryClass={cs.LG}
}