Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 15
How to use ahmedHamdi/IR-fr-en-gemma with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("ahmedHamdi/IR-fr-en-gemma")
sentences = [
"In late Victorian England, young Jude Fawley (Christopher Eccleston) dreams of attending university. Following an unhappy first marriage to a country girl, Arabella (Rachel Griffiths), who abruptly leaves him with a note, he becomes a bricklayer and moves to Christminster to pursue his dream. There he meets his beautiful cousin, Sue Bridehead (Kate Winslet), who is as intelligent and unconventional as he is. They quickly fall in love, but will have to face the great difficulties and scandal caused by their extramarital affair…",
"In 63 BC, Pompey conquered Jerusalem and the city was sacked. He entered the Temple to seize the treasure of Solomon and massacred the priests there. He discovered that the treasure is only a collection of scrolls of the Torah. These Pompey held over a fire until an old priest reached for them imploringly. Pompey relented and handed them to the old man and left to carry out massacres of enemy villages and towns. Many years later, a series of rebellions break out against the authority of Rome, so the Romans crucify many of the leaders and place Herod the Great on Judea's throne. A carpenter named Joseph and his wife Mary, who is about to give birth, arrive in Bethlehem for the census. Not having found accommodation for the night, they take refuge in a stable, where the child, Jesus, is born. The shepherds, who have followed the Magi from the East, gather to worship him. However, Herod, informed of the birth of a child-king, orders the centurion Lucius to take his men to Bethlehem and kill all the newborn male children. Mary and Joseph flee to Egypt with the child. The Massacre of the Innocents occurs, Herod dies, killed in his death throes by his son Herod Antipas, who then takes power. In Nazareth, Jesus, who is now twelve years old, is working with Joseph when soldiers arrive under the command of Lucius, who knows now that Jesus escaped the massacre of the infants. But Lucius does nothing and only asks that Mary and Joseph register their son's birth before the year's end. Years pass and Jewish rebels led by Barabbas and Judas Iscariot prepare to attack a caravan carrying the next governor of Judea, Pontius Pilate and his wife Claudia. The ambush fails, partly due to the diligence of Lucius, and Barabbas and Judas flee for their lives. Pilate and Herod Antipas meet on the banks of the River Jordan, where John the Baptist preaches to the crowds. Jesus arrives here, now 30 years of age. He is baptized by John, who recognizes that he is the Messiah. Jesus goes into the desert, where he is tempted by Satan. After forty days, Jesus travels to Galilee, where he recruits his Apostles. In Jerusalem, Herod Antipas arrests John the Baptist, who is visited by Jesus in prison. Judas leaves the rebel Barabbas and joins the Apostles. Jesus begins to preach and gather crowds, among which are Claudia, Pilate's wife, and Lucius. Herod reluctantly beheads John on a whim of his stepdaughter, Salome, who despises him. Herod, Pilate and the High Priest Caiaphas are terrorized by the works and miracles of Jesus. Barabbas plots a revolt in Jerusalem during Passover, during which time Jesus enters the holy city in triumph and goes to the Temple to preach. The rebels storm the Antonia Fortress, but the legions of Pilate, having learned of the plot, ambush and crush the revolt, massacring the rebels, leaving Barabbas as the sole survivor who ends up getting arrested. Jesus meets the disciples on the evening of Thursday, having supper one last time with them and afterwards goes to pray at Gethsemane. In the meantime, Judas wants Jesus to free Judea from the Romans, and, to force his hand, Judas delivers him to the Jewish authorities. Jesus is brought before Caiaphas and then brought before Pilate. Pilate starts the trial, but sensing that the issue is one of Jewish sensibilities, sends him to Herod Antipas, who, in turn, sends him back. Pilate is infuriated by Antipas' returning of Jesus and commands his soldiers to scourge Jesus. The people demand the release of Barabbas, and Pilate bows to their pressure and sentences Jesus to be crucified. Jesus, wearing a crown of thorns on his head, carries his cross to Golgotha where he is crucified with two thieves, one of them being the penitent thief Dismas and the other, the Impenitent thief, Gestas. Desperate because he has betrayed Jesus to his death, Judas hangs himself and his body is found by Barabbas. Jesus dies in front of his mother, the apostle John, a few soldiers, Claudia (Pilate's wife), and Lucius (who utters the fateful words: He is truly the Christ). His body is taken down from the cross and is carried to a rock tomb. Two days later, Mary Magdalene finds the tomb empty, and encounters the Risen Jesus.",
"In the Victorian period, Jude Fawley is a bright young lower-class man who dreams of a university education. Circumstances conspire against him, and he is forced into a job as a stonemason and an unhappy marriage to a country girl, Arabella. He remains true to his dream and, months later, after his wife's sudden departure, he heads for the city. He thinks education is available for any man who is willing to work hard. However, he is rejected by the university based primarily on his lower-class status. During this period, he encounters his cousin, Sue Bridehead, who is beautiful and intelligent, and shares his disdain for convention. Whilst Jude is enraptured by Sue, and vice versa, she marries Jude's former school teacher, Phillotson, after Jude tells her he is married to Arabella. The marriage of Sue and Phillotson is not a success, as she refuses to give herself sexually or romantically to her husband. She leaves Phillotson to join Jude in what turns out to be a rough life, moving from place to place as Jude picks up occasional work as a stonemason. Jude learns that Arabella bore a son, whom she named Jude (Juey) soon after she left Jude. The boy comes to live with his father Jude, and Sue. Sue gives birth to two children. Agnostic and independent, she refuses to legalise their arrangement by marriage. Sue and Jude are forbidden a permanent rental lodging because their living arrangement without marriage is considered scandalous. Sue tells Juey that the family cannot stay long at their present lodging because there are too many of them. The next day Sue and Jude return to their lodging to find that Juey has killed his half-siblings and committed suicide, hanging himself. His suicide note says the reason: Becos we were to menny. Each of the couple falls into a deep depression after the deaths of their children. Turning to the religion she previously rejected, Sue comes to believe that God has judged and punished the couple for not having married. She decides to return to Phillotson, although she finds him sexually repugnant, as he is her true husband in the eyes of God. A year after the death of their children, Jude and Sue happen to meet when separately visiting the tombstones of their children. They both look worse for wear. Jude demands that Sue tell him whether she still loves him, to which she replies, You've always known. After a passionate kiss, she walks away from Jude to return to Phillotson. As Sue walks away, Jude shouts to her, We are man and wife, if ever two people were on this earth!",
"Wealthy socialite Lois Frazer, divorcing her fortune-hunter husband, Howard, finds a gun he had bought. She kills him with it in front of the new man in her life, Lt. Ed Cullen, a homicide detective with the San Francisco police. Cullen takes control, discarding the weapon and moving the body. Cullen ends up assigned to investigate the case, assisted by kid brother Andy, who is new to the homicide division and delays his honeymoon to keep working on his first big case. The gun is found and used in another killing by a young punk, Nito Capa, and Cullen—with few options to save himself and his paramour Lois—tries to pin both crimes on him. However, Andy keeps connecting Ed to the first murder, catching him in a number of evasions and lies. In desperation, Ed knocks Andy out, ties and gags him, and calls Lois and tells her they need to flee. Police roadblocks seal off the city, but Andy has a hunch where Ed took Lois to hide, at the abandoned ruins of Fort Point under the Golden Gate Bridge where Andy and his brother played together when they were children. Their escape plan almost works, but they are ultimately arrested. Outside the courtroom, Ed sees Lois affectionately offering to do anything for her lawyer if he can keep her from being convicted. Defeated, Ed offers her a cigarette and they share a final goodbye gaze."
]
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': 256, '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})
)
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("ahmedHamdi/IR-fr-en-gemma")
# Run inference
sentences = [
"Sheba Miller, a working-class girl, dreams of a life of luxury. Her father owns a cigar shop, while she works as a stenographer. Jack, another working man, is madly in love with her and has even asked her father for his consent to their marriage. Although Pa Miller loves Jack and would like to see his daughter marry him, Sheba refuses because of his current salary. One day, she convinces him to take her to a chic and exclusive nightclub, the Pirates Den. Once they arrive and are seated, he is shocked by the prices and suggests they go somewhere else; this leads to an argument. As the couple is about to leave, an advertisement is placed for a leg contest, and Sheba decides to enter. She wins first place and is presented with her prize by Nickey Solomon, a gangster. Finally, Nickey proposes to Sheba, but before they can get married, Solomon, short on cash, robs a cigar shop and, in doing so, shoots the man behind the counter. Unbeknownst to him, he has shot Sheba's father. As the two are about to head out for another night on the town now that they have money, they stop at her father's cigar shop to say hello. As they approach, they see the police stationed nearby, and Nickey realizes what he has done. He convinces Sheba to stay in the car while he checks what happened. He speaks briefly to the police and then tells them that her father is fine and is now at the station helping the police identify a robber. In reality, however, her father is in the hospital being treated for his gunshot wound. Nickey convinces Sheba to continue their date, and they go to the club, but Jack, who suspects Solomon of being behind the robbery, asks the police to help him with his plan to frame him. They manage to get Nickey to unwittingly confess to the crime and convince him to leave town, but they arrest him at the train station before he has a chance to board. Solomon is taken to jail, and Sheba is informed that her father is perfectly fine. Humiliated by the experience, Sheba agrees to marry Jack with his $35-a-week salary.",
"Alice White plays Sheba Miller, a working-class girl who dreams about living a life of luxury. Her father runs a cigar store while she works as a stenographer. Jack, a soda jerk, is madly in love with her and has even asked her father for his consent to their marriage. Although Pa Miller likes Jack and would like to see his daughter marry him, Sheba refuses him on the wage he currently earns. One day, she convinces him to take her to a fancy exclusive nightclub, the Pirates Den. Once they arrive and are seated, he is shocked at the prices and suggests that they go elsewhere; this leads to an argument. As the couple is about to leave, an announcement is made for a leg contest and Sheba decides to enter. She wins first place and is awarded her prize by Nickey Solomon, a gangster. Dazzled by his fancy clothes and car, Sheba accepts his attentions and give Jack the air. Eventually Nickey asks Sheba to marry him, but before they tie the knot, Solomon, who is low on cash, robs a cigar store and in the process shoots the man behind the counter. Without knowing it, he has shot Sheba's father. As the two are about to head out for another night on the town now that they have money, they stop at her father's cigar store to say hello. As they approach, they see police stationed around and Nickey realizes what he has done. He convinces Sheba to stay in the car while he checks out what happened. He talks a bit to the police and then tells her that her father is all right and that he is now at the police station to help the police identify a thief. In reality, however, her father is at the hospital being treated for the gunshot wound. Nickey convinces Sheba to continue their date and they drive to the club, but Jack, who suspects that Solomon was behind the robbery, asks the police to help with his entrapment plan. They manage to get Nickey to unwittingly confess to the crime and convince him to skip town, but they arrest him at the train station before he has a chance to board. Solomon is taken to jail and Sheba is informed that her father is perfectly fine. Sheba, humbled by the experience, agrees to marry Jack on his $35 a week salary.",
"Raj Sharma is a young playboy who meets three young women at different stages in his life and learns important lessons about love along the way. As the story opens in 2008, it leads to a series of flashbacks describing his growth both emotional and ethical. 1996, Switzerland – Mahi On a trip to Switzerland with his friends, Raj runs into Mahi Pasricha on the Eurail, who is on vacation with her friends and family. Mahi is a sweet, dreamy girl who believes in true love and is hoping to find her 'Raj' (a reference to Dilwale Dulhania Le Jayenge (1995)) i.e. her true love. When she misses her train, Raj helps her reach the airport through a different route. On the way, they share a kiss after Raj reads her a poem he wrote about her. At the airport, when she opens the paper on which Raj had written the poem, she finds it blank. Raj boasts to his friends about what happened between the pair and how he took full advantage of the situation when she was alone. Mahi overhears this and is shocked and heartbroken. Raj realizes that she has overheard his conversation with his friends and shamefacedly leaves. 2002, Mumbai – Radhika 6 years after the Switzerland episode, Raj has moved to Mumbai and found a job with Microsoft as a game designer with his best friend Sachin Kashyap. Pretty soon, he enters into a live-in relationship with neighbor Radhika Kapoor, an aspiring model. Having received an offer to move to Sydney for a Halo 3 game launch, he expects to be able to leave Radhika and move on, assuming she is capable of handling a break-up. This vision is shattered when Radhika declares that she intends to sacrifice her career to marry Raj and join him in Australia. He makes up reasons to Radhika so as to prevent them from getting married, but she remains firm. Raj, unable to express his commitment phobia, boards his flight on the morning of his wedding to Radhika. Radhika learns this while waiting for him at the registrar's office dressed as a bride, and is left crestfallen and heartbroken. 2007, Sydney – Gayatri 5 years down the line, Raj now enjoys a successful career along with Sachin in Sydney. He meets Gayatri Divecha, a feisty and independent woman who studies at business school during the day, and moonlights as a taxi-driver at night. As they date, he gains feelings for her. He also realizes that his feelings for her challenge his misgivings towards commitment. He proposes to her, but Gayatri turns him down, saying that she is happy with her life as she is and she doesn't believe in marriage and commitment. Rejection cuts Raj deep. He recalls when he broke the hearts of Mahi and Radhika, realizing how they must have felt. He decides to seek them out and ask for forgiveness.",
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.9117, 0.0916],
# [0.9117, 1.0000, 0.0746],
# [0.0916, 0.0746, 1.0000]])
sentence_0 and sentence_1| sentence_0 | sentence_1 | |
|---|---|---|
| type | string | string |
| details |
|
|
| sentence_0 | sentence_1 |
|---|---|
An unbelievable heatwave hits the British island of Fara in the middle of winter. At the Swan Inn, tension rises along with the temperature. The mysterious guest, Hanson, will eventually reveal the cause of this strange microclimate: aliens are preparing to invade Earth, and the intense heat is essential for their survival… |
Jeff and Frankie Callum run The Swan, an inn on the island of Fara, somewhere off the English coast. Jeff, a professional novelist, hires a secretary, but this turns out to be Angela Roberts, a younger woman with whom he had an affair some time before, and who has come to the island with the intent of luring Jeff away from his wife, or at least causing trouble in their marriage. The Callums moved to Fara so that Jeff could escape Angela's amorous advances, although as far as Frankie knows, it was only to escape the tedium of life on the mainland. Not helping matters is the fact that despite it being the middle of winter, Fara is experiencing a stifling and inexplicable heat wave, with temperatures rising rapidly. It has become so hot that cars stall, beer bottles shatter, televisions explode, and telephones have ceased to work. Into this tense situation comes Godfrey Hanson, a mysterious scientist from the mainland, who rents a room at The Swan. Hanson spends his time exploring the isl... |
Rasputin made his healing powers known in Russia by curing a tavern keeper's wife. He then decided to go to the capital to become important. He hypnotized several people, which allowed him to gain access to the Tsar's court. |
In the Russian countryside, Rasputin heals the sick wife of an innkeeper (Derek Francis). When he is later hauled before an Orthodox bishop for his sexual immorality and violence, the innkeeper springs to the monk's defence. Rasputin protests that he is sexually immoral because he likes to give God sins worth forgiving (loosely based on Rasputin's rumored connection to Khlysty, an obscure Christian sect which believed that those deliberately committing fornication, then repenting bitterly, would be closer to God). He also claims to have healing powers in his hands, and is unperturbed by the bishop's accusation that his power comes from Satan. Rasputin heads for Saint Petersburg, where he forces his way into the home of Dr Zargo (Pasco), from where he begins his campaign to gain influence over the Tsarina (Asherson). He manipulates one of the Tsarina's ladies-in-waiting, Sonia (Shelley), whom he uses to satisfy his voracious sexual appetite and gain access to the Tsarina. He places her ... |
The film depicts the Willard family on a trip to Europe. The family crosses the Atlantic Ocean aboard the SS United States. |
Harry Willard finally makes good his promise to take his bride of 20 years on a long-delayed trip by ship to Europe. They are accompanied by their 19-year-old son (Elliott), 18-year-old daughter (Amy), and 11-year-old son (Skipper). From the time they arrive at the dock, an unending series of comedy adventures and romantic encounters ensue until, exhausted but happy, they leave with memories that will stay with them all for years to come. |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false
}
per_device_train_batch_size: 4per_device_eval_batch_size: 4multi_dataset_batch_sampler: round_robinoverwrite_output_dir: Falsedo_predict: Falseeval_strategy: noprediction_loss_only: Trueper_device_train_batch_size: 4per_device_eval_batch_size: 4per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1num_train_epochs: 3max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_ratio: 0.0warmup_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: 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: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: round_robinrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss |
|---|---|---|
| 0.1229 | 500 | 0.0107 |
| 0.2458 | 1000 | 0.0318 |
| 0.3686 | 1500 | 0.0667 |
| 0.4915 | 2000 | 0.1008 |
| 0.6144 | 2500 | 0.0844 |
| 0.7373 | 3000 | 0.0762 |
| 0.8602 | 3500 | 0.075 |
| 0.9830 | 4000 | 0.0713 |
| 1.1059 | 4500 | 0.039 |
| 1.2288 | 5000 | 0.0322 |
| 1.3517 | 5500 | 0.0399 |
| 1.4746 | 6000 | 0.0394 |
| 1.5974 | 6500 | 0.0259 |
| 1.7203 | 7000 | 0.0258 |
| 1.8432 | 7500 | 0.0215 |
| 1.9661 | 8000 | 0.0189 |
| 2.0890 | 8500 | 0.0077 |
| 2.2118 | 9000 | 0.0138 |
| 2.3347 | 9500 | 0.0077 |
| 2.4576 | 10000 | 0.003 |
| 2.5805 | 10500 | 0.0073 |
| 2.7034 | 11000 | 0.0088 |
| 2.8262 | 11500 | 0.0047 |
| 2.9491 | 12000 | 0.0078 |
@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
google/embeddinggemma-300m