Views
No views yet




1import torch
2from transformers import AutoTokenizer, AutoModel
3
4# Configuration
5MODEL_ID = "Omartificial-Intelligence-Space/SA-BERT-V1"
6DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
8# Load tokenizer and model
9tokenizer = AutoTokenizer.from_pretrained(MODEL_ID , token= "PASS_READ_TOKEN_HERE")
10model = AutoModel.from_pretrained(MODEL_ID , token = "PASS_READ_TOKEN_HERE").to(DEVICE).eval()
11
12def embed_sentence(text: str) -> torch.Tensor:
13 """
14 Tokenizes `text`, feeds it through SA-BERT-V1, and returns
15 a 768-dimensional mean-pooled sentence embedding.
16 """
17 # Encode the text
18 enc = tokenizer(
19 text,
20 truncation=True,
21 padding="max_length",
22 max_length=256,
23 return_tensors="pt"
24 ).to(DEVICE)
25
26 # Forward pass
27 with torch.no_grad():
28 outputs = model(**enc).last_hidden_state # shape: (1, seq_len, 768)
29
30 # Mean-pooling over valid tokens
31 mask = enc["attention_mask"].unsqueeze(-1) # shape: (1, seq_len, 1)
32 summed = (outputs * mask).sum(dim=1) # shape: (1, 768)
33 counts = mask.sum(dim=1).clamp(min=1e-9) # shape: (1, 1)
34 embedding = summed / counts # shape: (1, 768)
35
36 return embedding.squeeze(0) # shape: (768,)
37
38# Example usage
39if __name__ == "__main__":
40 sentences = [
41 "شتبي من البقالة؟",
42 "كيف حالك؟",
43 "وش رايك في الموضوع هذا؟"
44 ]
45 for s in sentences:
46 vec = embed_sentence(s)
47 print(f"Sentence: {s}\nEmbedding shape: {vec.shape}\n")1@misc{nacar2025SABERTV1,
2 title={SA-BERT-V1: Fine-Tuned Saudi-Dialect Embeddings},
3 author={Nacar, Omer & Sibaee, Serry},
4 year={2025},
5 publisher={Omartificial-Intelligence-Space},
6 howpublished={\url{https://huggingface.co/Omartificial-Intelligence-Space/SA-BERT-V1}},
7}
8
9@inproceedings{abdul-mageed-etal-2021-arbert,
10 title = "{ARBERT} {\&} {MARBERT}: Deep Bidirectional Transformers for {A}rabic",
11 author = "Abdul-Mageed, Muhammad and Elmadany, AbdelRahim and Nagoudi, El Moatez Billah",
12 booktitle = "Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)",
13 year = "2021",
14 publisher = "Association for Computational Linguistics",
15 pages = "7088--7105",
16}