Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 13
How to use redis/model-a-baseline with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("redis/model-a-baseline")
sentences = [
"who is the publisher of the norton anthology american literature",
"W. W. Norton & Company W. W. Norton & Company is an American publishing company based in New York City. It has been owned wholly by its employees since the early 1960s. The company is known for its \"Norton Anthologies\" (particularly The Norton Anthology of English Literature) and its texts in the Norton Critical Editions series, the latter of which are frequently assigned in university literature courses.",
"New Orleans La Nouvelle-Orléans (New Orleans) was founded in Spring of 1718 (7 May has become the traditional date to mark the anniversary, but the actual day is unknown[25]) by the French Mississippi Company, under the direction of Jean-Baptiste Le Moyne de Bienville, on land inhabited by the Chitimacha. It was named for Philippe II, Duke of Orléans, who was Regent of the Kingdom of France at the time. His title came from the French city of Orléans.",
"I Really Like You The music video was directed by Peter Glanz. Jepsen filmed part of the song's music video on 16 February 2015, in front of the Mondrian Hotel in Manhattan alongside Tom Hanks, Justin Bieber and a troupe of dancers. Also making cameo appearances in the video are Rudy Mancuso and Andrew B. Bachelor (A.K.A. King Bach), well-known users of the short-form video sharing application Vine. The video was released on 6 March 2015.[15] CBC Music's Nicolle Weeks described it as \"a more affable version\" of the music video for The Verve's \"Bitter Sweet Symphony\" (1997).[16] The music video has been rated as one of 10 Best Music Videos of 2015 (So Far) by the readers of Billboard.[17]"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from thenlper/gte-small. It maps sentences & paragraphs to a 384-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': 128, 'do_lower_case': False, 'architecture': 'BertModel'})
(1): Pooling({'word_embedding_dimension': 384, '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): 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("redis/model-a-baseline")
# Run inference
sentences = [
'what are the 5 liberties of the first amendment',
'First Amendment to the United States Constitution The First Amendment (Amendment I) to the United States Constitution prohibits the making of any law respecting an establishment of religion, ensuring that there is no prohibition on the free exercise of religion, abridging the freedom of speech, infringing on the freedom of the press, interfering with the right to peaceably assemble, or prohibiting the petitioning for a governmental redress of grievances. It was adopted on December 15, 1791, as one of the ten amendments that constitute the Bill of Rights.',
"Jake and the Never Land Pirates Jake and the Never Land Pirates (also known as Captain Jake and the Never Land Pirates in the fourth season and associated merchandise[1]) is an Annie Award-winning musical and interactive American children's animated television series shown on Disney Junior. It is based on Disney's Peter Pan franchise, which in turn is based on the famous book and play by British author J. M. Barrie. It is the first Disney Junior original show following the switch from Playhouse Disney. It stars Sean Ryan Fox from Henry Danger, Megan Richie, Jadon Sand, David Arquette, Corey Burton, Jeff Bennett, Loren Hoskins and Dee Bradley Baker. The title character Jake was previously voiced by Colin Ford, and then later by Cameron Boyce, while Izzy was voiced for the first three seasons by Madison Pettis and Cubby was voiced by Jonathan Morgan Heit. The series is created by Disney veteran Bobs Gannaway, whose works include another Disney Junior series, Mickey Mouse Clubhouse, and films such as Secret of the Wings, The Pirate Fairy and Planes: Fire & Rescue. The last episode aired on November 6, 2016.",
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 384]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.7343, 0.0079],
# [0.7343, 1.0000, 0.0383],
# [0.0079, 0.0383, 1.0000]])
NanoMSMARCO and NanoNQInformationRetrievalEvaluator| Metric | NanoMSMARCO | NanoNQ |
|---|---|---|
| cosine_accuracy@1 | 0.38 | 0.46 |
| cosine_accuracy@3 | 0.58 | 0.64 |
| cosine_accuracy@5 | 0.66 | 0.72 |
| cosine_accuracy@10 | 0.8 | 0.74 |
| cosine_precision@1 | 0.38 | 0.46 |
| cosine_precision@3 | 0.1933 | 0.2133 |
| cosine_precision@5 | 0.132 | 0.152 |
| cosine_precision@10 | 0.08 | 0.08 |
| cosine_recall@1 | 0.38 | 0.44 |
| cosine_recall@3 | 0.58 | 0.6 |
| cosine_recall@5 | 0.66 | 0.69 |
| cosine_recall@10 | 0.8 | 0.72 |
| cosine_ndcg@10 | 0.5747 | 0.5959 |
| cosine_mrr@10 | 0.5051 | 0.5642 |
| cosine_map@100 | 0.5164 | 0.5592 |
NanoBEIR_meanNanoBEIREvaluator with these parameters:{
"dataset_names": [
"msmarco",
"nq"
],
"dataset_id": "lightonai/NanoBEIR-en"
}
| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.42 |
| cosine_accuracy@3 | 0.61 |
| cosine_accuracy@5 | 0.69 |
| cosine_accuracy@10 | 0.77 |
| cosine_precision@1 | 0.42 |
| cosine_precision@3 | 0.2033 |
| cosine_precision@5 | 0.142 |
| cosine_precision@10 | 0.08 |
| cosine_recall@1 | 0.41 |
| cosine_recall@3 | 0.59 |
| cosine_recall@5 | 0.675 |
| cosine_recall@10 | 0.76 |
| cosine_ndcg@10 | 0.5853 |
| cosine_mrr@10 | 0.5347 |
| cosine_map@100 | 0.5378 |
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
who played in the movie throw momma from the train |
Anne Ramsey Angelina (Anne) Ramsey (March 27, 1929[1] – August 11, 1988) was an American stage, television, and film actress. She was best known for portraying Mama Fratelli in The Goonies (1985) and Mrs. Lift, mother of Danny DeVito's protagonist, in Throw Momma from the Train (1987). The latter film saw Ramsey nominated for a Golden Globe Award and the Academy Award for Best Supporting Actress. |
Aye Mere Watan Ke Logo "Aye Mere Watan Ke Logo" (Hindi: ऐ मेरे वतन के लोगों; "O' people of my country") is a Hindi patriotic song written by Kavi Pradeep, composed by C. Ramchandra, and performed by Lata Mangeshkar. The song commemorates Indian soldiers who died during the Sino-Indian War in 1962. The song was first performed live by Mangeshkar on 27 January 1963 at the National Stadium in New Delhi in the presence of President Sarvepalli Radhakrishnan and Prime Minister Jawaharlal Nehru, on account of Republic Day (26 January) 1963, which was just two months after the end of the war. |
when was the wall in san diego built |
Mexico–United States barrier In September 2017, the U.S. government announced the start of construction of eight prototype barriers made from concrete and other materials.[51][52] On June 3, 2018 the San Diego section of the US border wall construction began. [53] |
The Dance of Dragons At the Wall, Jon Snow (Kit Harington) retreats from Hardhome defeated, accompanied by the surviving wildlings, much to the chagrin of some of the Night's Watch. In the North, Stannis Baratheon (Stephen Dillane) reluctantly allows Melisandre (Carice van Houten) to sacrifice his daughter Shireen (Kerry Ingram) after Ramsay Bolton (Iwan Rheon) sabotages his resources, resulting to his army's damaged morale. In Braavos, Arya Stark (Maisie Williams), detours from her mission given by Jaqen H'ghar (Tom Wlaschiha) to reconnoiter Meryn Trant (Ian Beattie) instead. In Dorne, Jaime Lannister (Nikolaj Coster-Waldau) secures Myrcella Baratheon's (Nell Tiger Free) release from Doran Martell's (Alexander Siddig) court against an indignant Ellaria Sand (Indira Varma). In Meereen, the Sons of the Harpy attack the stadium of Daznak's Pit in an attempt to assassinate Daenerys Targaryen (Emilia Clarke), who is rescued by Jorah Mormont (Iain Glen) and her firstborn dragon, Drogon. Lea... |
urology is the study of diseases of the |
Urology Urology (from Greek οὖρον ouron "urine" and -λογία -logia "study of"), also known as genitourinary surgery, is the branch of medicine that focuses on surgical and medical diseases of the male and female urinary-tract system and the male reproductive organs. Organs under the domain of urology include the kidneys, adrenal glands, ureters, urinary bladder, urethra, and the male reproductive organs (testes, epididymis, vas deferens, seminal vesicles, prostate, and penis). |
The Jackie Gleason Show By far the most memorable and popular of Gleason's characters was blowhard Brooklyn bus driver Ralph Kramden, featured originally in a series of Cavalcade skits known as "The Honeymooners", with Pert Kelton as his wife Alice, and Art Carney as his upstairs neighbor Ed Norton. These were so popular that in 1955 Gleason suspended the variety format and filmed The Honeymooners as a regular half-hour sitcom (television's first spin-off), co-starring Carney, Audrey Meadows (who had replaced the blacklisted Kelton after the earlier move to CBS), and Joyce Randolph. Finishing 19th in the ratings, these 39 episodes were subsequently rerun constantly in syndication, often five nights a week, with the cycle repeating every two months for decades. They are probably the most familiar body of work from 1950s television with the exception of I Love Lucy starring Lucille Ball and Desi Arnaz. |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false
}
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
what is the political system that the united states follows in regards to elections |
Primary election The United States is one of few countries to select candidates through popular vote in a primary election system; most countries rely on party leaders to vote candidates, as was previously the case in the U.S.[9] In modern politics, primary elections have been described as a significant vehicle for taking decision-making from political insiders to the voters, though this is disputed by select political science research.[10] The selection of candidates for federal, state, and local general elections takes place in primary elections organized by the public administration for the general voting public to participate in for the purpose of nominating the respective parties' official candidates; state voters start the electoral process for governors and legislators through the primary process, as well as for many local officials from city councilors to county commissioners.[11] The candidate who moves from the primary to be successful in the general election takes public off... |
Bob Gaudio Robert John "Bob" Gaudio (born November 17, 1942) is an American singer, songwriter, musician, and record producer, and the keyboardist/backing vocalist for The Four Seasons. |
what caused the unusual landscape at the valley of fire |
Valley of Fire State Park Complex uplifting and faulting of the region, followed by extensive erosion, have created the present landscape. The rough floor and jagged walls of the park contain brilliant formations of eroded sandstone and sand dunes more than 150 million years old. Other important rock formations include limestones, shales, and conglomerates.[4] |
Fundamental Constitutions of Carolina Because the Fundamental Constitutions were drafted during John Locke's service to one of Province of Carolina proprietors, Anthony Ashley Cooper, it is widely alleged that Locke had a major role in the making of the Constitutions. In the view of historian David Armitage[5] and political scientist Vicki Hsueh, the Constitutions were co-authored by Locke and his patron Cooper, known also as 1st Earl of Shaftesbury.[6] However the document was a legal document written for and signed and sealed by the eight Lord proprietors to whom Charles II had granted the colony; Locke was only a paid secretary. He wrote it much as a lawyer writes a will.[4] |
according to the guinness world records what author has the most published works |
Guinness World Records The book itself holds a world record, as the best-selling copyrighted book of all time. As of the 2017 edition, it is now in its 62nd year of publication, published in 100 countries and 23 languages. The international franchise has extended beyond print to include television series and museums. The popularity of the franchise has resulted in Guinness World Records becoming the primary international authority on the cataloguing and verification of a huge number of world records; the organisation employs official record adjudicators authorised to verify the authenticity of the setting and breaking of records.[2] |
The Big Chill (film) The Big Chill is a 1983 American comedy-drama film directed by Lawrence Kasdan, starring Tom Berenger, Glenn Close, Jeff Goldblum, William Hurt, Kevin Kline, Mary Kay Place, Meg Tilly, and JoBeth Williams. The plot focuses on a group of baby boomers who attended the University of Michigan, reuniting after 15 years when their friend Alex commits suicide. Kevin Costner was cast as Alex, but all scenes showing his face were cut. It was filmed in Beaufort, South Carolina.[2] |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false
}
eval_strategy: stepsper_device_train_batch_size: 128per_device_eval_batch_size: 128learning_rate: 8e-05weight_decay: 0.005max_steps: 1125warmup_ratio: 0.1fp16: Truedataloader_drop_last: Truedataloader_num_workers: 1dataloader_prefetch_factor: 1load_best_model_at_end: Trueoptim: adamw_torchddp_find_unused_parameters: Falsepush_to_hub: Truehub_model_id: redis/model-a-baselineeval_on_start: Trueoverwrite_output_dir: Falsedo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 128per_device_eval_batch_size: 128per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 8e-05weight_decay: 0.005adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 3.0max_steps: 1125lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_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: Falsefp16: Truefp16_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: Truedataloader_num_workers: 1dataloader_prefetch_factor: 1past_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Trueignore_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_torchoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthproject: huggingfacetrackio_space_id: trackioddp_find_unused_parameters: Falseddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Trueresume_from_checkpoint: Nonehub_model_id: redis/model-a-baselinehub_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: Trueuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Trueprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | Validation Loss | NanoMSMARCO_cosine_ndcg@10 | NanoNQ_cosine_ndcg@10 | NanoBEIR_mean_cosine_ndcg@10 |
|---|---|---|---|---|---|---|
| 0 | 0 | - | 2.1869 | 0.6259 | 0.6583 | 0.6421 |
| 0.3556 | 250 | 0.3907 | 0.0761 | 0.5880 | 0.6146 | 0.6013 |
| 0.7112 | 500 | 0.0814 | 0.0680 | 0.5666 | 0.6170 | 0.5918 |
| 1.0669 | 750 | 0.0714 | 0.0634 | 0.5580 | 0.5846 | 0.5713 |
| 1.4225 | 1000 | 0.0406 | 0.0614 | 0.5747 | 0.5959 | 0.5853 |
@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{henderson2017efficient,
title={Efficient Natural Language Response Suggestion for Smart Reply},
author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
year={2017},
eprint={1705.00652},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
Base model
thenlper/gte-small