File size: 7,473 Bytes
df867d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cce5e4
df867d1
0cce5e4
df867d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdc9ccd
 
df867d1
 
fdc9ccd
 
 
df867d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d681ea8
 
df867d1
 
 
0344dd8
df867d1
0344dd8
df867d1
 
 
 
 
 
0344dd8
 
df867d1
 
 
 
 
 
 
 
 
 
 
bb4c669
0344dd8
df867d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# EthioBBPE

A robust, production-ready Byte-Level BPE (BBPE) tokenizer training environment built with Hugging Face's `tokenizers` library. EthioBBPE provides a flexible framework for training high-quality tokenizers on any text corpus with advanced features like checkpointing and compressed storage.

## ✨ Features

- **Byte-Level Encoding**: Handles any Unicode character seamlessly, eliminating unknown token (`<unk>`) issues.
- **End-to-End Pipeline**: From raw text corpus to a ready-to-use `tokenizer.json`.
- **Hugging Face Compatible**: Directly usable with `transformers` models.
- **Flexible Configuration**: Customize vocabulary size, minimum frequency, and special tokens.
- **Multi-Format Support**: Train on `.txt`, `.json`, `.jsonl`, or `.parquet` datasets.
- **Production Ready**: 
  - ✅ Automatic checkpointing for fault-tolerant training
  - ✅ Gzip compression for efficient storage (~60% space savings)
  - ✅ Structured logging with progress tracking
  - ✅ Auto-generated model cards for Hugging Face Hub

## 📦 Installation

```bash
pip install -r requirements.txt
```

## 🚀 Quick Start

### Option A: One-Command Training (Recommended for Amharic Bible Datasets)

If you have the Synaxarium and Canon Biblical datasets in `data/`:

```bash
# Run the complete pipeline
./run_training.sh
```

Or manually:

```bash
# Step 1: Prepare datasets from parquet files
python scripts/prepare_datasets.py --output_dir ./data

# Step 2: Train with advanced features
python scripts/train_tokenizer.py \
    --data_dir ./data \
    --vocab_size 8000 \
    --model_name EthioBBPE_AmharicBible \
    --compression_format gzip \
    --compression_level 9 \
    --enable_quantization \
    --quantization_bits 8 \
    --max_checkpoints 3
```

### Option B: Standard Training

### 1. Prepare Your Data

Place your training corpus in the `data/` directory. Supported formats: `.txt`, `.json`, `.jsonl`, `.parquet`

For parquet files, use the data preparation script:
```bash
python scripts/prepare_data.py --data_dir ./data --output ./data/training_corpus.txt
```

### 2. Train the Tokenizer

**Using CLI:**
```bash
python scripts/train_tokenizer.py \
    --data_dir ./data \
    --model_name EthioBBPE \
    --vocab_size 30000 \
    --min_frequency 2
```

**Advanced Options:**
```bash
python scripts/train_tokenizer.py \
    --data_dir ./data \
    --model_name EthioBBPE \
    --vocab_size 32000 \
    --min_frequency 2 \
    --special_tokens "<pad>" "<unk>" "<s>" "</s>" "<mask>" \
    --use_checkpoint \
    --checkpoint_dir ./models/checkpoints \
    --save_compressed
```

**Using Python API:**
```python
from scripts.bbpe_trainer import BBPEConfig, EthioBBPETrainer

# Configure
config = BBPEConfig(
    vocab_size=32000,
    min_frequency=2,
    show_progress=True,
    special_tokens=["<pad>", "<unk>", "<s>", "</s>", "<mask>"],
    use_checkpoint=True,
    save_compressed=True
)

trainer = EthioBBPETrainer(config=config)
trainer.train()  # Uses config.data_dir automatically
trainer.save()   # Uses config.model_name automatically

# Test it
text = "Hello world! This is a test."
tokens = trainer.tokenize(text)
print(f"Tokens: {tokens}")
```

### 3. Load and Use

```python
from tokenizers import Tokenizer

# Load the trained tokenizer
tokenizer = Tokenizer.from_file("models/EthioBBPE/tokenizer.json")

# Encode
encoded = tokenizer.encode("Hello world this is a test")
print(encoded.ids)
print(encoded.tokens)

# Decode
decoded = tokenizer.decode(encoded.ids)
print(decoded)
```

