Metadata-Version: 2.4
Name: build-slm
Version: 1.1.1
Summary: Research-Grade TPU-Native Language Model Training and Inference Framework
Home-page: https://github.com/niranjankumark/slm
Author: Niranjan Kumar K.
License: Apache-2.0
Project-URL: Homepage, https://github.com/niranjankumark/slm
Project-URL: Documentation, https://github.com/niranjankumark/slm/blob/main/docs/USER_GUIDE.md
Project-URL: Bug Tracker, https://github.com/niranjankumark/slm/issues
Keywords: transformer,slm,language-model,tpu,jax,xla,deep-learning,instruction-tuning,rope,rmsnorm,swiglu,kv-cache
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Provides-Extra: tpu
Requires-Dist: jax[tpu]; extra == "tpu"
Provides-Extra: gpu
Requires-Dist: jax[cuda]; extra == "gpu"
Provides-Extra: cpu
Requires-Dist: jax; extra == "cpu"
Provides-Extra: dev
Requires-Dist: twine; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# SLM: Research-Grade TPU-Native Language Model Framework

**Package name:** `build-slm` &nbsp;|&nbsp; **Import name:** `slm` &nbsp;|&nbsp; **Author:** Niranjan Kumar K. &nbsp;|&nbsp; **Version:** 1.1.1 &nbsp;|&nbsp; **License:** Apache-2.0

An advanced, scalable, research-grade language model training and inference framework optimized exclusively for Google Colab TPU accelerators using JAX and XLA, featuring a 100% pure-Python CPU reference implementation.

See [the user guide](docs/USER_GUIDE.md), [the Google Colab TPU guide](docs/COLAB_TPU_GUIDE.md), [the benchmark report](docs/BENCHMARK_REPORT.md), and [the automated test report](docs/TEST_REPORT.md).

---

## Highlights

- **TPU-Native JAX/XLA Engine**: High-throughput training on Google Colab TPU (v2-8, v3-8, v4-8) with bfloat16 mixed precision and float32 master weights.
- **Advanced Architecture**: Causal multi-head attention, vectorized RoPE, numerically stable RMSNorm in float32, SwiGLU feed-forward networks, and pre-normalization.
- **Sequence Packing**: Static-shape sequence multi-packing with 2D block-diagonal causal masks and padding-aware loss masks.
- **Multi-Device TPU Scaling**: Automatic topology inspection, JAX device mesh, and `NamedSharding` across TPU cores.
- **Dedicated Instruction Tuning**: SFT pipeline supporting QA, Alpaca-style instruction-response, multi-turn, reasoning, and math datasets with **assistant-only loss masking**.
- **Inference Optimization**: Stateful KV-caching for O(1) decoding, greedy search, temperature, top-k, nucleus top-p, and repetition penalties.
- **Data Quality Intelligence**: Multi-stage cleaning, unicode NFKC, mojibake repair, HTML/boilerplate stripping, SimHash deduplication, 10-domain classification, and zero-leakage disjoint splitting.
- **Comprehensive Evaluation**: Top-1, Top-5, Top-10 token accuracy, word accuracy, perplexity, Expected Calibration Error (ECE), and long-context position-bucket evaluation.
- **Safe Migration & Recovery**: Atomic checkpoint saving with SHA-256 parameter checksums and backward-compatible v4-to-v5 `.kni` migration.

---

## What's new in 1.1 — models that keep learning

- **`model.learn()`** — continue learning from the current weights (not a retrain): text, files, folders, Q/A pairs, conversations. Replay of old data + a light weight anchor prevent forgetting, a safety check rolls back any update that damages old knowledge, and a self-quiz retrains whatever it still gets wrong.
- **`model.learn()` with no data = self-learning** — the model quizzes itself on everything it knows (and on your `feedback()`), then trains only on its mistakes.
- **`model.ask()` / `model.chat()`** — assistant-style answers that stay accurate with little data: exact facts from the knowledge memory, the neural generator when it is confident *and* grounded, otherwise the best verbatim sentences from your documents (BM25). Unknown questions get "I don't know" instead of a confident guess.
- **NumPy fast engine** — batched training and a real KV cache, mathematically identical to the pure-Python reference (verified by parity tests), ~10–100× faster. Falls back to pure Python automatically.
- **Auto-sizing** — leave the dimensions out and the model, learning rate and epochs are matched to your data size.
- Many correctness fixes — see [CHANGELOG.md](CHANGELOG.md).

---

## Installation

```bash
# Base install (NumPy fast engine; still runs on pure Python if NumPy is missing)
pip install build-slm

# With TPU acceleration (Google Colab TPU)
pip install "build-slm[tpu]"

# With GPU acceleration (CUDA)
pip install "build-slm[gpu]"

# With CPU-only JAX
pip install "build-slm[cpu]"
```

---

## Quick Start

```python
from slm import *

model = slm()                                  # sizes itself to your data
model.train("folder_path", verbose=False)      # learn your documents

print(model.ask("Who founded Orbit Labs?"))    # grounded, assistant-style answer
print(model.ask("Who founded Orbit Labs?", return_details=True))  # + mode, confidence, sources

# Keep learning — continues from the current weights
model.learn([
    {"question": "Who leads the SLM project?", "answer": "Niranjan Kumar K. leads the SLM project."},
    "New paragraphs of text, a file path, or a folder path also work.",
])

# Correct it, then let it improve itself
model.feedback("Who leads the SLM project?", correction="Niranjan Kumar K.")
model.learn()                                  # self-learning: quiz itself, fix mistakes

print(model.chat("Hi! What do you know about the Aurora Solar Farm?"))
model.save("models/my_model")                  # knowledge + weights in one .kni file
```

`learn()` works on an untrained model too — it builds one from the data you give it.

### How `ask()` chooses an answer

| Source | Used when | Why it is accurate |
|---|---|---|
| `memory` | a fact taught with `learn()` / `feedback()` / `instruction_tune()` matches the question | exact stored answer, available instantly |
| `generate` | the network is confident and its answer is supported by retrieved passages | neural answer, checked against your data |
| `retrieve` | otherwise | best verbatim sentences from your documents — cannot hallucinate |
| `unknown` | nothing supports an answer | says so instead of guessing |

Force one with `mode="memory" | "generate" | "retrieve"`.

### Classic API (unchanged)

```python
from slm import *

model = slm(vocab_size=512, context_length=128, d_model=64, heads=4, layers=2, ff_dim=128)
report = model.train("folder_path", epochs=3, batch_size=4, gradient_accumulation_steps=2,
                     checkpoint_path="models/my_model.kni", use_advanced_cleaning=True)
output = model.predict("The research showed that", max_tokens=80, temperature=0.7, top_p=0.9)
```

Use `model.save("models/name")` and `model.load("models/name")` to store or restore a model. The only accepted model extension is `.kni`; it is added automatically when omitted. Checkpoints from 1.0.x load unchanged and give identical predictions.

### Honest expectations

A model trained from scratch on a few documents will not write like a large pretrained LLM. What 1.1 guarantees is that answers are *accurate*: grounded in what the model was taught, with the source and confidence available, and "I don't know" when it does not know. Fluency of the neural generator grows with data and model size.
