juanwisz/modernbert-python-code-retrieval
SentenceTransformer based on answerdotai/ModernBERT-base
This is a sentence-transformers model finetuned from answerdotai/ModernBERT-base on the codesearchnet 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 <!-- at revision 8949b909ec900327062f0ebf497f51aef5e6f0c8 -->
- Maximum Sequence Length: 4096 tokens
- Output Dimensionality: 768 dimensions
- Similarity Function: Cosine Similarity
- Training Dataset:
- codesearchnet <!-- - Language: Unknown --> <!-- - License: Unknown -->
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': 4096, 'do_lower_case': False}) with Transformer model: ModernBertModel
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, '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-transformersThen you can load this model and run inference.
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("juanwisz/modernbert-python-code-retrieval")
# Run inference
sentences = [
'Validates control dictionary for the experiment context',
'def __validateExperimentControl(self, control):\n """ Validates control dictionary for the experiment context"""\n # Validate task list\n taskList = control.get(\'tasks\', None)\n if taskList is not None:\n taskLabelsList = []\n\n for task in taskList:\n validateOpfJsonValue(task, "opfTaskSchema.json")\n validateOpfJsonValue(task[\'taskControl\'], "opfTaskControlSchema.json")\n\n taskLabel = task[\'taskLabel\']\n\n assert isinstance(taskLabel, types.StringTypes), \\\n "taskLabel type: %r" % type(taskLabel)\n assert len(taskLabel) > 0, "empty string taskLabel not is allowed"\n\n taskLabelsList.append(taskLabel.lower())\n\n taskLabelDuplicates = filter(lambda x: taskLabelsList.count(x) > 1,\n taskLabelsList)\n assert len(taskLabelDuplicates) == 0, \\\n "Duplcate task labels are not allowed: %s" % taskLabelDuplicates\n\n return',
'def load_file_list(path=None, regx=\'\\.jpg\', printable=True, keep_prefix=False):\n r"""Return a file list in a folder by given a path and regular expression.\n\n Parameters\n ----------\n path : str or None\n A folder path, if `None`, use the current directory.\n regx : str\n The regx of file name.\n printable : boolean\n Whether to print the files infomation.\n keep_prefix : boolean\n Whether to keep path in the file name.\n\n Examples\n ----------\n >>> file_list = tl.files.load_file_list(path=None, regx=\'w1pre_[0-9]+\\.(npz)\')\n\n """\n if path is None:\n path = os.getcwd()\n file_list = os.listdir(path)\n return_list = []\n for _, f in enumerate(file_list):\n if re.search(regx, f):\n return_list.append(f)\n # return_list.sort()\n if keep_prefix:\n for i, f in enumerate(return_list):\n return_list[i] = os.path.join(path, f)\n\n if printable:\n logging.info(\'Match file list = %s\' % return_list)\n logging.info(\'Number of files = %d\' % len(return_list))\n return return_list',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [3, 3]<!--
Direct Usage (Transformers)
<details><summary>Click to see the direct usage in Transformers</summary>
</details> -->
<!--
Downstream Usage (Sentence Transformers)
You can finetune this model on your own dataset.
<details><summary>Click to expand</summary>
</details> -->
<!--
Out-of-Scope Use
List how the model may foreseeably be misused and address what users ought not to do with the model. -->
<!--
Bias, Risks and Limitations
What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model. -->
<!--
Recommendations
What are recommendations with respect to the foreseeable issues? For example, filtering explicit content. -->
Training Details
Training Dataset
codesearchnet
- Dataset: codesearchnet
- Size: 412,178 training samples
- Columns: <code>query</code> and <code>positive</code>
- Approximate statistics based on the first 1000 samples: | | query | positive | |:--------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------| | type | string | string | | details | <ul><li>min: 4 tokens</li><li>mean: 73.72 tokens</li><li>max: 2258 tokens</li></ul> | <ul><li>min: 46 tokens</li><li>mean: 300.87 tokens</li><li>max: 3119 tokens</li></ul> |
- Samples: | query | positive | |:------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | <code>Extracts the list of arguments that start with any of the specified prefix values</code> | <code>def findArgs(args, prefixes):<br> """<br> Extracts the list of arguments that start with any of the specified prefix values<br> """<br> return list([<br> arg for arg in args<br> if len([p for p in prefixes if arg.lower().startswith(p.lower())]) > 0<br> ])</code> | | <code>Removes any arguments in the supplied list that are contained in the specified blacklist</code> | <code>def stripArgs(args, blacklist):<br> """<br> Removes any arguments in the supplied list that are contained in the specified blacklist<br> """<br> blacklist = [b.lower() for b in blacklist]<br> return list([arg for arg in args if arg.lower() not in blacklist])</code> | | <code>Executes a child process and captures its output</code> | <code>def capture(command, input=None, cwd=None, shell=False, raiseOnError=False):<br> """<br> Executes a child process and captures its output<br> """<br> <br> # Attempt to execute the child process<br> proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True)<br> (stdout, stderr) = proc.communicate(input)<br> <br> # If the child process failed and we were asked to raise an exception, do so<br> if raiseOnError == True and proc.returncode != 0:<br> raise Exception(<br> 'child process ' + str(command) +<br> ' failed with exit code ' + str(proc.returncode) +<br> '\nstdout: "' + stdout + '"' +<br> '\nstderr: "' + stderr + '"'<br> )<br> <br> return CommandOutput(proc.returncode, stdout, stderr)</code> |
- Loss: <code>MultipleNegativesRankingLoss</code> with these parameters:
{
"scale": 20.0,
"similarity_fct": "cos_sim"
}Evaluation Dataset
codesearchnet
- Dataset: codesearchnet
- Size: 23,107 evaluation samples
- Columns: <code>query</code> and <code>positive</code>
- Approximate statistics based on the first 1000 samples: | | query | positive | |:--------|:-------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------| | type | string | string | | details | <ul><li>min: 5 tokens</li><li>mean: 168.27 tokens</li><li>max: 2118 tokens</li></ul> | <ul><li>min: 48 tokens</li><li>mean: 467.9 tokens</li><li>max: 4096 tokens</li></ul> |
- Samples: | query | positive | |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | <code>Train a deepq model.<br><br> Parameters<br> -------<br> env: gym.Env<br> environment to train on<br> network: string or a function<br> neural network to use as a q function approximator. If string, has to be one of the names of registered models in baselines.common.models<br> (mlp, cnn, convonly). If a function, should take an observation tensor and return a latent variable tensor, which<br> will be mapped to the Q function heads (see buildqfunc in baselines.deepq.models for details on that)<br> seed: int or None<br> prng seed. The runs with the same seed "should" give the same results. If None, no seeding is used.<br> lr: float<br> learning rate for adam optimizer<br> totaltimesteps: int<br> number of env steps to optimizer for<br> buffersize: int<br> size of the replay buffer<br> explorationfraction: float<br> fraction of entire training period over which the exploration rate is annealed<br> explorationfinaleps: float<br> final value of ra...</code> | <code>def learn(env,<br> network,<br> seed=None,<br> lr=5e-4,<br> totaltimesteps=100000,<br> buffersize=50000,<br> explorationfraction=0.1,<br> explorationfinaleps=0.02,<br> trainfreq=1,<br> batchsize=32,<br> printfreq=100,<br> checkpointfreq=10000,<br> checkpointpath=None,<br> learningstarts=1000,<br> gamma=1.0,<br> targetnetworkupdatefreq=500,<br> prioritizedreplay=False,<br> prioritizedreplayalpha=0.6,<br> prioritizedreplaybeta0=0.4,<br> prioritizedreplaybetaiters=None,<br> prioritizedreplayeps=1e-6,<br> paramnoise=False,<br> callback=None,<br> loadpath=None,<br> network_kwargs<br> ):<br> """Train a deepq model.<br><br> Parameters<br> -------<br> env: gym.Env<br> environment to train on<br> network: string or a function<br> neural network to use as a q function approximator. If string, has to be one of the ...</code> | | <code>Save model to a pickle located at `path`</code> | <code>def save_act(self, path=None):<br> """Save model to a pickle located at `path`"""<br> if path is None:<br> path = os.path.join(logger.get_dir(), "model.pkl")<br><br> with tempfile.TemporaryDirectory() as td:<br> save_variables(os.path.join(td, "model"))<br> arc_name = os.path.join(td, "packed.zip")<br> with zipfile.ZipFile(arc_name, 'w') as zipf:<br> for root, dirs, files in os.walk(td):<br> for fname in files:<br> file_path = os.path.join(root, fname)<br> if file_path != arc_name:<br> zipf.write(file_path, os.path.relpath(file_path, td))<br> with open(arc_name, "rb") as f:<br> model_data = f.read()<br> with open(path, "wb") as f:<br> cloudpickle.dump((model_data, self._act_params), f)</code> | | <code>CNN from Nature paper.</code> | <code>def nature_cnn(unscaled_images, convkwargs):<br> """<br> CNN from Nature paper.<br> """<br> scaledimages = tf.cast(unscaledimages, tf.float32) / 255.<br> activ = tf.nn.relu<br> h = activ(conv(scaledimages, 'c1', nf=32, rf=8, stride=4, initscale=np.sqrt(2),<br> **convkwargs))<br> h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, initscale=np.sqrt(2), **convkwargs))<br> h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, initscale=np.sqrt(2), **convkwargs))<br> h3 = convtofc(h3)<br> return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))</code> |
- Loss: <code>MultipleNegativesRankingLoss</code> with these parameters:
{
"scale": 20.0,
"similarity_fct": "cos_sim"
}Training Hyperparameters
Non-Default Hyperparameters
eval_strategy: epochper_device_train_batch_size: 4gradient_accumulation_steps: 4learning_rate: 2e-05num_train_epochs: 10warmup_steps: 1000fp16: True
All Hyperparameters
<details><summary>Click to expand</summary>
overwrite_output_dir: Falsedo_predict: Falseeval_strategy: epochprediction_loss_only: Trueper_device_train_batch_size: 4per_device_eval_batch_size: 8per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 4eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 2e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 10max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_ratio: 0.0warmup_steps: 1000log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Truesave_safetensors: Truesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseno_cuda: Falseuse_cpu: Falseuse_mps_device: Falseseed: 42data_seed: Nonejit_mode_eval: Falseuse_ipex: Falsebf16: Falsefp16: Truefp16_opt_level: O1half_precision_backend: autobf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: 0ddp_backend: Nonetpu_num_cores: Nonetpu_metrics_debug: Falsedebug: []dataloader_drop_last: Falsedataloader_num_workers: 0dataloader_prefetch_factor: Nonepast_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_min_num_params: 0fsdp_config: {'minnumparams': 0, 'xla': False, 'xlafsdpv2': False, 'xlafsdpgrad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_config: {'splitbatches': False, 'dispatchbatches': None, 'evenbatches': True, 'useseedablesampler': True, 'nonblocking': False, 'gradientaccumulationkwargs': None}deepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torchoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_inputs_for_metrics: Falseinclude_for_metrics: []eval_do_concat_batches: Truefp16_backend: autopush_to_hub_model_id: Nonepush_to_hub_organization: Nonemp_parameters:auto_find_batch_size: Falsefull_determinism: Falsetorchdynamo: Noneray_scope: lastddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Nonedispatch_batches: Nonesplit_batches: Noneinclude_tokens_per_second: Falseinclude_num_input_tokens_seen: Falseneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseeval_use_gather_object: Falseaverage_tokens_across_devices: Falseprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportional
</details>
Training Logs
<details><summary>Click to expand</summary>
</details>
Framework Versions
- Python: 3.11.11
- Sentence Transformers: 3.3.1
- Transformers: 4.48.0
- PyTorch: 2.5.1+cu121
- Accelerate: 1.2.1
- Datasets: 3.2.0
- Tokenizers: 0.21.0
Citation
BibTeX
ModernBERT
@misc{warner2024smarterbetterfasterlonger,
title={Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast, Memory Efficient, and Long Context Finetuning and Inference},
author={Benjamin Warner and Antoine Chaffin and Benjamin Clavié and Orion Weller and Oskar Hallström and Said Taghadouini and Alexis Gallagher and Raja Biswas and Faisal Ladhak and Tom Aarsen and Nathan Cooper and Griffin Adams and Jeremy Howard and Iacopo Poli},
year={2024},
eprint={2412.13663},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2412.13663},
}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",
}MultipleNegativesRankingLoss
@misc{henderson2017efficient,
title={Efficient Natural Language Response Suggestion for Smart Reply},
author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
year={2017},
eprint={1705.00652},
archivePrefix={arXiv},
primaryClass={cs.CL}
}<!--
Glossary
Clearly define terms in order to be accessible across audiences. -->
<!--
Model Card Authors
Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction. -->
<!--
Model Card Contact
Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors. -->
