benjamintli/code-retrieval-combined
Viewer • Updated • 215k • 13
How to use benjamintli/modernbert-code with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("benjamintli/modernbert-code")
sentences = [
"@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 }",
"fetch function with the same interface than in cozy-client-js",
"Convert this tuple to the equivalent Erlang external representation.\n\n@param buf\nan output stream to which the encoded tuple should be written.",
"Delete a customer by it's id.\n\n@param int $id The id\n\n@return bool\n@throws \\Throwable in case something went wrong when deleting."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from answerdotai/ModernBERT-base on the 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.
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})
)
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-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]])
evalInformationRetrievalEvaluator| 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 |
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
protected function sendMusicMsgToJsonString(WxSendMusicMsg $msg) |
formatter WxSendMusicMsg to Json string |
def getBlocks(self): |
self.buflistblks.execute(conn) |
function obj(/key,value, key,value .../) { |
builds an object immediate where keys can be expressions |
CachedMultipleNegativesRankingLoss with these parameters:{
"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
}
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
def save |
self.attributes, options = extract_uniqueness_token(attributes) |
def _update_summary(self, summary=None): |
summary.total_leaves) |
def chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y): |
Returns the effective precession spin from mass1, mass2, spin1x, |
CachedMultipleNegativesRankingLoss with these parameters:{
"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
}
per_device_train_batch_size: 1024num_train_epochs: 1learning_rate: 8e-05warmup_steps: 0.05bf16: Trueeval_strategy: stepsper_device_eval_batch_size: 1024push_to_hub: Truehub_model_id: modernbert-codeload_best_model_at_end: Truedataloader_num_workers: 4batch_sampler: no_duplicatesper_device_train_batch_size: 1024num_train_epochs: 1max_steps: -1learning_rate: 8e-05lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0.05optim: 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: stepsper_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-codehub_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: {}| Epoch | Step | Training Loss | Validation Loss | eval_cosine_ndcg@10 |
|---|---|---|---|---|
| 0.0526 | 10 | 5.2457 | 2.4469 | 0.4195 |
| 0.1053 | 20 | 1.3973 | 0.6956 | 0.7742 |
| 0.1579 | 30 | 0.5500 | 0.4000 | 0.8560 |
| 0.2105 | 40 | 0.3429 | 0.2878 | 0.8891 |
| 0.2632 | 50 | 0.2487 | 0.2250 | 0.9104 |
| 0.3158 | 60 | 0.2080 | 0.1872 | 0.9256 |
| 0.3684 | 70 | 0.1768 | 0.1656 | 0.9312 |
| 0.4211 | 80 | 0.1525 | 0.1501 | 0.9352 |
| 0.4737 | 90 | 0.1402 | 0.1374 | 0.9397 |
| 0.5263 | 100 | 0.1343 | 0.1317 | 0.9413 |
| 0.5789 | 110 | 0.1217 | 0.1242 | 0.9444 |
| 0.6316 | 120 | 0.1180 | 0.1199 | 0.9454 |
| 0.6842 | 130 | 0.1164 | 0.1149 | 0.9476 |
| 0.7368 | 140 | 0.1146 | 0.1106 | 0.9494 |
| 0.7895 | 150 | 0.1091 | 0.1080 | 0.9494 |
| 0.8421 | 160 | 0.1085 | 0.1055 | 0.9506 |
| 0.8947 | 170 | 0.1062 | 0.1041 | 0.9511 |
| 0.9474 | 180 | 0.1130 | 0.1030 | 0.9517 |
| 1.0 | 190 | 0.0924 | 0.1024 | 0.9519 |
@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",
}
@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}
}
Base model
answerdotai/ModernBERT-base