Matryoshka Representation Learning
Paper • 2205.13147 • Published • 30
Run DannieAI/bge-base-Apple-matryoshka on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Use HF Jobs to fine-tune https://huggingface.co/DannieAI/bge-base-Apple-matryoshka. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Use HF Jobs to run batch inference with https://huggingface.co/DannieAI/bge-base-Apple-matryoshka on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
How to use DannieAI/bge-base-Apple-matryoshka with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("DannieAI/bge-base-Apple-matryoshka")
sentences = [
"approaches that connect suppliers to external \nfunding for energy efficiency projects while scaling \nthe program and accelerating reductions.\nIn 2023, more than 100 supplier facilities participated \nin our energy efficiency program, achieving more \nthan 2 billion kilowatt-hours of electricity savings and \nmore than 2,200,000 MMBtu in additional energy \nsavings. Together, we estimate that this avoided \nnearly 1.7 million metric tons of CO2e, representing \na 25 percent increase since 2022.\nTo address gaps in our renewable energy needs \nbeyond what’s provided by Apple-created projects, \nwe directly purchase renewable electricity through \navailable utility green energy programs — about \n5 percent of our total corporate load in 2023. \nColocation and distribution facility vendors supply \nabout 3 percent of our total load of renewable energy. \nAnd in certain situations, we purchase renewable \nenergy certificates (RECs).58 These RECs, which \naccount for about 2 percent of our total load, share \nthe same power grid as the Apple facility they \nsupport, where available. These purchases are \nsubject to the same standards as our Apple‑created \nrenewable energy projects. Appendix A \nprovides additional details on Apple’s renewable \nenergy solutions.\n91%\nApple-created renewable \nsources account for \nabout 91 percent of the \nrenewable electricity that \nour facilities use.\nSupporting social impact\nOur Power for Impact program, which launched in \n2019, continues to help provide local communities \nwith needed energy resources. With funding from \nApple, local communities and organizations benefit \nfrom access to cost‑effective renewable energy. \nApple is currently supporting more than 20 renewable \nelectricity projects around the world, including in the \nPhilippines, Thailand, and South Africa. Read more \nabout Power for Impact on page 31.\n2024 Environmental Progress Report\b\n26\nEngagement and Advocacy\nData\nAppendix\nIntroduction \nContents\nEnvironmental Initiatives\nApple 2030\nResources\nSmarter ChemistryTransitioning our suppliers \nto renewable electricity\nThe electricity that our manufacturing suppliers use \nrepresents the largest single source of greenhouse \ngas emissions throughout our manufacturing supply \nchain. That’s why our efforts to facilitate our entire \nsupply chain’s transition to 100 percent renewable \nelectricity are essential to reaching our 2030 carbon \nneutrality goal.\nOur Supplier Clean Energy Program (CEP) helps \nenable suppliers’ transition to renewable electricity by \nadvocating for policy changes, providing information \nand access to renewable energy procurement \noptions, and creating engagement opportunities \nwith renewable energy experts. By engaging in this \nprogram, our suppliers can implement best practices \nin advocating for and procuring renewable energy \nacross their corporate operations, including those \nassociated with Apple production. The program also \nequips them to share lessons learned with other \npartners throughout their value chains, extending \nbenefits beyond the scope of Apple.\nPROCUREMENT MECHANISMS\nSupplier renewable energy procurement \nmechanisms\nOur suppliers are implementing clean energy solutions using a variety of contracting \nmechanisms. In 2023, suppliers relied mostly on renewable energy certificates (RECs) \nto meet their CEP commitments, largely due to the expansion of China’s Green Energy \nCertificate (GEC) and the recognition of GECs as a primary instrument for tracking \nrenewable energy consumption. Apple views the strategic use of well-designed REC",
"How much power savings have been achieved across primary device lines since 2008?",
"what types of projects are targeted by carbon offset funds for unavoidable business emissions?",
"how many metric tons of co2e were avoided by supplier energy efficiency projects?"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from BAAI/bge-base-en-v1.5 on the json dataset. It maps sentences & paragraphs 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'}}, 'module_output_name': 'token_embeddings', 'architecture': 'BertModel'})
(1): Pooling({'embedding_dimension': 768, 'pooling_mode': 'cls', 'include_prompt': True})
(2): Normalize({})
)
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("DannieAI/bge-base-Apple-matryoshka")
# Run inference
queries = [
'projects. The five Green Source Rider projects have \na combined capacity of 22 megawatts. In 2017, \nwe made long-term commitments to five more \nsolar projects in North Carolina, for an additional \n85 megawatts of renewable energy.\nThe energy efficiency measures we’ve implemented \nat our Maiden data centers include use of outside air \ncooling through a waterside economizer during night \nand cool-weather hours, which, along with water \nstorage, allows the chillers to be idle 75 percent \nof\xa0the time.\nMaiden, North Carolina: Grid mix versus. Apple-sourced renewable energy \nElectricity use in 2023: 453 million kWh\nEmissions avoided in 2023: 121,00 million MT CO2e3\nDefault grid mix\n%\nx\nApple actual renewable energy allocation\n%\nGas\n43\nApple’s solar projects\n88\nNuclear\n32\nApple’s wind projects\n12\nCoal\n11\nSource: 2023 energy data. \nRenewable\n10\nHydro\n4\nSource: eGRID 2022.\n2 \t In our 2023 Environmental Progress Report, \nwe stated that we operate eight data centers. \nFor fiscal year 2023, we no longer include the \nNewark, CA data center as it has been sold in \nfiscal year 2022.\n3 \t Emissions avoided are calculated using the GHG \nProtocol methodology for calculating market-\nbased emissions.\n2024 Environmental Progress Report\x08 89\nEngagement and Advocacy\nEnvironmental Initiatives\nData\nIntroduction \nContents\nAppendixPrineville, Oregon\n100 percent renewable since opening May 2012\nTo support our Prineville data center, we signed a \n200-megawatt power purchase agreement for a \nnew Oregon wind farm, the Montague Wind Power \nFacility, which entered commercial operation at the \nend of 2019.\nThis is in addition to our power purchase agreement \nfor the 56-megawatt Solar Star Oregon II project \nlocated just a few miles from our data center. This \nsolar PV project came online and began supporting \nthe data center in 2017. To strengthen the connection \nbetween Apple and these projects, we use Oregon’s \nDirect Access program to supply the renewable \nenergy from these projects directly to our data center.\nAlso supporting the data center are two microhydro \nprojects that harness the power of water flowing \nthrough local irrigation canals that have been \noperating for over 60 years. To supplement these \nprojects, we executed a long-term purchase \nagreement for all environmental attributes from \na 69-megawatt portfolio of eight solar projects \nin Oregon.\nOur Prineville data center takes advantage of the cool \nand dry climate by cooling its servers with outside \nair whenever possible. Indirect evaporative cooling \nis enabled when the outside air temperature gets too \nhigh to cool the servers with outside air alone.\nPrineville, Oregon: Grid mix versus Apple-sourced renewable energy\nElectricity use in 2023: 269 million kWh\nEmissions avoided in 2023: 79,800 million CO2e4\nDefault grid mix\n%\nx\nApple actual renewable energy allocation\n%\nHydro\n51\nApple’s solar projects\n38\nGas\n31\nApple’s wind projects\n60\nRenewable\n18\nApple’s microhydro projects\n2\nSource: eGrid 2022.\nSource: 2023 energy data. \nReno, Nevada\n100 percent renewable since opening',
]
documents = [
'how many million kWh of electricity did the prineville data center use in 2023?',
'why is sea freight preferred over air cargo for reducing carbon footprint?',
'What year has been set as the goal to transition to fully fiber-based device packaging?',
]
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.6869, 0.2901, 0.2612]])
dim_768InformationRetrievalEvaluator with these parameters:{
"truncate_dim": 768
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.0069 |
| cosine_accuracy@3 | 0.0138 |
| cosine_accuracy@5 | 0.0138 |
| cosine_accuracy@10 | 0.055 |
| cosine_precision@1 | 0.0069 |
| cosine_precision@3 | 0.0046 |
| cosine_precision@5 | 0.0028 |
| cosine_precision@10 | 0.0055 |
| cosine_recall@1 | 0.0069 |
| cosine_recall@3 | 0.0138 |
| cosine_recall@5 | 0.0138 |
| cosine_recall@10 | 0.055 |
| cosine_ndcg@10 | 0.0234 |
| cosine_mrr@10 | 0.0147 |
| cosine_map@100 | 0.0481 |
dim_512InformationRetrievalEvaluator with these parameters:{
"truncate_dim": 512
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.0069 |
| cosine_accuracy@3 | 0.0138 |
| cosine_accuracy@5 | 0.0138 |
| cosine_accuracy@10 | 0.0505 |
| cosine_precision@1 | 0.0069 |
| cosine_precision@3 | 0.0046 |
| cosine_precision@5 | 0.0028 |
| cosine_precision@10 | 0.005 |
| cosine_recall@1 | 0.0069 |
| cosine_recall@3 | 0.0138 |
| cosine_recall@5 | 0.0138 |
| cosine_recall@10 | 0.0505 |
| cosine_ndcg@10 | 0.0223 |
| cosine_mrr@10 | 0.0144 |
| cosine_map@100 | 0.0481 |
dim_256InformationRetrievalEvaluator with these parameters:{
"truncate_dim": 256
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.0069 |
| cosine_accuracy@3 | 0.0115 |
| cosine_accuracy@5 | 0.0115 |
| cosine_accuracy@10 | 0.0482 |
| cosine_precision@1 | 0.0069 |
| cosine_precision@3 | 0.0038 |
| cosine_precision@5 | 0.0023 |
| cosine_precision@10 | 0.0048 |
| cosine_recall@1 | 0.0069 |
| cosine_recall@3 | 0.0115 |
| cosine_recall@5 | 0.0115 |
| cosine_recall@10 | 0.0482 |
| cosine_ndcg@10 | 0.0205 |
| cosine_mrr@10 | 0.013 |
| cosine_map@100 | 0.0465 |
dim_128InformationRetrievalEvaluator with these parameters:{
"truncate_dim": 128
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.0023 |
| cosine_accuracy@3 | 0.0046 |
| cosine_accuracy@5 | 0.0046 |
| cosine_accuracy@10 | 0.0413 |
| cosine_precision@1 | 0.0023 |
| cosine_precision@3 | 0.0015 |
| cosine_precision@5 | 0.0009 |
| cosine_precision@10 | 0.0041 |
| cosine_recall@1 | 0.0023 |
| cosine_recall@3 | 0.0046 |
| cosine_recall@5 | 0.0046 |
| cosine_recall@10 | 0.0413 |
| cosine_ndcg@10 | 0.0146 |
| cosine_mrr@10 | 0.0073 |
| cosine_map@100 | 0.0402 |
dim_64InformationRetrievalEvaluator with these parameters:{
"truncate_dim": 64
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.0069 |
| cosine_accuracy@3 | 0.0115 |
| cosine_accuracy@5 | 0.0115 |
| cosine_accuracy@10 | 0.0413 |
| cosine_precision@1 | 0.0069 |
| cosine_precision@3 | 0.0038 |
| cosine_precision@5 | 0.0023 |
| cosine_precision@10 | 0.0041 |
| cosine_recall@1 | 0.0069 |
| cosine_recall@3 | 0.0115 |
| cosine_recall@5 | 0.0115 |
| cosine_recall@10 | 0.0413 |
| cosine_ndcg@10 | 0.0187 |
| cosine_mrr@10 | 0.0124 |
| cosine_map@100 | 0.0409 |
positive and anchor| positive | anchor | |
|---|---|---|
| type | string | string |
| modality | text | text |
| details |
|
|
| positive | anchor |
|---|---|
from home, upstream impacts |
What is the breakdown of avoided carbon emissions across initiatives like low-carbon materials and clean energy? |
stores in California. |
How does onsite power generation from rooftop solar and biogas work with battery microgrids? |
from home, upstream impacts |
How many metric tons of greenhouse gases were avoided through supplier clean energy programs and low-carbon materials? |
MatryoshkaLoss with these parameters:{
"loss": "MultipleNegativesRankingLoss",
"matryoshka_dims": [
768,
512,
256,
128,
64
],
"matryoshka_weights": [
1,
1,
1,
1,
1
],
"n_dims_per_step": -1
}
per_device_train_batch_size: 32num_train_epochs: 4learning_rate: 2e-05lr_scheduler_type: cosinewarmup_steps: 0.1gradient_accumulation_steps: 16per_device_eval_batch_size: 16load_best_model_at_end: Truebatch_sampler: no_duplicatesper_device_train_batch_size: 32num_train_epochs: 4max_steps: -1learning_rate: 2e-05lr_scheduler_type: cosinelr_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: 16average_tokens_across_devices: Truemax_grad_norm: 1.0label_smoothing_factor: 0.0bf16: Falsefp16: 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: 16prediction_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: 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: 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: Nonebatch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}warmup_ratio: None| Epoch | Step | Training Loss | dim_768_cosine_ndcg@10 | dim_512_cosine_ndcg@10 | dim_256_cosine_ndcg@10 | dim_128_cosine_ndcg@10 | dim_64_cosine_ndcg@10 |
|---|---|---|---|---|---|---|---|
| 1.0 | 4 | - | 0.0169 | 0.0222 | 0.0156 | 0.0140 | 0.0140 |
| 2.0 | 8 | - | 0.0219 | 0.0252 | 0.0205 | 0.0139 | 0.0182 |
| 2.5161 | 10 | 10.9379 | - | - | - | - | - |
| 3.0 | 12 | - | 0.0234 | 0.0238 | 0.0198 | 0.0169 | 0.0193 |
| 4.0 | 16 | - | 0.0234 | 0.0223 | 0.0205 | 0.0146 | 0.0187 |
@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{kusupati2024matryoshka,
title={Matryoshka Representation Learning},
author={Aditya Kusupati and Gantavya Bhatt and Aniket Rege and Matthew Wallingford and Aditya Sinha and Vivek Ramanujan and William Howard-Snyder and Kaifeng Chen and Sham Kakade and Prateek Jain and Ali Farhadi},
year={2024},
eprint={2205.13147},
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
BAAI/bge-base-en-v1.5