/ Модель

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

Контекст
1 024 токена
Параметры
50,8 млн
Лицензия
Apache 2.0
Архитектура
darja_gpt_v5 · dense
Опубликована
23 сен 2026

darja-gpt-50m

Генерация текстаТекст → текст3 профессии

Компактная авторегрессионная модель для генерации текстов на алжирской даридже с управлением тематическим регистром.

726скачиваний за 30 дней0лайковвеса обновлены25 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

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

Darja-GPT-50M — авторегрессионная языковая модель, разработанная Touati Kamel и обученная с нуля на алжирской даридже. Она предназначена для генерации текста с учётом тематического регистра: кулинарного, спортивного, технического, разговорного, повествовательного и других. Модель использует декодерную архитектуру причинного языкового моделирования, доменные LoRA-адаптеры и поддержку Classifier-Free Guidance для управления стилем генерации. В метаданных указано 50,8 млн параметров и контекст 1024 токена; README сообщает о BPE-токенизаторе с 24 тысячами единиц и обучении на арабской графике и Arabizi.

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

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

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

Ограничения

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

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

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

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

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

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

Открыть на Hugging Face

Darja-GPT-50M: Domain-Conditioned Causal LM for Algerian Darija

License Dataset Tokenizer Parameters Fertility Win Framework

Darja-GPT-50M is an open-source, 54.8M parameter causal language model trained from scratch exclusively on Algerian Darija (الدارجة الجزائرية / Dziri).

Unlike previous efforts that retrofitted bidirectional masked encoders (e.g. DziriBERT) with sequence-to-sequence decoders, Darja-GPT is built natively as a modern autoregressive decoder with dedicated per-domain Low-Rank Adapters (DomainLoRALinear) and support for Classifier-Free Guidance (CFG) at inference time. This architecture solves the register-collapse and domain-leakage issues common in low-resource dialect modeling, enabling reliable steering across culinary, sports, technical, podcast, narrative, and colloquial registers.


Table of Contents

  1. Key Innovations & Empirical Findings
  2. End-to-End Pipeline Architecture
  3. Model Architecture & Mathematical Specifications
  4. Exact Parameter Accounting
  5. Domain Conditioning & Classifier-Free Guidance (CFG)
  6. Custom Darija Tokenizer & Benchmark
  7. Training Data & Pre-Training Recipe
  8. Quantitative & Qualitative Evaluation
  9. Quickstart & Inference Guide
  10. Known Limitations & Responsible AI
  11. Citation & Contact

Key Innovations & Empirical Findings

1. From FiLM to Native Domain Adapters

In earlier iterations (v3 & v4), domain steering was attempted via FiLM (Feature-wise Linear Modulation) — projecting domain embeddings to scale and shift intermediate activations. However, architectural diagnostics revealed that FiLM failed to learn distinct domain representations:

  • FiLM Failure Mode: Domain weight distances remained shallow (only 15%–20% variation around the mean; overall activation RMS stalled at ~0.230), resulting in severe cross-domain contamination (e.g., cooking recipes leaking into podcast prompts).
  • The v5 Adapter Breakthrough: Replacing FiLM with dedicated domain-specific LoRA layers (DomainLoRALinear) on attention output projections (o_proj) and MLP down-projections (down_proj) produced weight delta distances of 118%–173% of the mean. Each domain maintains independent low-rank updates (rank r = 16, α = 16.0), eliminating representation compromise.

2. Classifier-Free Guidance (CFG) in an Autoregressive LM

To our knowledge, this is the first deployment of Classifier-Free Guidance for dialectal autoregressive language generation:

  • During training, domain IDs are dropped to an unconditional baseline (<NULL>, d = 6) with probability p = 0.10.
  • At generation time, conditional logits z_cond and unconditional logits z_NULL are extrapolated:
z_guided = z_NULL + s · (z_cond - z_NULL)
  • Setting guidance scale s ∈ [1.5, 2.5] completely suppresses out-of-domain leakages and sharpens domain-specific terminology without degrading grammatical flow.

3. Native Darija Morphology Tokenizer

