Upload 9 files
Browse files- .gitattributes +1 -0
- README.md +471 -0
- config.json +16 -0
- configuration_sovythos.py +54 -0
- generation_config.json +13 -0
- modeling_sovythos.py +176 -0
- sovythos.png +3 -0
- special_tokens_map.json +18 -0
- tokenizer.json +0 -0
- tokenizer_config.json +24 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
sovythos.png filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,3 +1,474 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
- ar
|
| 6 |
+
tags:
|
| 7 |
+
- sovereign
|
| 8 |
+
- sovythos
|
| 9 |
+
- llm
|
| 10 |
+
- transformer
|
| 11 |
+
- pytorch
|
| 12 |
+
- arabic
|
| 13 |
+
- egyptian-arabic
|
| 14 |
+
- english
|
| 15 |
+
- code
|
| 16 |
+
- open-source
|
| 17 |
+
- llama-architecture
|
| 18 |
+
- gqa
|
| 19 |
+
- rope
|
| 20 |
+
- swiglu
|
| 21 |
+
- safetensors
|
| 22 |
+
- gguf
|
| 23 |
+
pipeline_tag: text-generation
|
| 24 |
---
|
| 25 |
+
|
| 26 |
+
<p align="center">
|
| 27 |
+
<img src="https://huggingface.co/my0919175/Sovythos-303M-Base/resolve/main/sovythos.png" width="320" alt="SOVYTHOS-V2">
|
| 28 |
+
</p>
|
| 29 |
+
|
| 30 |
+
<h1 align="center">🦋 SOVYTHOS-V2</h1>
|
| 31 |
+
<h3 align="center">Sovythos Egyptian Reasoning & Code Base Model</h3>
|
| 32 |
+
|
| 33 |
+
<p align="center">
|
| 34 |
+
<b>A production-grade, Llama-compatible decoder-only Transformer trained entirely from scratch for Arabic, English, and Code.</b>
|
| 35 |
+
</p>
|
| 36 |
+
|
| 37 |
+
<p align="center">
|
| 38 |
+
|
| 39 |
+

|
| 40 |
+

|
| 41 |
+

|
| 42 |
+

|
| 43 |
+

|
| 44 |
+

|
| 45 |
+

|
| 46 |
+

