Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 15
How to use rookshanks/gemma_300m_grocery with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("rookshanks/gemma_300m_grocery")
sentences = [
"kinder",
"Category: Pantry > Cereal & Breakfast > Kids Cereals\nBrand: Kelloggs\nProduct: Frosted Flakes Cereal\nSize: 355 g",
"Category: Pantry > Easy Meals & Sides > Macaroni & Cheese\nBrand: Bens\nProduct: BISTRO EXPRESS Brown Basmati Rice\nSize: 240 g\nDescription: BEN'S ORIGINAL BISTRO EXPRESS Brown Basmati Rice brings the rich, nutty aromas and flavours of India to your dinner table in just 90 seconds. This microwave rice side dish offers authentic 100% whole grain Indian brown basmati rice to make your meals more flavourful. BEN'S ORIGINAL BISTRO EXPRESS rice comes in a BPA-free microwavable pouch that makes cooking easier by eliminating prep and cleanup. To get this brown rice ready to serve, all you have to do is place the pouch in the microwave and cook it for 90 seconds, or pour the contents into a skillet and heat thoroughly. Perfect as a flavourful rice side dish or as part of a main course meal, this basmati rice is delicious paired with your favourite curries, braised or roasted meats, or served plain. This whole grain rice contains no artificial colours, flavours, or preservatives. BEN'S ORIGINAL brand is dedicated to creating meals and experiences that offer everyone a seat at the table.One 240g pouch of BEN'S ORIGINAL BISTRO EXPRESS Brown Basmati RiceMicrowave rice pouch that helps you enjoy hassle-free dining with a taste of deliciously flavoured rice in just 90 secondsEach pouch offers authentic 100% whole grain Indian brown basmati rice to make your meals more flavourfulPair this cooked rice side dish with your favourite protein or serve it plain for a quick bitePlace the pouch in the microwave and cook it for 90 seconds, or pour the contents into a skillet and heat thoroughly",
"Category: Dairy & Eggs > Yogurt > Kid Friendly\nBrand: Danone\nProduct: Kids Yogurt Drink, Strawberry, Paw Patrol\nSize: 6x93.0 ml\nDescription: You only want the very best for your family – and so do we! That’s why our strawberry yogurt drink is made with real fruit purée and 5g of sugar per serving. Every awesome flavour of Danino drinkable yogurt is also a yummy source of calcium with a cool Paw Patrol character on the bottle! A delight to be enjoyed whenever and wherever you like, since it keeps for up to 8 hours out of the fridge*.*This product must be first kept refrigerated, and then can be kept up to 8 hours out of the refrigerator unopened. Product should then be consumed and not be refrigerated again to preserve taste.Source of CalciumReal Fruit PureeOnly 5g of sugar per servingValue pack of 6 bottlesB Corp Certified"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from google/embeddinggemma-300m. 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': 2048, 'do_lower_case': False, 'architecture': 'Gemma3TextModel'})
(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})
(2): Dense({'in_features': 768, 'out_features': 3072, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})
(3): Dense({'in_features': 3072, 'out_features': 768, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})
(4): 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("rookshanks/gemma_300m_grocery")
# Run inference
queries = [
"miracle reds superfood",
]
documents = [
'Categories: Pantry > Canned & Pickled > Natural and Organic, Natural and Organic > Canned > Fruit and Vegetables\nBrand: Muir Glen\nProduct: Fire Roasted Crushed Tomatoes\nSize: 796 ml\nDescription: Whole tomatoes are harvested at peak flavour, roasted over an open flame that blackens the skin and sears in the unique flavour of fire-roasted goodness. Then they are crushed for easy use in soups, sauces and stews. 1/2 cupA gluten-free foodOrganicNon GMO',
'Category: Fruits & Vegetables > Fresh Vegetables > Carrots, Radish & Root Vegetables\nBrand: none\nProduct: Red Carrot\nSold by weight\nDescription: A sweet, earthy flavour with a satisfyingly crisp texture in every bite. Shred these carrots raw into salads for a bright crunch, or roast them whole to deepen their natural sweetness for a simple side dish. They also add a foundational flavour and colour to hearty soups and stews.',
"Category: Snacks, Chips & Candy > Chips & Snacks > Snack & Granola Bars\nBrand: Kashi\nProduct: Chewy Chia Whole Grain Bars Dark Chocolate, Almond & Sea Salt\nSize: 175 g\nDescription: Our chewy granola bars are truly lovable. They bring our unique blend of whole grains together with whole, roasted nuts and succulent dark chocolate. And with 4g of fibre per serving, they are as nourishing and tasty.Combining dark chocolate, roasted almonds and a touch of sea salt with chia means you can enjoy sweet and salty flavour with 0.1 g omega-3 polyunsaturates in one satisfyingly chewy granola bar.A sweet and salty granola bar made with whole grain oats, crunchy almonds, rich dark chocolate and a touch of sea salt.Chewy, Tasty, Simple. Kashi Chewy Whole Grain Bars arethe perfect snack for the whole family. Great for snacking at home, at school, at the office, or when you're on the go!13g Whole Grains per serving per serving; 4g fibre per servingNo artificial flavours or coloursNon-GMO Project Verified",
]
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.2978, 0.3890, 0.0984]])
val_concordanceTripletEvaluator| Metric | Value |
|---|---|
| cosine_accuracy | 0.7988 |
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
waffles |
Category: Frozen Food > Bakery & Breakfast > Waffles & Pancakes |
Category: Frozen Food > Bakery & Breakfast > Waffles & Pancakes |
hot sauce for wings |
Category: Pantry > Condiments & Sauces > Hot & Chili Sauces |
Category: Meat > Chicken & Turkey > Chicken Wings |
pop-tarts churro |
Category: Pantry > Cereal & Breakfast > Toaster Pastries |
Category: Snacks, Chips & Candy > Chips & Snacks > Chips |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"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 |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
broccoli florets |
Category: Fruits & Vegetables > Fresh Cut Fruits & Vegetables > Fresh Cut Vegetables |
Categories: Fruits & Vegetables > Fresh Vegetables > International & Specialty Vegetables, International Foods > East Asian Foods > Fruits & Vegetables |
organic strawberry spread for toast |
Category: Natural and Organic > Cereals, Spreads & Syrups > Spread |
Category: Natural and Organic > Cereals, Spreads & Syrups > Spread |
balsamic vinaigrette for salad |
Category: Pantry > Condiments & Sauces > Salad Dressing |
Category: Pantry > Canned & Pickled > Pickled & Marinated Vegetables |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false,
"directions": [
"query_to_doc"
],
"partition_mode": "joint",
"hardness_mode": null,
"hardness_strength": 0.0
}
eval_strategy: epochper_device_train_batch_size: 32learning_rate: 2e-05num_train_epochs: 5warmup_ratio: 0.1bf16: Trueprompts: {'anchor': 'query', 'positive': 'document', 'negative': 'document'}overwrite_output_dir: Falsedo_predict: Falseeval_strategy: epochprediction_loss_only: Trueper_device_train_batch_size: 32per_device_eval_batch_size: 8per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_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: 5max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_ratio: 0.1warmup_steps: 0log_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: Falsebf16: Truefp16: Falsefp16_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: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_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: Noneadafactor: Falsegroup_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: Trueuse_legacy_prediction_loop: Falsepush_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_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: Noneinclude_tokens_per_second: Falseinclude_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: Trueprompts: {'anchor': 'query', 'positive': 'document', 'negative': 'document'}batch_sampler: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | Validation Loss | val_concordance_cosine_accuracy |
|---|---|---|---|---|
| 0.1748 | 25 | 1.3746 | - | - |
| 0.3497 | 50 | 0.8075 | - | - |
| 0.5245 | 75 | 0.7834 | - | - |
| 0.6993 | 100 | 0.8104 | - | - |
| 0.8741 | 125 | 0.7395 | - | - |
| 1.0 | 143 | - | 0.5356 | 0.7900 |
| 1.0490 | 150 | 0.7583 | - | - |
| 1.2238 | 175 | 0.5064 | - | - |
| 1.3986 | 200 | 0.464 | - | - |
| 1.5734 | 225 | 0.5096 | - | - |
| 1.7483 | 250 | 0.4995 | - | - |
| 1.9231 | 275 | 0.4491 | - | - |
| 2.0 | 286 | - | 0.5027 | 0.8049 |
| 2.0979 | 300 | 0.3885 | - | - |
| 2.2727 | 325 | 0.2072 | - | - |
| 2.4476 | 350 | 0.2757 | - | - |
| 2.6224 | 375 | 0.2693 | - | - |
| 2.7972 | 400 | 0.2528 | - | - |
| 2.9720 | 425 | 0.234 | - | - |
| 3.0 | 429 | - | 0.5396 | 0.7988 |
@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{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-300m