Trained from scratch on conversational Algerian Darja transcripts, our 24,000-vocabulary lossless BPE tokenizer achieves 1.459 tokens/word across all 11,151 corpus documents (5-fold out-of-fold, zero leakage; 1.474 on the 335 strictly held-out documents), delivering a 38.6% fertility reduction (95% CI [38.4%, 38.9%]) compared to foundation models like Qwen2.5 / Qwen3 (2.378 tokens/word). It outperforms all open-weights generative decoder tokenizers (+12.8% vs. Jais, +13.1% vs. ALLaM) and ties regional encoder MARBERT (1.464) while using 2× to 4.2× fewer vocabulary parameters than regional WordPiece encoders (DziriBERT 1.448, DarijaBERT 1.450).


End-to-End Pipeline Architecture

The entire project operates across four synchronized stages: data curation, morphological tokenization, distributed pre-training with dual-dropout regularization, and dual-stream CFG inference.

flowchart TD
    subgraph Data["1. Data Curation & Preprocessing"]
        C["Algerian Darja Corpus (11,151 documents)"] --> M["Domain Consolidation (6 Domains + NULL)"]
        M --> CH["Document-Level Chunking (1,024-token blocks)"]
        CH --> REG["Dual-Dropout Regularization (Tag: 20% | CFG: 10%)"]
    end

    subgraph Tokenizer["2. Tokenizer Pipeline"]
        T_CORPUS["Raw Conversational Text"] --> BPE["Byte-Level BPE (24,000 Vocab)"]
        BPE --> FER["Fertility: 1.459 Tokens/Word (-38.6% vs Qwen2.5)"]
    end

    subgraph Training["3. Pre-Training (Single T4 GPU)"]
        PADDED["52,038 Packed Examples"] --> TRAIN["AdamW + Cosine Schedule (Peak LR 3e-4)"]
        TRAIN --> CKPT["Best Checkpoint (Step 3,000 / Eval Loss 5.978)"]
    end

    subgraph Inference["4. CFG Inference Engine"]
        PROMPT["Prompt with Domain Tag d"] --> DUAL["Dual Stream: z_cond(d) and z_uncond(NULL)"]
        DUAL --> CFG["CFG Logit Extrapolation (Scale s in [1.5, 2.5])"]
        CFG --> GEN["Nucleus Sampling (p=0.9) + Repetition Penalty (1.3)"]
    end

    FER --> CH
    REG --> PADDED
    CKPT --> PROMPT

Detailed Pipeline Stages:

  1. Curated Ingestion: Transcripts from 11,151 YouTube videos covering cooking, tech reviews, sports commentary, vlogs, and storytelling were sanitized and mapped to canonical domain identifiers.
  2. Deterministic Chunking & Static Padding: To eliminate cross-document attention bleed, each document was chunked strictly within its own boundary into consecutive 1,024-token blocks and right-padded with <pad> (token ID 0). Padding tokens were assigned target labels of -100.
  3. Dual-Dropout Preprocessing:
    • Text-Tag Dropout (p = 0.20): In 20% of training samples, the text tag (e.g. <cooking> ) was omitted from the prompt string while keeping domain_ids = 1. This forced the model's adapter weights to model the lexical and syntactic domain distribution directly rather than simply learning a shallow prompt prefix association.
    • CFG Dropout (p = 0.10): In 10% of training steps, domain_ids was dynamically reassigned to the unconditional virtual index 6: <NULL>, jointly training conditional and unconditional distributions without needing additional data.

Model Architecture & Mathematical Specifications

Darja-GPT-50M employs a modern autoregressive transformer architecture with SwiGLU non-linearities, Rotary Position Embeddings (RoPE), pre-layer RMSNorm with Head-level RMSNorm for queries and keys, tied word embeddings, and native Domain LoRA Adapters.

