/ Модель

Характеристики

Контекст
512 токенов
Параметры
105 млн
Лицензия
Apache 2.0
Архитектура
dzair · dense
Библиотека
transformers
Опубликована
16 сен 2026

DZAIR

Заполнение пропусковТекст → текст4 профессии
432скачиваний за 30 дней4лайкавеса обновлены18 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

DZAIR — энкодер алжирской дариджи для извлечения представлений и дообучения под задачи классификации.

DZAIR — двунаправленный текстовый энкодер на 105,3 млн параметров, разработанный командой algerian-nlp и обученный с нуля для алжирской дариджи. Он кодирует текст в векторные представления и предназначен для извлечения признаков, кластеризации, поиска похожих текстов и дообучения для классификации тональности, эмоций, тем и диалектных разновидностей.

Модель имеет 12 слоёв энкодера с размерностью скрытого состояния 768 и контекстом до 512 токенов. Она рассчитана на дариджу в арабском письме и латинской транслитерации Arabizi, включая переключение на французский. В описанных тестах DZAIR превзошла DziriBERT на двух наборах тональности, но результаты различались по задачам и ограничены размерами тестовых выборок.

DZAIR не предназначена для генерации текста, машинного перевода или языков и диалектов за пределами алжирской дариджи. Модель не оценивалась на предвзятость, токсичность и фактическую точность; её не следует использовать для автоматизированных решений, затрагивающих людей. Лицензия — Apache-2.0.

Сценарии применения

  • классификация тональности сообщений на арабской даридже
  • анализ тональности текста на Arabizi
  • классификация эмоций и тем в алжирских сообщениях
  • извлечение векторов предложений на даридже
  • кластеризация и поиск похожих текстов на даридже
  • инициализация модели поиска по текстам на даридже

Ограничения

Не предназначена для генерации текста, машинного перевода и языков вне алжирской дариджи. Не оценивалась на предвзятость, токсичность и фактическую точность; тестовые наборы некоторых оценок невелики.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит4

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

DZAIR

DZAIR (الجزائر) is a 105.3M-parameter bidirectional text encoder trained from scratch for Algerian Darija (arq) across Arabic script, Latin Arabizi, and French code-switching, using 19.18M deduplicated rows (1.314B tokens) from 10 decontaminated sources.

Under a shared 10-seed evaluation protocol, DZAIR outperforms DziriBERT on Latin Arabizi sentiment (65.52% vs. 63.22% accuracy) and forum Arabic sentiment (96.33% vs. 94.30%) while using ~20% fewer backbone parameters (68.44M vs. 85.05M).

TaskBidirectional Text Encoder & Representation Learning
Architecture12L × 768 RTD + GDES (GQA 12Q/4KV, SwiGLU, Pre-RMSNorm, QK-Norm, RoPE)
Parameters105.3M released (68.44M backbone, 128.8M joint training)
Input / ScriptsArabic script (arq-Arab), Latin Arabizi (arq-Latn), FR code-switching (max 512 tokens)
Formats IncludedPyTorch FP32 (safetensors), PyTorch FP16 (fp16/), ONNX FP32 & INT8 (onnx/)
License (Weights)Apache-2.0
Author(s)Abderahmane Ainouche, Algerian NLP Collective

Quickstart

Install dependencies:

pip install torch transformers

Feature Extraction (PyTorch FP32)

The model architecture ships directly with the weights (modeling_dzair.py), so pass trust_remote_code=True:

import torch
from transformers import AutoModel, AutoTokenizer

REPO = "algerian-nlp/DZAIR"
tokenizer = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)
encoder = AutoModel.from_pretrained(REPO, trust_remote_code=True).eval()

texts = [
    "يعطيك الصحة خويا، بارك الله فيك",           # Arabic script
    "ya3tik saha khoya, bon courage f projet",   # Arabizi + French code-switch
]

# Lowercase Latin input before encoding to match pretraining vocabulary
inputs = tokenizer([t.lower() for t in texts], padding=True, return_tensors="pt")

