Instructions to use algerian-nlp/DZAIR-2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use algerian-nlp/DZAIR-2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="algerian-nlp/DZAIR-2", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("algerian-nlp/DZAIR-2", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
DZAIR-2
DZAIR-2 (الجزائر 2) is a second-generation 171.9M-parameter bidirectional encoder built from scratch for Algerian Darija (arq) across Arabic script, Latin Arabizi, and French code-switching. It combines Bipartite Complementary Cross-Attention pretraining ([MASK]-free visible encoder inputs, 100% per-token supervision), Block-AttnRes depth routing, Gated Full Multi-Head Attention, and two-stage RoPE (512 -> 2,048) over a deduplicated, decontaminated 501.6M-token Algerian corpus trained for 12 epochs (~5.96B supervised tokens).
Under a shared 10-seed evaluation protocol across 5 Algerian Darija benchmarks (42,848 training / 7,849 test examples total), DZAIR-2 achieves a 5-task macro average of 76.75% Accuracy / 72.38% Macro-F1, outperforming DziriBERT (75.40% / 70.36%) and DZAIR v1 (73.68% / 67.63%) on overall score and winning all Arabic-script and code-switched sentiment tasks (DarijaDz, Twifil, Ranim).
| Task | Bidirectional Text Encoder & Representation Learning (arq) |
| Architecture | 16L (8 Block-AttnRes depth blocks) × 768, 12 MHA heads, Gated Attention, QK-Norm, SwiGLU, RoPE |
| Parameters | 171,889,664 released (49,152,768 tied embeddings + 122,736,896 backbone; 202.57M total during pretraining) |
| Context / Vocab | Max 2,048 tokens (512 -> 2,048 two-stage curriculum), 64,000-piece Unigram tokenizer (dzair-tok-64k) |
| Formats Included | PyTorch FP32 (model.safetensors), PyTorch FP16 (fp16/), ONNX FP32 (onnx/model.onnx) |
| Pooling Default | Attention-masked mean pooling (pooling_mode="mean" in Dzair2Config) |
| Pretraining | 12 epochs, 75,408 steps, 5.96B supervised tokens on 971,415 stitched docs (496.65M train tokens/epoch) |
| License (Weights) | Apache-2.0 |
| Author(s) | Abderahmane Ainouche, Algerian NLP Collective |
Quickstart
Install dependencies:
pip install torch transformers
The architecture ships directly with the weights (modeling_dzair2.py), so pass trust_remote_code=True.
Feature Extraction (Mean-Pooled Embeddings)
Because bipartite pretraining places sequence-level reconstruction pressure on contextual tokens rather than [CLS] alone (effective_rank_tok = 233.55 vs. effective_rank_cls = 15.85), mean pooling over non-padding tokens is strongly recommended for embeddings and retrieval:
import torch
from transformers import AutoModel, AutoTokenizer
REPO = "algerian-nlp/DZAIR-2"
tokenizer = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)
model = AutoModel.from_pretrained(REPO, trust_remote_code=True).eval()
texts = [
"يعطيك الصحة خويا، بارك الله فيك", # Arabic script
"wesh rak khoya, 5la3touni b had l'khedma chaba", # Latin Arabizi (digits preserved)
"راني en retard على الـ rendez-vous تاع الطبيب.", # Darija + French code-switch
]
# Lowercase Latin text before encoding while preserving Arabizi digits (3, 5, 7, 9)
inputs = tokenizer(
[t.lower() for t in texts],
padding=True,
truncation=True,
max_length=512,
return_tensors="pt",
)
with torch.inference_mode():
outputs = model(**inputs)
mask = inputs["attention_mask"].unsqueeze(-1).float()
embeddings = (outputs.last_hidden_state * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
print(embeddings.shape) # torch.Size([3, 768])
Sequence Classification
Dzair2ForSequenceClassification uses config.pooling_mode == "mean" by default:
from transformers import AutoModelForSequenceClassification
classifier = AutoModelForSequenceClassification.from_pretrained(
"algerian-nlp/DZAIR-2",
trust_remote_code=True,
num_labels=3,
).eval()
logits = classifier(**inputs).logits
print(logits.shape) # torch.Size([3, 3])
Token Classification (NER / POS)
from transformers import AutoModelForTokenClassification
tagger = AutoModelForTokenClassification.from_pretrained(
"algerian-nlp/DZAIR-2",
trust_remote_code=True,
num_labels=9,
).eval()
token_logits = tagger(**inputs).logits
print(token_logits.shape) # torch.Size([3, seq_len, 9])
Half-Precision (FP16) & ONNX (FP32)
Validated half-precision and ONNX exports ship inside the same repository under fp16/ and onnx/:
# PyTorch FP16
encoder_fp16 = AutoModel.from_pretrained(
"algerian-nlp/DZAIR-2",
subfolder="fp16",
trust_remote_code=True,
).eval()
# ONNX Runtime CPU (FP32)
import onnxruntime
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer
REPO = "algerian-nlp/DZAIR-2"
tokenizer = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)
onnx_path = hf_hub_download(REPO, "onnx/model.onnx")
session = onnxruntime.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
encoded = tokenizer(["wesh rak khoya", "واش راك خويا"], padding=True, return_tensors="np")
hidden = session.run(
None,
{"input_ids": encoded["input_ids"], "attention_mask": encoded["attention_mask"]},
)[0]
Input Conventions
- Lowercase Latin text before tokenizing.
dzair-tok-64kwas trained with lowercased Latin characters. - Preserve Arabizi phoneme digits (
2,3,5,7,9). The corpus masker binds subword boundary markers forward onto digit-initial Arabizi stems (5la3touni,3lina); do not strip or transliterate numerals. - Keep French/Darija clitics intact (
l',d',ma-kansh). Tokenizer boundaries and PMI grouping preserve apostrophe and hyphen clitic splits. - Use
bfloat16orfloat32inference. InternalPre-RMSNormlayers upcast tofloat32automatically before casting back to activation dtype.
Downstream Evaluation
All models were fine-tuned under identical conditions: 10 random seeds (38, 66, 216, 128, 214, 412, 180, 14, 196, 42), 3 epochs, AdamW (lr=5e-5, weight_decay=0.0), linear decay to zero with zero warmup, gradient norm clipping 1.0, max_length=512, and best-epoch test selection. Scores report 10-seed mean ± std Accuracy (%) / Macro-F1 (%).
Matched-Protocol 10-Seed Comparison (bs=64 on >=7k splits, bs=8 on <=1.2k splits)
| Task (Train / Test, Batch Size) | DziriBERT Acc / F1 | DZAIR v1 Acc / F1 | DZAIR-2 Acc / F1 | Delta vs. DziriBERT |
|---|---|---|---|---|
darijadz_sa (37,974 / 4,746, bs=64) |
76.94±0.36 / 64.85±0.92 | 76.76±0.15 / 65.16±0.73 | 79.06±0.29 / 68.35±1.22 | +2.12 / +3.50 |
twifil_sentiment (7,077 / 2,360, bs=64) |
80.45±0.21 / 79.83±0.20 | 78.41±0.20 / 77.80±0.22 | 81.00±0.41 / 80.35±0.47 | +0.55 / +0.52 |
ranim_sentiment (1,200 / 300, bs=8) |
94.23±0.74 / 93.64±0.80 | 96.23±0.39 / 95.83±0.41 | 96.37±0.60 / 95.99±0.66 | +2.14 / +2.35 |
narabizi_sentiment (997 / 143, bs=8) |
62.38±1.43 / 55.43±2.36 | 67.55±1.37 / 61.26±1.96 | 66.57±2.35 / 60.83±2.32 | +4.19 / +5.40 |
narabizi_topic (997 / 143, bs=8) |
63.01±1.73 / 58.07±2.10 | 49.44±1.55 / 38.10±3.92 | 60.77±1.91 / 56.41±2.43 | -2.24 / -1.66 |
| 5-Task Macro Average | 75.40 / 70.36 | 73.68 / 67.63 | 76.75 / 72.38 | +1.35 / +2.02 |
- Balanced accuracy highlights: On imbalanced 4-class
darijadz_sa,DZAIR-2reaches 67.23% balanced accuracy vs. 63.78% forDziriBERTand 64.24% forDZAIR v1. Across the 3-taskbs=8suite,DZAIR-2leads at 74.57% Acc / 71.08% Macro-F1 / 70.78% Balanced Acc. - Large-batch small-dataset sensitivity (
bs=64on 997 rows): Runningbs=64onnarabizi_sentiment/narabizi_topicperforms only48total optimizer steps over 3 epochs (vs.375atbs=8). Underbs=64, scores compress to62.52 / 50.15(DZAIR-2) and63.36 / 56.05(DziriBERT) onnarabizi_sentiment, and49.93 / 28.28vs.57.69 / 49.60onnarabizi_topic.
Pooling Ablation (Mean vs. CLS, Seed 42, bs=8)
Because [CLS] acts primarily as a document anchor for cross-attention reconstruction queries rather than a standalone pooling bottleneck, pooling_mode="mean" beats pooling_mode="cls" on every benchmark:
| Task | DZAIR-2 (cls) Acc / F1 |
DZAIR-2 (mean) Acc / F1 |
Gain |
|---|---|---|---|
darijadz_sa |
76.34 / 65.50 | 78.51 / 69.69 | +2.17 / +4.18 |
twifil_sentiment |
78.64 / 78.14 | 80.21 / 79.54 | +1.57 / +1.39 |
narabizi_sentiment |
60.14 / 46.65 | 68.53 / 62.75 | +8.39 / +16.10 |
narabizi_topic |
56.64 / 47.59 | 58.74 / 50.94 | +2.10 / +3.35 |
ranim_sentiment |
95.33 / 94.78 | 96.67 / 96.34 | +1.33 / +1.56 |
Architecture
| Component | Specification |
|---|---|
| Parameters | 171,889,664 released (49,152,768 tied embedding + final norm; 122,736,896 encoder; +30,682,112 4L predictor discarded at export) |
| Backbone Depth & Routing | 16 Transformer layers organized into 8 Block-AttnRes depth blocks (2 layers per block) with zero-initialized learned depth queries |
| Hidden Width / Heads | 768 hidden dim, 12 full multi-head attention (MHA) heads (head_size=64), hidden_dropout=0.1, attention_dropout=0.1 |
| Attention Mechanism | QK-Norm -> Rotary Position Embeddings (rope_theta=160,000.0) -> Scaled Dot-Product Attention -> element-wise Gated Attention (sigmoid(X W_g)) |
| Normalization & MLP | Bias-free Pre-RMSNorm (eps=1e-5, fp32 upcast) + SwiGLU (intermediate_size=2,048) |
| Context Length | 2,048 tokens (trained with a two-stage 512 -> 2,048 context extension curriculum) |
| Tokenizer | dzair-tok-64k — 64,000-piece SentencePiece Unigram (DebertaV2Tokenizer conventions, byte fallback, digit splitting, unk/pad/cls/sep/mask = 1/0/2/3/4) |
| Pretraining Objective | Bipartite Complementary Cross-Attention: content units split 50/50 into disjoint halves; the encoder processes [CLS] + visible_half + [SEP] with zero [MASK] tokens and exact original position_ids, while a 4-layer Cross-Attention Predictor reconstructs every masked token from the complementary view under document-isolated 3D packing |
Pretraining Corpus & Contamination Controls
Pretrained on 971,415 stitched documents (501,645,244 packed tokens = 496,650,699 train across 961,702 documents + 4,994,545 validation across 9,713 documents) spanning 10 decontaminated Algerian Darija sources:
| Source | Domain | Documents | Packed Tokens |
|---|---|---|---|
nasrellahkharroubi/DarijaDz |
Social comments | 566,049 | 262,178,793 |
DarjaCore/algerian-darja-forum-posts |
Algerian forums & chat | 362,652 | 181,047,486 |
touati-kamel/algerian-darja-corpus |
Podcasts & long-form transcripts | 16,304 | 45,138,821 |
DarjaCore/algerian-darja-sample |
Short social posts | 14,333 | 7,057,811 |
ayoubkirouane/Algerian-Darija |
General Darija web | 6,497 | 3,712,184 |
touati-kamel/algerian-arabic-english-translation-50k |
Parallel EN–Darija | 4,130 | 1,817,422 |
awras/algerian-darija-dictionary-v1 |
Darija lexicon | 451 | 215,640 |
awras/algerian-english-translation-v1 |
Parallel EN–Darija | 413 | 195,984 |
81melody/algerian-realestate-ner-dataset |
Algerian real-estate ads | 385 | 182,181 |
arbml/PADIC |
Parallel Maghrebi dialect (DZ) | 201 | 98,922 |
| Total | 971,415 | 501,645,244 |
- Script distribution (packed tokens): Arabic script 458,252,298 (
91.35%), code-switched mixed 38,524,705 (7.68%), Latin Arabizi 4,868,241 (0.97%). - Overlap stitching & PMI grouping:
325,812overlappingstride=256windows were stitched back into continuous long documents (eliminating 320,301,227 duplicate overlap characters), and 30,059,496 tokens (5.99%) carry corpus-mined multi-word PMI collocation span tags (max_span_words=4). - Decontamination: Exact-match and span decontamination scrubbed 16,674 evaluation-overlapping spans before pretraining, including against
darijadz_saand the downstream test splits.
Pretraining Details & Diagnostics
| Parameter | Measured Value |
|---|---|
| Hardware | 1× NVIDIA H100 NVL MIG (3g.47gb), 43.83 GiB peak VRAM, 40,481.8 tok/s mean throughput |
| Duration / Steps | 75,408 optimizer steps (12 epochs, global batch 128, ~`29.79hours /107,239.4s`) |
| Optimizers | MuonClip (lr=0.02, momentum=0.95, ns_steps=5, wd=0.1, qk_clip_tau=100.0) on 2D hidden weights + AdamW (lr=2e-4, betas=(0.9, 0.98), wd=0.1 embeddings, 0.0 norms/queries/biases) |
| Schedule / Regularization | Two-stage context (512 epochs 1–10 -> 2,048 epochs 11–12), WSD (1 - sqrt(t) cooldown), EMA 0.999, bf16, SentencePiece subword sampling (alpha=0.1) |
Held-Out Val (step 75,250) |
Val CE 5.1563 (val_ppl = 173.52), token accuracy 23.30% (arabizi 42.52%, mixed 32.60%, arabic 22.65%, PMI spans 41.25%) |
| Representation Health | Token RankMe 233.55, token anisotropy 0.2399, parallel bitext cosine 0.8746, QK-Norm RMS 1.05 (qk_clipped_layers = 0 at final stage) |
| Export Verification | final-backbone.pt -> model.safetensors (687,581,712 bytes), state_max_abs_diff = 0.0, hidden_max_abs_diff = 0.0, reload cosine 0.9999999999999809 |
Exported Precision & ONNX Fidelity
| Build | Path in Repo | Bytes / Size | Cosine vs. FP32 | Max Abs Diff | Verification Gate |
|---|---|---|---|---|---|
| PyTorch FP32 | model.safetensors |
687.6 MB | 1.000000 | 0.0 | Reference (>= 0.99999 reload) |
| PyTorch FP16 | fp16/model.safetensors |
345.1 MB (dir) | 0.9999998 | 3.82e-02 | Accepted (>= 0.99900) |
ONNX FP32 (opset 18) |
onnx/model.onnx |
691.2 MB | 1.000000 | 3.43e-05 | Accepted (>= 0.99999) |
| ONNX INT8 (Dynamic) | — |
176.2 MB | 0.965638 | 43.44 | Rejected & removed (< 0.98000 gate) |
Uncalibrated dynamic QInt8 quantization dropped below the 0.98000 cosine gate and was excluded from the release; fp16/ and onnx/model.onnx pass all fidelity checks (export_report.json, fp16/quant_report.json, onnx/onnx_report.json).
Intended Use, Limitations & Scope
- Recommended uses: Fine-tuning for Algerian Darija classification (sentiment, topic, dialect, intent), sequence tagging (NER/POS), and extracting mean-pooled cross-script Darija representations across Arabic script, Latin Arabizi, and French code-switching.
- Out-of-scope uses: Autoregressive text generation (bidirectional encoder only, no decoder head), machine translation without an encoder-decoder adapter, non-Algerian dialects (Moroccan/Tunisian/Gulf) where Algerian-specific pretraining assumptions do not hold, and high-stakes automated decisions affecting individuals.
- Known limitations: Pretraining data reflects real Algerian social media, forums, and podcasts (
91.35%Arabic script vs.0.97%pure Arabizi +7.68%code-switched mixed) and can encode colloquial profanity or social biases. On very small pure-Arabizi multi-class datasets (997rows),DziriBERTremains slightly ahead on 5-classnarabizi_topic(63.01%vs.60.77%) under untunedlr=5e-5, 3 epochs. The model has not been evaluated on toxicity, demographic bias, or tasks beyond the five downstream suites reported above (twifil_emotion,did_algiers, and zero-shot retrieval remain unmeasured).
The Name
Dzair (الجزائر) is the Algerian name for Algeria itself. DZAIR-2 builds directly on the DZAIR encoder family as a higher-capacity, longer-context, cross-script second-generation backbone for Algerian Darija.
Citation
@misc{algerian_nlp_dzair2_2026,
title = {DZAIR-2: A Second-Generation Bidirectional Encoder for Algerian Darija},
author = {Ainouche, Abderahmane and Algerian NLP Collective},
year = {2026},
url = {https://huggingface.co/algerian-nlp/DZAIR-2}
}
License
Model weights and custom modeling code are released under Apache-2.0.
- Downloads last month
- 52
Evaluation results
- Accuracy (10-seed mean, bs=64) on DarijaDz sentiment (test, 4,746 rows)self-reported0.791
- Macro F1 (10-seed mean, bs=64) on DarijaDz sentiment (test, 4,746 rows)self-reported0.683
- Accuracy (10-seed mean, bs=64) on Twifil sentiment (test, 2,360 rows)self-reported0.810
- Macro F1 (10-seed mean, bs=64) on Twifil sentiment (test, 2,360 rows)self-reported0.803
- Accuracy (10-seed mean, bs=8) on Ranim sentiment (test, 300 rows)self-reported0.964
- Macro F1 (10-seed mean, bs=8) on Ranim sentiment (test, 300 rows)self-reported0.960
- Accuracy (10-seed mean, bs=8) on Narabizi sentiment (test, 143 rows)self-reported0.666
- Macro F1 (10-seed mean, bs=8) on Narabizi sentiment (test, 143 rows)self-reported0.608