flowchart TD
    subgraph Inputs["Model Inputs"]
        TOK["input_ids [B, T]"]
        DOM["domain_ids [B] (0..6)"]
        MASK["attention_mask [B, T]"]
    end

    subgraph EmbeddingLayer["Embedding & Weight Tying"]
        EMB["Token Embedding (24,000 × 512)"]
    end

    subgraph DecoderStack["12 × DecoderBlock Stack"]
        direction TB
        NORM1["RMSNorm 1 (512)"]
        
        subgraph AttnBlock["Causal Self-Attention"]
            QKV["q_proj, k_proj, v_proj (512 → 512)"]
            QKNORM["HeadRMSNorm on Q and K (d_head=64)"]
            ROPE["Rotary Position Embedding (RoPE, θ=10000)"]
            SDPA["Scaled Dot-Product Attention + Causal Mask"]
            O_BASE["Base o_proj Linear (512 → 512)"]
            O_LORA["DomainLoRA Adapters (7 × r=16 × 1024)"]
            O_COMB["Base + α/r · LoRA_B @ LoRA_A(x)"]
        end

        ADD1["Residual Connection (+)"]
        NORM2["RMSNorm 2 (512)"]

        subgraph MLPBlock["SwiGLU Feed-Forward Network"]
            GATE["gate_proj Linear (512 → 1408)"]
            UP["up_proj Linear (512 → 1408)"]
            SILU["SiLU(gate) ⊗ up"]
            DOWN_BASE["Base down_proj Linear (1408 → 512)"]
            DOWN_LORA["DomainLoRA Adapters (7 × r=16 × 1920)"]
            DOWN_COMB["Base + α/r · LoRA_B @ LoRA_A(x)"]
        end

        ADD2["Residual Connection (+)"]
    end

    subgraph OutputLayer["Prediction Head"]
        FINAL_NORM["Final RMSNorm (512)"]
        LM_HEAD["Tied LM Head Linear (512 → 24,000)"]
        LOGITS["logits [B, T, 24,000]"]
    end

    TOK --> EMB
    EMB --> NORM1
    EMB -.-> ADD1
    
    NORM1 --> QKV
    QKV --> QKNORM
    QKNORM --> ROPE
    ROPE --> SDPA
    MASK --> SDPA
    SDPA --> O_BASE
    SDPA --> O_LORA
    DOM -.-> O_LORA
    O_BASE --> O_COMB
    O_LORA --> O_COMB
    O_COMB --> ADD1
    
    ADD1 --> NORM2
    ADD1 -.-> ADD2
    
    NORM2 --> GATE
    NORM2 --> UP
    GATE --> SILU
    UP --> SILU
    SILU --> DOWN_BASE
    SILU --> DOWN_LORA
    DOM -.-> DOWN_LORA
    DOWN_BASE --> DOWN_COMB
    DOWN_LORA --> DOWN_COMB
    DOWN_COMB --> ADD2
    
    ADD2 --> FINAL_NORM
    FINAL_NORM --> LM_HEAD
    LM_HEAD --> LOGITS
    EMB --- LM_HEAD

Mathematical Formulations

  1. Pre-Layer & Head Normalization:
RMSNorm(x) = (x / sqrt(mean(x²) + ε)) ⊙ w

where ε = 1e-5. Queries and keys undergo per-head normalization HeadRMSNorm(q_h) with head dimension d_head = 64 prior to rotational embedding.

  1. Rotary Position Embeddings (RoPE):
RoPE(q_m, m) = q_m · cos(m · θ) + rotate_half(q_m) · sin(m · θ)

with base frequency θ = 10,000.0 and inverse frequencies θ_i = 10000^(-2(i-1)/d_head).

  1. Attention with Padding-Aware Causal Masking:
Attention(Q, K, V) = softmax((Q · K^T / sqrt(d_head)) + M_causal + M_key_pad) · V
  1. SwiGLU Feed-Forward Projection:
SwiGLU(x) = (SiLU(x · W_gate) ⊙ (x · W_up)) · W_down

where intermediate projection dimension d_ffn = 1,408 (aligned to 64).

  1. Domain LoRA Adapter Formulation (DomainLoRALinear):
y = x · W_0 + (α / r) · (x · A_d) · B_d

where W_0 is the frozen/shared base projection, A_d ∈ R^(d_in × r), B_d ∈ R^(r × d_out), rank r = 16, and scaling α = 16.0 (scaling = 1.0). B_d is initialized to zeros, ensuring training starts as an exact identity operation.


Exact Parameter Accounting