with torch.inference_mode():
    outputs = encoder(**inputs)

# Mean-pooled sentence embeddings
mask = inputs.attention_mask.unsqueeze(-1)
embeddings = (outputs.last_hidden_state * mask).sum(dim=1) / mask.sum(dim=1)
print(embeddings.shape)  # torch.Size([2, 768])

Sequence Classification

The classification head (CLS + MLP) matches the exact head used in the downstream benchmark table below:

from transformers import AutoModelForSequenceClassification

classifier = AutoModelForSequenceClassification.from_pretrained(
    "algerian-nlp/DZAIR",
    trust_remote_code=True,
    num_labels=2,
).eval()

logits = classifier(**inputs).logits
print(logits.shape)  # torch.Size([2, 2])

Half-Precision (FP16) & ONNX (FP32 / INT8)

All quantized and exported formats live inside algerian-nlp/DZAIR under fp16/ and onnx/:

# PyTorch FP16
encoder_fp16 = AutoModel.from_pretrained(
    "algerian-nlp/DZAIR",
    subfolder="fp16",
    trust_remote_code=True,
).eval()
# ONNX Runtime (no PyTorch required at inference time)
import onnxruntime
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer

REPO = "algerian-nlp/DZAIR"
tokenizer = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)
onnx_path = hf_hub_download(REPO, "onnx/model_int8.onnx")  # or "onnx/model.onnx"
session = onnxruntime.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])

texts = ["واش راك خويا لاباس عليك؟", "rani rayeh lel dar bech nchouf la famille ya kho"]
encoded = tokenizer([t.lower() for t in texts], padding=True, return_tensors="np")
hidden = session.run(
    None,
    {"input_ids": encoded["input_ids"], "attention_mask": encoded["attention_mask"]},
)[0]

Input notes:

  • Lowercase Latin text before tokenizing. The SentencePiece vocabulary was built on lowercased Latin; raw uppercase increases token fertility by ~10%.
  • Preserve Arabizi phoneme digits (3, 7, 9). They are represented as atomic pieces (~5% of Arabizi tokens carry them) and should not be transliterated away.

Evaluation

All downstream tasks were fine-tuned identically across both models: 10 seeds, 3 epochs, batch size 8, AdamW (lr=5e-5) with linear decay to zero, CLS + MLP head, selecting the best epoch on test accuracy. Every score below is a 10-seed mean.

Task (Test Size)DziriBERT Acc / F1DZAIR Acc / F1Delta
Narabizi sentiment, Arabizi (143)63.22 / 56.5865.52 / 59.61+2.31 / +3.03
Ranim sentiment, forum Arabic (300)94.30 / 93.7396.33 / 95.94+2.03 / +2.21
Twifil sentiment, Twitter (2,360)79.62 / 79.0378.94 / 78.34-0.68 / -0.69
Twifil emotion, 10 classes (1,278)69.12 / 39.1067.86 / 36.67-1.26 / -2.43
Algerian sentiment, social (92)90.11 / 89.4387.72 / 86.80-2.39 / -2.63
DID Algiers vs. MSA (5,289)93.63 / 75.0688.72 / 66.44-4.91 / -8.62
DID Algiers, balanced accuracy94.1791.83-2.34
Narabizi topic, 5 classes (143)63.57 / 58.4149.65 / 38.68-13.92 / -19.73
  • Algerian sentiment (92 rows): Small test size limits statistical resolution below ~2 points.
  • DID Algiers vs. MSA (5,289 rows): Test split is 96.2% MSA, making balanced accuracy (91.83% vs. 94.17%) more informative than raw accuracy.
  • Narabizi topic (143 rows): Under the fixed 3-epoch / batch-8 protocol, training runs for only 375 optimizer steps (learning rate halved by step 187); extending training to ~1,000 steps lifts DZAIR to 56.64% accuracy.

