Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup
Paper • 2101.06983 • Published • 3
How to use Jbbok/my-embeddinggemma-2-sec with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("Jbbok/my-embeddinggemma-2-sec")
sentences = [
"What was Honeywell International's other (income) expense in 2025?",
"company: HONEYWELL INTERNATIONAL INC | ticker: HON | type: 10-K | report_date: 2025-12-31\n**Other (Income) Expense**\n\n### Other (income) expense\n\n- 2025: $(1,247)\n- 2024: $(843)\n- 2023: $(830)",
"company: HONEYWELL INTERNATIONAL INC | ticker: HON | type: 10-K | report_date: 2025-12-31\n**INCOME BEFORE TAXES**\n\n### U.S.\n(us-gaap:IncomeLossFromContinuingOperationsBeforeIncomeTaxesDomestic)\n\n- 2025: $373 million [=373,000,000 USD]\n- 2024: $1,442 million [=1,442,000,000 USD]\n- 2023: $1,652 million [=1,652,000,000 USD]\n\n### Non-U.S.\n(us-gaap:IncomeLossFromContinuingOperationsBeforeIncomeTaxesForeign)\n\n- 2025: 5,103 million [=5,103,000,000 USD]\n- 2024: 4,802 million [=4,802,000,000 USD]\n- 2023: 4,539 million [=4,539,000,000 USD]\n\n### Total Income before taxes\n(us-gaap:IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest)\n\n- 2025: $5,476 million [=5,476,000,000 USD]\n- 2024: $6,244 million [=6,244,000,000 USD]\n- 2023: $6,191 million [=6,191,000,000 USD]",
"company: Mastercard Inc | ticker: MA | type: 10-K | report_date: 2025-12-31\nThe table below shows a summary of the cash flows from operating, investing and financing activities:\n\n*(unit: (in millions))*\n\n### Net cash provided by operating activities (For the Years Ended December 31,)\n\n- 2025: $17,648\n- 2024: $14,780\n- 2023: $11,980\n\n### Net cash used in investing activities (For the Years Ended December 31,)\n\n- 2025: (1,362)\n- 2024: (3,402)\n- 2023: (1,351)\n\n### Net cash used in financing activities (For the Years Ended December 31,)\n\n- 2025: (14,179)\n- 2024: (10,836)\n- 2023: (9,488)"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from google/embeddinggemma-2. It maps inputs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, classification, clustering, and more.
SentenceTransformer(
(0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'image': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'audio': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'video': {'method': 'forward', 'method_output_name': 'last_hidden_state'}, 'message': {'method': 'forward', 'method_output_name': 'last_hidden_state', 'format': 'structured'}}, 'module_output_name': 'token_embeddings', 'architecture': 'EmbeddingGemma2Model'})
(1): Pooling({'embedding_dimension': 768, 'pooling_mode': 'mean', 'include_prompt': True})
(2): Normalize({'module_input_name': 'sentence_embedding', 'module_output_name': 'sentence_embedding'})
)
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("Jbbok/my-embeddinggemma-2-sec")
# Run inference
queries = [
'Why can GE not predict the economic conditions that will exist when a new product is ready to enter service?',
]
documents = [
'company: GENERAL ELECTRIC CO | ticker: GE | type: 10-K | report_date: 2025-12-31\n**Competitive environment - We are dependent on the maintenance of existing product lines and service relationships, acceptance by our customers of new product and service introductions, competitive pricing and other terms, and technology and innovation leadership for revenue and earnings growth.** The segments in which we, other engine manufacturers and airframers operate, are highly competitive in terms of pricing, product and service quality, product development and entry into service, product durability, customer service, financing terms, the ability to respond to shifts in market demand and the ability to attract and retain skilled talent at all levels, including senior leadership. Our long-term operating results and competitive position depend substantially upon our ability to continue to improve or upgrade current products and services, to have our engines power leading existing and new aircraft platforms, to cultivate, maintain and grow long-term customer relationships and to increase our productivity over time as we perform on long-term service agreements. Our competitive position and success also depend on our ability to develop, introduce, and market new and innovative technology, products, services and platforms, such as the RISE program suite of technologies. The research and development cycle involved in bringing new products to market is often lengthy, it is inherently difficult to predict the economic conditions or competitive dynamics that will exist when any new product is complete, and our investments, to the extent they result in bringing a product to market, may generate weaker returns than we anticipated at the outset. Our capacity to invest in research and development efforts to advance our technologies, products and services, or to otherwise invest in emerging technologies or partner with other industry players, also depends on the financial resources that we have available for such investment relative to other capital allocation priorities. Under-investment in research and development and innovation, or investment in technologies that prove to be less competitive in the future (at the expense of alternative investment opportunities not pursued), could lead to loss of sales of our products or services in the future due to the long product development cycles in our business. The amounts that we do invest in research and development efforts may not lead to the development of new technologies or products on a timely basis or meet the needs of our customers as fully as competitive offerings, and we may face impairment charges for contract fulfillment costs that are capitalized as nonrecurring engineering costs if we determine recovery of the costs is not probable (see Note 1).',
'company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31\nWe are also subject to certain privacy, data protection, data management, AI, resiliency, information security and cybersecurity laws in other countries in which we operate, some of which are more stringent and/or expansive than those in the United States and may conflict with each other. The EU and UK General Data Protection Regulations (GDPR) impose legal and compliance obligations on companies that process personal data of individuals in the EU and UK, irrespective of the geographical location of the company, with the potential for significant fines for non-compliance (up to 4 percent of total annual worldwide revenue). The EU and UK GDPR also include requirements concerning the cross-border transfer of personal data and prompt notification of data breaches, in certain circumstances, to affected individuals and supervisory authorities. We are also subject to certain data protection laws in Member States in the EU, which may be more stringent than the EU GDPR. Other countries have also adopted or are considering similar omnibus privacy laws, including Australia, Brazil, Canada, China, India, Japan, the Philippines, Singapore, South Korea and Thailand. Certain countries also require in-country data processing and/or in-country storage of data or for us to provide foreign governments and other third parties broader access to our data and intellectual property. Data breach and operational outage notification laws or regulatory activities to encourage such notifications and regulatory activity and laws around resiliency, business continuity and third-party risk management are also becoming more prevalent in jurisdictions outside the United States in which we operate.\nOur privacy and data protection programs have become the subject of heightened scrutiny and review in certain jurisdictions, including in the EU, and we continue to enhance our privacy program to comply with applicable requirements and regulatory expectations. Our compliance with the various and often diverging legal frameworks around privacy, data protection, AI, resiliency, information security and cybersecurity, as well as increased regulatory and legislative activity in these areas, may result in higher technology, administrative and other operational costs and hinder our ability to deploy and scale technology, innovate quickly and effectively utilize data.\n**Anti-Money Laundering, Countering the Financing of Terrorism, Economic Sanctions and Anti-Corruption Compliance**',
'company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31\nAmerican Express cards could become less desirable to consumers and businesses generally due to surcharging, steering or other forms of discrimination, which could result in a decrease in cards-in-force, coverage and transaction volumes, including as a result of related actions we may take to enforce our merchant contractual provisions such as terminating merchant contracts. The impact could vary depending on such factors as: the industry or manner in which a surcharge is levied; how Card Members are surcharged or steered to other card products or payment forms at the point of sale; the ease and speed of implementation for merchants, merchant acquirers, processors, payment facilitators or other merchant service providers, including as a result of new or emerging technologies such as AI and agentic commerce; the size and recurrence of the underlying charges; and whether and to what extent these actions are applied to other forms of payment, including whether it varies depending on the type of card (e.g., credit or debit), product, network, acquirer or issuer. We also increasingly rely on merchant acquirers, processors and payment facilitators to manage certain aspects of our merchant relationships and promote and support the acceptance and usage of our cards, but they may have business interests, strategies or goals that are inconsistent with ours. Discrimination against American Express cards could have a material adverse effect on our business, financial condition and results of operations, particularly where it only or disproportionately impacts credit card usage or card usage generally, our Card Members or our business.',
]
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.4498, 0.0411, 0.1949]])
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| modality | text | text | text |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
What were NVIDIA's total assets as of January 25, 2026? |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
What were NVIDIA's total assets as of January 25, 2026? |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
What were NVIDIA's total assets as of January 25, 2026? |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
company: NVIDIA CORP | ticker: NVDA | type: 10-K | report_date: 2026-01-25 |
CachedMultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"mini_batch_size": 16,
"mini_batch_num_tokens": null,
"gather_across_devices": false,
"directions": [
"query_to_doc"
],
"partition_mode": "joint",
"hardness_mode": null,
"hardness_strength": 0.0
}
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| modality | text | text | text |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
Why can GE not predict the economic conditions that will exist when a new product is ready to enter service? |
company: GENERAL ELECTRIC CO | ticker: GE | type: 10-K | report_date: 2025-12-31 |
company: GENERAL ELECTRIC CO | ticker: GE | type: 10-K | report_date: 2025-12-31 |
What privacy and data protection risks does American Express face, and how could they affect the company? |
company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31 |
company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31 |
How could merchant surcharging or steering American Express cards to other payment options affect American Express? |
company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31 |
company: AMERICAN EXPRESS CO | ticker: AXP | type: 10-K | report_date: 2025-12-31 |
CachedMultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"mini_batch_size": 16,
"mini_batch_num_tokens": null,
"gather_across_devices": false,
"directions": [
"query_to_doc"
],
"partition_mode": "joint",
"hardness_mode": null,
"hardness_strength": 0.0
}
per_device_train_batch_size: 32learning_rate: 2e-05warmup_steps: 0.1bf16: Trueper_device_eval_batch_size: 32load_best_model_at_end: Trueseed: 0prompts: {'anchor': 'task: search result | query: ', 'positive': 'title: none | text: ', 'negative': 'title: none | text: '}batch_sampler: no_duplicatesper_device_train_batch_size: 32num_train_epochs: 3max_steps: -1learning_rate: 2e-05lr_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: Nonetrackio_bucket_id: Nonetrackio_static_space_id: Noneper_device_eval_batch_size: 32prediction_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: Falsehub_private_repo: Nonehub_model_id: Nonehub_strategy: every_savehub_always_push: Falsehub_revision: Noneload_best_model_at_end: Trueignore_data_skip: Falserestore_callback_states_from_checkpoint: Falsefull_determinism: Falseseed: 0data_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: 0dataloader_pin_memory: Truedataloader_persistent_workers: Falsedataloader_prefetch_factor: Nonedataloader_multiprocessing_context: Nonedataloader_in_order: Trueremove_unused_columns: Truelabel_names: Nonetrain_sampling_strategy: randomlength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falseddp_static_graph: Noneddp_backend: Noneddp_timeout: 1800fsdp: Nonefsdp_config: Nonedeepspeed: Nonedebug: []skip_memory_metrics: Truedo_predict: Falseresume_from_checkpoint: Nonelocal_rank: -1prompts: {'anchor': 'task: search result | query: ', 'positive': 'title: none | text: ', 'negative': 'title: none | text: '}batch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}warmup_ratio: None| Epoch | Step | Training Loss | Validation Loss |
|---|---|---|---|
| 0.2479 | 30 | 1.0390 | - |
| 0.4959 | 60 | 0.3680 | - |
| 0.7438 | 90 | 0.2735 | - |
| 0.9917 | 120 | 0.2537 | - |
| 1.0 | 121 | - | 0.6994 |
| 1.2397 | 150 | 0.1704 | - |
| 1.4876 | 180 | 0.1617 | - |
| 1.7355 | 210 | 0.1602 | - |
| 1.9835 | 240 | 0.1513 | - |
| 2.0 | 242 | - | 0.6717 |
| 2.2314 | 270 | 0.1670 | - |
| 2.4793 | 300 | 0.1111 | - |
| 2.7273 | 330 | 0.1506 | - |
| 2.9752 | 360 | 0.1101 | - |
| 3.0 | 363 | - | 0.6962 |
@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}
}
@misc{oord2019representationlearningcontrastivepredictive,
title={Representation Learning with Contrastive Predictive Coding},
author={Aaron van den Oord and Yazhe Li and Oriol Vinyals},
year={2019},
eprint={1807.03748},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/1807.03748},
}
Base model
google/embeddinggemma-2