The model consists of 50,837,504 base parameters and 3,956,736 domain adapter parameters, totaling 54,794,240 parameters (54.8M):

ModuleComponentTensor DimensionsPer-Layer BasePer-Layer Adapters (r=16, D=7)12-Layer Total
Embeddingsmodel.embed_tokens[24000, 512]——12,288,000
Attention (×12)q_proj, k_proj, v_proj3 × [512, 512]786,432—9,437,184
q_norm, k_norm2 × [64]128—1,536
o_proj.base[512, 512]262,144—3,145,728
o_proj.adaptersA: [7, 16, 512], B: [7, 512, 16]—114,6881,376,256
MLP (×12)gate_proj, up_proj2 × [1408, 512]1,441,792—17,301,504
down_proj.base[512, 1408]720,896—8,650,752
down_proj.adaptersA: [7, 16, 1408], B: [7, 512, 16]—215,0402,580,480
Norms (×12)input_norm, post_attn_norm2 × [512]1,024—12,288
Final Normmodel.final_norm[512]——512
Output Headlm_head[24000, 512](Tied with Embeddings)—(0)
Subtotals3,212,416 / layer329,728 / layer
Total Base50,837,504
Total Adapters3,956,736
Grand Total54,794,240 (54.8M)

Domain Conditioning & Classifier-Free Guidance (CFG)

flowchart TD
    P["User Prompt (e.g. Cooking Recipe)"] --> TOK["Tokenize with Custom Darja BPE"]
    
    TOK --> B_COND["Conditional Stream: domain_ids = [d] (e.g. 1: cooking)"]
    TOK --> B_UNCOND["Unconditional Stream: domain_ids = [6] (NULL)"]
    
    B_COND --> M_COND["Model Forward with Domain LoRA"]
    B_UNCOND --> M_UNCOND["Model Forward with NULL LoRA"]
    
    M_COND --> LOG_COND["Conditional Logits z_cond"]
    M_UNCOND --> LOG_UNCOND["Unconditional Logits z_NULL"]
    
    LOG_COND --> CFG_MATH["CFG Logit Extrapolation: z_guided = z_NULL + s · (z_cond - z_NULL)"]
    LOG_UNCOND --> CFG_MATH
    
    CFG_MATH --> REP["Repetition Penalty (1.25 - 1.3)"]
    REP --> TEMP["Temperature Scaling (T=0.8)"]
    TEMP --> TOPP["Top-p Nucleus Filtering (p=0.9)"]
    TOPP --> SAMPLE["Multinomial Sampling"]
    SAMPLE --> EMIT["Emitted Next Token"]
    EMIT -.->|"Append to Sequence"| TOK

The architecture provides 7 independent low-rank adapter slots:

Domain IDTagCorpus SourcesDistinctive Lexical & Register Markers
0<general>Vlogs, comedy channels (DZjoker, Anes Tina, Mourad Oudia)Everyday colloquial slang, jokes, Arabizi code-switching, greetings
1<cooking>Traditional & modern culinary channels (Amina Cuisine, Chef Moha)Instructional imperatives, culinary terms (طاجين, بطاطا, مرقة, كوزينة, توابل)
2<tech>Tech reviews, hardware, electronics discussionsTelephony, hardware specifications, prices, English/French loanwords
3<sports>Football match reactions, CAN, national team analysis (Dzair Foot)Sports passion register, clubs (MCA, USMA, CRB), national team, Mahrez
4<podcast>Business, marketing, startup, and self-help podcastsEntrepreneurship terms, freelancing, mindset, formal conversational Arabic
5<story>Narrative folklore, storytelling, social chroniclesNarrative past tense, family relationships, traditional formulas (كان يا ما كان)
6<NULL>Unconditional baseline (trained with 10% dropout)Neutral background register; serves as reference baseline for CFG extrapolation

Custom Darija Tokenizer & Benchmark