Zero-shot diagnostic probe (separate protocol): On algerian-nlp/DziriEval MCQ with frozen weights via MLM pseudo-log-likelihood (Salazar et al., 2020), DZAIR scores 0.2760 vs. 0.2940 for DziriBERT (not comparable to the fine-tuned rows above).

Exported Precision & ONNX Fidelity

BuildPath in RepoSizeCosine vs. FP32Max Abs DiffVerification Gate
PyTorch FP32model.safetensors421.2 MB1.0000000.000000Reference
PyTorch FP16fp16/model.safetensors210.6 MB0.9999990.007960>= 0.99900
ONNX FP32onnx/model.onnx424.0 MB1.0000003.9e-06>= 0.99999
ONNX INT8 (Dynamic)onnx/model_int8.onnx108.4 MB0.9995790.206918>= 0.98000

Intended Use & Scope

Recommended uses:

  • Algerian Darija classification (sentiment, emotion, topic, dialect) via fine-tuning with a CLS + MLP head.
  • Sentence representation extraction, clustering, similarity, and retrieval initialization across Arabic script, Arabizi, and French code-switching.

Out-of-scope uses:

  • Text generation of any kind (bidirectional discriminator encoder) or machine translation.
  • Languages or dialects outside Algerian Darija.
  • Automated decisions affecting individuals.

Because pretraining includes social-media text, the encoder has observed informal and offensive language and is intended for research use. It has not been evaluated for bias, toxicity, or factuality.


Architecture

ComponentSpecification
Parameters105,304,320 released (68.44M backbone, 128.8M joint training)
Backbone12 discriminator layers, hidden dim 768, 3-layer width-384 generator (discarded at export)
AttentionGrouped-Query Attention (12Q / 4KV, head dim 64), global every layer, Pre-RMSNorm + per-head QK-Norm, RoPE
Feed-ForwardSwiGLU, intermediate size 1,792
Embedding SharingGradient-disentangled embedding sharing (discriminator learns a delta over frozen generator embeddings, folded at export)
Tokenizerdzair-tok-48k — 48,000-piece SentencePiece Unigram (DebertaV2Tokenizer, digit splitting & byte fallback enabled)
Context Length512 tokens
ObjectiveReplaced Token Detection (RTD): generator MLM + 50 × discriminator RTD; whole-word masking (linear 30% → 15%, 80/10/10 corruption)
Release Precisionfloat32 (model.safetensors), float16 (fp16/), ONNX float32 & QInt8 (onnx/)

dzair-tok-48k achieves 1.2847 Arabic token fertility (vs. 1.3178 baseline) with zero fallback pieces (vs. 1.91 UNK per 1k tokens) and zero encoding failures across 9 noise conditions over 486k encodings.


Training Data

Pretrained on 19,181,222 deduplicated rows (383,735,384 words) across 10 sources, packed into 1,282,929 sequences of length 512 (657M tokens/epoch, 1.314B tokens over 2 epochs).

SourceDomainScript Split (Ar/Lat/Mix)TierRowsWords
DarijaDzYouTube comments75/14/11unknown14,512,731203,907,035
forum-postsForums, chat80/3/17permissive3,290,408137,157,711
sampleShort social94/4/2permissive1,117,5625,327,792
ayoubGeneral web77/17/6permissive167,6692,998,064
touati-corpusPodcast transcripts60/0/40permissive9,71532,525,387
touati-50kParallel EN–Darija99/0/1permissive48,1771,316,680
awras-transParallel EN–Darija87/0/13unknown6,158155,112
awras-dictLexicon79/13/8permissive10,251154,460
PADICParallel dialect100/0/0unknown10,48775,577
81melodyReal-estate ads44/5/51permissive8,064117,566
Total~77/12/1119,181,222383,735,384
  • Script distribution: ~77% Arabic script (14.78M rows), ~12% Latin Arabizi (2.27M rows), ~11% mixed (2.14M rows).
  • Filtering & deduplication: 24.09M normalized rows → 23.41M after mechanical quality filtering (2.83% dropped) → 19.18M after global exact deduplication (18.0% removed, permissive-first keep order).
  • Decontamination: Screened against 17,284 evaluation texts with 258 matching rows excluded (exact matching; paraphrases not filtered).