|
| 47 |
+
|
| 48 |
+
</p>
|
| 49 |
+
|
| 50 |
+
> ### ⚠️ Training Status: Early-Stage Checkpoint
|
| 51 |
+
> **This checkpoint is an early snapshot from an ongoing training run — it is NOT the final SOVYTHOS-V2 release.** The model is uploaded at this stage for architecture testing, integration testing (`transformers`/GGUF compatibility), and community feedback purposes only.
|
| 52 |
+
>
|
| 53 |
+
> Expect at this stage:
|
| 54 |
+
> - Weak or incoherent generations on many prompts
|
| 55 |
+
> - Little to no instruction-following ability (this is a **Base**, non-instruction-tuned model on top of being early-stage)
|
| 56 |
+
> - Validation loss still actively decreasing — quality will improve substantially with further training
|
| 57 |
+
>
|
| 58 |
+
> Training is actively continuing. Follow this repository for updates as later checkpoints are released.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## 📋 Table of Contents
|
| 63 |
+
|
| 64 |
+
- [Overview](#overview)
|
| 65 |
+
- [Model Specifications](#model-specifications)
|
| 66 |
+
- [Architecture Details](#architecture-details)
|
| 67 |
+
- [Tokenizer](#tokenizer)
|
| 68 |
+
- [Training](#training)
|
| 69 |
+
- [Try It Now (Google Colab)](#-try-it-now-google-colab)
|
| 70 |
+
- [Usage](#usage)
|
| 71 |
+
- [GGUF Inference](#gguf-inference)
|
| 72 |
+
- [Intended Uses](#intended-uses)
|
| 73 |
+
- [Limitations](#limitations)
|
| 74 |
+
- [Roadmap](#roadmap)
|
| 75 |
+
- [Citation](#citation)
|
| 76 |
+
- [License](#license)
|
| 77 |
+
|
| 78 |
+
---
|
| 79 |
+
|
| 80 |
+
## 🦋 Overview
|
| 81 |
+
|
| 82 |
+
**SOVYTHOS-V2** is the second-generation foundation model of the **Sovythos AI Project** — a fully open-source, decoder-only Transformer trained **from randomly initialized weights** on a multilingual corpus spanning Modern Standard Arabic, Egyptian Arabic, English, and programming languages.
|
| 83 |
+
|
| 84 |
+
This release represents a significant architectural leap from the original 66M Base model, scaling to **~300 million parameters** while adopting a **Llama-compatible** design (RMSNorm, RoPE, GQA, SwiGLU) to ensure seamless deployment across the modern inference ecosystem, including `llama.cpp`, `llama-cpp-python`, and Hugging Face transformers.
|
| 85 |
+
|
| 86 |
+
SOVYTHOS-V2 is released as a **Base (Pretrained)** model. It has not undergone instruction tuning or RLHF and is intended for researchers, developers, and educators who require a sovythos, transparent foundation for downstream training.
|
| 87 |
+
|
| 88 |
+
> **Key Design Principle:** Every component — from the tokenizer to the tensor naming convention — is engineered for **direct compatibility** with the Llama/GGUF toolchain. No conversion hacks required.
|
| 89 |
+
|
| 90 |
+
---
|
| 91 |
+
|
| 92 |
+
## 📊 Model Specifications
|
| 93 |
+
|
| 94 |
+
| Property | Value |
|
| 95 |
+
|----------|-------|
|
| 96 |
+
| **Model** | SOVYTHOS-V2 |
|
| 97 |
+
| **Parameters** | ~300 Million |
|
| 98 |
+
| **Architecture** | Decoder-only Transformer (Llama-style) |
|
| 99 |
+
| **Hidden Size** | 1,024 |
|
| 100 |
+
| **Layers** | 24 |
|
| 101 |
+
| **Attention Heads** | 16 (Query) / 4 (Key-Value) |
|
| 102 |
+
| **Head Dimension** | 64 |
|
| 103 |
+
| **Context Length** | 2,048 tokens |
|
| 104 |
+
| **RoPE Theta** | 1,000,000 |
|
| 105 |
+
| **Vocabulary Size** | 32,000 |
|
| 106 |
+
| **Framework** | PyTorch 2.x |
|
| 107 |
+
| **Weight Format** | Safetensors + GGUF (F16 / F32) |
|
| 108 |
+
| **Training** | From Scratch |
|
| 109 |
+
| **Release** | Base |
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## 🏗️ Architecture Details
|
| 114 |
+
|
| 115 |
+
SOVYTHOS-V2 implements a modern, efficient decoder stack aligned with the Llama architecture specification for frictionless ecosystem integration.
|
| 116 |
+
|
| 117 |
+
### Normalization
|
| 118 |
+
- **RMSNorm** applied pre-attention and post-attention (no bias, no learned affine shift)
|
| 119 |
+
|
| 120 |
+
### Position Encoding
|
| 121 |
+
- **RoPE (Rotary Position Embedding)** with rotate_half (NEOX-style) implementation
|
| 122 |
+
- Base frequency θ = 1,000,000
|
| 123 |
+
- Precomputed cosine/sine caches up to max sequence length
|
| 124 |
+
|
| 125 |
+
### Attention Mechanism
|
| 126 |
+
- **Grouped Query Attention (GQA)** with 16 query heads and 4 key-value heads
|
| 127 |
+
- Reduces KV-cache memory footprint by **4×** during inference compared to standard MHA
|
| 128 |
+
- Compatible with memory-efficient attention kernels (`scaled_dot_product_attention`)
|
| 129 |
+
|
| 130 |
+
### Feed-Forward Network
|
| 131 |
+
- **SwiGLU** activation with gated projection
|
| 132 |
+
- Hidden dimension rounded to nearest multiple of 256 for optimal GPU kernel utilization
|
| 133 |
+
- `gate_proj`, `up_proj`, `down_proj` naming matches Llama/GGUF conventions exactly
|
| 134 |
+
|
| 135 |
+
### Weight Initialization
|
| 136 |
+
- Gaussian initialization (σ = 0.02) for embeddings and linear layers
|
| 137 |
+
- Scaled down-projection and output-projection initialization by `1/√(2×layers)` to stabilize deep training
|
| 138 |
+
|
| 139 |
+
### Training Optimizations
|
| 140 |
+
- **torch.compile** graph mode (when available)
|
| 141 |
+
- **TF32** matmul acceleration on Ampere+
|
| 142 |
+
- **Automatic Mixed Precision (AMP)** with `fp16` forward pass
|
| 143 |
+
- **Gradient Checkpointing** for long-context training on consumer GPUs
|
| 144 |
+
- **Gradient Accumulation** with effective batch scaling
|
| 145 |
+
- **Cosine LR Decay** with linear warmup
|
| 146 |
+
- **Gradient Clipping** (max norm = 1.0)
|
| 147 |
+
|
| 148 |
+
---
|
| 149 |
+
|
| 150 |
+
## 🔤 Tokenizer
|
| 151 |
+
|
| 152 |
+
SOVYTHOS-V2 ships with a **custom-trained Byte-Pair Encoding (BPE)** tokenizer optimized for Arabic morphology, English, and code syntax.
|
| 153 |
+
|
| 154 |
+
### Design Choices
|
| 155 |
+
|
| 156 |
+
| Feature | Implementation |
|
| 157 |
+
|---------|---------------|
|
| 158 |
+
| **Pre-tokenization** | GPT-4 / cl100k-style regex split (Unicode-aware) |
|
| 159 |
+
| **Numerical Splitting** | Digits grouped by 3 (e.g., `1,234,567` → `1` `234` `567`) |
|
| 160 |
+
| **Fallback** | ByteLevel encoding for lossless coverage of any Unicode symbol |
|
| 161 |
+
| **Normalization** | NFC Unicode normalization (unifies Arabic hamza & diacritic forms) |
|
| 162 |
+
| **Special Tokens** | `<\|endoftext\|>`, `<\|pad\|>`, `<\|user\|>`, `<\|assistant\|>`, `<\|system\|>`, `<\|code\|>`, `<\|/code\|>`, `<\|think\|>`, `<\|/think\|>` |
|
| 163 |
+
| **Vocab Size** | 32,000 |
|
| 164 |
+
| **Min Frequency** | 2 |
|
| 165 |
+
|
| 166 |
+
### Coverage Efficiency (Tokens per Character)
|
| 167 |
+
|
| 168 |
+
Lower is better. Measured on a held-out sample of the training corpus:
|
| 169 |
+
|
| 170 |
+
| Domain | Tokens / Char | Notes |
|
| 171 |
+
|--------|---------------|-------|
|
| 172 |
+
| **Arabic (MSA + Egyptian)** | ~0.35 | Efficient subword decomposition for Semitic morphology |
|
| 173 |
+
| **English** | ~0.28 | Competitive with modern English-centric tokenizers |
|
| 174 |
+
| **Code** | ~0.42 | Strong performance on Python / JavaScript identifiers |
|
| 175 |
+
|
| 176 |
+
> The tokenizer is saved as a standard `tokenizer.json` (Hugging Face `tokenizers` format) and its merges/vocab are **directly compatible** with GGUF `gpt2` tokenizer model type.
|
| 177 |
+
|
| 178 |
+
---
|
| 179 |
+
|
| 180 |
+
## 🏋️ Training
|
| 181 |
+
|
| 182 |
+
SOVYTHOS-V2 was trained **entirely from scratch**. No pretrained weights from Llama, GPT, or any other foundation model were used as initialization.
|
| 183 |
+
|
| 184 |
+
### Data Pipeline
|
| 185 |
+
- **Corpus**: Multilingual web text, technical documentation, mathematical content, and code repositories
|
| 186 |
+
- **Languages**: Modern Standard Arabic, Egyptian Arabic, English, and multilingual programming languages
|
| 187 |
+
- **Cleaning**: Duplicate-line removal, short-line filtering (< 2 chars), NFC normalization, and aggressive deduplication of repeated contiguous lines
|
| 188 |
+
- **Format**: Binary tokenized memmap for high-throughout training with `np.uint16` encoding
|
| 189 |
+
|
| 190 |
+
### Training Recipe
|
| 191 |
+
|
| 192 |
+
| Hyperparameter | Value |
|
| 193 |
+
|----------------|-------|
|
| 194 |
+
| Optimizer | AdamW (β₁=0.9, β₂=0.95, ε=1e-8) |
|
| 195 |
+
| Peak Learning Rate | 3e-4 |
|
| 196 |
+
| Minimum Learning Rate | 3e-5 |
|
| 197 |
+
| Warmup Steps | 1,000 |
|
| 198 |
+
| LR Schedule | Cosine decay |
|
| 199 |
+
| Weight Decay | 0.1 (2D+ tensors only) |
|
| 200 |
+
| Max Gradient Norm | 1.0 |
|
| 201 |
+
| Precision | FP16 (AMP) with FP32 master weights |
|
| 202 |
+
| Batch Size | 4 (per device) |
|
| 203 |
+
| Gradient Accumulation | 8 steps |
|
| 204 |
+
| Effective Batch Size | 32 |
|
| 205 |
+
| Block Size | 512 tokens |
|
| 206 |
+
|
| 207 |
+
### Checkpointing & Resumption
|
| 208 |
+
- Checkpoints saved in **Safetensors** format (secure, fast, language-agnostic)
|
| 209 |
+
- Automatic resumption from `ckpt_dir/best/` including step count and best validation loss
|
| 210 |
+
- Best checkpoint selection based on validation loss
|
| 211 |
+
|
| 212 |
+
### Export
|
| 213 |
+
- **Native GGUF export** after training (or from existing checkpoints via `--export_gguf_only`)
|
| 214 |
+
- Supported quantizations: `F32`, `F16` (post-hoc Q4/Q8 via `llama.cpp` tools)
|
| 215 |
+
- Tensor name map strictly follows Llama GGUF specification (`blk.{i}.attn_q.weight`, `blk.{i}.ffn_gate.weight`, etc.)
|
| 216 |
+
|
| 217 |
+
---
|
| 218 |
+
|
| 219 |
+
## 🚀 Try It Now (Google Colab)
|
| 220 |
+
|
| 221 |
+
The fastest way to test SOVYTHOS-V2 is directly through 🤗 `transformers`, using the custom model code shipped in this repository (`trust_remote_code=True`). No manual setup, no cloning — just run the cell below in a fresh Colab notebook.
|
| 222 |
+
|
| 223 |
+
```python
|
| 224 |
+
# ============================================================
|
| 225 |
+
# 🔱 SOVYTHOS-V2 (303M-Base) — Colab Quickstart
|
| 226 |
+
# ============================================================
|
| 227 |
+
|
| 228 |
+
!pip install -q -U transformers accelerate safetensors
|
| 229 |
+
|
| 230 |
+
import torch
|
| 231 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 232 |
+
|
| 233 |
+
MODEL_ID = "my0919175/Sovythos-303M-Base"
|
| 234 |
+
|
| 235 |
+
print("🔄 Loading tokenizer...")
|
| 236 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 237 |
+
|
| 238 |
+
print("🔄 Loading model...")
|
| 239 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 240 |
+
MODEL_ID,
|
| 241 |
+
dtype=torch.float32,
|
| 242 |
+
trust_remote_code=True,
|
| 243 |
+
).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 244 |
+
model.eval()
|
| 245 |
+
|
| 246 |
+
# Chat-style prompt using the built-in special tokens
|
| 247 |
+
prompt = "<|user|>\nمرحبا, احكيلي عن نفسك\n<|assistant|>\n"
|
| 248 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
|
| 249 |
+
|
| 250 |
+
with torch.no_grad():
|
| 251 |
+
output = model.generate(
|
| 252 |
+
input_ids,
|
| 253 |
+
max_new_tokens=150,
|
| 254 |
+
do_sample=True,
|
| 255 |
+
temperature=0.8,
|
| 256 |
+
top_k=40,
|
| 257 |
+
top_p=0.9,
|
| 258 |
+
repetition_penalty=1.15,
|
| 259 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 260 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
> **Note:** This is an **early-stage training checkpoint** of a **Base** (non-instruction-tuned) model — not the final release. Outputs may be short, repetitive, incoherent, or diverge from the prompt entirely; this is expected at this stage of training and is not a loading error. Quality will improve as training progresses and with the upcoming Instruct release.
|
| 267 |
+
>
|
| 268 |
+
> When prompted `Do you wish to run the custom code? [y/N]`, type **y** — this loads `configuration_sovythos.py` and `modeling_sovythos.py` from this repo, which implement the GQA + RoPE + SwiGLU architecture described above.
|
| 269 |
+
|
| 270 |
+
---
|
| 271 |
+
|
| 272 |
+
## 💻 Usage
|
| 273 |
+
|
| 274 |
+
### Loading with 🤗 Transformers (Recommended)
|
| 275 |
+
|
| 276 |
+
This repository ships with `trust_remote_code`-compatible files (`configuration_sovythos.py`, `modeling_sovythos.py`), so it works directly with the standard `AutoModelForCausalLM` / `AutoTokenizer` API — no need to clone the original training repo:
|
| 277 |
+
|
| 278 |
+
```python
|
| 279 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 280 |
+
import torch
|
| 281 |
+
|
| 282 |
+
model_id = "my0919175/Sovythos-303M-Base"
|
| 283 |
+
|
| 284 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 285 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 286 |
+
model_id, dtype=torch.float32, trust_remote_code=True
|
| 287 |
+
).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 288 |
+
|
| 289 |
+
prompt = "<|user|>\nThe capital of Egypt is\n<|assistant|>\n"
|
| 290 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
|
| 291 |
+
|
| 292 |
+
output = model.generate(
|
| 293 |
+
input_ids,
|
| 294 |
+
max_new_tokens=50,
|
| 295 |
+
temperature=0.8,
|
| 296 |
+
top_k=40,
|
| 297 |
+
top_p=0.9,
|
| 298 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 299 |
+
)
|
| 300 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
### Loading with the Native Training Code
|
| 304 |
+
|
| 305 |
+
If you have the original training repository (`model.py`, `train.py`) available locally, you can also load the checkpoint directly through the native `Model` class, which supports the custom KV-cache and generation loop used during training/research:
|
| 306 |
+
|
| 307 |
+
```python
|
| 308 |
+
from model import Model
|
| 309 |
+
|
| 310 |
+
model = Model.from_pretrained("sovythos_ckpt/best", device="cuda")
|
| 311 |
+
|
| 312 |
+
text = "The capital of Egypt is"
|
| 313 |
+
ids = tokenizer.encode(text).ids
|
| 314 |
+
input_ids = torch.tensor([ids], device="cuda")
|
| 315 |
+
|
| 316 |
+
output = model.generate(
|
| 317 |
+
input_ids,
|
| 318 |
+
max_new_tokens=50,
|
| 319 |
+
temperature=0.8,
|
| 320 |
+
top_k=40,
|
| 321 |
+
top_p=0.9,
|
| 322 |
+
eos_token_id=tokenizer.token_to_id("<|endoftext|>")
|
| 323 |
+
)
|
| 324 |
+
print(tokenizer.decode(output[0].tolist()))
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
### Using the Tokenizer Directly
|
| 328 |
+
|
| 329 |
+
```python
|
| 330 |
+
from tokenizers import Tokenizer
|
| 331 |
+
|
| 332 |
+
tok = Tokenizer.from_file("tokenizer.json")
|
| 333 |
+
encoded = tok.encode("إزيك يا كبير؟")
|
| 334 |
+
print(encoded.ids) # [ ... ]
|
| 335 |
+
print(tok.decode(encoded.ids)) # "إزيك يا كبير؟"
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
---
|
| 339 |
+
|
| 340 |
+
## 🚀 GGUF Inference
|
| 341 |
+
|
| 342 |
+
Because SOVYTHOS-V2 uses **Llama-compatible tensor naming** and a **GPT-2-format tokenizer**, the exported GGUF file runs out-of-the-box with `llama.cpp` and `llama-cpp-python`.
|
| 343 |
+
|
| 344 |
+
### llama-cpp-python
|
| 345 |
+
|
| 346 |
+
```python
|
| 347 |
+
from llama_cpp import Llama
|
| 348 |
+
|
| 349 |
+
llm = Llama(
|
| 350 |
+
model_path="sovythos-v2.f16.gguf",
|
| 351 |
+
n_ctx=2048,
|
| 352 |
+
n_gpu_layers=-1, # Offload all layers to GPU
|
| 353 |
+
verbose=False
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
output = llm(
|
| 357 |
+
"The capital of Egypt is",
|
| 358 |
+
max_tokens=50,
|
| 359 |
+
temperature=0.8,
|
| 360 |
+
top_k=40,
|
| 361 |
+
top_p=0.9,
|
| 362 |
+
stop=["<|endoftext|>"]
|
| 363 |
+
)
|
| 364 |
+
print(output["choices"][0]["text"])
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
### llama.cpp CLI
|
| 368 |
+
|
| 369 |
+
```bash
|
| 370 |
+
./main -m sovythos-v2.f16.gguf -n 50 --temp 0.8 --top-k 40 --top-p 0.9 -p "The capital of Egypt is"
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
> **No conversion scripts required.** The GGUF file is produced directly by the training framework with correct `llama` arch metadata.
|
| 374 |
+
|
| 375 |
+
---
|
| 376 |
+
|
| 377 |
+
## 🎯 Intended Uses
|
| 378 |
+
|
| 379 |
+
SOVYTHOS-V2 is designed as a **research and development foundation** for:
|
| 380 |
+
|
| 381 |
+
- Continued pretraining on domain-specific corpora
|
| 382 |
+
- Supervised fine-tuning (SFT) for chat or task-specific behavior
|
| 383 |
+
- Instruction tuning and alignment experiments
|
| 384 |
+
- Educational exploration of modern decoder-only architectures
|
| 385 |
+
- Arabic NLP research (MSA, Egyptian dialect, code-switching)
|
| 386 |
+
- Low-resource and Sovythos AI development
|
| 387 |
+
|
| 388 |
+
> **Not intended for:** Direct deployment as a production chatbot without additional safety fine-tuning and evaluation.
|
| 389 |
+
|
| 390 |
+
---
|
| 391 |
+
|
| 392 |
+
## ⚠️ Limitations
|
| 393 |
+
|
| 394 |
+
As a **Base (pretrained)** model, SOVYTHOS-V2 exhibits expected limitations:
|
| 395 |
+
|
| 396 |
+
- **No instruction following** without fine-tuning
|
| 397 |
+
- **Hallucination** of factual information (names, dates, technical details)
|
| 398 |
+
- **Repetition** in long-form generation
|
| 399 |
+
- **Incomplete reasoning** on complex multi-step problems
|
| 400 |
+
- **Limited context coherence** beyond a few hundred tokens in zero-shot settings
|
| 401 |
+
- **Code generation** produces syntactically valid structures but may contain logic errors
|
| 402 |
+
|
| 403 |
+
These limitations are standard for base models of this scale and will be addressed in future Instruct/Chat releases.
|
| 404 |
+
|
| 405 |
+
---
|
| 406 |
+
|
| 407 |
+
## 🛣️ Roadmap
|
| 408 |
+
|
| 409 |
+
| Milestone | Status |
|
| 410 |
+
|-----------|--------|
|
| 411 |
+
| 🟡 SOVYTHOS-V2 Base | **In Training (early checkpoint published)** |
|
| 412 |
+
| ⬜ SOVYTHOS-V2 Base (final) | Planned |
|
| 413 |
+
| ⬜ SOVYTHOS-V2-Instruct | Planned |
|
| 414 |
+
| ⬜ SOVYTHOS Chat | Planned |
|
| 415 |
+
| ⬜ Larger Parameter Models (1B+) | Planned |
|
| 416 |
+
| ⬜ Long Context Extension (8K+) | Planned |
|
| 417 |
+
| ⬜ Advanced Reasoning Tuning | Planned |
|
| 418 |
+
| ⬜ Improved Egyptian Dialect Understanding | Planned |
|
| 419 |
+
|
| 420 |
+
---
|
| 421 |
+
|
| 422 |
+
## 🌌 Sovythos AI Project
|
| 423 |
+
|
| 424 |
+
SOVYTHOS-V2 is the flagship foundation model of the **Sovythos AI Project**, an open ecosystem dedicated to building transparent, multilingual language models with **native Arabic support** and modern reasoning capabilities.
|
| 425 |
+
|
| 426 |
+
The project prioritizes:
|
| 427 |
+
- **Sovereignty**: Full training pipeline ownership (data → tokenizer → model → export)
|
| 428 |
+
- **Transparency**: Open weights, open code, open training logs
|
| 429 |
+
- **Accessibility**: GGUF compatibility for edge and consumer hardware
|
| 430 |
+
- **Community**: Research-first releases with clear limitation disclosures
|
| 431 |
+
|
| 432 |
+
---
|
| 433 |
+
|
| 434 |
+
## 📖 Citation
|
| 435 |
+
|
| 436 |
+
If you use SOVYTHOS-V2 in your research, please cite:
|
| 437 |
+
|
| 438 |
+
```bibtex
|
| 439 |
+
@misc{sovythosv2,
|
| 440 |
+
title={SOVYTHOS-V2: Sovythos Egyptian Reasoning and Code Base Model},
|
| 441 |
+
author={Mahmoud Yasser},
|
| 442 |
+
year={2026},
|
| 443 |
+
publisher={Hugging Face},
|
| 444 |
+
howpublished={\url{https://huggingface.co/my0919175/Sovythos-303M-Base}}
|
| 445 |
+
}
|
| 446 |
+
```
|
| 447 |
+
|
| 448 |
+
---
|
| 449 |
+
|
| 450 |
+
## 👨💻 Creator
|
| 451 |
+
|
| 452 |
+
**Mahmoud Yasser**
|
| 453 |
+
|
| 454 |
+
Founder of the **Sovythos AI Project**
|
| 455 |
+
|
| 456 |
+
---
|
| 457 |
+
|
| 458 |
+
## 📄 License
|
| 459 |
+
|
| 460 |
+
**Apache License 2.0**
|
| 461 |
+
|
| 462 |
+
---
|
| 463 |
+
|
| 464 |
+
<p align="center">
|
| 465 |
+
|
| 466 |
+
### 🦋 Welcome to the next chapter of the Sovythos ecosystem.
|
| 467 |
+
|
| 468 |
+
This is an early, actively-training checkpoint shared in the spirit of open, transparent development — not a finished product. Researchers, developers, and builders who believe in open, sovereign AI are welcome to follow along as training progresses.
|
| 469 |
+
|
| 470 |
+
Future checkpoints will bring lower loss, better coherence, instruction tuning, and long-context support.
|
| 471 |
+
|
| 472 |
+
⭐ If you find this project useful, please consider following the repository and sharing your experiments.
|
| 473 |
+
|
| 474 |
+
</p>
|
config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vocab_size": 32000,
|
| 3 |
+
"dim": 1024,
|
| 4 |
+
"n_layers": 24,
|
| 5 |
+
"n_heads": 16,
|
| 6 |
+
"n_kv_heads": 4,
|
| 7 |
+
"max_seq_len": 1024,
|
| 8 |
+
"rope_theta": 1000000.0,
|
| 9 |
+
"norm_eps": 1e-06,
|
| 10 |
+
"ffn_multiple_of": 256,
|
| 11 |
+
"ffn_dim_multiplier": null,
|
| 12 |
+
"tie_embeddings": true,
|
| 13 |
+
"dropout": 0.0,
|
| 14 |
+
"use_grad_checkpoint": true,
|
| 15 |
+
"identity": "SOVYTHOS-V2"
|
| 16 |
+
}
|
configuration_sovythos.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class SovythosConfig(PretrainedConfig):
|
| 4 |
+
model_type = "sovythos"
|
| 5 |
+
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
vocab_size=32000,
|
| 9 |
+
dim=1024,
|
| 10 |
+
n_layers=24,
|
| 11 |
+
n_heads=16,
|
| 12 |
+
n_kv_heads=4,
|
| 13 |
+
max_seq_len=2048,
|
| 14 |
+
rope_theta=1000000.0,
|
| 15 |
+
norm_eps=1e-06,
|
| 16 |
+
ffn_multiple_of=256,
|
| 17 |
+
ffn_dim_multiplier=None,
|
| 18 |
+
tie_embeddings=True,
|
| 19 |
+
dropout=0.0,
|
| 20 |
+
use_grad_checkpoint=False,
|
| 21 |
+
identity="SOVYTHOS-V2",
|
| 22 |
+
bos_token_id=0,
|
| 23 |
+
eos_token_id=0,
|
| 24 |
+
pad_token_id=1,
|
| 25 |
+
**kwargs,
|
| 26 |
+
):
|
| 27 |
+
self.vocab_size = vocab_size
|
| 28 |
+
self.dim = dim
|
| 29 |
+
self.hidden_size = dim
|
| 30 |
+
self.n_layers = n_layers
|
| 31 |
+
self.num_hidden_layers = n_layers
|
| 32 |
+
self.n_heads = n_heads
|
| 33 |
+
self.num_attention_heads = n_heads
|
| 34 |
+
self.n_kv_heads = n_kv_heads
|
| 35 |
+
self.num_key_value_heads = n_kv_heads
|
| 36 |
+
self.max_seq_len = max_seq_len
|
| 37 |
+
self.max_position_embeddings = max_seq_len
|
| 38 |
+
self.rope_theta = rope_theta
|
| 39 |
+
self.norm_eps = norm_eps
|
| 40 |
+
self.rms_norm_eps = norm_eps
|
| 41 |
+
self.ffn_multiple_of = ffn_multiple_of
|
| 42 |
+
self.ffn_dim_multiplier = ffn_dim_multiplier
|
| 43 |
+
self.tie_embeddings = tie_embeddings
|
| 44 |
+
self.dropout = dropout
|
| 45 |
+
self.use_grad_checkpoint = use_grad_checkpoint
|
| 46 |
+
self.identity = identity
|
| 47 |
+
kwargs.pop("tie_word_embeddings", None)
|
| 48 |
+
super().__init__(
|
| 49 |
+
bos_token_id=bos_token_id,
|
| 50 |
+
eos_token_id=eos_token_id,
|
| 51 |
+
pad_token_id=pad_token_id,
|
| 52 |
+
tie_word_embeddings=tie_embeddings,
|
| 53 |
+
**kwargs,
|
| 54 |
+
)
|
generation_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 0,
|
| 3 |
+
"eos_token_id": 0,
|
| 4 |
+
"pad_token_id": 1,
|
| 5 |
+
"do_sample": true,
|
| 6 |
+
"temperature": 0.8,
|
| 7 |
+
"top_k": 40,
|
| 8 |
+
"top_p": 0.9,
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from transformers import PreTrainedModel
|
| 6 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 7 |
+
from .configuration_sovythos import SovythosConfig
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RMSNorm(nn.Module):
|
| 11 |
+
def __init__(self, dim, eps=1e-06):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.eps = eps
|
| 14 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
dtype = x.dtype
|
| 18 |
+
x = x.float()
|
| 19 |
+
rms = x.pow(2).mean(-1, keepdim=True)
|
| 20 |
+
x = x * torch.rsqrt(rms + self.eps)
|
| 21 |
+
return self.weight * x.to(dtype)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def precompute_rope(head_dim, max_seq_len, theta, device, dtype=torch.float32):
|
| 25 |
+
inv_freq = 1.0 / theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)
|
| 26 |
+
t = torch.arange(max_seq_len, device=device).float()
|
| 27 |
+
freqs = torch.outer(t, inv_freq)
|
| 28 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 29 |
+
return emb.cos().to(dtype), emb.sin().to(dtype)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def rotate_half(x):
|
| 33 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 34 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def apply_rope(x, cos, sin, offset=0):
|
| 38 |
+
T = x.shape[-2]
|
| 39 |
+
cos = cos[offset:offset + T][None, None, :, :]
|
| 40 |
+
sin = sin[offset:offset + T][None, None, :, :]
|
| 41 |
+
return x * cos + rotate_half(x) * sin
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def repeat_kv(x, n_rep):
|
| 45 |
+
if n_rep == 1:
|
| 46 |
+
return x
|
| 47 |
+
B, Hkv, T, D = x.shape
|
| 48 |
+
return x[:, :, None, :, :].expand(B, Hkv, n_rep, T, D).reshape(B, Hkv * n_rep, T, D)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Attention(nn.Module):
|
| 52 |
+
def __init__(self, cfg):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.n_heads = cfg.n_heads
|
| 55 |
+
self.n_kv_heads = cfg.n_kv_heads
|
| 56 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
| 57 |
+
self.head_dim = cfg.dim // cfg.n_heads
|
| 58 |
+
self.dropout = cfg.dropout
|
| 59 |
+
self.q_proj = nn.Linear(cfg.dim, cfg.n_heads * self.head_dim, bias=False)
|
| 60 |
+
self.k_proj = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False)
|
| 61 |
+
self.v_proj = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False)
|
| 62 |
+
self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.dim, bias=False)
|
| 63 |
+
self.q_norm = RMSNorm(self.head_dim, cfg.norm_eps)
|
| 64 |
+
self.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)
|
| 65 |
+
|
| 66 |
+
def forward(self, x, cos, sin):
|
| 67 |
+
B, T, C = x.shape
|
| 68 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 69 |
+
k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 70 |
+
v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 71 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 72 |
+
q = apply_rope(q, cos, sin)
|
| 73 |
+
k = apply_rope(k, cos, sin)
|
| 74 |
+
k = repeat_kv(k, self.n_rep)
|
| 75 |
+
v = repeat_kv(v, self.n_rep)
|
| 76 |
+
out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0)
|
| 77 |
+
out = out.transpose(1, 2).contiguous().view(B, T, -1)
|
| 78 |
+
return self.o_proj(out)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class FeedForward(nn.Module):
|
| 82 |
+
def __init__(self, cfg):
|
| 83 |
+
super().__init__()
|
| 84 |
+
hidden = int(2 * (4 * cfg.dim) / 3)
|
| 85 |
+
if cfg.ffn_dim_multiplier is not None:
|
| 86 |
+
hidden = int(cfg.ffn_dim_multiplier * hidden)
|
| 87 |
+
hidden = cfg.ffn_multiple_of * ((hidden + cfg.ffn_multiple_of - 1) // cfg.ffn_multiple_of)
|
| 88 |
+
self.gate_proj = nn.Linear(cfg.dim, hidden, bias=False)
|
| 89 |
+
self.up_proj = nn.Linear(cfg.dim, hidden, bias=False)
|
| 90 |
+
self.down_proj = nn.Linear(hidden, cfg.dim, bias=False)
|
| 91 |
+
|
| 92 |
+
def forward(self, x):
|
| 93 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class DecoderBlock(nn.Module):
|
| 97 |
+
def __init__(self, cfg):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.input_layernorm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 100 |
+
self.self_attn = Attention(cfg)
|
| 101 |
+
self.post_attention_layernorm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 102 |
+
self.mlp = FeedForward(cfg)
|
| 103 |
+
|
| 104 |
+
def forward(self, x, cos, sin):
|
| 105 |
+
x = x + self.self_attn(self.input_layernorm(x), cos, sin)
|
| 106 |
+
x = x + self.mlp(self.post_attention_layernorm(x))
|
| 107 |
+
return x
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class SovythosPreTrainedModel(PreTrainedModel):
|
| 111 |
+
config_class = SovythosConfig
|
| 112 |
+
base_model_prefix = "model"
|
| 113 |
+
supports_gradient_checkpointing = True
|
| 114 |
+
|
| 115 |
+
def _init_weights(self, module):
|
| 116 |
+
if isinstance(module, nn.Linear):
|
| 117 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 118 |
+
if module.bias is not None:
|
| 119 |
+
nn.init.zeros_(module.bias)
|
| 120 |
+
elif isinstance(module, nn.Embedding):
|
| 121 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class SovythosForCausalLM(SovythosPreTrainedModel):
|
| 125 |
+
def __init__(self, config):
|
| 126 |
+
super().__init__(config)
|
| 127 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.dim)
|
| 128 |
+
self.layers = nn.ModuleList([DecoderBlock(config) for _ in range(config.n_layers)])
|
| 129 |
+
self.norm = RMSNorm(config.dim, config.norm_eps)
|
| 130 |
+
self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 131 |
+
if config.tie_embeddings:
|
| 132 |
+
self.lm_head.weight = self.embed_tokens.weight
|
| 133 |
+
self.head_dim = config.dim // config.n_heads
|
| 134 |
+
self._rope_cache = {}
|
| 135 |
+
self.post_init()
|
| 136 |
+
|
| 137 |
+
def get_input_embeddings(self):
|
| 138 |
+
return self.embed_tokens
|
| 139 |
+
|
| 140 |
+
def set_input_embeddings(self, value):
|
| 141 |
+
self.embed_tokens = value
|
| 142 |
+
|
| 143 |
+
def get_output_embeddings(self):
|
| 144 |
+
return self.lm_head
|
| 145 |
+
|
| 146 |
+
def _rope_for(self, device, dtype):
|
| 147 |
+
# ملاحظة: بنحسب rope live بدل ما نعتمد على register_buffer، لأن
|
| 148 |
+
# transformers بيحمل الموديل عادةً عبر meta-device (low_cpu_mem_usage)
|
| 149 |
+
# وأي buffer معمول persistent=False ومش موجود في checkpoint بيفضل
|
| 150 |
+
# ذاكرة غير مهيأة (garbage) بدل القيم الحقيقية بعد النقل من meta لـ real.
|
| 151 |
+
key = str(device)
|
| 152 |
+
if key not in self._rope_cache:
|
| 153 |
+
cos, sin = precompute_rope(self.head_dim, self.config.max_seq_len, self.config.rope_theta, device=device)
|
| 154 |
+
self._rope_cache[key] = (cos, sin)
|
| 155 |
+
return self._rope_cache[key]
|
| 156 |
+
|
| 157 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
|
| 158 |
+
cos, sin = self._rope_for(input_ids.device, torch.float32)
|
| 159 |
+
h = self.embed_tokens(input_ids)
|
| 160 |
+
for layer in self.layers:
|
| 161 |
+
h = layer(h, cos, sin)
|
| 162 |
+
h = self.norm(h)
|
| 163 |
+
logits = self.lm_head(h)
|
| 164 |
+
loss = None
|
| 165 |
+
if labels is not None:
|
| 166 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 167 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 168 |
+
loss = F.cross_entropy(
|
| 169 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 170 |
+
shift_labels.view(-1),
|
| 171 |
+
ignore_index=-100,
|
| 172 |
+
)
|
| 173 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits)
|
| 174 |
+
|
| 175 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 176 |
+
return {"input_ids": input_ids}
|
sovythos.png
ADDED
|
Git LFS Details
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "<|endoftext|>",
|
| 3 |
+
"eos_token": "<|endoftext|>",
|
| 4 |
+
"unk_token": "<|endoftext|>",
|
| 5 |
+
"pad_token": "<|pad|>",
|
| 6 |
+
"additional_special_tokens": [
|
| 7 |
+
"<|user|>",
|
| 8 |
+
"<|assistant|>",
|
| 9 |
+
"<|system|>",
|
| 10 |
+
"<|code|>",
|
| 11 |
+
"<|/code|>",
|
| 12 |
+
"<|think|>",
|
| 13 |
+
"<|/think|>",
|
| 14 |
+
"<|egy|>",
|
| 15 |
+
"<|msa|>",
|
| 16 |
+
"<|en|>"
|
| 17 |
+
]
|
| 18 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"model_max_length": 2048,
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"bos_token": "<|endoftext|>",
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"unk_token": "<|endoftext|>",
|
| 8 |
+
"pad_token": "<|pad|>",
|
| 9 |
+
"added_tokens_decoder": {
|
| 10 |
+
"0": {"content": "<|endoftext|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 11 |
+
"1": {"content": "<|pad|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 12 |
+
"2": {"content": "<|user|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 13 |
+
"3": {"content": "<|assistant|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 14 |
+
"4": {"content": "<|system|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 15 |
+
"5": {"content": "<|code|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 16 |
+
"6": {"content": "<|/code|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 17 |
+
"7": {"content": "<|think|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 18 |
+
"8": {"content": "<|/think|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 19 |
+
"9": {"content": "<|egy|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 20 |
+
"10": {"content": "<|msa|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
|
| 21 |
+
"11": {"content": "<|en|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
|
| 22 |
+
},
|
| 23 |
+
"chat_template": "{% for message in messages %}{% if message['role'] == 'system' %}{{ '<|system|>\n' + message['content'] + '\n' }}{% elif message['role'] == 'user' %}{{ '<|user|>\n' + message['content'] + '\n' }}{% elif message['role'] == 'assistant' %}{{ '<|assistant|>\n' + message['content'] + '<|endoftext|>\n' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% endif %}"
|
| 24 |
+
}
|