We conducted a full-corpus, zero-leakage benchmark across 30 open-weights tokenizers (29 distinct external vocabularies + silma-ai/SILMA-9B-Instruct-v1.0 alias) over all 11,151 untruncated documents (34,336,366 words / 186,106,376 characters across all 6 domains) from the Algerian Darja Corpus using 5-fold group-stratified out-of-fold evaluation, 10,000-replicate paired bootstrap CIs, and Holm-Bonferroni tie tiers. On the exact 335 strictly held-out documents (1,013,800 words), the shipped touati-kamel/darja-tokenizer-50m-conditioned scores 1.474 vs. 1.476 for the 5-fold OOF recipe. All evaluations used raw document text without domain tags or special tokens.

Tokenizer Comparison on Full-Corpus Algerian Darja (11,151 Docs, Zero Leakage)

#TokenizerRole / ArchitectureVocab SizeFertility ↓Bytes / Tok ↑UNK %Ours Needs Fewer Tokens By (95% CI)Tie Tier
1alger-ia/dziribertEncoder (Darija WordPiece)*50,0001.4486.680.01%-0.8% [-1.0%, -0.6%]T1
2SI2M-Lab/DarijaBERTEncoder (Darija WordPiece)*80,0001.4506.670.00%-0.7% [-0.9%, -0.5%]T1
3★ Custom Darja 24K BPE (5-fold OOF)Custom Decoder BPE24,0001.4596.620.00%Baseline (5-fold OOF)T2
4UBC-NLP/MARBERTEncoder (Dialect WordPiece)*100,0001.4646.600.09%+0.3% [+0.0%, +0.5%]T2
5inceptionai/jais-family-590mDecoder LLM84,9921.6745.770.00%+12.8% [+12.5%, +13.1%]T3
6ALLaM-AI/ALLaM-7B-Instruct-previewDecoder LLM64,0001.6805.750.00%+13.1% [+12.8%, +13.4%]T4
7CAMeL-Lab/bert-base-arabic-camelbert-mixEncoder30,0001.6875.730.37%†+13.5% [+13.2%, +13.8%]T5
8aubmindlab/bert-base-arabertv2Encoder64,0001.7705.460.64%†+17.6% [+17.3%, +17.8%]T6
9aubmindlab/aragpt2-baseDecoder LLM64,0001.8265.290.00%+20.1% [+19.7%, +20.4%]T7
10bigscience/bloom-560mDecoder LLM250,6801.8285.290.00%+20.1% [+19.8%, +20.4%]T7
11FacebookAI/xlm-roberta-baseEncoder250,0021.9934.850.00%+26.8% [+26.5%, +27.0%]T8
12facebook/mbart-large-50Seq2Seq250,0541.9934.850.00%+26.8% [+26.5%, +27.0%]T8
13mistralai/Mistral-Nemo-Base-2407Decoder LLM131,0722.0144.800.00%+27.5% [+27.2%, +27.8%]T9
14openai/gpt-oss-20bDecoder LLM200,0192.0674.680.00%+29.4% [+29.1%, +29.6%]T10
15facebook/nllb-200-distilled-600MSeq2Seq256,2042.0804.650.09%+29.8% [+29.6%, +30.1%]T11
16MBZUAI-Paris/Atlas-Chat-2B (+ SILMA-9B alias)Decoder LLM256,0002.1534.490.00%+32.2% [+32.0%, +32.5%]T12
17QCRI/Fanar-1-9BDecoder LLM128,2562.1584.480.00%+32.4% [+32.1%, +32.6%]T13
18google/mt5-smallSeq2Seq250,1002.2334.330.00%+34.6% [+34.4%, +34.9%]T14
19Qwen/Qwen2.5-0.5BDecoder LLM151,6652.3784.060.00%+38.6% [+38.4%, +38.9%]T15
20Qwen/Qwen3-0.6BDecoder LLM151,6692.3784.060.00%+38.6% [+38.4%, +38.9%]T15
21google-bert/bert-base-multilingual-casedEncoder119,5472.3974.030.08%+39.1% [+38.9%, +39.4%]T16
22EleutherAI/gpt-neox-20bDecoder LLM50,2773.8742.500.00%+62.3% [+62.1%, +62.5%]T17
23microsoft/phi-4Decoder LLM100,3523.8872.490.00%+62.4% [+62.2%, +62.7%]T18
24allenai/OLMo-2-1124-7BDecoder LLM100,2783.8872.490.00%+62.4% [+62.2%, +62.7%]T18
25deepseek-ai/deepseek-llm-7b-baseDecoder LLM100,0154.8541.990.00%+69.9% [+69.8%, +70.1%]T19
26mistralai/Mistral-7B-v0.3Decoder LLM32,7684.9891.940.00%+70.7% [+70.6%, +70.9%]T20
27microsoft/Phi-3-mini-4k-instructDecoder LLM32,0115.0781.900.00%+71.3% [+71.1%, +71.4%]T21
28HuggingFaceTB/SmolLM2-360MDecoder LLM49,1525.2131.850.00%+72.0% [+71.9%, +72.2%]T22
29openai-community/gpt2Decoder LLM50,2575.5651.740.00%+73.8% [+73.6%, +73.9%]T23
30tiiuae/falcon-7bDecoder LLM65,0245.6651.710.00%+74.2% [+74.1%, +74.4%]T24

