CoolFace
Modelpublic

Abdalrahmankamel/matryoshka-arabert

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
1likes32downloads
Model Card

<div align="center">

๐ŸŒŸ AraBERT Matryoshka Embeddings

High-Quality Arabic Sentence Embeddings with Flexible Dimensions

![Model](https://huggingface.co/Abdalrahmankamel/matryoshka-arabert) ![License](https://opensource.org/licenses/Apache-2.0) ![Language](https://en.wikipedia.org/wiki/Arabic)

</div>


๐ŸŽฏ Model Overview

This model enhances AraBERTv02 with Matryoshka Representation Learning and LoRA adaptation to generate superior Arabic sentence embeddings. It supports multiple embedding dimensions (8, 64, 128, 256) from a single model, offering flexibility between performance and efficiency.

โœจ Key Features

FeatureDescription
๐Ÿ”„ Multi-DimensionalSingle model supports 4 different embedding sizes (8, 64, 128, 256)
๐Ÿš€ High PerformanceOutperforms base AraBERT across all dimensions
๐Ÿ“Š Arabic NLI OptimizedTrained specifically on Arabic Natural Language Inference
โšก Efficient InferenceSmaller dimensions for faster processing
๐ŸŽฏ Triplet Loss TrainingEnhanced semantic understanding through triplet learning

๐Ÿ› ๏ธ Quick Start

Installation

bash
pip install git+https://github.com/Abdalrahman54/matryoshka-wrapper.git

Basic Usage

python
from matryoshka_wrapper import load_model, MatryoshkaWrapper
from torch.nn.functional import cosine_similarity

# Load model with desired dimension
repo_name = "Abdalrahmankamel/matryoshka-arabert"
model, tokenizer = load_model(repo_name, dim="256")

# Example texts
text1 = "ู‡ุฐุง ุงู„ู…ู†ุชุฌ ูƒุงู† ู…ุฎูŠุจู‹ุง ู„ู„ุขู…ุงู„."
text2 = "ู‡ุฐู‡ ุงู„ุจุถุงุนุฉ ุฑุงุฆุนุฉ!"

# Generate embeddings
emb1 = model.get_embedding(text1, tokenizer, dim="256").squeeze()
emb2 = model.get_embedding(text2, tokenizer, dim="256").squeeze()

# Calculate similarity
similarity = cosine_similarity(emb1.unsqueeze(0), emb2.unsqueeze(0)).item()
print(f"๐Ÿ” Cosine Similarity: {similarity:.4f}")

๐Ÿ“Š Performance Comparison

Triplet Example

python
# Triplet data example
anchor = "ุงู„ุทูู„ ูŠู„ุนุจ ููŠ ุงู„ุญุฏูŠู‚ุฉ"
positive = "ูˆู„ุฏ ุตุบูŠุฑ ูŠู„ู‡ูˆ ููŠ ุงู„ุจุณุชุงู†"      # Similar sentence
negative = "ุงู„ุณูŠุงุฑุฉ ุชุณูŠุฑ ููŠ ุงู„ุดุงุฑุน"         # Different sentence

# Generate embeddings
anchor_emb = model.get_embedding(anchor, tokenizer, dim="256").squeeze()
positive_emb = model.get_embedding(positive, tokenizer, dim="256").squeeze()
negative_emb = model.get_embedding(negative, tokenizer, dim="256").squeeze()

# Calculate similarities
sim_positive = cosine_similarity(anchor_emb.unsqueeze(0), positive_emb.unsqueeze(0)).item()
sim_negative = cosine_similarity(anchor_emb.unsqueeze(0), negative_emb.unsqueeze(0)).item()

print("๐Ÿ” Triplet Results:")
print(f"๐Ÿ“Š Anchor โ†” Positive: {sim_positive:.4f}")
print(f"๐Ÿ“Š Anchor โ†” Negative: {sim_negative:.4f}")
print(f"๐Ÿ“ˆ Margin: {sim_positive - sim_negative:.4f}")

if sim_positive > sim_negative:
    print("โœ… Triplet Success!")
else:
    print("โŒ Triplet Failed!")

Dimension Comparison

python
# Compare across all dimensions
text1 = "ุงุทูุงู„ ูŠู…ุฑุญูˆู† ุณูˆูŠุงู‹ ุจุงู„ูƒุฑุฉ ููŠ ุงู„ู…ุณุงุญุงุช ุงู„ุฎุถุฑุงุก"
text2 = "ุฃุทูุงู„ ูŠู„ุนุจูˆู† ูƒุฑุฉ ุงู„ู‚ุฏู… ุนู„ู‰ ุงู„ุนุดุจ"

dimensions = [8, 64, 128, 256]

print("๐Ÿ” Multi-Dimensional Similarity Comparison")
print("=" * 50)

for dim in dimensions:
    model, tokenizer = load_model(repo_name, dim=str(dim))
    
    emb1 = model.get_embedding(text1, tokenizer, dim=str(dim)).squeeze()
    emb2 = model.get_embedding(text2, tokenizer, dim=str(dim)).squeeze()
    
    similarity = cosine_similarity(emb1.unsqueeze(0), emb2.unsqueeze(0)).item()
    
    print(f"๐Ÿ“ Dim {dim:>3}: Similarity = {similarity:.4f} | Shape = {emb1.shape}")

๐ŸŽฏ Use Cases

โœ… Recommended Uses

  • โ€”Semantic Search: Find similar Arabic documents or passages
  • โ€”Information Retrieval: Enhance search systems with semantic understanding
  • โ€”Content Recommendation: Suggest related Arabic content
  • โ€”Document Clustering: Group similar Arabic texts
  • โ€”Question Answering: Retrieve relevant contexts for Arabic QA

โŒ Limitations

  • โ€”Non-Arabic Text: Optimized specifically for Arabic language
  • โ€”Classification Tasks: Not directly trained for classification
  • โ€”Generative Tasks: Not suitable for text generation or translation
  • โ€”Dialectal Variations: May underperform on specific Arabic dialects

๐Ÿ—๏ธ Model Architecture

ComponentDetails
Base Modelaubmindlab/bert-base-arabertv02
EnhancementLoRA (Low-Rank Adaptation)
Training ObjectiveTriplet Loss
Embedding Dimensions8, 64, 128, 256
LanguageArabic

๐Ÿ”ฌ Training Details

Training Configuration

ParameterValue
Loss FunctionTriplet Loss
Adaptation MethodLoRA
PrecisionFP16 Mixed Precision
Epochs3
Batch Size32
OptimizerAdamW
HardwareNVIDIA A100
Training Time~7 hours

Dataset


๐Ÿ“ˆ Evaluation Metrics

  • โ€”Cosine Similarity: Primary similarity measure
  • โ€”Mean Average Precision (MAP): Retrieval performance
  • โ€”Recall@K: Top-K retrieval accuracy
  • โ€”Triplet Accuracy: Correct triplet ranking percentage

โš ๏ธ Bias and Limitations

Potential Biases

  • โ€”Inherits biases from AraBERT base model and training datasets
  • โ€”May favor Modern Standard Arabic over dialectal variants
  • โ€”Performance varies across different Arabic domains and regions

Recommendations

  • โ€”Evaluate on target domain before deployment
  • โ€”Use human oversight for critical applications
  • โ€”Test with diverse Arabic text sources

๐ŸŒ Environmental Impact

  • โ€”Hardware: NVIDIA A100 GPU
  • โ€”Training Duration: ~7 hours
  • โ€”Carbon Footprint: Calculated using ML CO2 Impact Calculator

๐Ÿ“š Citation

If you use this model in your research, please cite:

bibtex
@misc{kamel2025arabert-matryoshka,
  author = {Abdalrahman Kamel},
  title = {AraBERT Matryoshka: Multi-Dimensional Arabic Sentence Embeddings with Triplet Loss},
  year = {2025},
  url = {https://huggingface.co/Abdalrahmankamel/matryoshka-arabert},
  note = {Hugging Face Model Repository}
}

๐Ÿ™ Acknowledgments

  • โ€”AraBERT Team: For the excellent base model (aubmindlab/bert-base-arabertv02)
  • โ€”Sentence Transformers: For the robust training framework
  • โ€”Matryoshka Representation Learning: For the innovative nested embedding approach
  • โ€”Arabic NLI Dataset: Omartificial-Intelligence-Space for the training data

๐Ÿ“„ License

This model is released under the Apache 2.0 License.


<div align="center">

Developed by [Abdalrahman Kamel](https://huggingface.co/Abdalrahmankamel)

Advancing Arabic NLP through innovative embedding techniques

</div>