## 🏗️ Architecture

The `EthioBBPE` architecture follows these steps:
1. **Pre-tokenization**: Splits text into words while preserving byte-level integrity.
2. **Byte Conversion**: Converts all characters into their byte representations.
3. **BPE Training**: Learns merge operations based on frequency in the corpus.
4. **Vocabulary Creation**: Generates a fixed-size vocabulary of byte-level tokens.
5. **Compression** (optional): Applies gzip compression to vocabulary for efficient storage.

## 📂 Project Structure

```text
Ethio_BBPE/
├── data/                       # Raw training data
│   ├── *.parquet              # Parquet datasets
│   └── training_corpus.txt    # Prepared training corpus
├── models/                     # Output directory for trained models
│   ├── EthioBBPE/             # Trained tokenizer
│   │   ├── tokenizer.json     # Main tokenizer file
│   │   ├── vocab.json.gz      # Compressed vocabulary
│   │   ├── config.json        # Training configuration
│   │   └── README.md          # Model card
│   └── checkpoints/           # Training checkpoints
├── scripts/
│   ├── bbpe_trainer.py        # Core logic (BBPEConfig, EthioBBPETrainer)
│   ├── train_tokenizer.py     # CLI entry point
│   ├── prepare_data.py        # Data preparation from parquet
│   └── example_usage.py       # Usage examples
├── requirements.txt           # Dependencies
└── README.md                  # This file
```

## 🔧 Advanced Features

### Checkpointing
Automatically saves training progress and can resume from the latest checkpoint:
```bash
python scripts/train_tokenizer.py --use_checkpoint --checkpoint_dir ./checkpoints
```

### Compression
Saves vocabulary in gzip format, reducing storage by ~60%:
```bash
python scripts/train_tokenizer.py --save_compressed
```

Output includes both standard `tokenizer.json` and compressed `vocab.json.gz`.

### Custom Special Tokens
Define custom special tokens for your use case:
```bash
python scripts/train_tokenizer.py --special_tokens "<pad>" "<unk>" "<s>" "</s>"
```

## 🤗 Hugging Face Hub Integration

### Loading from Hub
```python
from transformers import AutoTokenizer

# Load directly from the Hub
tokenizer = AutoTokenizer.from_pretrained("Nexuss0781/Ethio-BBPE")

# Encode text
output = tokenizer.encode("Hello world this is a test")
print(output.tokens)
```

### Uploading Your Own Trained Model
```python
from huggingface_hub import HfApi

api = HfApi()
api.upload_folder(
    folder_path="./models/EthioBBPE",
    repo_id="your-username/your-repo-name",
    repo_type="model",
    token="YOUR_HF_TOKEN"
)
```

## 📊 Training Statistics & Metrics

### Final Model Performance

**Training Configuration:**
- **Vocabulary Size**: 32,000
- **Minimum Frequency**: 2
- **Special Tokens**: [PAD], [UNK], [CLS], [SEP], [MASK]
- **Checkpointing**: Enabled
- **Compression**: Enabled (Gzip)

**Dataset:**
- **Sources**: Synaxarium + Biblical Amharic-English datasets
- **Training Samples**: 61,576 texts
- **Total Characters**: 6,789,143

**Test Results (Amharic Text):**
| Test Sample | Input Length | Tokens Generated | Perfect Reconstruction |
|-------------|--------------|------------------|------------------------|
| Special chars (፠፠፠...) | 18 | 1 | ✅ YES |
| Classical text | 124 | 58 | ✅ YES |
| Mixed content | 35 | 7 | ✅ YES |
| Long paragraph | 241 | 68 | ✅ YES |

**Overall Metrics:**
- **Total Characters Tested**: 418
- **Total Tokens Generated**: 134
- **Average Characters per Token**: 3.12
- **Perfect Reconstruction Rate**: 100% ✅

**Storage Efficiency:**
- **Uncompressed Vocab**: ~3.8 MB
- **Compressed Vocab (.gz)**: ~1.5 MB
- **Space Saved**: ~60%

### Training Log
See `training_log.txt` for detailed training output. Metrics saved in `models/EthioBBPE/training_metrics.json`.

## 📄 License

MIT License