*Lossy normalization audit: dziribert, DarijaBERT, and MARBERT strip Arabic diacritics and lowercase text, and are encoder-only masked BERT models rather than generative decoders. Custom Darja 24K BPE is lossless and ranks #1 overall in <cooking> (1.427) and <tech> (1.448).
†High UNK rates (>0.1%) artificially flatter the apparent fertility of WordPiece models by replacing unsegmented characters with [UNK].


Training Data & Pre-Training Recipe

1. Corpus: touati-kamel/algerian-darja-corpus (conditioned subset)

  • Total Documents: 11,151 high-quality transcript documents
  • Raw Volume: ~186.1 million characters / ~34.3 million words
  • Token Count: ~53.3 million packed tokens
  • Data Balance: Curated YouTube conversational transcripts, podcasts, cooking shows, comedy sketches, and sports commentary, cleaned and tagged with domain markers.

2. Sequence Packing & Training Setup

  • Chunking Pipeline: Rather than truncating long transcripts, texts were concatenated with <eos> boundaries and packed into exact 1,024-token chunks, yielding 52,038 dense training sequences (~4.8× data yield improvement over naive truncation).
  • Optimizer: AdamW (beta1 = 0.9, beta2 = 0.95, weight_decay = 0.1)
  • Regularization: Label smoothing eps = 0.1, gradient clipping at 1.0
  • Schedule: Cosine learning rate decay with linear warmup (peak LR 3e-4, 500 warmup steps)
  • CFG Dropout: 10% probability of assigning domain_ids = 6 (<NULL>) per batch
  • Text-Tag Dropout: 20% probability of removing prefix tag from training text
  • Hardware: Single NVIDIA T4 GPU (16 GB VRAM) on Kaggle Notebooks
  • Training Runtime: ~6.8 hours for 6 full epochs (4,884 optimizer steps)
  • Best Checkpoint: Step 3,000 (eval loss 5.978) selected via load_best_model_at_end = True

Quantitative & Qualitative Evaluation

1. Held-Out Perplexity

Evaluated on 335 strictly held-out test documents (never seen during training, split with fixed seed):

  • Raw Held-out Eval Loss: 5.2890
  • Raw Held-out Perplexity: 198.15 (For context, training-time best eval loss was ~5.978; the packed held-out perplexity demonstrates zero overfitting and solid generalizability across dialects).

2. Weight Diagnostic (FiLM vs. LoRA Adapters)

Direct inspection of weight-delta Frobenius norms ||ΔW||_F across all 12 layers:

Layer TypeComparison PairFiLM Distance (v4)v5 Adapter Distance (LoRA)Finding
Attention o_projCooking vs. Tech0.9221.412 (+53%)Distinct lexical heads
Attention o_projSports vs. Cooking1.1241.731 (+54%)Strong topical separation
MLP down_projCooking vs. NULL0.7631.184 (+55%)Strong divergence from neutral
MLP down_projSports vs. NULL0.6821.365 (+100%)Powerful specialized sport projection

3. Qualitative Steering Regimes

