---
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):\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"
- source_sentence: python remove parenthesis around stringf
sentences:
- "def format_screen(strng):\n \"\"\"Format a string for screen printing.\n\n\
\ This removes some latex-type format codes.\"\"\"\n # Paragraph continue\n\
\ par_re = re.compile(r'\\\\$',re.MULTILINE)\n strng = par_re.sub('',strng)\n\
\ return strng"
- "def do_striptags(value):\n \"\"\"Strip SGML/XML tags and replace adjacent\
\ whitespace by one space.\n \"\"\"\n if hasattr(value, '__html__'):\n \
\ value = value.__html__()\n return Markup(unicode(value)).striptags()"
- "def _replace_file(path, content):\n \"\"\"Writes a file if it doesn't already\
\ exist with the same content.\n\n This is useful because cargo uses timestamps\
\ to decide whether to compile things.\"\"\"\n if os.path.exists(path):\n \
\ with open(path, 'r') as f:\n if content == f.read():\n print(\"\
Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n\
\ return\n\n with open(path, 'w') as f:\n f.write(content)"
- source_sentence: python out of range float values are not json compliant
sentences:
- "def show():\n \"\"\"Show (print out) current environment variables.\"\"\"\n\
\ env = get_environment()\n\n for key, val in sorted(env.env.items(), key=lambda\
\ item: item[0]):\n click.secho('%s = %s' % (key, val))"
- "def default_number_converter(number_str):\n \"\"\"\n Converts the string\
\ representation of a json number into its python object equivalent, an\n int,\
\ long, float or whatever type suits.\n \"\"\"\n is_int = (number_str.startswith('-')\
\ and number_str[1:].isdigit()) or number_str.isdigit()\n # FIXME: this handles\
\ a wider range of numbers than allowed by the json standard,\n # etc.: float('nan')\
\ and float('inf'). But is this a problem?\n return int(number_str) if is_int\
\ else float(number_str)"
- "def __get_float(section, name):\n \"\"\"Get the forecasted float from json\
\ section.\"\"\"\n try:\n return float(section[name])\n except (ValueError,\
\ TypeError, KeyError):\n 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\t\
os.utime(filename, (atime, mtime))"
- "def paste(cmd=paste_cmd, stdout=PIPE):\n \"\"\"Returns system clipboard contents.\n\
\ \"\"\"\n return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')"
- "def paste(xsel=False):\n \"\"\"Returns system clipboard contents.\"\"\"\n\
\ selection = \"primary\" if xsel else \"clipboard\"\n try:\n return\
\ subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"\
utf-8\")\n except OSError as why:\n raise XclipNotFound"
- source_sentence: python strftime miliseconds fixed width
sentences:
- "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 check_hash_key(query_on, key):\n \"\"\"Only allows == against query_on.hash_key\"\
\"\"\n return (\n isinstance(key, BaseCondition) and\n (key.operation\
\ == \"==\") and\n (key.column is query_on.hash_key)\n )"
- "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)"
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](https://www.SBERT.net) model finetuned from [benjamintli/modernbert-cosqa](https://huggingface.co/benjamintli/modernbert-cosqa) on the [cosqa-llm-filtered-hard-negatives](https://huggingface.co/datasets/benjamintli/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](https://huggingface.co/benjamintli/modernbert-cosqa)
- **Maximum Sequence Length:** 512 tokens
- **Output Dimensionality:** 768 dimensions
- **Similarity Function:** Cosine Similarity
- **Training Dataset:**
- [cosqa-llm-filtered-hard-negatives](https://huggingface.co/datasets/benjamintli/cosqa-llm-filtered-hard-negatives)
- **Language:** en
### Model Sources
- **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
- **Repository:** [Sentence Transformers on GitHub](https://github.com/huggingface/sentence-transformers)
- **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
### 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:
```bash
pip install -U sentence-transformers
```
Then you can load this model and run inference.
```python
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](https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html#sentence_transformers.evaluation.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](https://huggingface.co/datasets/benjamintli/cosqa-llm-filtered-hard-negatives) at [1585731](https://huggingface.co/datasets/benjamintli/cosqa-llm-filtered-hard-negatives/tree/1585731575d5b96ffdce2c27b70c8943a61edf75)
* Size: 19,963 training samples
* Columns: anchor, positive, and negative
* Approximate statistics based on the first 1000 samples:
| | anchor | positive | negative |
|:--------|:---------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|
| type | string | string | string |
| details |
python 2d array to dict | def 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 python | def _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 python | def b2u(string):
""" bytes to unicode """
if (isinstance(string, bytes) or
(PY2 and isinstance(string, str))):
return string.decode('utf-8')
return string | def 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: [CachedMultipleNegativesRankingLoss](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cachedmultiplenegativesrankingloss) with these parameters:
```json
{
"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](https://huggingface.co/datasets/benjamintli/cosqa-llm-filtered-hard-negatives) at [1585731](https://huggingface.co/datasets/benjamintli/cosqa-llm-filtered-hard-negatives/tree/1585731575d5b96ffdce2c27b70c8943a61edf75)
* Size: 2,219 evaluation samples
* Columns: anchor, positive, and negative
* Approximate statistics based on the first 1000 samples:
| | anchor | positive | negative |
|:--------|:---------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|
| type | string | string | string |
| details | way to change the string "python" to have all uppercase letters | def 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 python | def 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 python | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | def 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: [CachedMultipleNegativesRankingLoss](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cachedmultiplenegativesrankingloss) with these parameters:
```json
{
"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`: 1024
- `num_train_epochs`: 10
- `learning_rate`: 2e-06
- `warmup_steps`: 0.1
- `bf16`: True
- `eval_strategy`: epoch
- `per_device_eval_batch_size`: 1024
- `push_to_hub`: True
- `hub_model_id`: modernbert-cosqa-hard-negatives
- `load_best_model_at_end`: True
- `dataloader_num_workers`: 4
- `batch_sampler`: no_duplicates
#### All Hyperparameters