Matryoshka Representation Learning
Paper • 2205.13147 • Published • 27
How to use matt-wisdom/KEmbed-naija-v1 with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("matt-wisdom/KEmbed-naija-v1")
sentences = [
"Nigeria oil money no good again?",
"Awọn ti wọn jọ figagbaga ninu idibo abẹle nigba naa ni Funsho Williams ati Wahab Dosunmu. Ọdun mẹjọ lo lo ni ipo gẹgẹ bi gomina ipinlẹ Eko lati ọdun 1999 titi de ọdun 2007, ti Babatunde Fashola ti ẹgbẹ oṣelu Action Congress, ti awọn eniyan gbagbọ wi pe Tinubu jẹ baba isalẹ fun si gbajọba. Bola Tinubu ati ọrọ Baba isalẹ Ero ọpọlọpọ eniyan nipe Tinubu ni baba isale ni ipinlẹ Eko nitori awọn iroyin pe oun lo di ọrọ aje ipinlẹ Eko mu. Bakan naa ni iroyin gbe ni ọdun 2009 pe oun ati Fashola to jẹ gomina ipinlẹ Eko nigba naa kii ṣe ọrẹ mọ, amọ ti Fashola si pada wọle fun igba keji. Amọ ni ọdun 2015 ni igbagbọ wa pe Tinubu lo fi Akinwunmi Anbode sibẹ gẹgẹ bi gomina, eleyii ti Fashola tako nigba naa. Lẹyin naa lo tun fa ọwọ gomina to wa nibẹ lọwọlọwọ Babajide Sanwo-Olu si oke, lẹyin to kẹyin si Akinwunmi Ambode to dije dupo fun saa keji gẹgẹ bi gomina ipinlẹ Eko amọ to padanu.",
"Nigeria oil dey fall down, but e no mean say economy go bad. Na so so we go still manage to carry on. Oil still dey help, but person no dey talk well well about e.",
"The economy of Nigeria depend well well on oil money. But e good make we find other ways make money."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from BAAI/bge-m3. It maps sentences & paragraphs to a 1024-dimensional dense vector space and can be used for retrieval.
SentenceTransformer(
(0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}}, 'module_output_name': 'token_embeddings', 'architecture': 'XLMRobertaModel'})
(1): Pooling({'embedding_dimension': 1024, '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("sentence_transformers_model_id")
# Run inference
sentences = [
'What position did Bukola Saraki hold in the Nigerian Senate?',
"Sinima to gun ni ọrọ oṣelu Naijiria, ko fẹ ẹ ni opin: Nibi ti ọrọ de e duro yii, ko si ẹni to le sọ pe ibi kan ni yoo ja si nigbẹyin. Nigba ti awuyewuye yii bẹrẹ, Adams Oshiomole lo dipo alaga ẹgbẹ APC mu. Ni ba ti se n sọrọ yi, ile ẹjọ giga ti yẹ aga nidi Oshiomole ti awọn miran si ti n ja witiwiti lati wa ni ipo alaga. Labẹ pe ibẹrẹ kọ l'onisẹ, afi ẹni ba laa ja, awọn ti o fi ẹgbẹ oselu APC silẹ fun Oshiomole bi Aarẹ ile asofin agba tẹlẹ ri Bukola Saraki ni wọn wa n gba Godwin Obaseki lalejo ninu ẹgbẹ oselu PDP bayi. Njẹ ajọsepọ awọn to kora jọ lati doju ija kọ ara wọn wọnyi, yoo jẹ ọlọjọ pipẹ tabi awọn naa yoo pada wa tutọ si ara wọn loju? Oju re e, iran ree lọrọ to wa nilẹ yi.",
'Ọjọ Aje, Mọnde, ọsẹ yii, nijọba ipinlẹ Kwara, latọwọ Kọmisanna to n ri sọrọ ijọba ibilẹ ati lọba lọba, Aliyu Saifudeen, buwọ lu Ismail Yahaya Alebiosu gẹgẹ bii Olupo ti ilu Ajasẹ-Ipo tuntun. Kọmiṣanna sọ pe, awọn yan Ismall Yahaya Alebiosu gẹgẹ bii Olupo, nitori oun lo tọ si ipo naa. O fi kun un pe gomina fọwọ si iyansipo rẹ, ti yoo si maa ṣe atilẹyin fun un nigbakugba ti ọba alaye naa ba nilo iranlọwọ ijọba. Nigba ti Ọba Alebiosu n tẹwọ gba iwe iyansipo rẹ, o dupẹ lọwọ Gomina ipinlẹ Kwara, Abdulrahman Abdulrasaq, fun bo ṣe tẹle ohun ti awọn araalu n fẹ, to si buwọ lu iyansipo oun, o waa jẹjẹẹ pe oun ko ni i kuna lati maa ṣe ojuse oun, bẹẹ lo ṣeleri pe oun ko ni i ja awọn eeyan ilu naa kulẹ nigba kankan.',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 1024]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.4805, 0.3301],
# [0.4805, 1.0000, 0.5117],
# [0.3301, 0.5117, 0.9961]], dtype=torch.bfloat16)
nigerian-valTripletEvaluator| Metric | Value |
|---|---|
| cosine_accuracy | 0.7925 |
anchor and positive| anchor | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| anchor | positive |
|---|---|
Where is Cosmas Maduka from? |
Maduka, an Igbo Christian from Nnewi, Anambra State was born into the family of Mr. Peter and Mrs. Rose Maduka in the City of Jos. Maduka began his entrepreneurial journey at the age of six, two years after his father died. He dropped out of primary school and started hawking Akara, a popular Nigerian food staple made from beans to support his mother. |
Which year was Mayotte created? |
Mayotte broke away from the Comoros and remained with France after the Comoros declared its independence following in the 1974 referendum. Mayotte became an overseas department on 31 March 2011 and became an outermost region of the European Union on 1 January 2014, following a March 2009 referendum with an overwhelming result in favour of the department status. |
Ọdun wo ni Deborah Oluwaseyi Joshua gbe awo orin rẹ akọkọ jade? |
In July 2015, she signed a record deal with Island Records. In 2015, she signed a two-year endorsement deal with Pepsi. Shay released her debut studio album Seyi or Shay in November 2015. |
MatryoshkaLoss with these parameters:{
"loss": "MultipleNegativesRankingLoss",
"matryoshka_dims": [
1024,
512,
256,
128,
64
],
"matryoshka_weights": [
1,
1,
1,
1,
1
],
"n_dims_per_step": -1
}
anchor and positive| anchor | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| anchor | positive |
|---|---|
A cikin wace jami'a ce Manouchka Kelly Labouba ta kammala digirinta na PhD? |
In 2005, she studied Film & Media Studies at University of California, Santa Barbara. Then, in 2007, he obtained Master de Recherche, Arts from Bordeaux Montaigne University. Later he graduated with a M.A. Critical Studies and then Ph.D. Cinema and Media Studies from University of Southern California to obtain and also graduated with a Certificate in the Business of Entertainment. |
Who represented Kaduna South in the 2019 Nigerian Senate? |
The 2019 Nigerian Senate election in Kaduna State held on February 23, 2019, to elect members of the Nigerian Senate to represent Kaduna State. Kwari Suleiman Abdu representing Kaduna North, Sani Uba representing Kaduna Central both won on the platform of All Progressives Congress. while Laah Danjuma Tella representing Kaduna South returned to parliament on the platform of People's Democratic Party Results. |
Who is the former governor of Lagos state that also ran for Nigerian President? |
Aare Muhammadu Buhari ti ki Asiwaju Bola Ahmed Tinubu u oriire, bee lo si ke si gbogbo awon omo Naijiria ki won fowosowopo pelu aare adiboyan naa. Buhari ni, ki awon ti ibo naa ko dun mo ninu gba ile ejo lo, ki won loo rojo nibe, nitori ohun to sele ninu ibo yii fihan pe ko si mago-mago kankan. O ni, Tinubu funra re padanu ipinle Eko, tii se ipinle re, bee loun naa padanu ipinle oun, tii se ipinle Katsina, eyi si fihan pe ko si eru kan ninu eto idibo naa, eni tawon eeyan fe lo wole ibo. O loun setan ati seto igbejoba pada fun Tinubu atawon eeyan re ko too di pe ojo igbejobo sile de ninu osu karun-un, odun yii. |
MatryoshkaLoss with these parameters:{
"loss": "MultipleNegativesRankingLoss",
"matryoshka_dims": [
1024,
512,
256,
128,
64
],
"matryoshka_weights": [
1,
1,
1,
1,
1
],
"n_dims_per_step": -1
}
eval_strategy: stepsgradient_accumulation_steps: 16learning_rate: 5e-06num_train_epochs: 1lr_scheduler_type: cosinewarmup_steps: 0.05bf16: Truedataloader_num_workers: 2load_best_model_at_end: Truedo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 8per_device_eval_batch_size: 8gradient_accumulation_steps: 16eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-06weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 1max_steps: -1lr_scheduler_type: cosinelr_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: 2dataloader_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: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_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: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Validation Loss | nigerian-val_cosine_accuracy |
|---|---|---|---|
| 0.7033 | 2 | 8.0186 | 0.8019 |
| 1.3516 | 4 | 5.7152 | 0.7925 |
| 2.0 | 6 | 5.6023 | 0.7925 |
| 0.9714 | 17 | 1.8886 | 0.7925 |
@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-m3