Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup
Paper • 2101.06983 • Published • 2
How to use benjamintli/modernbert-cosqa with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("benjamintli/modernbert-cosqa")
sentences = [
"python create path if doesnt exist",
"def clean_whitespace(string, compact=False):\n \"\"\"Return string with compressed whitespace.\"\"\"\n for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n ('\\t', ' '), (' ', ' ')):\n string = string.replace(a, b)\n if compact:\n for a, b in (('\\n', ' '), ('[ ', '['),\n (' ', ' '), (' ', ' '), (' ', ' ')):\n string = string.replace(a, b)\n return string.strip()",
"def rotateImage(img, angle):\n \"\"\"\n\n querries scipy.ndimage.rotate routine\n :param img: image to be rotated\n :param angle: angle to be rotated (radian)\n :return: rotated image\n \"\"\"\n imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n return imgR",
"def check_create_folder(filename):\n \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from benjamintli/modernbert-cosqa. 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': 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})
)
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-cosqa")
# Run inference
queries = [
"first duplicate element in list in python",
]
documents = [
'def purge_duplicates(list_in):\n """Remove duplicates from list while preserving order.\n\n Parameters\n ----------\n list_in: Iterable\n\n Returns\n -------\n list\n List of first occurences in order\n """\n _list = []\n for item in list_in:\n if item not in _list:\n _list.append(item)\n return _list',
'def getRect(self):\n\t\t"""\n\t\tReturns the window bounds as a tuple of (x,y,w,h)\n\t\t"""\n\t\treturn (self.x, self.y, self.w, self.h)',
'def python_mime(fn):\n """\n Decorator, which adds correct MIME type for python source to the decorated\n bottle API function.\n """\n @wraps(fn)\n def python_mime_decorator(*args, **kwargs):\n response.content_type = "text/x-python"\n\n return fn(*args, **kwargs)\n\n return python_mime_decorator',
]
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.5986, -0.0006, -0.0122]])
evalInformationRetrievalEvaluator| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.6197 |
| cosine_accuracy@3 | 0.8847 |
| cosine_accuracy@5 | 0.939 |
| cosine_accuracy@10 | 0.9778 |
| cosine_precision@1 | 0.6197 |
| cosine_precision@3 | 0.2949 |
| cosine_precision@5 | 0.1878 |
| cosine_precision@10 | 0.0978 |
| cosine_recall@1 | 0.6197 |
| cosine_recall@3 | 0.8847 |
| cosine_recall@5 | 0.939 |
| cosine_recall@10 | 0.9778 |
| cosine_ndcg@10 | 0.8125 |
| cosine_mrr@10 | 0.7577 |
| cosine_map@100 | 0.7588 |
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
python code for opening geojson file |
def _loadfilepath(self, filepath, **kwargs): |
python 3 none compare with int |
def is_natural(x): |
design db memory cache python |
def refresh(self, document): |
CachedMultipleNegativesRankingLoss with these parameters:{
"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
}
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
how to remove masked items in python array |
def ma(self): |
python deepcopy basic type |
def deepcopy(self, memo): |
python number of non nan rows in a row |
def count_rows_with_nans(X): |
CachedMultipleNegativesRankingLoss with these parameters:{
"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
}
per_device_train_batch_size: 1024num_train_epochs: 10learning_rate: 2e-06warmup_steps: 0.1bf16: Trueeval_strategy: epochper_device_eval_batch_size: 1024push_to_hub: Truehub_model_id: modernbert-cosqaload_best_model_at_end: Truedataloader_num_workers: 4batch_sampler: no_duplicatesper_device_train_batch_size: 1024num_train_epochs: 10max_steps: -1learning_rate: 2e-06lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0.1optim: 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: epochper_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-cosqahub_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 |
|---|---|---|---|---|
| 1.0 | 8 | - | 0.3550 | 0.8071 |
| 1.25 | 10 | 1.0218 | - | - |
| 2.0 | 16 | - | 0.3508 | 0.8110 |
| 2.5 | 20 | 0.9890 | - | - |
| 3.0 | 24 | - | 0.3466 | 0.8131 |
| 3.75 | 30 | 0.9778 | - | - |
| 4.0 | 32 | - | 0.3439 | 0.8136 |
| 5.0 | 40 | 0.9507 | 0.3417 | 0.8148 |
| 6.0 | 48 | - | 0.3404 | 0.8120 |
| 6.25 | 50 | 0.9429 | - | - |
| 7.0 | 56 | - | 0.3387 | 0.8131 |
| 7.5 | 60 | 0.9267 | - | - |
| 8.0 | 64 | - | 0.3378 | 0.8127 |
| 8.75 | 70 | 0.9396 | - | - |
| 9.0 | 72 | - | 0.3370 | 0.8106 |
| 10.0 | 80 | 0.9099 | 0.3366 | 0.8125 |
@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}
}
Unable to build the model tree, the base model loops to the model itself. Learn more.