benjamintli/code-retrieval-combined-v2
Viewer • Updated • 315k • 25
How to use benjamintli/modernbert-code-v2 with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("benjamintli/modernbert-code-v2")
sentences = [
"// Uint is a helper routine that allocates a new uint value to store v and\n// returns a pointer to it. This is useful when assigning optional parameters.",
"func (c *Animation) GetCurrentTimeWithParams(v *AnimationGetCurrentTimeParams) (float64, error) {\n\tresp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"Animation.getCurrentTime\", Params: v})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar chromeData struct {\n\t\tResult struct {\n\t\t\tCurrentTime float64\n\t\t}\n\t}\n\n\tif resp == nil {\n\t\treturn 0, &gcdmessage.ChromeEmptyResponseErr{}\n\t}\n\n\t// test if error first\n\tcerr := &gcdmessage.ChromeErrorResponse{}\n\tjson.Unmarshal(resp.Data, cerr)\n\tif cerr != nil && cerr.Error != nil {\n\t\treturn 0, &gcdmessage.ChromeRequestErr{Resp: cerr}\n\t}\n\n\tif err := json.Unmarshal(resp.Data, &chromeData); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn chromeData.Result.CurrentTime, nil\n}",
"func Uint(v uint) *uint {\n\tp := new(uint)\n\t*p = v\n\treturn p\n}",
"def after_init_app(self, app: FlaskUnchained):\n \"\"\"\n Configure the JSON encoder for Flask to be able to serialize Enums,\n LocalProxy objects, and SQLAlchemy models.\n \"\"\"\n self.set_json_encoder(app)\n app.before_first_request(self.register_model_resources)"
]
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-v2 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-v2")
# Run inference
queries = [
"If MultiTenantMiddleware is used, filter queryset by request.site_id",
]
documents = [
"def get_queryset(self):\n '''\n If MultiTenantMiddleware is used, filter queryset by request.site_id\n '''\n queryset = super(PageList, self).get_queryset()\n if hasattr(self.request, 'site_id'):\n queryset = queryset.filter(site_id=self.request.site_id)\n return queryset",
'def reduce_ticks(ax, which, maxticks=3):\n """Given a pyplot axis, resamples its `which`-axis ticks such that are at most\n `maxticks` left.\n\n Parameters\n ----------\n ax : axis\n The axis to adjust.\n which : {\'x\' | \'y\'}\n Which axis to adjust.\n maxticks : {3, int}\n Maximum number of ticks to use.\n\n Returns\n -------\n array\n An array of the selected ticks.\n """\n ticks = getattr(ax, \'get_{}ticks\'.format(which))()\n if len(ticks) > maxticks:\n # make sure the left/right value is not at the edge\n minax, maxax = getattr(ax, \'get_{}lim\'.format(which))()\n dw = abs(maxax-minax)/10.\n start_idx, end_idx = 0, len(ticks)\n if ticks[0] < minax + dw:\n start_idx += 1\n if ticks[-1] > maxax - dw:\n end_idx -= 1\n # get reduction factor\n fac = int(len(ticks) / maxticks)\n ticks = ticks[start_idx:end_idx:fac]\n return ticks',
'function (isPublic, name, data, ttl, published_at, coreid) {\n var rawFn = function (msg) {\n try {\n msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60));\n if (published_at) {\n msg.setTimestamp(moment(published_at).toDate());\n }\n }\n catch (ex) {\n logger.error("onCoreHeard - " + ex);\n }\n return msg;\n };\n\n var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent";\n var userID = (this.userID || "").toLowerCase() + "/";\n name = (name) ? name.toString() : name;\n if (name && name.indexOf && (name.indexOf(userID) == 0)) {\n name = name.substring(userID.length);\n }\n\n data = (data) ? data.toString() : data;\n this.sendNONTypeMessage(msgName, { event_name: name, _raw: rawFn }, data);\n }',
]
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.9183, -0.0231, -0.0561]])
evalInformationRetrievalEvaluator| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.873 |
| cosine_accuracy@3 | 0.9367 |
| cosine_accuracy@5 | 0.9543 |
| cosine_accuracy@10 | 0.973 |
| cosine_precision@1 | 0.873 |
| cosine_precision@3 | 0.3122 |
| cosine_precision@5 | 0.1909 |
| cosine_precision@10 | 0.0973 |
| cosine_recall@1 | 0.873 |
| cosine_recall@3 | 0.9367 |
| cosine_recall@5 | 0.9543 |
| cosine_recall@10 | 0.973 |
| cosine_ndcg@10 | 0.9241 |
| cosine_mrr@10 | 0.9083 |
| cosine_map@100 | 0.9094 |
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
Start the asyncio event loop and runs the application. |
def main(): |
Initialize the pool manager with the number of pools, the entry sizes for each |
public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) { |
// List lists all of the documents in an index. The documents are returned in |
func (x *Index) List(c context.Context, opts *ListOptions) *Iterator { |
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 |
|---|---|
This gets the version of OpenALPR |
def get_version(self): |
Remove all unnecessary comments from a lexer or parser file |
public String stripUnnecessaryComments(String javaContent, AntlrOptions options) { |
Serialize reply to array or JSON. |
function reply(packet, json) { |
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
}
eval_strategy: stepsper_device_train_batch_size: 1024per_device_eval_batch_size: 1024learning_rate: 8e-05num_train_epochs: 1warmup_steps: 0.05bf16: Truedataloader_num_workers: 4load_best_model_at_end: Truepush_to_hub: Truehub_model_id: modernbert-code-v2batch_sampler: no_duplicatesdo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 1024per_device_eval_batch_size: 1024gradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 8e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 1max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_ratio: Nonewarmup_steps: 0.05log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Trueenable_jit_checkpoint: Falsesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseuse_cpu: Falseseed: 42data_seed: Nonebf16: Truefp16: Falsebf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: -1ddp_backend: Nonedebug: []dataloader_drop_last: Falsedataloader_num_workers: 4dataloader_prefetch_factor: Nonedisable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Trueignore_data_skip: Falsefsdp: []fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}accelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedeepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torch_fusedoptim_args: Nonegroup_by_length: Falselength_column_name: lengthproject: huggingfacetrackio_space_id: trackioddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Truepush_to_hub: Trueresume_from_checkpoint: Nonehub_model_id: modernbert-code-v2hub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsehub_revision: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_for_metrics: []eval_do_concat_batches: Trueauto_find_batch_size: Falsefull_determinism: Falseddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_num_input_tokens_seen: noneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Trueuse_cache: Falseprompts: Nonebatch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | Validation Loss | eval_cosine_ndcg@10 |
|---|---|---|---|---|
| 0.0722 | 20 | 3.9983 | 1.3745 | 0.7545 |
| 0.1444 | 40 | 1.0297 | 0.7864 | 0.8493 |
| 0.2166 | 60 | 0.6830 | 0.5917 | 0.8833 |
| 0.2888 | 80 | 0.5476 | 0.5128 | 0.8973 |
| 0.3610 | 100 | 0.4891 | 0.4641 | 0.9028 |
| 0.4332 | 120 | 0.4436 | 0.4370 | 0.9098 |
| 0.5054 | 140 | 0.4304 | 0.4151 | 0.9154 |
| 0.5776 | 160 | 0.4101 | 0.3948 | 0.9161 |
| 0.6498 | 180 | 0.3910 | 0.3829 | 0.9190 |
| 0.7220 | 200 | 0.3794 | 0.3729 | 0.9188 |
| 0.7942 | 220 | 0.3668 | 0.3650 | 0.9207 |
| 0.8664 | 240 | 0.3683 | 0.3573 | 0.9230 |
| 0.9386 | 260 | 0.359 | 0.3534 | 0.9241 |
@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