Each domain was evaluated across 5 controlled experimental regimes:

  1. notag_null: Prompt with no text tag, evaluated on unconditional base (<NULL>).
  2. tag_null: Prompt with text tag, evaluated on unconditional base.
  3. tag_correct: Prompt with text tag + matching domain adapter.
  4. tag_mismatch: Causal test — Prompt text tag matches Domain A, but adapter is set to Domain B.
  5. tag_correct+CFG: Prompt with text tag + matching adapter guided via CFG (s = 2.5).

Key Findings from Empirical Samples:

  • Causal Override Proved (Mismatch Test): Feeding <cooking> prompt text into the <tech> adapter immediately injected electronics pricing, battery life, and Bluetooth mentions into cooking sentences, proving the adapter causally controls generation semantics rather than relying purely on text tag autoregression.
  • The "Mahrez" Sports Evaluation: In 5/5 independent seeded sports CFG draws, Riyad Mahrez appeared as the central subject. Detailed analysis confirmed this reflects true corpus distribution (Mahrez accounts for >80% of modern Algerian sports media mentions) rather than degenerate looping: each sample paired Mahrez with completely unique sets of international clubs (Barcelona, Man City, Chelsea) and national teams (Burkina Faso, Austria, Senegal, Egypt).
  • Narrative Coherence (<story>): Produced sustained multi-sentence folklore and personal narratives in 10/10 samples with no phrase-level degeneracy.

Quickstart & Inference Guide

Because Darja-GPT-50M-v5 uses custom rotary and domain-adapter layers, generation requires registering the configuration or using the standalone model file.

Installation & Modular Setup

You can either install the repository as an editable Python package or execute scripts directly:

# 1. Clone repository
git clone https://github.com/touati-kamel/darja-gpt.git
cd darja-gpt

# 2. Install dependencies & core package
pip install -e .

Quickstart CLI Generation

Run instant inference using the self-bootstrapping CLI or interactive mode:

# Interactive conversation session
python generate.py --interactive

# Direct CLI steering with CFG
python generate.py --domain cooking --cfg 2.2 --prompt "اليوم غادي نديرو وصفة بسيطة وسهلة، خاصنا"
python generate.py --domain sports --cfg 2.5 --prompt "البارح كانت مباراة كبيرة وقوية بزاف"

Programmatic Python Usage

from darja_gpt import load_darja_gpt, generate_cfg

# Load model and tokenizer
tokenizer, model, device = load_darja_gpt(
    model_id="touati-kamel/darja-gpt-50m",
    tokenizer_id="touati-kamel/darja-tokenizer-50m"
)

# Generate with Classifier-Free Guidance
output = generate_cfg(
    model=model,
    tokenizer=tokenizer,
    prompt="اليوم غادي نديرو وصفة بسيطة وسهلة، خاصنا",
    domain_name="cooking",
    guidance_scale=2.2,
    max_new_tokens=150,
    device=device
)
print(output)

Complete Low-Level Generation Script (Standalone HF)

import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM

# 1. Load Tokenizer & Model
MODEL_ID = "touati-kamel/darja-gpt-50m"
TOKENIZER_ID = "touati-kamel/darja-tokenizer-50m"

device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_ID)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, trust_remote_code=True).to(device)
model.eval()

# Domain Mapping
DOMAIN_TO_IDX = {
    "<general>": 0,
    "<cooking>": 1,
    "<tech>": 2,
    "<sports>": 3,
    "<podcast>": 4,
    "<story>": 5,
    "<NULL>": 6
}
NULL_DOMAIN_IDX = 6

