Text Generation
Transformers
Safetensors
Sanskrit
sansar
sanskrit
devanagari
slp1
causal-lm
base-model
custom_code
Eval Results (legacy)
Instructions to use MuseMesh/sansar-20m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MuseMesh/sansar-20m with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="MuseMesh/sansar-20m", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("MuseMesh/sansar-20m", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use MuseMesh/sansar-20m with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "MuseMesh/sansar-20m" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MuseMesh/sansar-20m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/MuseMesh/sansar-20m
- SGLang
How to use MuseMesh/sansar-20m with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "MuseMesh/sansar-20m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MuseMesh/sansar-20m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "MuseMesh/sansar-20m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MuseMesh/sansar-20m", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use MuseMesh/sansar-20m with Docker Model Runner:
docker model run hf.co/MuseMesh/sansar-20m
v0.1.0: tokv3_v01_d20m (ex-Gita 0.7177)
Browse files- CHANGELOG.md +9 -0
- LICENSE +11 -0
- LICENSE-CODE +4 -0
- README.md +235 -0
- config.json +35 -0
- configuration_sansar.py +79 -0
- eval/bpb.json +83 -0
- eval/smoke_test.json +35 -0
- eval/verification.json +120 -0
- eval/verse_scores.json +57 -0
- generation_config.json +10 -0
- model.safetensors +3 -0
- modeling_sansar.py +280 -0
- special_tokens_map.json +6 -0
- tokenization_sansar.py +125 -0
- tokenizer.model +3 -0
- tokenizer_config.json +16 -0
- training/data_meta.json +144 -0
- training/summary.json +144 -0
- translit.py +549 -0
CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Changelog
|
| 2 |
+
|
| 3 |
+
Versions are git tags on this repository (`v0.1.0`, ...). Load a fixed version with `from_pretrained("MuseMesh/sansar-20m", revision="v0.1.0", trust_remote_code=True)`.
|
| 4 |
+
|
| 5 |
+
## v0.1.0 (2026-10-02)
|
| 6 |
+
|
| 7 |
+
- Weights of training run `tokv3_v01_d20m` (experiment TOK-v3 screen, arm v0.1: the released tokenizer, F4 recipe at d20m), step 6,968, 0.34B tokens.
|
| 8 |
+
- Held-out ex-Gītā 0.7177 bits per Devanagari byte.
|
| 9 |
+
- First release of this size. Tokenizer: sansar-sanskrit-tokenizer v0.1.0 (bundled).
|
LICENSE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The model weights (model.safetensors) and the tokenizer model (tokenizer.model) in this repository are
|
| 2 |
+
licensed under the Creative Commons Attribution-NonCommercial 4.0 International licence (CC BY-NC 4.0):
|
| 3 |
+
https://creativecommons.org/licenses/by-nc/4.0/
|
| 4 |
+
|
| 5 |
+
You may use, share and adapt them for non-commercial purposes (research, teaching, non-profit work) with
|
| 6 |
+
attribution to "Sansar, Muse Mesh Private Limited". For commercial use contact kushal@muse-mesh.com; a
|
| 7 |
+
commercially licensed model trained only on permissively licensed text is planned as a separate release.
|
| 8 |
+
|
| 9 |
+
The code is licensed separately under Apache-2.0 (see LICENSE-CODE).
|
| 10 |
+
|
| 11 |
+
Copyright 2026 Muse Mesh Private Limited
|
LICENSE-CODE
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The Python code in this repository (configuration_sansar.py, modeling_sansar.py, tokenization_sansar.py,
|
| 2 |
+
translit.py) is licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0
|
| 3 |
+
|
| 4 |
+
Copyright 2026 Muse Mesh Private Limited
|
README.md
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
language:
|
| 4 |
+
- sa
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
tags:
|
| 8 |
+
- sanskrit
|
| 9 |
+
- devanagari
|
| 10 |
+
- slp1
|
| 11 |
+
- causal-lm
|
| 12 |
+
- base-model
|
| 13 |
+
- sansar
|
| 14 |
+
datasets:
|
| 15 |
+
- ai4bharat/sangraha
|
| 16 |
+
- chronbmm/sanskrit-monolingual-pretraining
|
| 17 |
+
model-index:
|
| 18 |
+
- name: sansar-20m
|
| 19 |
+
results:
|
| 20 |
+
- task:
|
| 21 |
+
type: text-generation
|
| 22 |
+
name: Sanskrit language modelling
|
| 23 |
+
dataset:
|
| 24 |
+
type: sansar-e0-heldout
|
| 25 |
+
name: Sansar E0 held-out Sanskrit sets
|
| 26 |
+
metrics:
|
| 27 |
+
- type: bits_per_byte
|
| 28 |
+
name: "bits per Devanagari byte, pooled excluding the Bhagavad-gītā (E0 held-out sets)"
|
| 29 |
+
value: 0.7177
|
| 30 |
+
- type: bits_per_byte
|
| 31 |
+
name: "bits per Devanagari byte, pooled over all five E0 sets"
|
| 32 |
+
value: 0.7102
|
| 33 |
+
- type: bits_per_byte
|
| 34 |
+
name: "bits per Devanagari byte, dcs_gold"
|
| 35 |
+
value: 0.7065
|
| 36 |
+
- type: bits_per_byte
|
| 37 |
+
name: "bits per Devanagari byte, prose"
|
| 38 |
+
value: 0.6887
|
| 39 |
+
- type: bits_per_byte
|
| 40 |
+
name: "bits per Devanagari byte, ood"
|
| 41 |
+
value: 0.7225
|
| 42 |
+
- type: bits_per_byte
|
| 43 |
+
name: "bits per Devanagari byte, vedic"
|
| 44 |
+
value: 0.9685
|
| 45 |
+
- type: bits_per_byte
|
| 46 |
+
name: "bits per Devanagari byte, gita"
|
| 47 |
+
value: 0.5129
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
# Sansar 20M
|
| 51 |
+
|
| 52 |
+
A 27.1M-parameter Sanskrit language model trained from scratch, from the **Sansar** project at [Muse Mesh](https://muse-mesh.com) ([Hugging Face](https://huggingface.co/MuseMesh)): Sanskrit language models, their corpus and their tokenizer. Size class: the d20m preset: 6 layers, width 512 (18.9M parameters outside the embeddings; 27.1M in total with the 8k vocabulary and untied head).
|
| 53 |
+
|
| 54 |
+
- **This version: v0.1.0** = training run `tokv3_v01_d20m`, finished 2026-10-02 (experiment TOK-v3 screen, arm v0.1: the released tokenizer, F4 recipe at d20m).
|
| 55 |
+
- **Held-out score**: 0.7177 bits per Devanagari byte (pooled over four held-out sets, excluding the Bhagavad-gītā; lower is better).
|
| 56 |
+
- **Base model**: it continues Devanagari Sanskrit text; it is not instruction-tuned.
|
| 57 |
+
- **Why this checkpoint**: The best 20M-class checkpoint on the held-out ex-Gītā number (0.7177, against 0.7537 for the best 20M run of the earlier AdamW recipe). It was trained as the control arm of the tokenizer v0.2 screen, which kept v0.1.
|
| 58 |
+
|
| 59 |
+
## Quick start
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
import torch
|
| 63 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 64 |
+
|
| 65 |
+
repo = "MuseMesh/sansar-20m"
|
| 66 |
+
tok = AutoTokenizer.from_pretrained(repo, revision="v0.1.0", trust_remote_code=True)
|
| 67 |
+
model = AutoModelForCausalLM.from_pretrained(repo, revision="v0.1.0", trust_remote_code=True)
|
| 68 |
+
|
| 69 |
+
inputs = tok("संस्कृतं नाम दैवी वाक्", return_tensors="pt") # Devanagari in
|
| 70 |
+
out = model.generate(**inputs, max_new_tokens=50, do_sample=True, temperature=0.8, top_k=100)
|
| 71 |
+
print(tok.decode(out[0], skip_special_tokens=True)) # Devanagari out
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Needs `transformers` (tested with 5.18.0), `torch` and `sentencepiece`. `trust_remote_code=True` runs three small files from this repository: `modeling_sansar.py` (the network), `tokenization_sansar.py` and `translit.py` (Devanagari <-> SLP1); read them before you run them. The weights are stored in bfloat16 (transformers 5 loads them as such); pass `dtype=torch.float32` for fp32, usually the faster choice on a CPU. The tokenizer adds no BOS/EOS: training records were separated by `</s>` only.
|
| 75 |
+
|
| 76 |
+
What this checkpoint wrote for that prompt (CPU, `torch.manual_seed(0)`, 50 new tokens):
|
| 77 |
+
|
| 78 |
+
```text
|
| 79 |
+
संस्कृतं नाम दैवी वाक् । तस्मिस्तु - स्वोपासकस्य मानसवतो विवाहकाले आगत्य 'महाराज' नाम्ना वसन्तों विवाहकाले आगत्य तु ऽ
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
and with greedy decoding:
|
| 83 |
+
|
| 84 |
+
```text
|
| 85 |
+
संस्कृतं नाम दैवी वाक् । अनयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थ
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
To score text instead of generating it, call the model with `labels=input_ids`; `loss` is the mean negative log-likelihood per token in nats.
|
| 89 |
+
|
| 90 |
+
## Model details
|
| 91 |
+
|
| 92 |
+
| | |
|
| 93 |
+
|---|---|
|
| 94 |
+
| Architecture | decoder-only transformer, pre-LayerNorm (LayerNorm without bias), no biases anywhere |
|
| 95 |
+
| Layers / heads / width | 6 / 8 / 512 (head dim 64); MLP 4x = 2,048 |
|
| 96 |
+
| Positions | rotary (base 10,000; half-split pairing), no position table |
|
| 97 |
+
| Attention | causal SDPA; queries and keys RMS-normalised per head (QK-norm) |
|
| 98 |
+
| MLP activation | squared ReLU |
|
| 99 |
+
| Output head | separate (untied), zero-initialised |
|
| 100 |
+
| Vocabulary | 8,000 (SentencePiece unigram over SLP1, [MuseMesh/sansar-sanskrit-tokenizer](https://huggingface.co/MuseMesh/sansar-sanskrit-tokenizer) v0.1.0) |
|
| 101 |
+
| Context | 512 tokens (about 3.6 kB of Devanagari text at the training data's 6.94 Devanagari bytes per token) |
|
| 102 |
+
| Parameters, total | 27,073,024 |
|
| 103 |
+
| Parameters, non-embedding | 18,881,024 |
|
| 104 |
+
| Token embedding | 4,096,000 |
|
| 105 |
+
| Output head | 4,096,000 |
|
| 106 |
+
| Weights in this repo | bfloat16 safetensors (trained as fp32 master weights under bf16 autocast) |
|
| 107 |
+
|
| 108 |
+
## Training
|
| 109 |
+
|
| 110 |
+
| | |
|
| 111 |
+
|---|---|
|
| 112 |
+
| Optimizer, block matrices | Muon (18,874,368 params): momentum 0.95 (Nesterov), 5 Newton-Schulz steps in bf16, peak lr 0.02, update scaled by sqrt(max(1, rows/cols)), no weight decay |
|
| 113 |
+
| Optimizer, everything else | AdamW: embedding + head (8,192,000 params) with weight decay 0.1, LayerNorm gains without; peak lr 0.001, betas (0.9, 0.95), eps 1e-8 |
|
| 114 |
+
| Learning-rate schedule | linear warm-up over 200 steps, then cosine decay to 0.1 x peak at step 6,968 (Muon and AdamW share it) |
|
| 115 |
+
| Batch | 96 sequences x 1 accumulation steps x 512 tokens = 49,152 tokens per step |
|
| 116 |
+
| Steps | 6,968 |
|
| 117 |
+
| Tokens seen | 342,491,136 (1.00 passes over 342.5M training tokens) |
|
| 118 |
+
| Gradient clipping | global norm 1.0 |
|
| 119 |
+
| Dropout | 0.0 |
|
| 120 |
+
| Precision | bf16 autocast, fp32 master weights, torch.compile |
|
| 121 |
+
| Seed | 1337 |
|
| 122 |
+
| Data sampling | 512-token windows at uniformly random offsets of the token stream (records separated by `</s>`), so passes are counted in expectation |
|
| 123 |
+
| Hardware | 1x NVIDIA RTX 3060 12 GB, power-capped at 150 W |
|
| 124 |
+
| Wall time | 51 min (3,067 s), 114k tokens/s |
|
| 125 |
+
| Compute cost | own hardware, no cloud cost |
|
| 126 |
+
| Final validation | loss 3.3781 nats/token = 0.6975 bits per Devanagari byte on the run's own validation split (0.5% of records by near-duplicate cluster; not comparable across data slices) |
|
| 127 |
+
|
| 128 |
+
Training code: `scripts/train/train.py`, `model.py` and `muon.py` of the Sansar repository; the exact arguments are in `training/summary.json`.
|
| 129 |
+
|
| 130 |
+
## Training data
|
| 131 |
+
|
| 132 |
+
A 23.5% record subset of `train_slice_plus_clean` (records whose sha1(id) falls in the band [0.50, 0.735); 3,549,167 records, 2.38 GB of cleaned Devanagari), the same text the larger plus_clean models were trained on at one quarter of the size. After held-out masking: 3,530,019 training records, 342.5M tokens. The run saw 342.5M tokens = **one pass**.
|
| 133 |
+
|
| 134 |
+
Held-out texts excluded by dedup key and **masked inside training records** (28-character windows, stride 4: 36,077 records masked, 3.9M characters removed, 5,340 records dropped). The Gītā is still partly memorised through near-copies in commentaries, so it stays out of the headline number.
|
| 135 |
+
|
| 136 |
+
The text comes from the Sansar corpus, which collects Sanskrit in Devanagari from public sources: classical e-text collections (GRETIL, SARIT, Muktabodha, the Digital Corpus of Sanskrit, DharmaNexus and others), Sanskrit Wikisource and Wikipedia, dictionaries, and the Sanskrit parts of web-crawl datasets (AI4Bharat Sangraha, IndicCorp, MADLAD-400, the sanskrit-monolingual-pretraining collection). Every record keeps its provenance and a licence tier (T0 permissive, T1 share-alike, T2 non-commercial, T3 no licence statement or all rights reserved). The training slice mixes all tiers: a large share is licensed for non-commercial use only and some sources state no licence, which is why the weights are released under CC BY-NC 4.0 (see Licence). Old archive.org OCR of printed books is left out (it measurably hurt the models).
|
| 137 |
+
|
| 138 |
+
Preparation: Unicode NFC; standalone `/` and `//` read as daṇḍa `।` and double daṇḍa `॥`; machine reference markers (verse numbers of digital editions) stripped; transliterated to SLP1 and tokenized; one `</s>` after every record; a 0.5% validation split by near-duplicate cluster.
|
| 139 |
+
|
| 140 |
+
## Evaluation
|
| 141 |
+
|
| 142 |
+
**Metric**: bits per Devanagari byte (lower is better): the model's negative log-likelihood of a text divided by the UTF-8 byte count of the same text in Devanagari, so models with different tokenizers are measured against the same denominator. Scored teacher-forced with `scripts/train/eval_bpb.py`: each set's records joined with `</s>` into one stream, 512-token windows with stride 256 (every scored token after the first window has at least 256 tokens of context), text cleaned exactly as the training text was.
|
| 143 |
+
|
| 144 |
+
**Sets** (E0, frozen before any model was trained and excluded from training): `dcs_gold` 3,000 sentences of the Digital Corpus of Sanskrit gold standard (classical), `prose` 2,470 prose passages, `ood` 2,000 web, Wikipedia and other out-of-domain texts, `vedic` 1,000 accented Ṛgveda pādas, `gita` all 700 verses of the Bhagavad-gītā. **The headline is pooled excluding the Gītā** (byte-weighted over the other four): the Gītā is quoted inside commentaries and epics throughout the training text, so its column measures memorisation.
|
| 145 |
+
|
| 146 |
+
| | ex-Gītā (headline) | pooled, all five | dcs_gold | prose | ood | vedic | gita (memorisation) |
|
| 147 |
+
|---|---:|---:|---:|---:|---:|---:|---:|
|
| 148 |
+
| E0 sets (9,170 items) | **0.7177** | 0.7102 | 0.7065 | 0.6887 | 0.7225 | 0.9685 | 0.5129 |
|
| 149 |
+
|
| 150 |
+
**Verse completion** (600 verses: 200 each from the Bhagavad-gītā, Mahābhārata and Rāmāyaṇa; the model gets the first half-verse and greedily writes the second, stopping at ॥ or a newline): chrF 0.090, exact match 0/600. chrF credits shared character n-grams, so it rewards plausible vocabulary even when the half-verse is not the right one.
|
| 151 |
+
|
| 152 |
+
### Reference points
|
| 153 |
+
|
| 154 |
+
Same metric and sets. External models were scored zero-shot with their own tokenizers and a 2,048-token window (stride 1,024), which gives them more context than our 512-token window; their training data may contain the public `ood` and `prose` texts.
|
| 155 |
+
|
| 156 |
+
| model | parameters | ex-Gītā | clean_v1 ex-Gītā | notes |
|
| 157 |
+
|---|---:|---:|---:|---|
|
| 158 |
+
| [Sansar 20M](https://huggingface.co/MuseMesh/sansar-20m) v0.1.0 (this model) | 27.1M | 0.7177 | n/a | TOK-v3 screen, arm v0.1, 0.34B tokens |
|
| 159 |
+
| [Sansar 60M](https://huggingface.co/MuseMesh/sansar-60m) v0.1.0 | 63.2M | 0.6434 | n/a | F0, 1.34B tokens |
|
| 160 |
+
| [Sansar 125M](https://huggingface.co/MuseMesh/sansar-125m) v0.1.0 | 97.2M | 0.6039 | 0.6254 | F6-clean-2x, 2.66B tokens |
|
| 161 |
+
| [Sansar 350M](https://huggingface.co/MuseMesh/sansar-350m) v0.1.0 | 318.4M | 0.5720 | 0.5937 | F7, 2.66B tokens |
|
| 162 |
+
| [Sansar 350M](https://huggingface.co/MuseMesh/sansar-350m) v0.2.0 | 318.4M | 0.5547 | 0.5773 | F9, 5.09B tokens |
|
| 163 |
+
| Krutrim-2-instruct (zero-shot, nf4) | 12B | 0.512 | n/a | general model, 2,048-token window |
|
| 164 |
+
| Sarvam-1 (zero-shot, fp16) | 2.5B | 0.750 | n/a | general model, 2,048-token window |
|
| 165 |
+
| Gemma 4 E2B (zero-shot, fp16) | 4B | 0.892 | n/a | general model, 2,048-token window |
|
| 166 |
+
|
| 167 |
+
### Checked before release
|
| 168 |
+
|
| 169 |
+
- `modeling_sansar.py` against the training code (`scripts/train/model.py`), fp32 on CPU, 6 inputs (one held-out text per set, cropped to 512 tokens, and 512 random ids): with the same bf16 weights the logits are identical (max |difference| 0.0e+00); against the fp32 training weights the bf16 storage moves logits by at most 0.159.
|
| 170 |
+
- Bits per byte on the first 20 records of each set with `eval_bpb.py`'s own scoring: 0.68017 (training checkpoint, fp32) vs 0.68017 (this repo, bf16 weights) = +0.0006%.
|
| 171 |
+
- Tokenizer: the same ids as the evaluation pipeline on 100/100 sample texts with `fence_latin=False` (95/100 with the default fence; the rest contain English words); Devanagari round trip exact on 100/100.
|
| 172 |
+
- Left-padded batches give the same logits as single sequences (max |difference| 1.4e-05).
|
| 173 |
+
|
| 174 |
+
## Limitations
|
| 175 |
+
|
| 176 |
+
- **Base model.** It continues Sanskrit text. It has not been instruction-tuned or aligned: it does not follow instructions, answer questions or chat, and it will not refuse anything.
|
| 177 |
+
- **It makes things up.** Output is fluent-looking Sanskrit that can be ungrammatical, mix registers and invent verses, authors and works. Do not use it as a source of quotations or facts; exact verse recall is close to zero (see verse completion).
|
| 178 |
+
- **Other languages in the data.** The training text still holds some Hindi, Marathi and Pali lines that passed the Sanskrit filters of the time (a stricter filter came after this run), so the model can drift into Hindi.
|
| 179 |
+
- **Small and short.** 27M parameters and a 512-token context. This implementation has no key/value cache, so long generations are slow (each new token re-reads the last 512).
|
| 180 |
+
- **Vedic** is the weakest register: accent marks fragment the tokenization and Vedic text is a small share of the training data.
|
| 181 |
+
- **Script.** Devanagari in and out. English words inside the text are fenced by the tokenizer so they come back unchanged; the model never saw the fence marks in training, so its predictions around them are weaker (`AutoTokenizer.from_pretrained(..., fence_latin=False)` reproduces the training encoding, but then Latin letters decode as Devanagari). IAST and other Indic scripts are not transliterated for you.
|
| 182 |
+
- **What the corpus says, the model says.** Most of the text is religious, philosophical and classical literature, plus modern web and news Sanskrit; the model reproduces its views and its errors, including OCR errors that survived in web-crawl sources.
|
| 183 |
+
- **The Gītā is memorised** in part (see the `gita` column), so do not read its score as generalisation.
|
| 184 |
+
|
| 185 |
+
## Versions
|
| 186 |
+
|
| 187 |
+
Each version is a git tag on this repository; `main` is the newest. Pin one with `revision="v0.1.0"`. A version is one training run, named by its run id in the Sansar experiment log.
|
| 188 |
+
|
| 189 |
+
| version | date | training run | tokens seen | ex-Gītā | clean_v1 ex-Gītā |
|
| 190 |
+
|---|---|---|---:|---:|---:|
|
| 191 |
+
| v0.1.0 | 2026-10-02 | `tokv3_v01_d20m` (TOK-v3 screen, arm v0.1) | 0.34B | 0.7177 | n/a |
|
| 192 |
+
|
| 193 |
+
All runs of this size (ex-Gītā on the same E0 sets):
|
| 194 |
+
|
| 195 |
+
| run | date | recipe | ex-Gītā | status |
|
| 196 |
+
|---|---|---|---:|---|
|
| 197 |
+
| E8 slp1_uni8k | 2026-09-12 | 6L/8H/512, AdamW, learned positions, tied head, 0.39B tokens, key-only held-out exclusion | 0.7537 | not staged |
|
| 198 |
+
| E9 slp1_uni8k (+ seed 2 on a Kaggle T4) | 2026-09-12 | 11L/6H/384 (same total params), AdamW, 0.39B tokens | 0.7552 / 0.7681 | not staged (seed 2: no checkpoint) |
|
| 199 |
+
| VISION-OCR arms A-D (8 runs) | 2026-10-03 | 6L/8H/512, F4 recipe, 90M tokens | 0.791-0.803 | no checkpoints kept |
|
| 200 |
+
| TOK-v3 screen, arm v0.1 | 2026-10-02 | 6L/8H/512, F4 recipe (Muon + rotary/QK-norm/untied head/ReLU^2), 0.34B tokens of the plus_clean slice | 0.7177 | **v0.1.0** |
|
| 201 |
+
|
| 202 |
+
## Files
|
| 203 |
+
|
| 204 |
+
| file | what |
|
| 205 |
+
|---|---|
|
| 206 |
+
| `model.safetensors` | the weights, bfloat16 (no optimizer state) |
|
| 207 |
+
| `config.json`, `generation_config.json` | architecture and default sampling settings |
|
| 208 |
+
| `configuration_sansar.py`, `modeling_sansar.py` | the network for transformers (`auto_map`, trust_remote_code) |
|
| 209 |
+
| `tokenizer.model`, `tokenization_sansar.py`, `translit.py`, `tokenizer_config.json`, `special_tokens_map.json` | the tokenizer ([MuseMesh/sansar-sanskrit-tokenizer](https://huggingface.co/MuseMesh/sansar-sanskrit-tokenizer) v0.1.0) with its Devanagari <-> SLP1 wrapper |
|
| 210 |
+
| `eval/bpb.json`, `eval/verse_scores.json` | the evaluation outputs quoted above |
|
| 211 |
+
| `eval/verification.json`, `eval/smoke_test.json` | the release checks and the sample generations |
|
| 212 |
+
| `training/summary.json`, `training/data_meta.json` | every training argument, the loss curve's evaluation points, and the data preparation record |
|
| 213 |
+
| `LICENSE`, `LICENSE-CODE`, `CHANGELOG.md` | licences and version history |
|
| 214 |
+
|
| 215 |
+
## Licence
|
| 216 |
+
|
| 217 |
+
This release is for research and non-commercial use. The training data includes texts licensed for non-commercial use only and texts without a licence statement, used here for research. A commercially licensed model, trained only on permissively licensed text, is planned as a separate release with its own version line.
|
| 218 |
+
|
| 219 |
+
- Weights (`model.safetensors`) and `tokenizer.model`: **CC BY-NC 4.0** (`LICENSE`). Non-commercial use (research, teaching, non-profit work) with attribution to "Sansar, Muse Mesh Private Limited".
|
| 220 |
+
- Code (`configuration_sansar.py`, `modeling_sansar.py`, `tokenization_sansar.py`, `translit.py`): **Apache-2.0** (`LICENSE-CODE`).
|
| 221 |
+
- Commercial use: contact kushal@muse-mesh.com.
|
| 222 |
+
|
| 223 |
+
## Citation
|
| 224 |
+
|
| 225 |
+
```bibtex
|
| 226 |
+
@misc{sansar_20m_2026,
|
| 227 |
+
title = {Sansar 20M: a Sanskrit language model},
|
| 228 |
+
author = {Muse Mesh},
|
| 229 |
+
year = {2026},
|
| 230 |
+
note = {v0.1.0},
|
| 231 |
+
url = {https://huggingface.co/MuseMesh/sansar-20m}
|
| 232 |
+
}
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
Contact: kushal@muse-mesh.com
|
config.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SansarForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_sansar.SansarConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_sansar.SansarForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"bias": false,
|
| 10 |
+
"block_size": 512,
|
| 11 |
+
"bos_token_id": 1,
|
| 12 |
+
"dtype": "bfloat16",
|
| 13 |
+
"eos_token_id": 2,
|
| 14 |
+
"initializer_range": 0.02,
|
| 15 |
+
"layer_norm_eps": 1e-05,
|
| 16 |
+
"logit_cap": 0.0,
|
| 17 |
+
"mlp_ratio": 4,
|
| 18 |
+
"model_type": "sansar",
|
| 19 |
+
"n_embd": 512,
|
| 20 |
+
"n_head": 8,
|
| 21 |
+
"n_layer": 6,
|
| 22 |
+
"pad_token_id": 2,
|
| 23 |
+
"qk_norm": true,
|
| 24 |
+
"relu_sq": true,
|
| 25 |
+
"rope": true,
|
| 26 |
+
"rope_theta": 10000.0,
|
| 27 |
+
"tie_word_embeddings": false,
|
| 28 |
+
"torch_dtype": "bfloat16",
|
| 29 |
+
"transformers_version": "5.18.0",
|
| 30 |
+
"untied_head": true,
|
| 31 |
+
"use_cache": false,
|
| 32 |
+
"value_embed": false,
|
| 33 |
+
"value_embed_layers": "",
|
| 34 |
+
"vocab_size": 8000
|
| 35 |
+
}
|
configuration_sansar.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration of the Sansar Sanskrit language models (Muse Mesh).
|
| 2 |
+
|
| 3 |
+
Code licence: Apache-2.0 (LICENSE-CODE). The model weights are licensed separately (LICENSE).
|
| 4 |
+
"""
|
| 5 |
+
from transformers import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SansarConfig(PretrainedConfig):
|
| 9 |
+
"""A compact pre-LayerNorm GPT. The flags select the two architectures the Sansar runs used:
|
| 10 |
+
|
| 11 |
+
- ``rope=False, qk_norm=False, untied_head=False, relu_sq=False``: learned position table, GELU (tanh) MLP, output
|
| 12 |
+
head tied to the token embedding (the E8 to F3 models).
|
| 13 |
+
- ``rope=True, qk_norm=True, untied_head=True, relu_sq=True``: rotary positions, RMS-normalised queries and keys,
|
| 14 |
+
a separate output head, squared-ReLU MLP (the F4 recipe and every model after it).
|
| 15 |
+
|
| 16 |
+
``value_embed`` and ``logit_cap`` are supported for completeness; no released model uses them.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
model_type = "sansar"
|
| 20 |
+
attribute_map = {
|
| 21 |
+
"hidden_size": "n_embd",
|
| 22 |
+
"num_hidden_layers": "n_layer",
|
| 23 |
+
"num_attention_heads": "n_head",
|
| 24 |
+
"max_position_embeddings": "block_size",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
vocab_size: int = 8000,
|
| 30 |
+
block_size: int = 512,
|
| 31 |
+
n_layer: int = 6,
|
| 32 |
+
n_head: int = 8,
|
| 33 |
+
n_embd: int = 512,
|
| 34 |
+
mlp_ratio: int = 4,
|
| 35 |
+
bias: bool = False,
|
| 36 |
+
rope: bool = False,
|
| 37 |
+
rope_theta: float = 10000.0,
|
| 38 |
+
qk_norm: bool = False,
|
| 39 |
+
untied_head: bool = False,
|
| 40 |
+
relu_sq: bool = False,
|
| 41 |
+
value_embed: bool = False,
|
| 42 |
+
value_embed_layers: str = "",
|
| 43 |
+
logit_cap: float = 0.0,
|
| 44 |
+
layer_norm_eps: float = 1e-5,
|
| 45 |
+
initializer_range: float = 0.02,
|
| 46 |
+
bos_token_id: int = 1,
|
| 47 |
+
eos_token_id: int = 2,
|
| 48 |
+
pad_token_id: int = 2,
|
| 49 |
+
tie_word_embeddings=None,
|
| 50 |
+
use_cache: bool = False,
|
| 51 |
+
**kwargs,
|
| 52 |
+
):
|
| 53 |
+
self.vocab_size = vocab_size
|
| 54 |
+
self.block_size = block_size
|
| 55 |
+
self.n_layer = n_layer
|
| 56 |
+
self.n_head = n_head
|
| 57 |
+
self.n_embd = n_embd
|
| 58 |
+
self.mlp_ratio = mlp_ratio
|
| 59 |
+
self.bias = bias
|
| 60 |
+
self.rope = rope
|
| 61 |
+
self.rope_theta = rope_theta
|
| 62 |
+
self.qk_norm = qk_norm
|
| 63 |
+
self.untied_head = untied_head
|
| 64 |
+
self.relu_sq = relu_sq
|
| 65 |
+
self.value_embed = value_embed
|
| 66 |
+
self.value_embed_layers = value_embed_layers
|
| 67 |
+
self.logit_cap = logit_cap
|
| 68 |
+
self.layer_norm_eps = layer_norm_eps
|
| 69 |
+
self.initializer_range = initializer_range
|
| 70 |
+
self.use_cache = use_cache
|
| 71 |
+
if tie_word_embeddings is None:
|
| 72 |
+
tie_word_embeddings = not untied_head
|
| 73 |
+
super().__init__(
|
| 74 |
+
bos_token_id=bos_token_id,
|
| 75 |
+
eos_token_id=eos_token_id,
|
| 76 |
+
pad_token_id=pad_token_id,
|
| 77 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 78 |
+
**kwargs,
|
| 79 |
+
)
|
eval/bpb.json
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"arm": "tokv3_v01",
|
| 3 |
+
"ckpt": "/home/kushal/sansar/data/experiments/train/runs/tokv3_v01_d20m/ckpt.pt",
|
| 4 |
+
"tokenizer": "/home/kushal/sansar/data/experiments/tok/e2/spm_slp1_unigram_8000_v2.model",
|
| 5 |
+
"vocab_size": 8000,
|
| 6 |
+
"transliterate": "slp1",
|
| 7 |
+
"strip_refs": false,
|
| 8 |
+
"clean": "deva",
|
| 9 |
+
"text_field": "text_deva",
|
| 10 |
+
"denominator": "bytes_deva_utf8",
|
| 11 |
+
"block": 512,
|
| 12 |
+
"stride": 256,
|
| 13 |
+
"step": 6968,
|
| 14 |
+
"param_counts": {
|
| 15 |
+
"total": 27073024,
|
| 16 |
+
"embedding": 4096000,
|
| 17 |
+
"token_embedding": 4096000,
|
| 18 |
+
"position_embedding": 0,
|
| 19 |
+
"value_embedding": 0,
|
| 20 |
+
"head": 4096000,
|
| 21 |
+
"non_embedding": 18881024
|
| 22 |
+
},
|
| 23 |
+
"method": "records joined with EOS into one stream per set; sliding window, only the last `stride` predictions of each window after the first are scored; nats / Devanagari UTF-8 bytes of the cleaned text / ln 2",
|
| 24 |
+
"per_set": {
|
| 25 |
+
"dcs_gold": {
|
| 26 |
+
"records": 3000,
|
| 27 |
+
"tokens": 49763,
|
| 28 |
+
"tokens_scored": 49762,
|
| 29 |
+
"bytes_deva_utf8": 370794,
|
| 30 |
+
"nll_nats": 181577.925,
|
| 31 |
+
"bpb": 0.70649,
|
| 32 |
+
"nll_per_token": 3.64893,
|
| 33 |
+
"bytes_deva_per_token": 7.4512
|
| 34 |
+
},
|
| 35 |
+
"gita": {
|
| 36 |
+
"records": 700,
|
| 37 |
+
"tokens": 22518,
|
| 38 |
+
"tokens_scored": 22517,
|
| 39 |
+
"bytes_deva_utf8": 166845,
|
| 40 |
+
"nll_nats": 59318.667,
|
| 41 |
+
"bpb": 0.51292,
|
| 42 |
+
"nll_per_token": 2.63439,
|
| 43 |
+
"bytes_deva_per_token": 7.4094
|
| 44 |
+
},
|
| 45 |
+
"ood": {
|
| 46 |
+
"records": 2000,
|
| 47 |
+
"tokens": 425704,
|
| 48 |
+
"tokens_scored": 425703,
|
| 49 |
+
"bytes_deva_utf8": 2921851,
|
| 50 |
+
"nll_nats": 1463285.41,
|
| 51 |
+
"bpb": 0.72251,
|
| 52 |
+
"nll_per_token": 3.43734,
|
| 53 |
+
"bytes_deva_per_token": 6.8636
|
| 54 |
+
},
|
| 55 |
+
"prose": {
|
| 56 |
+
"records": 2470,
|
| 57 |
+
"tokens": 145348,
|
| 58 |
+
"tokens_scored": 145347,
|
| 59 |
+
"bytes_deva_utf8": 1015536,
|
| 60 |
+
"nll_nats": 484759.998,
|
| 61 |
+
"bpb": 0.68866,
|
| 62 |
+
"nll_per_token": 3.33519,
|
| 63 |
+
"bytes_deva_per_token": 6.9869
|
| 64 |
+
},
|
| 65 |
+
"vedic": {
|
| 66 |
+
"records": 1000,
|
| 67 |
+
"tokens": 16714,
|
| 68 |
+
"tokens_scored": 16713,
|
| 69 |
+
"bytes_deva_utf8": 77606,
|
| 70 |
+
"nll_nats": 52100.069,
|
| 71 |
+
"bpb": 0.96854,
|
| 72 |
+
"nll_per_token": 3.11734,
|
| 73 |
+
"bytes_deva_per_token": 4.6432
|
| 74 |
+
}
|
| 75 |
+
},
|
| 76 |
+
"pooled": {
|
| 77 |
+
"tokens": 660047,
|
| 78 |
+
"bytes_deva_utf8": 4552632,
|
| 79 |
+
"nll_nats": 2241042.069,
|
| 80 |
+
"bpb": 0.71017
|
| 81 |
+
},
|
| 82 |
+
"seconds": 9.4
|
| 83 |
+
}
|
eval/smoke_test.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"size": "20m",
|
| 3 |
+
"version": "v0.1.0",
|
| 4 |
+
"transformers": "5.18.0",
|
| 5 |
+
"torch": "2.14.0+cu130",
|
| 6 |
+
"dtype_loaded": "torch.bfloat16",
|
| 7 |
+
"load_seconds": 0.1,
|
| 8 |
+
"prompt": "संस्कृतं नाम दैवी वाक्",
|
| 9 |
+
"prompt_tokens": 9,
|
| 10 |
+
"prompt_pieces_slp1": [
|
| 11 |
+
"▁",
|
| 12 |
+
"saMskft",
|
| 13 |
+
"aM",
|
| 14 |
+
"▁nAma",
|
| 15 |
+
"▁",
|
| 16 |
+
"dEv",
|
| 17 |
+
"I",
|
| 18 |
+
"▁",
|
| 19 |
+
"vAk"
|
| 20 |
+
],
|
| 21 |
+
"sampled_seed0": {
|
| 22 |
+
"new_tokens": 50,
|
| 23 |
+
"seconds": 1.0,
|
| 24 |
+
"text": "संस्कृतं नाम दैवी वाक् । तस्मिस्तु - स्वोपासकस्य मानसवतो विवाहकाले आगत्य 'महाराज' नाम्ना वसन्तों विवाहकाले आगत्य तु ऽ",
|
| 25 |
+
"do_sample": true,
|
| 26 |
+
"temperature": 0.8,
|
| 27 |
+
"top_k": 100
|
| 28 |
+
},
|
| 29 |
+
"greedy": {
|
| 30 |
+
"new_tokens": 50,
|
| 31 |
+
"seconds": 0.9,
|
| 32 |
+
"text": "संस्कृतं नाम दैवी वाक् । अनयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थयोरर्थ",
|
| 33 |
+
"do_sample": false
|
| 34 |
+
}
|
| 35 |
+
}
|
eval/verification.json
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"size": "20m",
|
| 3 |
+
"version": "v0.1.0",
|
| 4 |
+
"run": "tokv3_v01_d20m",
|
| 5 |
+
"torch": "2.14.0+cu130",
|
| 6 |
+
"transformers": "5.18.0",
|
| 7 |
+
"hf_load_seconds": 0.2,
|
| 8 |
+
"hf_param_counts": {
|
| 9 |
+
"total": 27073024,
|
| 10 |
+
"embedding": 4096000,
|
| 11 |
+
"head": 4096000,
|
| 12 |
+
"non_embedding": 18881024
|
| 13 |
+
},
|
| 14 |
+
"orig_param_counts": {
|
| 15 |
+
"total": 27073024,
|
| 16 |
+
"embedding": 4096000,
|
| 17 |
+
"token_embedding": 4096000,
|
| 18 |
+
"position_embedding": 0,
|
| 19 |
+
"value_embedding": 0,
|
| 20 |
+
"head": 4096000,
|
| 21 |
+
"non_embedding": 18881024
|
| 22 |
+
},
|
| 23 |
+
"tied_head": false,
|
| 24 |
+
"hf_head_equals_wte": false,
|
| 25 |
+
"logits": [
|
| 26 |
+
{
|
| 27 |
+
"input": "dcs_gold",
|
| 28 |
+
"tokens": 19,
|
| 29 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 30 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 31 |
+
"max_abs_diff_vs_fp32_master": 0.050026655197143555,
|
| 32 |
+
"mean_abs_diff_vs_fp32_master": 0.007199867628514767,
|
| 33 |
+
"argmax_agree_vs_fp32_master": 1.0,
|
| 34 |
+
"logit_abs_max": 14.390743255615234
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"input": "gita",
|
| 38 |
+
"tokens": 27,
|
| 39 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 40 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 41 |
+
"max_abs_diff_vs_fp32_master": 0.05633831024169922,
|
| 42 |
+
"mean_abs_diff_vs_fp32_master": 0.007845329120755196,
|
| 43 |
+
"argmax_agree_vs_fp32_master": 1.0,
|
| 44 |
+
"logit_abs_max": 14.983847618103027
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"input": "ood",
|
| 48 |
+
"tokens": 512,
|
| 49 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 50 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 51 |
+
"max_abs_diff_vs_fp32_master": 0.09844303131103516,
|
| 52 |
+
"mean_abs_diff_vs_fp32_master": 0.009610326960682869,
|
| 53 |
+
"argmax_agree_vs_fp32_master": 0.998046875,
|
| 54 |
+
"logit_abs_max": 19.00731658935547
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"input": "prose",
|
| 58 |
+
"tokens": 61,
|
| 59 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 60 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 61 |
+
"max_abs_diff_vs_fp32_master": 0.05675983428955078,
|
| 62 |
+
"mean_abs_diff_vs_fp32_master": 0.007296254858374596,
|
| 63 |
+
"argmax_agree_vs_fp32_master": 1.0,
|
| 64 |
+
"logit_abs_max": 17.56630516052246
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"input": "vedic",
|
| 68 |
+
"tokens": 22,
|
| 69 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 70 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 71 |
+
"max_abs_diff_vs_fp32_master": 0.05190229415893555,
|
| 72 |
+
"mean_abs_diff_vs_fp32_master": 0.008906053379178047,
|
| 73 |
+
"argmax_agree_vs_fp32_master": 1.0,
|
| 74 |
+
"logit_abs_max": 13.91469955444336
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"input": "random_512",
|
| 78 |
+
"tokens": 512,
|
| 79 |
+
"max_abs_diff_vs_same_bf16_weights": 0.0,
|
| 80 |
+
"mean_abs_diff_vs_same_bf16_weights": 0.0,
|
| 81 |
+
"max_abs_diff_vs_fp32_master": 0.15868473052978516,
|
| 82 |
+
"mean_abs_diff_vs_fp32_master": 0.010886614210903645,
|
| 83 |
+
"argmax_agree_vs_fp32_master": 0.990234375,
|
| 84 |
+
"logit_abs_max": 16.144594192504883
|
| 85 |
+
}
|
| 86 |
+
],
|
| 87 |
+
"logits_max_abs_diff_impl": 0.0,
|
| 88 |
+
"logits_max_abs_diff_bf16_storage": 0.15868473052978516,
|
| 89 |
+
"left_padding_max_abs_diff": 1.430511474609375e-05,
|
| 90 |
+
"tokenizer_ids_identical": "95/100",
|
| 91 |
+
"tokenizer_first_difference": {
|
| 92 |
+
"set": "ood",
|
| 93 |
+
"index": 2
|
| 94 |
+
},
|
| 95 |
+
"tokenizer_ids_identical_fence_latin_false": "100/100",
|
| 96 |
+
"tokenizer_roundtrip_exact": "100/100",
|
| 97 |
+
"bpb_sample": {
|
| 98 |
+
"records_per_set": 20,
|
| 99 |
+
"block": 512,
|
| 100 |
+
"stride": 256,
|
| 101 |
+
"original_fp32_master": {
|
| 102 |
+
"pooled": 0.68017,
|
| 103 |
+
"dcs_gold": 0.74491,
|
| 104 |
+
"gita": 0.47254,
|
| 105 |
+
"ood": 0.68294,
|
| 106 |
+
"prose": 0.72442,
|
| 107 |
+
"vedic": 0.9819
|
| 108 |
+
},
|
| 109 |
+
"hf_bf16_weights_fp32_compute": {
|
| 110 |
+
"pooled": 0.68017,
|
| 111 |
+
"dcs_gold": 0.74491,
|
| 112 |
+
"gita": 0.47263,
|
| 113 |
+
"ood": 0.68295,
|
| 114 |
+
"prose": 0.72441,
|
| 115 |
+
"vedic": 0.98186
|
| 116 |
+
},
|
| 117 |
+
"pooled_rel_diff": 6.287091102380568e-06,
|
| 118 |
+
"seconds": 6.0
|
| 119 |
+
}
|
| 120 |
+
}
|
eval/verse_scores.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"eval_dir": "/home/kushal/sansar/data/experiments/train/f5/_vc_only",
|
| 3 |
+
"missing_predictions": [],
|
| 4 |
+
"overall": {
|
| 5 |
+
"answered": 600,
|
| 6 |
+
"macro_alt": 0.0,
|
| 7 |
+
"macro_chrF": 0.08965671244423863,
|
| 8 |
+
"macro_exact": 0.0,
|
| 9 |
+
"macro_exact_norm": 0.0,
|
| 10 |
+
"macro_exact_strict": 0.0,
|
| 11 |
+
"micro_alt": 0.0,
|
| 12 |
+
"micro_chrF": 0.08965671244423863,
|
| 13 |
+
"micro_exact": 0.0,
|
| 14 |
+
"micro_exact_norm": 0.0,
|
| 15 |
+
"micro_exact_strict": 0.0,
|
| 16 |
+
"n": 600
|
| 17 |
+
},
|
| 18 |
+
"per_task": {
|
| 19 |
+
"verse_completion": {
|
| 20 |
+
"alt": 0.0,
|
| 21 |
+
"answered": 600,
|
| 22 |
+
"chrF": 0.08965671244423863,
|
| 23 |
+
"exact": 0.0,
|
| 24 |
+
"exact_norm": 0.0,
|
| 25 |
+
"exact_strict": 0.0,
|
| 26 |
+
"n": 600
|
| 27 |
+
}
|
| 28 |
+
},
|
| 29 |
+
"predictions_file": "/home/kushal/sansar/data/experiments/train/hfmodels/tokv3_v01/verse_preds.jsonl",
|
| 30 |
+
"subtotals": {
|
| 31 |
+
"verse_completion/bhagavadgita": {
|
| 32 |
+
"alt": 0.0,
|
| 33 |
+
"chrF": 0.08548786162921766,
|
| 34 |
+
"exact": 0.0,
|
| 35 |
+
"exact_norm": 0.0,
|
| 36 |
+
"exact_strict": 0.0,
|
| 37 |
+
"n": 200
|
| 38 |
+
},
|
| 39 |
+
"verse_completion/mahabharata": {
|
| 40 |
+
"alt": 0.0,
|
| 41 |
+
"chrF": 0.09109963691412604,
|
| 42 |
+
"exact": 0.0,
|
| 43 |
+
"exact_norm": 0.0,
|
| 44 |
+
"exact_strict": 0.0,
|
| 45 |
+
"n": 200
|
| 46 |
+
},
|
| 47 |
+
"verse_completion/ramayana": {
|
| 48 |
+
"alt": 0.0,
|
| 49 |
+
"chrF": 0.09238263878937218,
|
| 50 |
+
"exact": 0.0,
|
| 51 |
+
"exact_norm": 0.0,
|
| 52 |
+
"exact_strict": 0.0,
|
| 53 |
+
"n": 200
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"unknown_prediction_ids": []
|
| 57 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"eos_token_id": 2,
|
| 4 |
+
"pad_token_id": 2,
|
| 5 |
+
"do_sample": true,
|
| 6 |
+
"temperature": 0.8,
|
| 7 |
+
"top_k": 100,
|
| 8 |
+
"max_new_tokens": 128,
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc945df21dbc682a2fb4823e58fea5e89b08d6f8ba0de4f9d2baa3a8b4eede02
|
| 3 |
+
size 54150168
|
modeling_sansar.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sansar Sanskrit language model as a transformers PreTrainedModel (load with trust_remote_code=True).
|
| 2 |
+
|
| 3 |
+
The module tree and parameter names are those of the training code (scripts/train/model.py in the Sansar
|
| 4 |
+
repository), so the released weights are the trained tensors with no renaming. The forward pass reproduces the training
|
| 5 |
+
model's logits (verified to fp32 rounding before release; see the model card).
|
| 6 |
+
|
| 7 |
+
Generation does not use a key/value cache: every step re-reads the last ``block_size`` (512) tokens. The models were
|
| 8 |
+
trained on 512-token windows, so text longer than that is read through a sliding window.
|
| 9 |
+
|
| 10 |
+
Code licence: Apache-2.0 (LICENSE-CODE). The model weights are licensed separately (LICENSE).
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
|
| 20 |
+
import transformers
|
| 21 |
+
from transformers import PreTrainedModel
|
| 22 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
from transformers import GenerationMixin
|
| 26 |
+
except ImportError: # older transformers
|
| 27 |
+
from transformers.generation import GenerationMixin
|
| 28 |
+
|
| 29 |
+
try: # transformers >= 5: init functions that skip tensors already loaded from the checkpoint
|
| 30 |
+
from transformers import initialization as _init
|
| 31 |
+
except ImportError:
|
| 32 |
+
_init = nn.init
|
| 33 |
+
|
| 34 |
+
from .configuration_sansar import SansarConfig
|
| 35 |
+
|
| 36 |
+
_TRANSFORMERS_V5 = int(transformers.__version__.split(".")[0]) >= 5
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def rotary_cos_sin(positions: torch.Tensor, head_dim: int, base: float):
|
| 40 |
+
"""cos, sin for each position, shape positions.shape + (head_dim,): the first half of the head dim pairs with the
|
| 41 |
+
second half (the layout of the training code)."""
|
| 42 |
+
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=positions.device, dtype=torch.float32) / head_dim))
|
| 43 |
+
ang = positions.to(torch.float32)[..., None] * inv
|
| 44 |
+
ang = torch.cat([ang, ang], dim=-1)
|
| 45 |
+
return ang.cos(), ang.sin()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
"""x: (B, H, T, hs); cos/sin: (T, hs) or (B, 1, T, hs). Rotation in float32, result in x's dtype."""
|
| 50 |
+
hs = x.shape[-1]
|
| 51 |
+
xf = x.float()
|
| 52 |
+
x1, x2 = xf[..., : hs // 2], xf[..., hs // 2:]
|
| 53 |
+
rotated = torch.cat([-x2, x1], dim=-1)
|
| 54 |
+
return (xf * cos + rotated * sin).to(x.dtype)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def value_embed_layers(cfg: SansarConfig) -> tuple:
|
| 58 |
+
if not cfg.value_embed:
|
| 59 |
+
return ()
|
| 60 |
+
if cfg.value_embed_layers.strip():
|
| 61 |
+
return tuple(sorted({int(x) for x in cfg.value_embed_layers.split(",") if x.strip()}))
|
| 62 |
+
k = min(3, cfg.n_layer // 2)
|
| 63 |
+
return tuple(range(k)) + tuple(range(cfg.n_layer - k, cfg.n_layer))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class LayerNorm(nn.Module):
|
| 67 |
+
"""LayerNorm with an optional bias (the released models have none)."""
|
| 68 |
+
|
| 69 |
+
def __init__(self, ndim: int, bias: bool, eps: float = 1e-5):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
| 72 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
| 73 |
+
self.eps = eps
|
| 74 |
+
|
| 75 |
+
def forward(self, x):
|
| 76 |
+
return F.layer_norm(x, self.weight.shape, self.weight, self.bias, self.eps)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class CausalSelfAttention(nn.Module):
|
| 80 |
+
def __init__(self, cfg: SansarConfig, value_embed: bool = False):
|
| 81 |
+
super().__init__()
|
| 82 |
+
assert cfg.n_embd % cfg.n_head == 0
|
| 83 |
+
self.n_head = cfg.n_head
|
| 84 |
+
self.n_embd = cfg.n_embd
|
| 85 |
+
self.rope = cfg.rope
|
| 86 |
+
self.qk_norm = cfg.qk_norm
|
| 87 |
+
self.c_attn = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=cfg.bias)
|
| 88 |
+
self.c_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias)
|
| 89 |
+
self.value_embed = value_embed
|
| 90 |
+
if value_embed:
|
| 91 |
+
self.v_scale = nn.Parameter(torch.tensor(0.5))
|
| 92 |
+
self.ve_scale = nn.Parameter(torch.tensor(0.5))
|
| 93 |
+
|
| 94 |
+
def forward(self, x, cos=None, sin=None, ve=None, attn_mask=None):
|
| 95 |
+
B, T, C = x.shape
|
| 96 |
+
hs = C // self.n_head
|
| 97 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
| 98 |
+
q = q.view(B, T, self.n_head, hs).transpose(1, 2)
|
| 99 |
+
k = k.view(B, T, self.n_head, hs).transpose(1, 2)
|
| 100 |
+
v = v.view(B, T, self.n_head, hs).transpose(1, 2)
|
| 101 |
+
if self.value_embed:
|
| 102 |
+
v = self.v_scale * v + self.ve_scale * ve.view(B, T, self.n_head, hs).transpose(1, 2).to(v.dtype)
|
| 103 |
+
if self.qk_norm:
|
| 104 |
+
q = F.rms_norm(q, (hs,)).to(v.dtype)
|
| 105 |
+
k = F.rms_norm(k, (hs,)).to(v.dtype)
|
| 106 |
+
if self.rope:
|
| 107 |
+
q = apply_rotary(q, cos, sin)
|
| 108 |
+
k = apply_rotary(k, cos, sin)
|
| 109 |
+
if attn_mask is None:
|
| 110 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True)
|
| 111 |
+
else:
|
| 112 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, is_causal=False)
|
| 113 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 114 |
+
return self.c_proj(y)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MLP(nn.Module):
|
| 118 |
+
def __init__(self, cfg: SansarConfig):
|
| 119 |
+
super().__init__()
|
| 120 |
+
hidden = cfg.mlp_ratio * cfg.n_embd
|
| 121 |
+
self.c_fc = nn.Linear(cfg.n_embd, hidden, bias=cfg.bias)
|
| 122 |
+
self.c_proj = nn.Linear(hidden, cfg.n_embd, bias=cfg.bias)
|
| 123 |
+
self.relu_sq = cfg.relu_sq
|
| 124 |
+
|
| 125 |
+
def forward(self, x):
|
| 126 |
+
h = self.c_fc(x)
|
| 127 |
+
h = F.relu(h).square() if self.relu_sq else F.gelu(h, approximate="tanh")
|
| 128 |
+
return self.c_proj(h)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class Block(nn.Module):
|
| 132 |
+
def __init__(self, cfg: SansarConfig, value_embed: bool = False):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.ln_1 = LayerNorm(cfg.n_embd, cfg.bias, cfg.layer_norm_eps)
|
| 135 |
+
self.attn = CausalSelfAttention(cfg, value_embed=value_embed)
|
| 136 |
+
self.ln_2 = LayerNorm(cfg.n_embd, cfg.bias, cfg.layer_norm_eps)
|
| 137 |
+
self.mlp = MLP(cfg)
|
| 138 |
+
|
| 139 |
+
def forward(self, x, cos=None, sin=None, ve=None, attn_mask=None):
|
| 140 |
+
x = x + self.attn(self.ln_1(x), cos, sin, ve, attn_mask)
|
| 141 |
+
x = x + self.mlp(self.ln_2(x))
|
| 142 |
+
return x
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class SansarPreTrainedModel(PreTrainedModel):
|
| 146 |
+
config_class = SansarConfig
|
| 147 |
+
base_model_prefix = "sansar" # no such attribute: weights load by their full names, never re-prefixed
|
| 148 |
+
_no_split_modules = ["Block"]
|
| 149 |
+
supports_gradient_checkpointing = False
|
| 150 |
+
|
| 151 |
+
def _init_weights(self, module):
|
| 152 |
+
"""Training-code initialisation; only used for tensors missing from a checkpoint (or a fresh model)."""
|
| 153 |
+
std = self.config.initializer_range
|
| 154 |
+
if isinstance(module, nn.Linear):
|
| 155 |
+
_init.normal_(module.weight, mean=0.0, std=std)
|
| 156 |
+
if module.bias is not None:
|
| 157 |
+
_init.zeros_(module.bias)
|
| 158 |
+
elif isinstance(module, nn.Embedding):
|
| 159 |
+
_init.normal_(module.weight, mean=0.0, std=std)
|
| 160 |
+
elif isinstance(module, LayerNorm):
|
| 161 |
+
_init.ones_(module.weight)
|
| 162 |
+
if module.bias is not None:
|
| 163 |
+
_init.zeros_(module.bias)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class SansarForCausalLM(SansarPreTrainedModel, GenerationMixin):
|
| 167 |
+
if _TRANSFORMERS_V5:
|
| 168 |
+
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
|
| 169 |
+
else:
|
| 170 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 171 |
+
|
| 172 |
+
def __init__(self, config: SansarConfig):
|
| 173 |
+
super().__init__(config)
|
| 174 |
+
parts = dict(wte=nn.Embedding(config.vocab_size, config.n_embd))
|
| 175 |
+
if not config.rope:
|
| 176 |
+
parts["wpe"] = nn.Embedding(config.block_size, config.n_embd)
|
| 177 |
+
self.ve_layers = value_embed_layers(config)
|
| 178 |
+
if config.value_embed:
|
| 179 |
+
parts["vte"] = nn.Embedding(config.vocab_size, config.n_embd)
|
| 180 |
+
parts.update(
|
| 181 |
+
h=nn.ModuleList([Block(config, value_embed=i in self.ve_layers) for i in range(config.n_layer)]),
|
| 182 |
+
ln_f=LayerNorm(config.n_embd, config.bias, config.layer_norm_eps),
|
| 183 |
+
)
|
| 184 |
+
self.transformer = nn.ModuleDict(parts)
|
| 185 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 186 |
+
self.post_init()
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------------ embeddings (for tying and resizing)
|
| 189 |
+
def get_input_embeddings(self):
|
| 190 |
+
return self.transformer.wte
|
| 191 |
+
|
| 192 |
+
def set_input_embeddings(self, value):
|
| 193 |
+
self.transformer.wte = value
|
| 194 |
+
|
| 195 |
+
def get_output_embeddings(self):
|
| 196 |
+
return self.lm_head
|
| 197 |
+
|
| 198 |
+
def set_output_embeddings(self, new_embeddings):
|
| 199 |
+
self.lm_head = new_embeddings
|
| 200 |
+
|
| 201 |
+
# ------------------------------------------------------------------ forward
|
| 202 |
+
def _cap(self, logits):
|
| 203 |
+
c = self.config.logit_cap
|
| 204 |
+
if c and c > 0:
|
| 205 |
+
return c * torch.tanh(logits.float() / c)
|
| 206 |
+
return logits
|
| 207 |
+
|
| 208 |
+
def forward(
|
| 209 |
+
self,
|
| 210 |
+
input_ids: torch.LongTensor = None,
|
| 211 |
+
attention_mask: torch.Tensor | None = None,
|
| 212 |
+
position_ids: torch.LongTensor | None = None,
|
| 213 |
+
labels: torch.LongTensor | None = None,
|
| 214 |
+
return_dict: bool | None = None,
|
| 215 |
+
**kwargs,
|
| 216 |
+
):
|
| 217 |
+
"""input_ids (B, T) with T <= block_size. attention_mask (B, T) of 1/0 for padded batches (left padding for
|
| 218 |
+
generation); without padding the model runs exactly the training forward pass. labels: as in other causal LMs
|
| 219 |
+
(the same ids as input_ids; shifted inside; -100 is ignored)."""
|
| 220 |
+
cfg = self.config
|
| 221 |
+
B, T = input_ids.shape
|
| 222 |
+
if T > cfg.block_size:
|
| 223 |
+
raise ValueError(f"sequence length {T} > block_size {cfg.block_size}; crop the input")
|
| 224 |
+
dev = input_ids.device
|
| 225 |
+
|
| 226 |
+
mask = None
|
| 227 |
+
if attention_mask is not None and not bool(attention_mask.bool().all()):
|
| 228 |
+
am = attention_mask.bool()
|
| 229 |
+
if position_ids is None:
|
| 230 |
+
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp(min=0)
|
| 231 |
+
causal = torch.ones(T, T, dtype=torch.bool, device=dev).tril()
|
| 232 |
+
mask = causal[None] & am[:, None, :]
|
| 233 |
+
mask = mask | torch.eye(T, dtype=torch.bool, device=dev)[None] # padded queries attend to themselves
|
| 234 |
+
mask = mask[:, None]
|
| 235 |
+
positions = position_ids if position_ids is not None else torch.arange(T, device=dev)
|
| 236 |
+
|
| 237 |
+
x = self.transformer.wte(input_ids)
|
| 238 |
+
if not cfg.rope:
|
| 239 |
+
x = x + self.transformer.wpe(positions)
|
| 240 |
+
cos = sin = None
|
| 241 |
+
if cfg.rope:
|
| 242 |
+
cos, sin = rotary_cos_sin(positions, cfg.n_embd // cfg.n_head, cfg.rope_theta)
|
| 243 |
+
if cos.dim() == 3: # (B, T, hs) -> (B, 1, T, hs)
|
| 244 |
+
cos, sin = cos[:, None], sin[:, None]
|
| 245 |
+
ve = self.transformer.vte(input_ids) if cfg.value_embed else None
|
| 246 |
+
for i, block in enumerate(self.transformer.h):
|
| 247 |
+
x = block(x, cos, sin, ve if i in self.ve_layers else None, mask)
|
| 248 |
+
x = self.transformer.ln_f(x)
|
| 249 |
+
logits = self._cap(self.lm_head(x))
|
| 250 |
+
|
| 251 |
+
loss = None
|
| 252 |
+
if labels is not None:
|
| 253 |
+
shift_logits = logits[:, :-1, :].float()
|
| 254 |
+
shift_labels = labels[:, 1:].to(dev)
|
| 255 |
+
loss = F.cross_entropy(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1),
|
| 256 |
+
ignore_index=-100)
|
| 257 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits)
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------------ generation (no KV cache)
|
| 260 |
+
@classmethod
|
| 261 |
+
def _supports_default_dynamic_cache(cls) -> bool:
|
| 262 |
+
return False
|
| 263 |
+
|
| 264 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
|
| 265 |
+
bs = self.config.block_size
|
| 266 |
+
if input_ids.shape[1] > bs:
|
| 267 |
+
input_ids = input_ids[:, -bs:]
|
| 268 |
+
if attention_mask is not None:
|
| 269 |
+
attention_mask = attention_mask[:, -bs:]
|
| 270 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 271 |
+
|
| 272 |
+
def num_parameters_by_kind(self) -> dict:
|
| 273 |
+
"""Parameter counts as the Sansar model cards report them (a tied head is counted once, in the embedding)."""
|
| 274 |
+
tok = self.transformer.wte.weight.numel()
|
| 275 |
+
pos = self.transformer.wpe.weight.numel() if "wpe" in self.transformer else 0
|
| 276 |
+
val = self.transformer.vte.weight.numel() if "vte" in self.transformer else 0
|
| 277 |
+
head = self.lm_head.weight.numel() if self.config.untied_head else 0
|
| 278 |
+
total = sum(p.numel() for p in self.parameters())
|
| 279 |
+
return {"total": total, "embedding": tok + pos + val, "head": head,
|
| 280 |
+
"non_embedding": total - tok - pos - val - head}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"unk_token": "<unk>",
|
| 3 |
+
"bos_token": "<s>",
|
| 4 |
+
"eos_token": "</s>",
|
| 5 |
+
"pad_token": "</s>"
|
| 6 |
+
}
|
tokenization_sansar.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sansar Sanskrit tokenizer for transformers: Devanagari in, token ids out, Devanagari back.
|
| 2 |
+
|
| 3 |
+
The SentencePiece model (tokenizer.model, the same file as MuseMesh/sansar-sanskrit-tokenizer v0.1.0) works on SLP1, a
|
| 4 |
+
lossless ASCII spelling of Devanagari. This class converts with the bundled translit.py, so callers only see Devanagari.
|
| 5 |
+
Latin-script runs (English words, IAST) are fenced with two private-use marks so they come back unchanged
|
| 6 |
+
(``fence_latin=True``, the default). Training and evaluation text was NOT fenced (Latin letters went through the SLP1
|
| 7 |
+
step as they were), so for text with Latin runs ``fence_latin=False`` reproduces the training token stream exactly,
|
| 8 |
+
at the price of Latin coming back as Devanagari on decode. Pure Devanagari text gives the same ids either way.
|
| 9 |
+
|
| 10 |
+
No BOS/EOS is added to encoded text: the models were trained on records separated by </s> (id 2), with no BOS.
|
| 11 |
+
|
| 12 |
+
Code licence: Apache-2.0 (LICENSE-CODE). tokenizer.model: CC BY-NC 4.0 (LICENSE).
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shutil
|
| 19 |
+
|
| 20 |
+
import sentencepiece as spm
|
| 21 |
+
from transformers import PreTrainedTokenizer
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from .translit import NFC, deva_to_slp1, slp1_to_deva
|
| 25 |
+
except ImportError: # imported as a plain module next to translit.py
|
| 26 |
+
from translit import NFC, deva_to_slp1, slp1_to_deva
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
| 29 |
+
|
| 30 |
+
_OPEN, _CLOSE = "", "" # fence for Latin runs; byte-fallback tokens in the model
|
| 31 |
+
_LATIN = re.compile(r"(?:[A-Za-zÀ-ɏḀ-ỿ][̀-ͯ]*)+")
|
| 32 |
+
_FENCED = re.compile(re.escape(_OPEN) + r"(.*?)" + re.escape(_CLOSE), re.S)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SansarTokenizer(PreTrainedTokenizer):
|
| 36 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 37 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 38 |
+
|
| 39 |
+
def __init__(self, vocab_file, unk_token="<unk>", bos_token="<s>", eos_token="</s>", pad_token="</s>",
|
| 40 |
+
clean_up_tokenization_spaces=False, fence_latin=True, **kwargs):
|
| 41 |
+
self.vocab_file = vocab_file
|
| 42 |
+
self.fence_latin = fence_latin
|
| 43 |
+
self.sp = spm.SentencePieceProcessor(model_file=vocab_file)
|
| 44 |
+
kwargs.setdefault("padding_side", "left") # left padding for batched generation
|
| 45 |
+
super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token,
|
| 46 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces, fence_latin=fence_latin, **kwargs)
|
| 47 |
+
|
| 48 |
+
# ------------------------------------------------------------------ transliteration
|
| 49 |
+
def to_slp1(self, text: str) -> str:
|
| 50 |
+
"""Devanagari -> the model's input: SLP1, with Latin runs fenced and kept as they are (if fence_latin)."""
|
| 51 |
+
text, out, pos = NFC(text), [], 0
|
| 52 |
+
if not self.fence_latin:
|
| 53 |
+
return deva_to_slp1(text)[0]
|
| 54 |
+
for m in _LATIN.finditer(text):
|
| 55 |
+
out.append(deva_to_slp1(text[pos:m.start()])[0])
|
| 56 |
+
out.append(_OPEN + m.group() + _CLOSE)
|
| 57 |
+
pos = m.end()
|
| 58 |
+
out.append(deva_to_slp1(text[pos:])[0])
|
| 59 |
+
return "".join(out)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def from_slp1(s: str) -> str:
|
| 63 |
+
out, pos = [], 0
|
| 64 |
+
for m in _FENCED.finditer(s):
|
| 65 |
+
out.append(slp1_to_deva(s[pos:m.start()])[0])
|
| 66 |
+
out.append(m.group(1))
|
| 67 |
+
pos = m.end()
|
| 68 |
+
out.append(slp1_to_deva(s[pos:])[0])
|
| 69 |
+
return "".join(out)
|
| 70 |
+
|
| 71 |
+
# ------------------------------------------------------------------ vocabulary
|
| 72 |
+
@property
|
| 73 |
+
def vocab_size(self) -> int:
|
| 74 |
+
return self.sp.get_piece_size()
|
| 75 |
+
|
| 76 |
+
def get_vocab(self):
|
| 77 |
+
vocab = {self.sp.id_to_piece(i): i for i in range(self.sp.get_piece_size())}
|
| 78 |
+
vocab.update(self.added_tokens_encoder)
|
| 79 |
+
return vocab
|
| 80 |
+
|
| 81 |
+
def _tokenize(self, text, **kwargs):
|
| 82 |
+
"""Text -> SentencePiece pieces in SLP1 (the pieces the model sees)."""
|
| 83 |
+
return self.sp.encode(self.to_slp1(text), out_type=str)
|
| 84 |
+
|
| 85 |
+
def _convert_token_to_id(self, token):
|
| 86 |
+
return self.sp.piece_to_id(token)
|
| 87 |
+
|
| 88 |
+
def _convert_id_to_token(self, index):
|
| 89 |
+
return self.sp.id_to_piece(int(index))
|
| 90 |
+
|
| 91 |
+
def convert_tokens_to_string(self, tokens):
|
| 92 |
+
"""Pieces -> Devanagari text (Latin runs restored). Special tokens are kept as written."""
|
| 93 |
+
specials = set(self.all_special_tokens)
|
| 94 |
+
out, buf = [], []
|
| 95 |
+
for t in tokens:
|
| 96 |
+
if t in specials:
|
| 97 |
+
if buf:
|
| 98 |
+
out.append(self.from_slp1(self.sp.decode_pieces(buf)))
|
| 99 |
+
buf = []
|
| 100 |
+
out.append(t)
|
| 101 |
+
else:
|
| 102 |
+
buf.append(t)
|
| 103 |
+
if buf:
|
| 104 |
+
out.append(self.from_slp1(self.sp.decode_pieces(buf)))
|
| 105 |
+
return "".join(out)
|
| 106 |
+
|
| 107 |
+
# ------------------------------------------------------------------ special tokens: none added
|
| 108 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 109 |
+
return list(token_ids_0) + (list(token_ids_1) if token_ids_1 is not None else [])
|
| 110 |
+
|
| 111 |
+
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
|
| 112 |
+
if already_has_special_tokens:
|
| 113 |
+
return super().get_special_tokens_mask(token_ids_0, token_ids_1, already_has_special_tokens=True)
|
| 114 |
+
return [0] * (len(token_ids_0) + (len(token_ids_1) if token_ids_1 is not None else 0))
|
| 115 |
+
|
| 116 |
+
def num_special_tokens_to_add(self, pair: bool = False) -> int:
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
| 120 |
+
if not os.path.isdir(save_directory):
|
| 121 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 122 |
+
out = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "tokenizer.model")
|
| 123 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out):
|
| 124 |
+
shutil.copyfile(self.vocab_file, out)
|
| 125 |
+
return (out,)
|
tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c9ad72544159bd726fd5c8d4665d58785b7ee4a1de5840f04daa1ca35cb6c382
|
| 3 |
+
size 115626
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "SansarTokenizer",
|
| 3 |
+
"auto_map": {
|
| 4 |
+
"AutoTokenizer": [
|
| 5 |
+
"tokenization_sansar.SansarTokenizer",
|
| 6 |
+
null
|
| 7 |
+
]
|
| 8 |
+
},
|
| 9 |
+
"unk_token": "<unk>",
|
| 10 |
+
"bos_token": "<s>",
|
| 11 |
+
"eos_token": "</s>",
|
| 12 |
+
"pad_token": "</s>",
|
| 13 |
+
"model_max_length": 512,
|
| 14 |
+
"padding_side": "left",
|
| 15 |
+
"clean_up_tokenization_spaces": false
|
| 16 |
+
}
|
training/data_meta.json
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"created": "2026-10-02T17:21:35",
|
| 3 |
+
"input": "/home/kushal/sansar/data/experiments/train/tokv3/subset.jsonl.gz",
|
| 4 |
+
"vocab_size": 8000,
|
| 5 |
+
"eos_id": 2,
|
| 6 |
+
"filters": {
|
| 7 |
+
"training_candidate": true,
|
| 8 |
+
"script_in": [
|
| 9 |
+
"deva"
|
| 10 |
+
],
|
| 11 |
+
"licence_tiers_any_of": "all",
|
| 12 |
+
"drop_known_heldout_overlap": true,
|
| 13 |
+
"exclude_key_files": [
|
| 14 |
+
"/home/kushal/sansar/data/experiments/tok/eval/eval_keys.txt",
|
| 15 |
+
"/home/kushal/sansar/data/experiments/eval/heldout_keys.txt"
|
| 16 |
+
],
|
| 17 |
+
"mask_heldout": true,
|
| 18 |
+
"mask_heldout_dirs": [
|
| 19 |
+
"/home/kushal/sansar/data/experiments/tok/eval",
|
| 20 |
+
"/home/kushal/sansar/data/experiments/eval"
|
| 21 |
+
],
|
| 22 |
+
"mask_window": 28,
|
| 23 |
+
"mask_stride": 4,
|
| 24 |
+
"transliterate": "slp1",
|
| 25 |
+
"assume_filtered": true,
|
| 26 |
+
"normalize_dandas": true,
|
| 27 |
+
"drop_rule_lines": true,
|
| 28 |
+
"strip_refs": true
|
| 29 |
+
},
|
| 30 |
+
"text_cleaning": {
|
| 31 |
+
"normalize_dandas": true,
|
| 32 |
+
"rule": "standalone '//' -> '॥', standalone '/' -> '।' (whitespace or string boundary on both sides), applied after NFC and after the dedup key is taken",
|
| 33 |
+
"danda_double_normalised": 316872,
|
| 34 |
+
"danda_single_normalised": 327245,
|
| 35 |
+
"records_with_danda_normalised": 312526,
|
| 36 |
+
"drop_rule_lines": true,
|
| 37 |
+
"rule_lines_dropped": 2,
|
| 38 |
+
"records_with_rule_lines": 2,
|
| 39 |
+
"records_dropped_all_rule_lines": 2,
|
| 40 |
+
"strip_refs": true,
|
| 41 |
+
"strip_refs_rule": "a token of >=2 digit groups (ASCII or Devanagari) joined by - , . । _ with an optional trailing pada letter (a-d / अ-द, optional virama) and optional bracket; `प्.`/`प्।`/`p.` + digits + optional letter + `)`; and a [bracketed] group that contains digits and no Devanagari word of >=3 base letters. A single digit group (`॥ २७ ॥`, `२७।`) is never touched. Whitespace is collapsed only on lines that lost a token, and a `॥ ॥` pair left behind by a cut is folded to one daṇḍa",
|
| 42 |
+
"ref_tokens_stripped": 206,
|
| 43 |
+
"ref_page_markers_stripped": 5,
|
| 44 |
+
"ref_bracket_groups_stripped": 576,
|
| 45 |
+
"ref_danda_pairs_collapsed": 2,
|
| 46 |
+
"ref_lines_emptied": 0,
|
| 47 |
+
"ref_chars_removed": 8700,
|
| 48 |
+
"records_with_refs_stripped": 220,
|
| 49 |
+
"records_dropped_all_refs": 0,
|
| 50 |
+
"ref_samples": [
|
| 51 |
+
"4।20",
|
| 52 |
+
"[भा.पु. 11.12.10]",
|
| 53 |
+
"[अ.श. 53]",
|
| 54 |
+
"[उ.नी. 3.17]",
|
| 55 |
+
"2.10]",
|
| 56 |
+
"[अ० ]",
|
| 57 |
+
"[26]",
|
| 58 |
+
"[उ.नी. 14.58]",
|
| 59 |
+
"10.31.06",
|
| 60 |
+
"[शृ.ति. 1.61]",
|
| 61 |
+
"[49]",
|
| 62 |
+
"[गी.गो. 4.1118]",
|
| 63 |
+
"3.2.21]",
|
| 64 |
+
"4.1.174]",
|
| 65 |
+
"[ल.मा. 10.38]",
|
| 66 |
+
"[उ.नी. 3.44]",
|
| 67 |
+
"[पा. 5.4.34]",
|
| 68 |
+
"[पा. 5.2.117]",
|
| 69 |
+
"10.29.35",
|
| 70 |
+
"[भा.पु. 10.33.35]",
|
| 71 |
+
"10.29.36",
|
| 72 |
+
"[अ० ३५० ]",
|
| 73 |
+
"[भा.पु. 10.82.48]",
|
| 74 |
+
"[31]",
|
| 75 |
+
"7।17)",
|
| 76 |
+
"[भा.पु. 10.29.6]",
|
| 77 |
+
"[भा.पु. 10.82.45]",
|
| 78 |
+
"10.29.09",
|
| 79 |
+
"[वि.मा. 2.14]",
|
| 80 |
+
"[.३पा.३ मू. ]"
|
| 81 |
+
],
|
| 82 |
+
"bytes_deva_utf8_counted": "after held-out masking and cleaning"
|
| 83 |
+
},
|
| 84 |
+
"heldout_mask": {
|
| 85 |
+
"probes": 17466,
|
| 86 |
+
"records_masked": 36077,
|
| 87 |
+
"spans_masked": 96335,
|
| 88 |
+
"chars_removed": 3887194,
|
| 89 |
+
"records_dropped_heldout_masked": 5340,
|
| 90 |
+
"by_set": {
|
| 91 |
+
"experiments/eval": 31360,
|
| 92 |
+
"tok/eval": 68247
|
| 93 |
+
},
|
| 94 |
+
"files_by_set": {
|
| 95 |
+
"tok/eval": 6,
|
| 96 |
+
"experiments/eval": 10
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
"val_split": {
|
| 100 |
+
"method": "blake2b(cluster id), else blake2b(phase3 dedup key)",
|
| 101 |
+
"permille": 5,
|
| 102 |
+
"cluster_file": "/home/kushal/sansar/data/unified_v3/neardup_clusters.jsonl.gz",
|
| 103 |
+
"cluster_memberships_loaded": 2221286,
|
| 104 |
+
"clustered_records": 446463,
|
| 105 |
+
"unclustered_records": 3101082,
|
| 106 |
+
"train_clustered_records": 444266,
|
| 107 |
+
"val_clustered_records": 2197
|
| 108 |
+
},
|
| 109 |
+
"records_read": 3555406,
|
| 110 |
+
"records_kept": 3547545,
|
| 111 |
+
"records_skipped": {
|
| 112 |
+
"not_training_candidate": 0,
|
| 113 |
+
"script": 0,
|
| 114 |
+
"licence": 0,
|
| 115 |
+
"empty": 0,
|
| 116 |
+
"bad_json": 0,
|
| 117 |
+
"excluded_heldout": 2519,
|
| 118 |
+
"records_dropped_heldout_masked": 5340,
|
| 119 |
+
"known_heldout_overlap": 0,
|
| 120 |
+
"all_rule_lines": 2
|
| 121 |
+
},
|
| 122 |
+
"train": {
|
| 123 |
+
"records": 3530019,
|
| 124 |
+
"tokens": 342491547,
|
| 125 |
+
"bytes_utf8": 974709531,
|
| 126 |
+
"utf8_bytes": 974709531,
|
| 127 |
+
"bpb_denominator": "bytes_deva_utf8",
|
| 128 |
+
"bytes_deva_utf8": 2376189693,
|
| 129 |
+
"bin": "/home/kushal/sansar/data/experiments/train/tokv3/prep_v01/train.bin",
|
| 130 |
+
"bytes_per_token": 2.8459,
|
| 131 |
+
"tokens_per_byte": 0.351378
|
| 132 |
+
},
|
| 133 |
+
"val": {
|
| 134 |
+
"records": 17526,
|
| 135 |
+
"tokens": 1852651,
|
| 136 |
+
"bytes_utf8": 5289937,
|
| 137 |
+
"utf8_bytes": 5289937,
|
| 138 |
+
"bpb_denominator": "bytes_deva_utf8",
|
| 139 |
+
"bytes_deva_utf8": 12944833,
|
| 140 |
+
"bin": "/home/kushal/sansar/data/experiments/train/tokv3/prep_v01/val.bin",
|
| 141 |
+
"bytes_per_token": 2.8553,
|
| 142 |
+
"tokens_per_byte": 0.350222
|
| 143 |
+
}
|
| 144 |
+
}
|
training/summary.json
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"run": "tokv3_v01_d20m",
|
| 3 |
+
"preset": "d20m",
|
| 4 |
+
"model_config": {
|
| 5 |
+
"vocab_size": 8000,
|
| 6 |
+
"block_size": 512,
|
| 7 |
+
"n_layer": 6,
|
| 8 |
+
"n_head": 8,
|
| 9 |
+
"n_embd": 512,
|
| 10 |
+
"dropout": 0.0,
|
| 11 |
+
"bias": false,
|
| 12 |
+
"mlp_ratio": 4,
|
| 13 |
+
"rope": true,
|
| 14 |
+
"qk_norm": true,
|
| 15 |
+
"untied_head": true,
|
| 16 |
+
"relu_sq": true,
|
| 17 |
+
"value_embed": false,
|
| 18 |
+
"value_embed_layers": ""
|
| 19 |
+
},
|
| 20 |
+
"param_counts": {
|
| 21 |
+
"total": 27073024,
|
| 22 |
+
"embedding": 4096000,
|
| 23 |
+
"token_embedding": 4096000,
|
| 24 |
+
"position_embedding": 0,
|
| 25 |
+
"value_embedding": 0,
|
| 26 |
+
"head": 4096000,
|
| 27 |
+
"non_embedding": 18881024
|
| 28 |
+
},
|
| 29 |
+
"tokenizer": "/home/kushal/sansar/data/experiments/tok/e2/spm_slp1_unigram_8000_v2.model",
|
| 30 |
+
"steps": 6968,
|
| 31 |
+
"tokens_seen": 342491136,
|
| 32 |
+
"tokens_per_step": 49152,
|
| 33 |
+
"batch_size": 96,
|
| 34 |
+
"grad_accum": 1,
|
| 35 |
+
"block_size": 512,
|
| 36 |
+
"compiled": true,
|
| 37 |
+
"dtype": "bf16",
|
| 38 |
+
"best_val_loss": 3.37815,
|
| 39 |
+
"best_bpb": 0.69751,
|
| 40 |
+
"mean_tok_s": 112327.3,
|
| 41 |
+
"median_tok_s": 113520.0,
|
| 42 |
+
"peak_gpu_mem_alloc_gb": 8.528,
|
| 43 |
+
"wall_seconds": 3067.4,
|
| 44 |
+
"evals": [
|
| 45 |
+
{
|
| 46 |
+
"step": 1000,
|
| 47 |
+
"val_loss": 3.9622,
|
| 48 |
+
"bpb": 0.8181,
|
| 49 |
+
"tokens_seen": 49152000,
|
| 50 |
+
"t": 446.8
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"step": 2000,
|
| 54 |
+
"val_loss": 3.7088,
|
| 55 |
+
"bpb": 0.7658,
|
| 56 |
+
"tokens_seen": 98304000,
|
| 57 |
+
"t": 885.6
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"step": 3000,
|
| 61 |
+
"val_loss": 3.5862,
|
| 62 |
+
"bpb": 0.7405,
|
| 63 |
+
"tokens_seen": 147456000,
|
| 64 |
+
"t": 1324.8
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"step": 4000,
|
| 68 |
+
"val_loss": 3.503,
|
| 69 |
+
"bpb": 0.7233,
|
| 70 |
+
"tokens_seen": 196608000,
|
| 71 |
+
"t": 1763.6
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"step": 5000,
|
| 75 |
+
"val_loss": 3.4378,
|
| 76 |
+
"bpb": 0.7098,
|
| 77 |
+
"tokens_seen": 245760000,
|
| 78 |
+
"t": 2202.7
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"step": 6000,
|
| 82 |
+
"val_loss": 3.3973,
|
| 83 |
+
"bpb": 0.7015,
|
| 84 |
+
"tokens_seen": 294912000,
|
| 85 |
+
"t": 2641.9
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"step": 6968,
|
| 89 |
+
"val_loss": 3.3781,
|
| 90 |
+
"bpb": 0.6975,
|
| 91 |
+
"tokens_seen": 342491136,
|
| 92 |
+
"t": 3067.4
|
| 93 |
+
}
|
| 94 |
+
],
|
| 95 |
+
"args": {
|
| 96 |
+
"data_dir": "data/experiments/train/tokv3/prep_v01",
|
| 97 |
+
"runs_dir": "data/experiments/train/runs",
|
| 98 |
+
"run": "tokv3_v01_d20m",
|
| 99 |
+
"preset": "d20m",
|
| 100 |
+
"n_layer": 0,
|
| 101 |
+
"n_head": 0,
|
| 102 |
+
"n_embd": 0,
|
| 103 |
+
"block_size": 512,
|
| 104 |
+
"batch_size": 96,
|
| 105 |
+
"grad_accum": 1,
|
| 106 |
+
"lr": 0.001,
|
| 107 |
+
"min_lr_frac": 0.1,
|
| 108 |
+
"warmup_steps": 200,
|
| 109 |
+
"max_steps": 6968,
|
| 110 |
+
"weight_decay": 0.1,
|
| 111 |
+
"optim": "muon",
|
| 112 |
+
"muon_lr": 0.02,
|
| 113 |
+
"muon_momentum": 0.95,
|
| 114 |
+
"rope": true,
|
| 115 |
+
"qk_norm": true,
|
| 116 |
+
"untied_head": true,
|
| 117 |
+
"relu_sq": true,
|
| 118 |
+
"value_embed": false,
|
| 119 |
+
"value_embed_layers": "",
|
| 120 |
+
"schedule": "cosine",
|
| 121 |
+
"warmdown_frac": 0.4,
|
| 122 |
+
"beta1": 0.9,
|
| 123 |
+
"beta2": 0.95,
|
| 124 |
+
"grad_clip": 1.0,
|
| 125 |
+
"dropout": 0.0,
|
| 126 |
+
"log_interval": 50,
|
| 127 |
+
"eval_interval": 1000,
|
| 128 |
+
"eval_batches": 40,
|
| 129 |
+
"eval_batch_size": 0,
|
| 130 |
+
"ckpt_minutes": 10.0,
|
| 131 |
+
"time_budget_min": 150.0,
|
| 132 |
+
"compile": 1,
|
| 133 |
+
"dtype": "bf16",
|
| 134 |
+
"resume": false,
|
| 135 |
+
"seed": 1337,
|
| 136 |
+
"sample_tokens": 120,
|
| 137 |
+
"sample_temperature": 0.8,
|
| 138 |
+
"sample_top_k": 100,
|
| 139 |
+
"prompt": "Darmakzetre kurukzetre samavetA yuyutsavaH",
|
| 140 |
+
"probe_steps": 0,
|
| 141 |
+
"device": "cuda"
|
| 142 |
+
},
|
| 143 |
+
"data_dir": "data/experiments/train/tokv3/prep_v01"
|
| 144 |
+
}
|
translit.py
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Strict, table-driven, REVERSIBLE Devanagari <-> SLP1 and Devanagari <-> IAST.
|
| 3 |
+
|
| 4 |
+
Design rules (E1 of docs/TOKENIZATION.md):
|
| 5 |
+
|
| 6 |
+
1. NFC is the frozen normalisation. Every public function normalises its input to NFC
|
| 7 |
+
first and returns NFC output. NFC *decomposes* the precomposed nukta letters
|
| 8 |
+
U+0958-U+095F, U+0929, U+0931, U+0934 (they are composition-excluded), so after NFC a
|
| 9 |
+
nukta is always a separate U+093C. Both forms are in the tables anyway.
|
| 10 |
+
2. Fail closed, never drop. A code point with no mapping is passed through unchanged AND
|
| 11 |
+
reported: every function returns ``(text, unmapped)`` where ``unmapped`` is a
|
| 12 |
+
``collections.Counter`` keyed by the offending character. Nothing is ever silently lost.
|
| 13 |
+
3. Round trip is the contract. deva -> slp1 -> deva and deva -> iast -> deva must return
|
| 14 |
+
the NFC input exactly, for every input, *unless* the input contains Latin letters
|
| 15 |
+
(see 5) or malformed Devanagari, both of which are reported.
|
| 16 |
+
4. Reserved ASCII. The romanised sides use a few ASCII characters as functional markers:
|
| 17 |
+
|
| 18 |
+
^ nukta (follows the consonant, precedes the vowel: k^a = U+0915 U+093C)
|
| 19 |
+
' avagraha % om (U+0950)
|
| 20 |
+
| cluster separator, only emitted where IAST would otherwise be ambiguous
|
| 21 |
+
(k|ha = क्ह, not ख; ka|i = कइ, not कै). It is only ever emitted BETWEEN two
|
| 22 |
+
letters, so on input a '|' that touches whitespace is read as a literal
|
| 23 |
+
character -- that is the ASCII dandaa of GRETIL-style romanised sources.
|
| 24 |
+
~ candrabindu (SLP1 only) / udatta U+0951 (SLP1 only)
|
| 25 |
+
+ short vowel prefix: +e +o +a (SLP1 only; IAST uses ĕ ŏ ă)
|
| 26 |
+
* candra vowel prefix: *e *o *a (SLP1 only; IAST uses ê ô â)
|
| 27 |
+
\\ anudatta U+0952 (SLP1 only)
|
| 28 |
+
|
| 29 |
+
IAST instead writes candrabindu m̐, udatta as combining acute U+0301 and anudatta as
|
| 30 |
+
combining grave U+0300. A *literal* occurrence of any reserved character in the source
|
| 31 |
+
is escaped by doubling it, so the mapping stays one-to-one.
|
| 32 |
+
5. Latin letters are the one thing that cannot round trip. On the Devanagari side every
|
| 33 |
+
Latin letter is a legal SLP1/IAST token, so "cafe" inside a Devanagari record comes back
|
| 34 |
+
as चफे. Such characters are reported (class ``latin``) rather than hidden; E1 counts how
|
| 35 |
+
many records of the corpus are affected.
|
| 36 |
+
6. Things deliberately NOT transliterated (identity in both directions, never reported):
|
| 37 |
+
danda U+0964, double danda U+0965, Devanagari digits U+0966-U+096F, the abbreviation
|
| 38 |
+
sign U+0970 and U+0971, ZWJ U+200D and ZWNJ U+200C, whitespace, and ASCII
|
| 39 |
+
punctuation/digits. SLP1 has no agreed spelling for any of them and inventing one would
|
| 40 |
+
be lossy -- and giving ZWJ/ZWNJ ASCII markers collided with the literal '_' that the DCS
|
| 41 |
+
and VedaWeb use as a text marker.
|
| 42 |
+
Parsing additionally accepts, but never emits, the spellings real-world romanised
|
| 43 |
+
Sanskrit actually uses: ṁ for the anusvara, and the ISO-15919 vowels ē ō r̥ l̥ r̥̄ l̥̄.
|
| 44 |
+
7. Vedic Extensions U+1CD0-U+1CFF are reported as unmapped and passed through, except
|
| 45 |
+
the two that are clearly SLP1 letters: jihvamuliya U+1CF5 (Z / ẖ) and upadhmaniya
|
| 46 |
+
U+1CF6 (V / ḫ). Devanagari Extended U+A8E0-U+A8FF is likewise reported and preserved.
|
| 47 |
+
8. ऌ and ळ are different letters and get different spellings, which published IAST often
|
| 48 |
+
conflates: vocalic ऌ/ॡ are ḷ/ḹ (SLP1 x/X) and retroflex ळ is ḻ, U+1E3B (SLP1 L). ISO-15919
|
| 49 |
+
uses ḷ for ळ; on input that reading loses to IAST's, so feed ISO through
|
| 50 |
+
:func:`iso15919_to_iast` first.
|
| 51 |
+
|
| 52 |
+
Philological note on the Vedic accents: the Rigveda's Devanagari convention marks
|
| 53 |
+
*anudatta* below (U+0952) and *svarita* above (U+0951) and leaves udatta unmarked, while
|
| 54 |
+
the romanised convention puts an acute on the *udatta* vowel. This module maps the signs,
|
| 55 |
+
not the accent theory: U+0951 <-> acute, U+0952 <-> grave, as specified for E1. Converting
|
| 56 |
+
a romanised Vedic text therefore produces a Devanagari string that is faithful as a
|
| 57 |
+
character mapping but does not match the printed Rigveda's accent placement.
|
| 58 |
+
|
| 59 |
+
The three-line summary of what the encodings look like:
|
| 60 |
+
|
| 61 |
+
धर्मक्षेत्रे कुरुक्षेत्रे Devanagari
|
| 62 |
+
Darmakzetre kurukzetre SLP1
|
| 63 |
+
dharmakṣetre kurukṣetre IAST
|
| 64 |
+
"""
|
| 65 |
+
from __future__ import annotations
|
| 66 |
+
|
| 67 |
+
import unicodedata
|
| 68 |
+
from collections import Counter
|
| 69 |
+
|
| 70 |
+
__all__ = [
|
| 71 |
+
'NFC', 'deva_to_slp1', 'slp1_to_deva', 'deva_to_iast', 'iast_to_deva',
|
| 72 |
+
'iso15919_to_iast', 'classify_char', 'AKSHARA_RE', 'split_aksharas', 'RESERVED',
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
VIRAMA = '्'
|
| 76 |
+
NUKTA = '़'
|
| 77 |
+
ZWNJ = ''
|
| 78 |
+
ZWJ = ''
|
| 79 |
+
|
| 80 |
+
RESERVED = "^'%|~/\\+*"
|
| 81 |
+
|
| 82 |
+
# --------------------------------------------------------------------------------------
|
| 83 |
+
# Tables. (devanagari, slp1, iast)
|
| 84 |
+
# --------------------------------------------------------------------------------------
|
| 85 |
+
|
| 86 |
+
CONSONANTS = [
|
| 87 |
+
('क', 'k', 'k'), ('ख', 'K', 'kh'), ('ग', 'g', 'g'), ('घ', 'G', 'gh'),
|
| 88 |
+
('��', 'N', 'ṅ'),
|
| 89 |
+
('च', 'c', 'c'), ('छ', 'C', 'ch'), ('ज', 'j', 'j'), ('झ', 'J', 'jh'),
|
| 90 |
+
('ञ', 'Y', 'ñ'),
|
| 91 |
+
('ट', 'w', 'ṭ'), ('ठ', 'W', 'ṭh'), ('ड', 'q', 'ḍ'), ('ढ', 'Q', 'ḍh'),
|
| 92 |
+
('ण', 'R', 'ṇ'),
|
| 93 |
+
('त', 't', 't'), ('थ', 'T', 'th'), ('द', 'd', 'd'), ('ध', 'D', 'dh'),
|
| 94 |
+
('न', 'n', 'n'),
|
| 95 |
+
('प', 'p', 'p'), ('फ', 'P', 'ph'), ('ब', 'b', 'b'), ('भ', 'B', 'bh'),
|
| 96 |
+
('म', 'm', 'm'),
|
| 97 |
+
('य', 'y', 'y'), ('र', 'r', 'r'), ('ल', 'l', 'l'), ('व', 'v', 'v'),
|
| 98 |
+
('श', 'S', 'ś'), ('ष', 'z', 'ṣ'), ('स', 's', 's'), ('ह', 'h', 'h'),
|
| 99 |
+
('ळ', 'L', 'ḻ'), # ळ -> l with line below
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
# (independent, dependent sign or None, slp1, iast)
|
| 103 |
+
VOWELS = [
|
| 104 |
+
('अ', None, 'a', 'a'),
|
| 105 |
+
('आ', 'ा', 'A', 'ā'),
|
| 106 |
+
('इ', 'ि', 'i', 'i'),
|
| 107 |
+
('ई', 'ी', 'I', 'ī'),
|
| 108 |
+
('उ', 'ु', 'u', 'u'),
|
| 109 |
+
('ऊ', 'ू', 'U', 'ū'),
|
| 110 |
+
('ऋ', 'ृ', 'f', 'ṛ'),
|
| 111 |
+
('ॠ', 'ॄ', 'F', 'ṝ'),
|
| 112 |
+
('ऌ', 'ॢ', 'x', 'ḷ'),
|
| 113 |
+
('ॡ', 'ॣ', 'X', 'ḹ'),
|
| 114 |
+
('ए', 'े', 'e', 'e'),
|
| 115 |
+
('ऐ', 'ै', 'E', 'ai'),
|
| 116 |
+
('ओ', 'ो', 'o', 'o'),
|
| 117 |
+
('औ', 'ौ', 'O', 'au'),
|
| 118 |
+
('ऎ', 'ॆ', '+e', 'ĕ'), # short e
|
| 119 |
+
('ऒ', 'ॊ', '+o', 'ŏ'), # short o
|
| 120 |
+
('ऄ', None, '+a', 'ă'), # short a
|
| 121 |
+
('ऍ', 'ॅ', '*e', 'ê'), # candra e
|
| 122 |
+
('ऑ', 'ॉ', '*o', 'ô'), # candra o
|
| 123 |
+
('ॲ', None, '*a', 'â'), # candra a
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
# marks that stand on their own (never fuse with the inherent vowel)
|
| 127 |
+
MARKS = [
|
| 128 |
+
('ं', 'M', 'ṃ'), # anusvara
|
| 129 |
+
('ः', 'H', 'ḥ'), # visarga
|
| 130 |
+
('ँ', '~', 'm̐'), # candrabindu
|
| 131 |
+
('ऽ', "'", "'"), # avagraha
|
| 132 |
+
('ॐ', '%', '%'), # om
|
| 133 |
+
('॑', '/', '́'), # udatta <-> combining acute
|
| 134 |
+
('॒', '\\', '̀'), # anudatta <-> combining grave
|
| 135 |
+
('ᳵ', 'Z', 'ẖ'), # jihvamuliya
|
| 136 |
+
('ᳶ', 'V', 'ḫ'), # upadhmaniya
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
# identity on both sides, never reported. ZWJ/ZWNJ are here rather than in MARKS on
|
| 140 |
+
# purpose: giving them ASCII markers would collide with the literal '_' that DCS and
|
| 141 |
+
# VedaWeb use as a text marker, and they survive a round trip untouched as themselves.
|
| 142 |
+
PASSTHROUGH = set('।॥॰ॱ') | {ZWJ, ZWNJ} | {chr(c) for c in range(0x0966, 0x0970)}
|
| 143 |
+
|
| 144 |
+
# precomposed nukta letters -> base + U+093C (NFC already does this; belt and braces)
|
| 145 |
+
PRECOMPOSED_NUKTA = {
|
| 146 |
+
'ऩ': 'न' + NUKTA, 'ऱ': 'र' + NUKTA, 'ऴ': 'ळ' + NUKTA,
|
| 147 |
+
'क़': 'क' + NUKTA, 'ख़': 'ख' + NUKTA, 'ग़': 'ग' + NUKTA,
|
| 148 |
+
'ज़': 'ज' + NUKTA, 'ड़': 'ड' + NUKTA, 'ढ़': 'ढ' + NUKTA,
|
| 149 |
+
'फ़': 'फ' + NUKTA, 'य़': 'य' + NUKTA,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
_SLP1, _IAST = 0, 1
|
| 153 |
+
|
| 154 |
+
CONS_FWD = {d: (s, i) for d, s, i in CONSONANTS}
|
| 155 |
+
VSIGN_FWD = {sign: (s, i) for _, sign, s, i in VOWELS if sign}
|
| 156 |
+
VIND_FWD = {ind: (s, i) for ind, _, s, i in VOWELS}
|
| 157 |
+
MARK_FWD = {d: (s, i) for d, s, i in MARKS}
|
| 158 |
+
|
| 159 |
+
# reverse: value -> devanagari
|
| 160 |
+
CONS_REV = [{s: d for d, s, i in CONSONANTS}, {i: d for d, s, i in CONSONANTS}]
|
| 161 |
+
VOWEL_REV = [{s: (ind, sign) for ind, sign, s, i in VOWELS},
|
| 162 |
+
{i: (ind, sign) for ind, sign, s, i in VOWELS}]
|
| 163 |
+
MARK_REV = [{s: d for d, s, i in MARKS}, {i: d for d, s, i in MARKS}]
|
| 164 |
+
|
| 165 |
+
def _straddles(prev: str, nxt: str, enc: int) -> bool:
|
| 166 |
+
"""Would the junction of two emitted pieces re-parse as a different token?
|
| 167 |
+
|
| 168 |
+
k + ha reads back as ख, ka + i as कै, ka + ī as कै + a stray macron. Checked in NFD,
|
| 169 |
+
which is what the parser matches on. SLP1 has only single-character tokens, so this is
|
| 170 |
+
always False there."""
|
| 171 |
+
m = MAXTOK[enc]
|
| 172 |
+
if m < 2 or not prev or not nxt:
|
| 173 |
+
return False
|
| 174 |
+
a = unicodedata.normalize('NFD', prev)
|
| 175 |
+
b = unicodedata.normalize('NFD', nxt)
|
| 176 |
+
trie = TRIE_NFD[enc]
|
| 177 |
+
for i in range(1, min(len(a), m - 1) + 1):
|
| 178 |
+
for j in range(1, min(len(b), m - i) + 1):
|
| 179 |
+
if a[-i:] + b[:j] in trie:
|
| 180 |
+
return True
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
# functional meaning of each reserved character, per encoding
|
| 184 |
+
_FUNC_COMMON = {'^': ('nukta', None), '|': ('sep', None)}
|
| 185 |
+
FUNC = [
|
| 186 |
+
dict(_FUNC_COMMON, **{c: ('mark', d) for d, c, _ in MARKS if c in RESERVED},
|
| 187 |
+
**{'+': ('vmod', None), '*': ('vmod', None)}),
|
| 188 |
+
dict(_FUNC_COMMON, **{c: ('mark', d) for d, _, c in MARKS if c in RESERVED}),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _build_trie(enc):
|
| 193 |
+
"""token -> (kind, payload); longest match wins. Reserved chars are handled separately."""
|
| 194 |
+
t = {}
|
| 195 |
+
for d, s, i in CONSONANTS:
|
| 196 |
+
t[(s, i)[enc]] = ('cons', d)
|
| 197 |
+
for ind, sign, s, i in VOWELS:
|
| 198 |
+
v = (s, i)[enc]
|
| 199 |
+
if v[0] not in RESERVED:
|
| 200 |
+
t[v] = ('vowel', (ind, sign))
|
| 201 |
+
for d, s, i in MARKS:
|
| 202 |
+
v = (s, i)[enc]
|
| 203 |
+
if v[0] not in RESERVED:
|
| 204 |
+
t[v] = ('mark', d)
|
| 205 |
+
for c in PASSTHROUGH:
|
| 206 |
+
t[c] = ('pass', c)
|
| 207 |
+
return t
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# Input-only spellings. Real-world "IAST" is rarely pure: GRETIL and the DCS write the
|
| 211 |
+
# anusvara as ṁ, VedaWeb writes ISO-15919 vowels. These are accepted when parsing and never
|
| 212 |
+
# emitted, so the canonical round trip is unaffected while iast -> deva stops mangling them.
|
| 213 |
+
# ISO's ḷ (= ळ) is NOT aliased: in IAST ḷ is vocalic ऌ and that reading wins.
|
| 214 |
+
IAST_INPUT_ALIASES = {
|
| 215 |
+
'ṁ': ('mark', 'ं'),
|
| 216 |
+
'ē': ('vowel', ('ए', 'े')), 'ō': ('vowel', ('ओ', 'ो')),
|
| 217 |
+
'r̥': ('vowel', ('ऋ', 'ृ')), 'l̥': ('vowel', ('ऌ', 'ॢ')),
|
| 218 |
+
'r̥̄': ('vowel', ('ॠ', 'ॄ')), 'l̥̄': ('vowel', ('ॡ', 'ॣ')),
|
| 219 |
+
'ṝ': ('vowel', ('ॠ', 'ॄ')),
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
TRIE = [_build_trie(_SLP1), _build_trie(_IAST)]
|
| 223 |
+
# parsing runs on NFD so that composed letters (ī = i + macron) line up with combining
|
| 224 |
+
# accents; build the NFD tries once, not per call
|
| 225 |
+
TRIE_NFD = [{unicodedata.normalize('NFD', k): v for k, v in t.items()} for t in TRIE]
|
| 226 |
+
MAXTOK = [max(len(k) for k in t) for t in TRIE_NFD]
|
| 227 |
+
# what the parser matches on: canonical tokens plus the input-only aliases
|
| 228 |
+
TRIE_PARSE = [dict(TRIE_NFD[0]),
|
| 229 |
+
dict(TRIE_NFD[1], **{unicodedata.normalize('NFD', k): v
|
| 230 |
+
for k, v in IAST_INPUT_ALIASES.items()})]
|
| 231 |
+
MAXTOK_PARSE = [max(len(k) for k in t) for t in TRIE_PARSE]
|
| 232 |
+
# characters that a passthrough would collide with when read back
|
| 233 |
+
RISKY = [set(k[0] for k in TRIE[0]) - PASSTHROUGH, set(k[0] for k in TRIE[1]) - PASSTHROUGH]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def NFC(text: str) -> str:
|
| 237 |
+
return unicodedata.normalize('NFC', text)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def classify_char(ch: str) -> str:
|
| 241 |
+
"""Bucket an unmapped character for reporting."""
|
| 242 |
+
cp = ord(ch)
|
| 243 |
+
if 0x0900 <= cp <= 0x097F:
|
| 244 |
+
return 'devanagari_unmapped'
|
| 245 |
+
if 0x1CD0 <= cp <= 0x1CFF:
|
| 246 |
+
return 'vedic_extensions'
|
| 247 |
+
if 0xA8E0 <= cp <= 0xA8FF:
|
| 248 |
+
return 'devanagari_extended'
|
| 249 |
+
if cp < 0x0250 and ch.isalpha():
|
| 250 |
+
return 'latin'
|
| 251 |
+
if unicodedata.combining(ch):
|
| 252 |
+
return 'combining'
|
| 253 |
+
if ch.isalpha():
|
| 254 |
+
return 'other_script'
|
| 255 |
+
return 'other'
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _safe_pass(ch: str, enc: int) -> bool:
|
| 259 |
+
"""True if passing this character through is reversible and unremarkable."""
|
| 260 |
+
if ch in PASSTHROUGH:
|
| 261 |
+
return True
|
| 262 |
+
if ch in RESERVED:
|
| 263 |
+
return True # escaped by doubling, so reversible
|
| 264 |
+
if ch in RISKY[enc]:
|
| 265 |
+
return False
|
| 266 |
+
cat = unicodedata.category(ch)
|
| 267 |
+
return cat[0] in 'ZPSN' or ch in '\n\t\r' or cat == 'Cc'
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# --------------------------------------------------------------------------------------
|
| 271 |
+
# Devanagari -> romanised
|
| 272 |
+
# --------------------------------------------------------------------------------------
|
| 273 |
+
|
| 274 |
+
def _to_roman(text: str, enc: int):
|
| 275 |
+
text = NFC(text)
|
| 276 |
+
unmapped: Counter = Counter()
|
| 277 |
+
out: list[str] = []
|
| 278 |
+
inh = None # index in out of the inherent 'a' still open for replacement
|
| 279 |
+
bare = False # last piece was a consonant closed by virama
|
| 280 |
+
|
| 281 |
+
def put(piece: str):
|
| 282 |
+
"""Append a piece, inserting the '|' separator wherever the junction would re-parse.
|
| 283 |
+
|
| 284 |
+
Two cases: an IAST digraph straddling the junction (k + ha -> k|ha), and a reserved
|
| 285 |
+
marker landing next to the same marker, where the doubling escape would otherwise
|
| 286 |
+
read the pair as a literal (avagraha + avagraha -> '|', not '')."""
|
| 287 |
+
if out and out[-1] and piece:
|
| 288 |
+
a, b = out[-1][-1], piece[0]
|
| 289 |
+
if (a == b and b in RESERVED and b != '|') or _straddles(out[-1], piece, enc):
|
| 290 |
+
out.append('|')
|
| 291 |
+
out.append(piece)
|
| 292 |
+
|
| 293 |
+
def raw(ch: str):
|
| 294 |
+
nonlocal inh, bare
|
| 295 |
+
inh, bare = None, False
|
| 296 |
+
put(ch + ch if ch in RESERVED else ch)
|
| 297 |
+
|
| 298 |
+
i, n = 0, len(text)
|
| 299 |
+
while i < n:
|
| 300 |
+
ch = text[i]
|
| 301 |
+
i += 1
|
| 302 |
+
if ch in PRECOMPOSED_NUKTA: # only reachable if caller skipped NFC
|
| 303 |
+
text = text[:i - 1] + PRECOMPOSED_NUKTA[ch] + text[i:]
|
| 304 |
+
n = len(text)
|
| 305 |
+
i -= 1
|
| 306 |
+
continue
|
| 307 |
+
if ch in CONS_FWD:
|
| 308 |
+
put(CONS_FWD[ch][enc])
|
| 309 |
+
out.append('a')
|
| 310 |
+
inh = len(out) - 1
|
| 311 |
+
bare = False
|
| 312 |
+
elif ch == NUKTA:
|
| 313 |
+
# a second nukta on the same consonant would emit '^^', which reads back as an
|
| 314 |
+
# escaped literal '^'; refuse rather than lose it silently
|
| 315 |
+
if inh is not None and inh == len(out) - 1 and out[inh - 1] != '^':
|
| 316 |
+
out.insert(inh, '^')
|
| 317 |
+
inh += 1
|
| 318 |
+
else:
|
| 319 |
+
unmapped[ch] += 1
|
| 320 |
+
raw(ch)
|
| 321 |
+
elif ch in VSIGN_FWD:
|
| 322 |
+
if inh is not None and inh == len(out) - 1:
|
| 323 |
+
v = VSIGN_FWD[ch][enc]
|
| 324 |
+
out[inh] = ('|' + v) if (len(out) > 1 and _straddles(out[-2], v, enc)) else v
|
| 325 |
+
inh = None
|
| 326 |
+
else:
|
| 327 |
+
unmapped[ch] += 1
|
| 328 |
+
raw(ch)
|
| 329 |
+
elif ch == VIRAMA:
|
| 330 |
+
if inh is not None and inh == len(out) - 1:
|
| 331 |
+
out.pop()
|
| 332 |
+
inh = None
|
| 333 |
+
bare = True
|
| 334 |
+
else:
|
| 335 |
+
unmapped[ch] += 1
|
| 336 |
+
raw(ch)
|
| 337 |
+
elif ch in VIND_FWD:
|
| 338 |
+
# an independent vowel right after a bare consonant would be read back as that
|
| 339 |
+
# consonant's dependent sign (र् + ऋ -> "rf" -> रृ), so separate them
|
| 340 |
+
if bare:
|
| 341 |
+
out.append('|')
|
| 342 |
+
inh, bare = None, False
|
| 343 |
+
put(VIND_FWD[ch][enc])
|
| 344 |
+
elif ch in MARK_FWD:
|
| 345 |
+
inh, bare = None, False
|
| 346 |
+
put(MARK_FWD[ch][enc])
|
| 347 |
+
elif ch in PASSTHROUGH:
|
| 348 |
+
inh, bare = None, False
|
| 349 |
+
out.append(ch)
|
| 350 |
+
else:
|
| 351 |
+
if not _safe_pass(ch, enc):
|
| 352 |
+
unmapped[ch] += 1
|
| 353 |
+
raw(ch)
|
| 354 |
+
return NFC(''.join(out)), unmapped
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def deva_to_slp1(text: str):
|
| 358 |
+
"""Devanagari -> SLP1. Returns (slp1, Counter of unmapped characters)."""
|
| 359 |
+
return _to_roman(text, _SLP1)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def deva_to_iast(text: str):
|
| 363 |
+
"""Devanagari -> IAST. Returns (iast, Counter of unmapped characters)."""
|
| 364 |
+
return _to_roman(text, _IAST)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
# --------------------------------------------------------------------------------------
|
| 368 |
+
# romanised -> Devanagari
|
| 369 |
+
# --------------------------------------------------------------------------------------
|
| 370 |
+
|
| 371 |
+
def _to_deva(text: str, enc: int):
|
| 372 |
+
text = unicodedata.normalize('NFD', NFC(text))
|
| 373 |
+
unmapped: Counter = Counter()
|
| 374 |
+
trie, maxtok, func = TRIE_PARSE[enc], MAXTOK_PARSE[enc], FUNC[enc]
|
| 375 |
+
out: list[str] = []
|
| 376 |
+
pend = None # consonant awaiting its vowel
|
| 377 |
+
nukta = False
|
| 378 |
+
|
| 379 |
+
def close():
|
| 380 |
+
nonlocal pend, nukta
|
| 381 |
+
if pend is not None:
|
| 382 |
+
out.append(pend)
|
| 383 |
+
if nukta:
|
| 384 |
+
out.append(NUKTA)
|
| 385 |
+
out.append(VIRAMA)
|
| 386 |
+
pend, nukta = None, False
|
| 387 |
+
|
| 388 |
+
def vowel(ind, sign):
|
| 389 |
+
nonlocal pend, nukta
|
| 390 |
+
if pend is not None:
|
| 391 |
+
out.append(pend)
|
| 392 |
+
if nukta:
|
| 393 |
+
out.append(NUKTA)
|
| 394 |
+
if sign is not None:
|
| 395 |
+
out.append(sign)
|
| 396 |
+
elif ind != 'अ':
|
| 397 |
+
unmapped[ind] += 1 # no dependent form (ऄ, ॲ) after a consonant
|
| 398 |
+
out.append(VIRAMA)
|
| 399 |
+
out.append(ind)
|
| 400 |
+
pend, nukta = None, False
|
| 401 |
+
else:
|
| 402 |
+
out.append(ind)
|
| 403 |
+
|
| 404 |
+
i, n = 0, len(text)
|
| 405 |
+
while i < n:
|
| 406 |
+
ch = text[i]
|
| 407 |
+
if ch in RESERVED:
|
| 408 |
+
if i + 1 < n and text[i + 1] == ch: # escaped literal
|
| 409 |
+
close()
|
| 410 |
+
out.append(ch)
|
| 411 |
+
i += 2
|
| 412 |
+
continue
|
| 413 |
+
kind, payload = func.get(ch, (None, None))
|
| 414 |
+
if kind == 'nukta' and pend is not None and not nukta:
|
| 415 |
+
nukta = True
|
| 416 |
+
i += 1
|
| 417 |
+
continue
|
| 418 |
+
if kind == 'sep':
|
| 419 |
+
# Our emitter only ever puts the separator BETWEEN two letters, so a '|' that
|
| 420 |
+
# touches whitespace is not ours: it is the ASCII dandaa that GRETIL-style
|
| 421 |
+
# romanised sources use. Keep it (and report it) instead of swallowing it.
|
| 422 |
+
if (text[i - 1] if i else ' ').isspace() or \
|
| 423 |
+
(text[i + 1] if i + 1 < n else ' ').isspace():
|
| 424 |
+
unmapped[ch] += 1
|
| 425 |
+
close()
|
| 426 |
+
out.append(ch)
|
| 427 |
+
else:
|
| 428 |
+
close()
|
| 429 |
+
i += 1
|
| 430 |
+
continue
|
| 431 |
+
if kind == 'vmod':
|
| 432 |
+
tok = text[i:i + 2]
|
| 433 |
+
hit = VOWEL_REV[enc].get(tok)
|
| 434 |
+
if hit:
|
| 435 |
+
vowel(*hit)
|
| 436 |
+
i += 2
|
| 437 |
+
continue
|
| 438 |
+
if kind == 'mark':
|
| 439 |
+
close()
|
| 440 |
+
out.append(payload)
|
| 441 |
+
i += 1
|
| 442 |
+
continue
|
| 443 |
+
unmapped[ch] += 1
|
| 444 |
+
close()
|
| 445 |
+
out.append(ch)
|
| 446 |
+
i += 1
|
| 447 |
+
continue
|
| 448 |
+
for L in range(min(maxtok, n - i), 0, -1):
|
| 449 |
+
hit = trie.get(text[i:i + L])
|
| 450 |
+
if hit:
|
| 451 |
+
kind, payload = hit
|
| 452 |
+
if kind == 'cons':
|
| 453 |
+
close()
|
| 454 |
+
pend = payload
|
| 455 |
+
elif kind == 'vowel':
|
| 456 |
+
vowel(*payload)
|
| 457 |
+
else:
|
| 458 |
+
close()
|
| 459 |
+
out.append(payload)
|
| 460 |
+
i += L
|
| 461 |
+
break
|
| 462 |
+
else:
|
| 463 |
+
if not _safe_pass(ch, enc):
|
| 464 |
+
unmapped[ch] += 1
|
| 465 |
+
close()
|
| 466 |
+
out.append(ch)
|
| 467 |
+
i += 1
|
| 468 |
+
close()
|
| 469 |
+
return NFC(''.join(out)), unmapped
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def slp1_to_deva(text: str):
|
| 473 |
+
"""SLP1 -> Devanagari. Returns (devanagari, Counter of unmapped characters)."""
|
| 474 |
+
return _to_deva(text, _SLP1)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def iast_to_deva(text: str):
|
| 478 |
+
"""IAST -> Devanagari. Returns (devanagari, Counter of unmapped characters)."""
|
| 479 |
+
return _to_deva(text, _IAST)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# --------------------------------------------------------------------------------------
|
| 483 |
+
# ISO-15919 (as VedaWeb writes it) -> our canonical IAST
|
| 484 |
+
# --------------------------------------------------------------------------------------
|
| 485 |
+
# Applied on NFD so that the pitch accents (combining acute/grave) survive on the vowel.
|
| 486 |
+
_ISO_PAIRS = [
|
| 487 |
+
('r̥̄', 'ṝ'), ('l̥̄', 'ḹ'), # r̥̄ l̥̄ -> ṝ ḹ
|
| 488 |
+
('r̥', 'ṛ'), ('l̥', 'ḷ'), # r̥ l̥ -> ṛ ḷ
|
| 489 |
+
('ḷ', 'ḻ'), # ISO ḷ is ळ, not vocalic l
|
| 490 |
+
('ṁ', 'ṃ'), # ṁ -> ṃ
|
| 491 |
+
('ē', 'e'), ('ō', 'o'), # ē ō -> e o
|
| 492 |
+
('ṉ', 'n'), ('ṟ', 'r'), # ṉ ṟ (nukta-ish ISO) -> n r
|
| 493 |
+
]
|
| 494 |
+
_ISO_ESCAPE = set(RESERVED) - {"'"} # keep ' meaning avagraha
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def iso15919_to_iast(text: str):
|
| 498 |
+
"""VedaWeb-style ISO-15919 (with pitch accents) -> our strict IAST.
|
| 499 |
+
|
| 500 |
+
Reserved characters other than the avagraha apostrophe are escaped by doubling, so the
|
| 501 |
+
result is a legal input to :func:`iast_to_deva`.
|
| 502 |
+
"""
|
| 503 |
+
src = unicodedata.normalize('NFD', NFC(text))
|
| 504 |
+
# longest source first so r̥̄ beats r̥
|
| 505 |
+
pairs = sorted(_ISO_PAIRS, key=lambda p: -len(unicodedata.normalize('NFD', p[0])))
|
| 506 |
+
pairs = [(unicodedata.normalize('NFD', a), b) for a, b in pairs]
|
| 507 |
+
out, i, n = [], 0, len(src)
|
| 508 |
+
unmapped: Counter = Counter()
|
| 509 |
+
while i < n:
|
| 510 |
+
for a, b in pairs:
|
| 511 |
+
if src.startswith(a, i):
|
| 512 |
+
out.append(b)
|
| 513 |
+
i += len(a)
|
| 514 |
+
break
|
| 515 |
+
else:
|
| 516 |
+
ch = src[i]
|
| 517 |
+
out.append(ch + ch if ch in _ISO_ESCAPE else ch)
|
| 518 |
+
i += 1
|
| 519 |
+
return NFC(''.join(out)), unmapped
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
# --------------------------------------------------------------------------------------
|
| 523 |
+
# Akshara segmentation (explicit Devanagari regex; NOT \X, which breaks after virama)
|
| 524 |
+
# --------------------------------------------------------------------------------------
|
| 525 |
+
_C = '[क-हक़-य़ॹ-ॿऩऱऴ]'
|
| 526 |
+
_V = '[ऄ-औॠॡॲ-ॷ]'
|
| 527 |
+
_S = '[ऺऻा-ौॎॏॕ-ॗॢॣ]'
|
| 528 |
+
_A = '[ऀ-ः॑-॔᳐-᳨ᳵᳶ꣠-꣱]'
|
| 529 |
+
AKSHARA_RE = (
|
| 530 |
+
f'(?:{_C}़?(?:्[]?{_C}़?)*(?:{_S}|्)?|{_V}़?{_S}?){_A}*'
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def split_aksharas(text: str):
|
| 535 |
+
"""Devanagari orthographic syllables; anything else comes back one code point per item."""
|
| 536 |
+
import regex
|
| 537 |
+
pat = regex.compile(f'{AKSHARA_RE}|.', regex.DOTALL)
|
| 538 |
+
return [m.group(0) for m in pat.finditer(text)]
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
if __name__ == '__main__':
|
| 542 |
+
import sys
|
| 543 |
+
for line in (sys.argv[1:] or ['धर्मक्षेत्रे कुरुक्षेत्रे समवेता युयुत्सवः ॥ १ ॥']):
|
| 544 |
+
s, us = deva_to_slp1(line)
|
| 545 |
+
a, ua = deva_to_iast(line)
|
| 546 |
+
print('deva :', line)
|
| 547 |
+
print('slp1 :', s, ' unmapped', dict(us))
|
| 548 |
+
print('iast :', a, ' unmapped', dict(ua))
|
| 549 |
+
print('back :', slp1_to_deva(s)[0] == NFC(line), iast_to_deva(a)[0] == NFC(line))
|