Training Data License Composition

The model weights are released under Apache-2.0. That grant applies to weights and code only and does not relicense the underlying training text. DarijaDz is excluded from permissive corpus releases while written terms remain pending.

TierRowsRow ShareWordsWord Share
Unknown14,529,37675.7%204,137,72453.2%
Permissive (MIT, Apache-2.0, CC-BY-4.0)4,651,84624.3%179,597,66046.8%

Training Details

ParameterValue
ObjectiveReplaced Token Detection (generator + 50 × discriminator)
OptimizerMuon (lr=0.02) on 2D hidden matrices + AdamW (lr=2e-4) on remaining parameters, EMA 0.999
Batch Size96 micro-batch × 10 accumulation = 491,520 tokens/step
Steps / Epochs2,672 optimizer steps (26,726 micro-batches), 2 epochs (1.314B tokens)
Loss TrajectoryTotal loss 48.22 → 15.42 (trough 14.75), single run without divergence
Hardware & Duration1× NVIDIA A10G (peak 16.7 GB VRAM, ~35k tok/s), 9 h 26 min

Repository Contents

FileSizeDescription / SHA-256
model.safetensors421.2 MBFolded float32 discriminator weights (E_G + delta) · SHA-256 b2448ca8dbc015cd90e13fce851122a15ac2855ff445c09f4af36d382709c006
config.json1.5 KBArchitecture config and auto_map for trust_remote_code
modeling_dzair.py59.0 KBSelf-contained model implementation
tokenizer.model967.8 KB48k SentencePiece Unigram model · SHA-256 6d50d8c119d0e9e15e548a473269a1e8e24609682e0e7243432a0a31de7897e6
tokenizer_config.json563 BDebertaV2Tokenizer settings ([PAD]/[UNK]/[CLS]/[SEP]/[MASK] at IDs 0–4)
tokenizer_rules.yaml2.1 KBVersioned text normalization rules used with the tokenizer
export_report.json1.4 KBVerified file sizes, SHA-256 checksums, parameter counts, and reload parity (max_abs_diff = 0.0)
fp16/model.safetensors210.6 MBFloat16 weights (subfolder="fp16") · SHA-256 8a9322b6b48bbb25edb9d80969265291f045cb1683cee9f4f61a1d2094da1523
fp16/quant_report.json331 BFP16 fidelity verification report
onnx/model.onnx424.0 MBONNX float32 graph (opset 18, dynamic axes) · SHA-256 a4bcd10ce5c71f51983069dee0de04ae4819d2b0a672ddac82c714fc1a6b019f
onnx/model_int8.onnx108.4 MBDynamically quantized INT8 ONNX graph (QInt8) · SHA-256 9c149d2b5cdb116347a8a07381a3c0e1365909f55de0a9d1906929757c138c96
onnx/onnx_report.json822 BONNX fidelity and CPU latency measurements

Reload verification confirms zero missing or unexpected keys and bit-identical weights (state_max_abs_diff = 0.0, hidden_max_abs_diff = 0.0).


The name

Dzair (الجزائر) is the Algerian name for Algeria itself. The collective's foundational encoder carries the country's name because it is built from scratch to represent how Algerians write across Arabic script, Latin Arabizi, and French code-switching.


Citation

@misc{algerian_nlp_dzair_2026,
  title  = {DZAIR: A Bidirectional Encoder for Algerian Darija},
  author = {Ainouche, Abderahmane and Algerian NLP Collective},
  year   = {2026},
  url    = {https://huggingface.co/algerian-nlp/DZAIR}
}

License

Weights and code are released under Apache-2.0. Refer to the Training Data License Composition section above regarding the underlying training text before redistributing derivatives.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers · fill-mask

Нельзя запустить

Модели нужен код из репозитория; автор пока не в списке доверенных организаций.

Класс архитектуры
DzairModel
Ревизия весов
e38e901

0 моделей