---
tags:
- sentence-transformers
- sentence-similarity
- feature-extraction
- dense
- generated_from_trainer
- dataset_size:193623
- loss:CachedMultipleNegativesRankingLoss
base_model: answerdotai/ModernBERT-base
widget:
- source_sentence: "@Override\n public void encode(final OtpOutputStream buf) {\n\
\ final int arity = elems.length;\n\n buf.write_tuple_head(arity);\n\
\n for (int i = 0; i < arity; i++) {\n buf.write_any(elems[i]);\n\
\ }\n }"
sentences:
- fetch function with the same interface than in cozy-client-js
- 'Convert this tuple to the equivalent Erlang external representation.
@param buf
an output stream to which the encoded tuple should be written.'
- 'Delete a customer by it''s id.
@param int $id The id
@return bool
@throws \Throwable in case something went wrong when deleting.'
- source_sentence: "func (md *RootMetadata) KeyGenerationsToUpdate() (kbfsmd.KeyGen,\
\ kbfsmd.KeyGen) {\n\treturn md.bareMd.KeyGenerationsToUpdate()\n}"
sentences:
- 'Return a mapping of table to alias for the primary table and joins.
@return array'
- // KeyGenerationsToUpdate wraps the respective method of the underlying BareRootMetadata
for convenience.
- " Platform.valueOf(platformName);\n DesiredCapabilities desiredCapabilities\
\ = new DesiredCapabilities(browser, version, platform);\n desiredCapabilities.setVersion(version);\n\
\ return createAndSetRemoteDriver(url, desiredCapabilities);\n }"
- source_sentence: "func (f *fsClient) GetAccess() (access string, policyJSON string,\
\ err *probe.Error) {\n\t// For windows this feature is not implemented.\n\tif\
\ runtime.GOOS == \"windows\" {\n\t\treturn \"\", \"\", probe.NewError(APINotImplemented{API:\
\ \"GetAccess\", APIType: \"filesystem\"})\n\t}\n\tst, err := f.fsStat(false)\n\
\tif err != nil {\n"
sentences:
- "\t\treturn \"\", \"\", err.Trace(f.PathURL.String())\n\t}\n\tif !st.Mode().IsDir()\
\ {\n\t\treturn \"\", \"\", probe.NewError(APINotImplemented{API: \"GetAccess\"\
, APIType: \"filesystem\"})\n\t}\n\t// Mask with os.ModePerm to get only inode\
\ permissions\n\tswitch st.Mode() & os.ModePerm {\n\tcase os.FileMode(0777):\n\
\t\treturn \"readwrite\", \"\", nil\n\tcase os.FileMode(0555):\n\t\treturn \"\
readonly\", \"\", nil\n\tcase os.FileMode(0333):\n\t\treturn \"writeonly\", \"\
\", nil\n\t}\n\treturn \"none\", \"\", nil\n}"
- // DeleteOperator deletes the specified operator.
- " foreach ($files as $storedfile) {\n $fs->import_external_file($storedfile);\n\
\ }\n }"
- source_sentence: "def close_database_session(session):\n \"\"\"Close connection\
\ with the database\"\"\"\n\n try:\n session.close()\n except OperationalError\
\ as e:\n raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])"
sentences:
- " if (is_array($this->data)) {\n $this->data[$attributeKey]\
\ = is_callable($attributeValue) ? $attributeValue($this->rawData) : $attributeValue;\n\
\ } else {\n $this->data->$attributeKey = is_callable($attributeValue)\
\ ? $attributeValue($this->rawData) : $attributeValue;\n }\n \
\ }\n return $this;\n }\n\n if (is_array($this->data))\
\ {\n $this->data[$name] = is_callable($value) ? $value($this->rawData)\
\ : $value;\n } else {\n $this->data->$name = is_callable($value)\
\ ? $value($this->rawData) : $value;\n }\n\n return $this;\n \
\ }"
- 'Waits for the timeout duration until the url responds with correct status code
@param routeUrl URL to check (usually a route one)
@param timeout Max timeout value to await for route readiness.
If not set, default timeout value is set to 5.
@param timeoutUnit TimeUnit used for timeout duration.
If not set, Minutes is used as default TimeUnit.
@param repetitions How many times in a row the route must respond successfully
to be considered available.
@param statusCodes list of status code that might return that service is up and
running.
It is used as OR, so if one returns true, then the route is considered valid.
If not set, then only 200 status code is used.'
- Close connection with the database
- source_sentence: "function onActiveEditorChanged(event, current, previous) {\n \
\ if (current && !current._codeMirror._lineFolds) {\n enableFoldingInEditor(current);\n\
\ "
sentences:
- Get playback settings such as shuffle and repeat.
- 'Save config data.
@param string $path
@param string $value
@param string $scope
@param int $scopeId
@return null'
- " }\n if (previous) {\n saveLineFolds(previous);\n \
\ }\n }"
datasets:
- benjamintli/code-retrieval-combined
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 answerdotai/ModernBERT-base
results:
- task:
type: information-retrieval
name: Information Retrieval
dataset:
name: eval
type: eval
metrics:
- type: cosine_accuracy@1
value: 0.9167054011341452
name: Cosine Accuracy@1
- type: cosine_accuracy@3
value: 0.9643023147717765
name: Cosine Accuracy@3
- type: cosine_accuracy@5
value: 0.9737845124105233
name: Cosine Accuracy@5
- type: cosine_accuracy@10
value: 0.9822441201078368
name: Cosine Accuracy@10
- type: cosine_precision@1
value: 0.9167054011341452
name: Cosine Precision@1
- type: cosine_precision@3
value: 0.32143410492392543
name: Cosine Precision@3
- type: cosine_precision@5
value: 0.19475690248210473
name: Cosine Precision@5
- type: cosine_precision@10
value: 0.09822441201078369
name: Cosine Precision@10
- type: cosine_recall@1
value: 0.9167054011341452
name: Cosine Recall@1
- type: cosine_recall@3
value: 0.9643023147717765
name: Cosine Recall@3
- type: cosine_recall@5
value: 0.9737845124105233
name: Cosine Recall@5
- type: cosine_recall@10
value: 0.9822441201078368
name: Cosine Recall@10
- type: cosine_ndcg@10
value: 0.9519116805931805
name: Cosine Ndcg@10
- type: cosine_mrr@10
value: 0.9419304852801657
name: Cosine Mrr@10
- type: cosine_map@100
value: 0.9425514042279245
name: Cosine Map@100
---
# SentenceTransformer based on answerdotai/ModernBERT-base
This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base) on the [code-retrieval-combined](https://huggingface.co/datasets/benjamintli/code-retrieval-combined) 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:** [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base)
- **Maximum Sequence Length:** 1024 tokens
- **Output Dimensionality:** 768 dimensions
- **Similarity Function:** Cosine Similarity
- **Training Dataset:**
- [code-retrieval-combined](https://huggingface.co/datasets/benjamintli/code-retrieval-combined)
### 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': 1024, '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-code")
# Run inference
queries = [
"function onActiveEditorChanged(event, current, previous) {\n if (current \u0026\u0026 !current._codeMirror._lineFolds) {\n enableFoldingInEditor(current);\n ",
]
documents = [
' }\n if (previous) {\n saveLineFolds(previous);\n }\n }',
'Save config data.\n\n@param string $path\n@param string $value\n@param string $scope\n@param int $scopeId\n\n@return null',
'Get playback settings such as shuffle and repeat.',
]
query_embeddings = model.encode_query(queries)
document_embeddings = model.encode_document(documents)
print(query_embeddings.shape, document_embeddings.shape)
# [1, 768] [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(query_embeddings, document_embeddings)
print(similarities)
# tensor([[0.6443, 0.0381, 0.0291]])
```
## 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.9167 |
| cosine_accuracy@3 | 0.9643 |
| cosine_accuracy@5 | 0.9738 |
| cosine_accuracy@10 | 0.9822 |
| cosine_precision@1 | 0.9167 |
| cosine_precision@3 | 0.3214 |
| cosine_precision@5 | 0.1948 |
| cosine_precision@10 | 0.0982 |
| cosine_recall@1 | 0.9167 |
| cosine_recall@3 | 0.9643 |
| cosine_recall@5 | 0.9738 |
| cosine_recall@10 | 0.9822 |
| **cosine_ndcg@10** | **0.9519** |
| cosine_mrr@10 | 0.9419 |
| cosine_map@100 | 0.9426 |
## Training Details
### Training Dataset
#### code-retrieval-combined
* Dataset: [code-retrieval-combined](https://huggingface.co/datasets/benjamintli/code-retrieval-combined) at [4403b52](https://huggingface.co/datasets/benjamintli/code-retrieval-combined/tree/4403b525f5962df8374b128e0863482e07cb1dc9)
* Size: 193,623 training samples
* Columns: query and positive
* Approximate statistics based on the first 1000 samples:
| | query | positive |
|:--------|:-------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|
| type | string | string |
| details |
protected function sendMusicMsgToJsonString(WxSendMusicMsg $msg)
{
$formatStr = '{
"touser":"%s",
"msgtype":"%s",
"music":
{
"title":"%s",
"description":"%s",
"musicurl":"%s",
"hqmusicurl":"%s",
"thumb_media_id":"%s"
}
}';
$result = sprintf($formatStr, $msg->getToUserName(),
$msg->getMsgType(),
$msg->getTitle(),
$msg->getDescription(),
$msg->getMusicUrl(),
$msg->getHQMusicUrl(),
$msg->getThumbMediaId()
);
return $result;
} | formatter WxSendMusicMsg to Json string
@param WxSendMusicMsg $msg
@return string |
| def getBlocks(self):
"""
Get the blocks that need to be migrated
"""
try:
conn = self.dbi.connection()
result = | self.buflistblks.execute(conn)
return result
finally:
if conn:
conn.close() |
| function obj(/*key,value, key,value ...*/) {
var result = {}
for(var n=0; n result[arguments[n]] = arguments[n+1]
}
return result
} | builds an object immediate where keys can be expressions |
* 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": 128,
"gather_across_devices": false,
"directions": [
"query_to_doc"
],
"partition_mode": "joint",
"hardness_mode": null,
"hardness_strength": 0.0
}
```
### Evaluation Dataset
#### code-retrieval-combined
* Dataset: [code-retrieval-combined](https://huggingface.co/datasets/benjamintli/code-retrieval-combined) at [4403b52](https://huggingface.co/datasets/benjamintli/code-retrieval-combined/tree/4403b525f5962df8374b128e0863482e07cb1dc9)
* Size: 21,514 evaluation samples
* Columns: query and positive
* Approximate statistics based on the first 1000 samples:
| | query | positive |
|:--------|:-------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|
| type | string | string |
| details | def save
self.attributes.stringify_keys!
self.attributes.delete('customer')
self.attributes.delete('product')
self.attributes.delete('credit_card')
self.attributes.delete('bank_account')
self.attributes.delete('paypal_account')
| self.attributes, options = extract_uniqueness_token(attributes)
self.prefix_options.merge!(options)
super
end |
| def _update_summary(self, summary=None):
"""Update all parts of the summary or clear when no summary."""
board_image_label = self._parts['board image label']
# get content for update or use blanks when no summary
if summary:
# make a board image with the swap drawn on it
# board, action, text = summary.board, summary.action, summary.text
board_image_cv = self._create_board_image_cv(summary.board)
self._draw_swap_cv(board_image_cv, summary.action)
board_image_tk = self._convert_cv_to_tk(board_image_cv)
text = ''
if not summary.score is None:
text += 'Score: {:3.1f}'.format(summary.score)
if (not summary.mana_drain_leaves is None) and\
(not summary.total_leaves is None):
text += ' Mana Drains: {}/{}' \
''.format(summary.mana_drain_leaves,
| summary.total_leaves)
else:
#clear any stored state image and use the blank
board_image_tk = board_image_label._blank_image
text = ''
# update the UI parts with the content
board_image_label._board_image = board_image_tk
board_image_label.config(image=board_image_tk)
# update the summary text
summary_label = self._parts['summary label']
summary_label.config(text=text)
# refresh the UI
self._base.update() |
| def chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
"""Returns the effective precession spin from mass1, mass2, spin1x,
spin1y, spin2x, and spin2y.
"""
xi1 = secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
xi2 = primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
return chi_p_from_xi1_xi2(xi1, xi2) | Returns the effective precession spin from mass1, mass2, spin1x,
spin1y, spin2x, and spin2y. |
* 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": 128,
"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`: 1
- `learning_rate`: 8e-05
- `warmup_steps`: 0.05
- `bf16`: True
- `eval_strategy`: steps
- `per_device_eval_batch_size`: 1024
- `push_to_hub`: True
- `hub_model_id`: modernbert-code
- `load_best_model_at_end`: True
- `dataloader_num_workers`: 4
- `batch_sampler`: no_duplicates
#### All Hyperparameters