A SentencePiece Unigram tokenizer and lightweight Python SDK purpose-built for Sindhi.
pip install sindhi-tokenizer Copy PIP instructions
A subword tokenizer purpose-built for the Sindhi language (سنڌي) in the Perso-Arabic script. Trained with SentencePiece Unigram with full observed-character coverage and byte-level fallback on 1.46M+ sentences. It was benchmarked against 14 baseline tokenizers across four evaluation registers. The benchmark has 18 entries: 14 baseline entries and four custom vocabulary sizes. Qwen2.5 and SindhiLM_v2 are identical in this evaluation, so the entries represent 17 distinct tokenizer behaviors. The round-trip check reports 0.0000% normalized-length loss on evaluated text; this does not establish exact identity for arbitrary input.
Sindhi is an Indo-Aryan language spoken by an estimated 25–30 million people, predominantly in the Sindh province of Pakistan and parts of India. Despite its rich literary heritage, Sindhi remains a severely under-resourced language in Natural Language Processing (NLP).
Existing modern Large Language Models (LLMs) and multilingual tokenizers (such as XLM-RoBERTa, LLaMA, Qwen, and BLOOM) under-represent Sindhi orthography, causing high token fertility, extreme sequence bloat, out-of-vocabulary (UNK) fallbacks, or destructive character drops.
Sindhi uses a 52-letter extended Perso-Arabic alphabet containing implosive consonants (ٻ, ڄ, ڏ, ڳ), aspirated digraphs (ڀ, ٿ, ڇ, ٺ), retroflex consonants (including ڻ), and specialized diacritics. General Arabic or Urdu tokenizers frequently split these single graphemes into multi-byte fallback sequences, dramatically inflating token counts.
When a tokenizer splits a single word into 3–5 subword fragments, context window efficiency drops proportionally. A 2048-token context window accommodates only ~707 Sindhi words under LLaMA 3.2 (fertility 2.896) or ~1,354 words under XLM-RoBERTa (1.512), compared to ~1,786 Sindhi words under CustomSindhi_64k (1.147).
Standard tokenizer benchmarks often report token fertility and UNK rate without checking decoded output. During this project's audit, a normalized-length round-trip check, followed by inspection of affected examples, surfaced text-shortening defects in existing tokenizers:
sindhi-tokenizer/ ├── .github/ │ └── workflows/ │ └── python-tests.yml # Automated CI workflow testing Python 3.9-3.12 ├── .gitignore # Excludes models, artifacts, cache, and virtualenvs ├── CITATION.cff # Citation File Format (v1.2.0) ├── DATA_SOURCES.md # Complete provenance, volume, and licensing documentation ├── LICENSE # MIT Open Source License ├── README.md # Central documentation index and project guide ├── pyproject.toml # PEP 517/621 package metadata and dependency configuration ├── requirements.txt # Exact runtime dependencies ├── demo/ │ ├── README.md # Instructions for running and deploying the demo │ └── app.py # Interactive Gradio comparison web app ├── docs/ │ ├── paper.md # Draft research manuscript, not yet published (14-baseline study) │ └── explainer.md # 21-page technical companion log and negative results ├── evaluation/ │ ├── README.md # Evaluation metrics guide and CLI/API documentation │ ├── __init__.py # Package initialization │ └── metrics.py # Fertility, single-token, UNK, byte-fallback, and fidelity engine ├── notebooks/ │ ├── README.md # Reproducible notebook guide │ ├── training.ipynb # Kaggle/Jupyter notebook: corpus download, split & training │ └── benchmark.ipynb # Kaggle/Jupyter notebook: 18-tokenizer evaluation suite ├── results/ │ └── README.md # Benchmark tables and summary report across 4 registers └── training/ ├── README.md # Training recipes, regex splitters, and negative results ├── __init__.py # Package initialization └── train_tokenizer.py # Standalone training script with optimal SentencePiece parameters Architecture and Workflow Diagrams 1. End-to-End System Architecture flowchart TD subgraph Data_Pipeline["1. Corpus Assembly & Preprocessing"] A1["Sindhi Wikipedia
(6,000 articles)"] --> P["Sentence Extraction & Cleaning
Drop fragments of 3 characters or fewer"] A2["Sindhi-NLP Dataset
(Twitter + Kawish + Awami Awaz)"] --> P A3["shaikhsalman Corpus
(20k rows, no language filter)"] --> P A4["Multilingual Regional Anchor
(Urdu, Persian, Arabic, repeated ×4, 16.1% of characters)"] --> P P --> C["Balanced Training Corpus
(1.46M+ Sentences)"] end subgraph Training_Engine["2. Model Training (SentencePiece)"] C --> SP["SentencePiece Unigram Trainer
split_by_whitespace=True"] SP --> M1["Custom 32k Model"] SP --> M2["Custom 64k Model (Flagship)"] SP --> M3["Custom 100k Model"] SP --> M4["Custom 150k Model"] end subgraph Evaluation_Suite["3. Rigorous Evaluation Engine"] M2 --> E["evaluation/metrics.py"] REG1["FLORES+ (snd_Arab)"] --> E REG2["Wikipedia Formal (25.4k sent)"] --> E REG3["Sentiment Informal (3.5k sent)"] --> E REG4["Sindh Line News (87.1k sent)"] --> E E --> MET["Metrics Computed:
• Normalized-Length Loss (0.000%)"] end subgraph Downstream["4. Downstream Deployment"] M2 --> HF["Hugging Face Hub
alinawazmahar/sindhi-tokenizer"] M2 --> GR["Interactive Gradio Demo
demo/app.py"] M2 --> LLM["Sindhi LLM Pretraining & NLP"] end 2. Text Encoding and Round-Trip Fidelity Flow sequenceDiagram autonumber participant Input as Raw Sindhi Text participant Norm as NFKC & Formatting Normalizer participant Tokenizer as SPMTokenizerAdapter participant Tokens as Subword Tokens / Byte IDs participant Output as Decoded Reconstructed Text participant Audit as Normalized-Length Check Input->>Norm: Normalize Unicode (NFKC) & remove zero-width formatting Norm->>Tokenizer: Clean text string Tokenizer->>Tokens: Encode via Unigram Viterbi path (out_type=int) Tokens->>Output: Decode token IDs back to string Output->>Audit: Compare Original vs Decoded Note over Audit: Loss = max(0, input_length - decoded_length) / input_length
Custom Model Result: 0.0000% normalized-length loss Dataset Documentation Training and evaluation records are separated where known, but the sentiment evaluation set shares publisher-adjacent provenance with a training source. See DATA_SOURCES.md for source details and licensing status.
Byte-Pair Encoding (BPE) merges the most frequent character pairs iteratively. In morphologically complex, agglutinative, or clitic-heavy languages like Sindhi, greedy merges frequently fuse grammatical suffixes onto root stems incorrectly.
The Unigram language model algorithm (Kudo, 2018) initializes an oversized vocabulary and optimizes subword segmentation using maximum likelihood:
$$P(X) = \max_{\mathbf{x} \in S(X)} \prod_{i=1}^{M} P(x_i)$$
This statistically discovers true morphological subwords while optimizing whole-sequence likelihood.
Consider the authentic Sindhi phrase: $$\text{خداوند ڪريم کيس اعليٰ ذهانت سان نوازيو هو}$$ (The Almighty Lord had blessed him with high intellect)
[' خداوند', ' ڪريم', ' کيس', ' اعليٰ', ' ذهانت', ' سان', ' نوازيو', ' هو'] Token ID Mapping: [12450, 4812, 1089, 7543, 14210, 521, 18920, 412] Round-trip check: Evaluated text showed 0.0000% normalized-length loss. This length-based check can miss equal-length substitutions or reorderings. Training Pipeline & Negative Results 1. Training Parameters (training/train_tokenizer.py) python training/train_tokenizer.py \ --corpus corpus.txt \ --vocab_size 64000 \ --model_prefix models/sindhi_custom_64000 model_type="unigram" character_coverage=1.0 (Ensures every single observed Unicode character is covered) byte_fallback=True (Unknown characters fall back to raw byte tokens ) split_by_whitespace=True unk_id=0, bos_id=1, eos_id=2, pad_id=-1 2. Documented Negative Results (What Failed and Why) In accordance with rigorous research standards, two negative experimental results are preserved in docs/explainer.md:
Requires Python 3.9 or newer. The SDK only installs SentencePiece and the Hugging Face Hub client; training and demo dependencies are optional.
pip install sindhi-tokenizer Quickstart from sindhi_tokenizer import SindhiTokenizer # Downloads the recommended 64k model once, then reuses the Hub cache. tokenizer = SindhiTokenizer.from_pretrained() text = "سنڌ جي تاريخ تمام قديم آهي" pieces = tokenizer.tokenize(text) token_ids = tokenizer.encode(text) print("Pieces:", pieces) print("Token IDs:", token_ids) print("Decoded:", tokenizer.decode(token_ids)) print("Vocabulary size:", tokenizer.vocab_size) # 64000 Choose another released vocabulary with vocab_size=32000, 100000, or 150000. You can also load a local .model file with SindhiTokenizer.from_file(path). Batch methods are encode_batch() and decode_batch().
To work on the repository and its training/demo tools:
git clone https://github.com/alinawazcode/sindhi-tokenizer.git cd sindhi-tokenizer pip install -e ".[dev,training,demo]" The model download is cached by Hugging Face Hub. The SDK code is MIT licensed; the model files are separately licensed under CC BY-SA 4.0. Review the model card for attribution and sharing terms before redistributing model files.
All 18 benchmark entries were evaluated across the four evaluation registers without subsampling. SindhiLM_v2 is identical to Qwen2.5 for this evaluation; the entries therefore represent 17 distinct tokenizer behaviors.
* TinyLlama_Sindhi and FahadQazi_BPE show apparent 0.000% UNK rates because both models silently delete unsupported characters rather than emitting a UNK token. FahadQazi_BPE shows real, severe character loss on round-trip fidelity testing alongside high byte-fallback. SindhiLM_v2 is numerically identical to Qwen2.5 across all metrics; both are listed in the table for completeness.
To verify that vocabulary expansion did not simply overfit high-frequency substrings, all tokenizers were evaluated on a targeted 22-word linguistic test suite spanning four distinct categories:
Note: As documented in the paper (§6), the tokenizer is designed for textual NLP representation; downstream task-specific fine-tuning (e.g. BLEU/ROUGE benchmarks) represents intended future work.
In accordance with rigorous academic transparency (see docs/paper.md §6), ten limitations are explicitly recorded:
Note: For the complete list of 21 baseline model citations and references, please refer to docs/paper.md.
This research and tokenizer implementation were developed at the Department of Computer Science, Shaikh Ayaz University, Shikarpur, Pakistan, under the supervision of Dr. Attaullah Sahito (academic supervisor, not an author).
If you use this tokenizer, benchmark code, or findings in your academic research or applications, please cite:
@misc{nawaz2026sindhitokenizer, author = {Nawaz, Ali and Fareed, Muqadas and Sadaf, Soonh}, title = {A Corpus-Driven Sindhi Subword Tokenizer: Design, Empirical Validation, and Benchmark Comparison Against Fourteen Existing Tokenizers}, year = {2026}, howpublished = {\url{https://github.com/alinawazcode/sindhi-tokenizer}}, note = {Department of Computer Science, Shaikh Ayaz University, Shikarpur, Pakistan} } Frequently Asked Questions (FAQ) 1. Why choose the 64k model over 32k or 150k? The 64,000 vocabulary size represents the empirical sweet spot between fertility efficiency (1.147 tokens/word) and embedding matrix parameter overhead. Scaling to 100k or 150k provides marginal fertility gains (1.133 and 1.125 respectively) but more than doubles the vocabulary table size, while the 32k model exhibits one minor loss on the standardized FLORES+ benchmark. 2. What does the round-trip length check measure? It applies Unicode NFKC, removes zero-width formatting characters and whitespace, then compares normalized input and decoded-output lengths. This detects shortening but can miss substitutions or reorderings that preserve length; 0.0000% is not proof of exact text identity. 3. Why is there a 15% mix of Urdu, Persian, and Arabic in the training corpus? Sindhi shares the Perso-Arabic alphabet and borrows significant religious, legal, and cultural vocabulary from Arabic and Persian, as well as shared regional terms with Urdu. This anchor (16.1% of characters, from 89,449 unique sentences repeated four times) was added by design to expose the subword vocabulary to shared Perso-Arabic root morphemes. 4. Why should I avoid transformers.LlamaTokenizer for loading this model? Certain versions of Hugging Face Transformers' LlamaTokenizer fail to load custom SentencePiece Unigram models correctly, silently substituting an empty or 3-token fallback vocabulary without throwing an exception. Always use sentencepiece.SentencePieceProcessor directly or via our verified SPMTokenizerAdapter. Project links Data verified by PyPI on Nov 14, 2026 Data provided by the project maintainers, verified at the time the release was uploaded to PyPI. Homepage Repository Models Key dates PyPI data Data sourced directly from PyPI's database. Released: Nov 14, 2026 Latest release 1 maintainer PyPI data Data sourced directly from PyPI's database. alinawazcode Credits Author: Ali Nawaz, Muqadas Fareed, Soonh Sadaf
Both files in this release have provenance metadata.
sindhi tokenizer sentencepiece unigram nlp low-resource-languages
Author: Ali Nawaz, Muqadas Fareed, Soonh Sadaf
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.
Both files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




