Views
No views yet
| Feature | Value |
|---|---|
| Algorithm | Unigram Language Model |
| Vocabulary Size | 32,000 tokens |
| Character Coverage | 99.95% |
| Script Support | Ge'ez (U+1200-U+137F) + Universal |
| Model Type | Probabilistic subword |
| OOV Handling | Excellent (character fallback) |
1{
2 "<unk>": 0, # Unknown token
3 "<s>": 1, # Beginning of sequence (BOS)
4 "</s>": 2, # End of sequence (EOS)
5 "<pad>": 3, # Padding token
6 "<mask>": 4, # Mask token (for MLM)
7}1import sentencepiece as spm
2
3# Load the SentencePiece model
4sp = spm.SentencePieceProcessor()
5sp.load("./sentencepiece.model")
6
7# Tokenize Tigrinya text
8text = "ሰላም! ከመይ ኣሎኻ? ሎምስ እንታይ ገይርካ?"
9
10# Get token IDs
11token_ids = sp.encode_as_ids(text)
12print(f"Token IDs: {token_ids}")
13
14# Get token pieces
15pieces = sp.encode_as_pieces(text)
16print(f"Pieces: {pieces}")
17
18# Decode back to text
19decoded = sp.decode_ids(token_ids)
20print(f"Decoded: {decoded}")1from transformers import LlamaTokenizer
2
3# Load as HuggingFace tokenizer (Llama-style)
4tokenizer = LlamaTokenizer.from_pretrained("./")
5
6# Use with transformers
7text = "ሰላም! ከመይ ኣሎኻ?"
8encoded = tokenizer(text, return_tensors="pt")
9print(f"Input IDs: {encoded['input_ids']}")
10print(f"Attention mask: {encoded['attention_mask']}")1from transformers import (
2 LlamaTokenizer,
3 LlamaForCausalLM,
4 TrainingArguments,
5 Trainer
6)
7
8# Load tokenizer
9tokenizer = LlamaTokenizer.from_pretrained("./")
10
11# Initialize model with correct vocab size
12vocab_size = len(tokenizer) # 32,000
13config = LlamaConfig(vocab_size=vocab_size)
14model = LlamaForCausalLM(config)
15
16# Tokenization function for datasets
17def tokenize_function(examples):
18 return tokenizer(
19 examples["text"],
20 padding=True,
21 truncation=True,
22 max_length=2048, # Longer sequences supported
23 return_tensors="pt"
24 )Original: ሰላም! ከመይ ኣሎኻ?
Pieces: ['▁ሰላ', 'ም', '!', '▁ከ', 'መይ', '▁ኣ', 'ሎ', 'ኻ', '?']
Token IDs: [1, 234, 567, 12, 890, 123, 456, 789, 13]
Token count: 9Original: ሎሚ ጽቡቕ መዓልቲ እዩ። ናብ ቤት ትምህርቲ ክኸይድ እየ።
Pieces: ['▁ሎ', 'ሚ', '▁ጽ', 'ቡ', 'ቕ', '▁መ', 'ዓል', 'ቲ', '▁እዩ', '።', '▁ና', 'ብ', '▁ቤት', '▁ትም', 'ህር', 'ቲ', '▁ክ', 'ከይ', 'ድ', '▁እየ', '།']
Token count: 21Original: Hello ሰላም! Computer ኮምፒዩተర 123
Pieces: ['▁Hello', '▁ሰላ', 'ም', '!', '▁Computer', '▁ኮ', 'ም', 'ፒ', 'ዩ', 'ተ', 'ር', '▁1', '2', '3']
Token count: 14tigrinya_sentencepiece_tokenizer/
├── sentencepiece.model # Main SentencePiece model
├── sentencepiece.vocab # Vocabulary file
├── tokenizer_config.json # HuggingFace config
└── README.md # This file1import sentencepiece as spm
2
3# Load model
4sp = spm.SentencePieceProcessor()
5sp.load("./sentencepiece.model")
6
7# Advanced tokenization options
8text = "ሰላም! ሎሚ ጽቡቕ መዓልቲ እዩ።"
9
10# Control output format
11ids = sp.encode_as_ids(text)
12pieces = sp.encode_as_pieces(text)
13proto = sp.encode_as_serialized_proto(text)
14
15# Sampling-based tokenization (for data augmentation)
16sampled_ids = sp.sample_encode_as_ids(text, nbest_size=-1, alpha=0.1)
17print(f"Sampled tokenization: {sampled_ids}")
18
19# Vocabulary information
20vocab_size = sp.get_piece_size()
21print(f"Vocabulary size: {vocab_size}")
22
23# Get piece information
24for i in range(min(20, vocab_size)):
25 piece = sp.id_to_piece(i)
26 score = sp.get_score(i)
27 print(f"ID {i}: '{piece}' (score: {score:.4f})")1# Efficient batch processing
2texts = [
3 "ሰላም ኣለኻ",
4 "ከመይ ዘሎኻ?",
5 "ሎሚ እንታይ ገይርካ?",
6 "ጽቡቕ መዓልቲ እዩ።"
7]
8
9# Batch encode
10batch_ids = [sp.encode_as_ids(text) for text in texts]
11batch_pieces = [sp.encode_as_pieces(text) for text in texts]
12
13print(f"Batch token counts: {[len(ids) for ids in batch_ids]}")1# Advanced text preprocessing for Tigrinya
2import unicodedata
3
4def preprocess_tigrinya_text(text):
5 # Unicode normalization (NFD)
6 text = unicodedata.normalize('NFD', text)
7
8 # Custom Tigrinya preprocessing
9 # Add any domain-specific cleaning here
10
11 return text
12
13# Apply preprocessing
14text = "ሰላም! ከመይ ኣሎኻ?"
15processed = preprocess_tigrinya_text(text)
16tokens = sp.encode_as_pieces(processed)1# From the main project directory
2python train_tigrinya_sentencepiece.py
3
4# Or using the unified interface
5python train_tokenizers.py --type sentencepiece1import sentencepiece as spm
2
3# Train custom SentencePiece model
4spm.SentencePieceTrainer.train(
5 input='data/tlmd.txt',
6 model_prefix='custom_tigrinya',
7 vocab_size=32000,
8 character_coverage=0.9995,
9 model_type='unigram',
10 max_sentence_length=4096,
11 shuffle_input_sentence=True,
12
13 # Special tokens
14 bos_id=1, eos_id=2, unk_id=0, pad_id=3,
15 bos_piece='<s>', eos_piece='</s>', unk_piece='<unk>', pad_piece='<pad>',
16
17 # Additional special tokens
18 user_defined_symbols=['<mask>'],
19
20 # Training parameters
21 num_threads=8,
22 split_by_unicode_script=True,
23 split_by_whitespace=True,
24 split_digits=True,
25 treat_whitespace_as_suffix=False,
26 allow_whitespace_only_pieces=True,
27
28 # Normalization
29 normalization_rule_name='nfkc',
30 remove_extra_whitespaces=True,
31 input_sentence_size=10000000,
32 mining_sentence_size=10000000,
33)1# Memory-efficient loading
2import sentencepiece as spm
3
4# Load with memory optimization
5sp = spm.SentencePieceProcessor()
6sp.load("./sentencepiece.model")
7
8# Enable parallel processing for batch inference
9sp.set_vocabulary_size(32000) # Optional: limit vocabulary
10
11# Use with multiprocessing
12from multiprocessing import Pool
13
14def tokenize_batch(texts):
15 sp_local = spm.SentencePieceProcessor()
16 sp_local.load("./sentencepiece.model")
17 return [sp_local.encode_as_ids(text) for text in texts]
18
19# Parallel processing
20with Pool(4) as pool:
21 results = pool.map(tokenize_batch, text_batches)1// C++ integration example
2#include "sentencepiece_processor.h"
3
4sentencepiece::SentencePieceProcessor processor;
5processor.Load("tigrinya_sentencepiece_tokenizer/sentencepiece.model");
6
7std::string text = "ሰላም! ከመይ ኣሎኻ?";
8std::vector<int> ids;
9processor.Encode(text, &ids);1from vllm import LLM, SamplingParams
2
3# Configure vLLM with custom tokenizer
4llm = LLM(
5 model="your_tigrinya_model",
6 tokenizer="./tigrinya_sentencepiece_tokenizer/",
7 tokenizer_mode="slow" # Use SentencePiece directly
8)
9
10# Generate text
11prompts = ["ሰላም! ሎሚ"]
12sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
13outputs = llm.generate(prompts, sampling_params)1# Evaluate tokenization quality
2def evaluate_tokenization_quality(texts, sp_model):
3 total_chars = sum(len(text) for text in texts)
4 total_tokens = sum(len(sp_model.encode_as_ids(text)) for text in texts)
5
6 compression_ratio = total_chars / total_tokens
7 avg_tokens_per_text = total_tokens / len(texts)
8
9 # Character coverage
10 vocab_chars = set()
11 for i in range(sp_model.get_piece_size()):
12 piece = sp_model.id_to_piece(i)
13 vocab_chars.update(piece.replace('▁', ''))
14
15 text_chars = set(''.join(texts))
16 coverage = len(vocab_chars & text_chars) / len(text_chars)
17
18 return {
19 'compression_ratio': compression_ratio,
20 'avg_tokens_per_text': avg_tokens_per_text,
21 'character_coverage': coverage
22 }
23
24# Test quality
25test_texts = [
26 "ሰላም! ከመይ ኣሎኻ?",
27 "ሎሚ ጽቡቕ መዓልቲ እዩ።",
28 "ናብ ቤት ትምህርቲ ክኸይድ እየ።"
29]
30
31quality_metrics = evaluate_tokenization_quality(test_texts, sp)
32print(f"Quality metrics: {quality_metrics}")1# Optimize for speed
2import sentencepiece as spm
3
4sp = spm.SentencePieceProcessor()
5sp.load("./sentencepiece.model")
6
7# Pre-compile for better performance
8sp.set_encode_extra_options("bos:eos") # Add BOS/EOS by default
9
10# Use appropriate data types
11text = "ሰላም! ከመይ ኣሎኻ?"
12ids = sp.encode_as_ids(text) # Faster than pieces for training1@misc{tigrinya_sentencepiece_tokenizer,
2 title={Tigrinya SentencePiece Tokenizer for LLM Training},
3 year={2024},
4 publisher={GitHub},
5 howpublished={\url{https://github.com/mewaeltsegay/tokenizer}}
6}1import sentencepiece as spm
2sp = spm.SentencePieceProcessor()
3sp.load("./sentencepiece.model")