@torch.no_grad()
def generate_darja_cfg(
    prompt: str,
    domain_tag: str = "<cooking>",
    guidance_scale: float = 2.0,
    max_new_tokens: int = 120,
    temperature: float = 0.8,
    top_p: float = 0.9,
    repetition_penalty: float = 1.25
):
    full_prompt = f"{domain_tag} {prompt}"
    input_ids = tokenizer.encode(full_prompt, return_tensors="pt").to(device)
    
    cond_domain = torch.tensor([DOMAIN_TO_IDX[domain_tag]], dtype=torch.long, device=device)
    uncond_domain = torch.tensor([NULL_DOMAIN_IDX], dtype=torch.long, device=device)
    generated = input_ids

    for _ in range(max_new_tokens):
        if generated.size(1) >= model.config.max_position_embeddings:
            break
            
        # Parallel forward passes for CFG
        logits_cond = model(input_ids=generated, domain_ids=cond_domain).logits[:, -1, :]
        logits_uncond = model(input_ids=generated, domain_ids=uncond_domain).logits[:, -1, :]
        
        # Classifier-Free Guidance extrapolation
        logits = logits_uncond + guidance_scale * (logits_cond - logits_uncond)
        
        # Repetition penalty
        for token_id in set(generated[0].tolist()):
            if logits[0, token_id] > 0:
                logits[0, token_id] /= repetition_penalty
            else:
                logits[0, token_id] *= repetition_penalty
                
        # Temperature & Top-p (Nucleus) sampling
        logits = logits / max(temperature, 1e-5)
        probs = F.softmax(logits, dim=-1)
        sorted_probs, sorted_indices = torch.sort(probs, descending=True)
        cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
        
        cutoff = cumulative_probs > top_p
        cutoff[..., 1:] = cutoff[..., :-1].clone()
        cutoff[..., 0] = False
        sorted_probs[cutoff] = 0.0
        sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)
        
        next_token = sorted_indices.gather(-1, torch.multinomial(sorted_probs, num_samples=1))
        generated = torch.cat([generated, next_token], dim=1)
        
        if next_token.item() == tokenizer.eos_token_id:
            break

    return tokenizer.decode(generated[0], skip_special_tokens=True)

# Example 1: Culinary Recipe in Algerian Darija
cooking_output = generate_darja_cfg(
    prompt="اليوم غادي نديرو وصفة بسيطة وسهلة، خاصنا",
    domain_tag="<cooking>",
    guidance_scale=2.2
)
print("--- Cooking Output ---")
print(cooking_output)

# Example 2: Sports Commentary
sports_output = generate_darja_cfg(
    prompt="البارح كانت مباراة كبيرة وقوية بزاف",
    domain_tag="<sports>",
    guidance_scale=2.5
)
print("\n--- Sports Output ---")
print(sports_output)

Known Limitations & Responsible AI

  1. Parameter Scale (54.8M):
    • This model is intended for fast stylistic generation, grammatical exploration, dialectal modeling, and low-compute deployment.
    • It is not an instruction-tuned assistant (not SFT aligned) and cannot perform complex multi-step reasoning, mathematical calculations, or factual QA.
  2. Entity Bias:
    • The sports domain exhibits high name-recurrence (e.g. Riyad Mahrez, Youcef Belaïli) reflecting YouTube sports talk media frequency in Algeria.
  3. Orthographic Heterogeneity:
    • Algerian Darija is traditionally an unstandardized spoken dialect with mixed Arabic and Latin (Arabizi) orthographies. While the tokenizer accommodates both, Arabic script accounts for ~90% of the training corpus.
  4. Code-Switching:
    • In technical and business podcast domains, the model naturally code-switches into French and English loanwords, reflecting authentic Algerian speech patterns.

Citation & Contact

If you use Darja-GPT-50M or the Algerian Darja Corpus in your research or project, please cite:

@misc{touati2026darjagpt50m,
  author       = {Kamel Touati},
  title        = {Darja-GPT-50M: Domain-Conditioned Causal Language Model for Algerian Darija with Classifier-Free Guidance},
  year         = {2026},
  publisher    = {Hugging Face},
  howpublished = {\url{https://huggingface.co/touati-kamel/darja-gpt-50m}}
}

@misc{touati2026darjacorpus,
  author       = {Kamel Touati},
  title        = {Algerian Darja Corpus: Multi-Domain Conversational Transcripts in Algerian Arabic},
  year         = {2026},
  publisher    = {Hugging Face},
  howpublished = {\url{https://huggingface.co/datasets/touati-kamel/algerian-darja-corpus}}
}

Developer: Kamel Touati (Hugging Face Profile)
License: Apache 2.0

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

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

GPU в ailist

Универсальный рантайм

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

Архитектура darja_gpt_v5 неизвестна transformers в образе рантайма.

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

0 моделей