cneuralnetwork/nanosarvam

A repo to train your own small sarvam-30b model

Python

77

1 commits

updated Mar 7, 2026

See the code

README

nanosarvam

nanosarvam architecture

A compact, from-scratch implementation of a Mixture-of-Experts (MoE) language model inspired by the Sarvam-30B and DeepSeek-V2 architectures.

Designed to be readable, hackable, and trainable on consumer GPUs.


Architecture

ComponentDetail
AttentionGrouped-Query Attention (GQA) with QK-Norm and RoPE
FFNSwiGLU dense block (layer 0) + MoE blocks (remaining layers)
MoE routingTop-K sparse routing with a shared always-active expert
NormalisationRMSNorm pre-norm throughout
Position encodingRotary Position Embeddings (RoPE)

Full config (~30 B parameters)

HyperparameterValue
Hidden dim4096
Layers19
Attention heads64
KV heads4
Head dim64
Vocab size262 144
Max sequence length131 072
Routed experts128
Active experts per token6
Expert hidden dim1024

Tiny config (~300 M parameters, fits on 8 GB VRAM)

Enabled with --tiny. Suitable for experimentation on a consumer GPU.

HyperparameterValue
Hidden dim1024
Layers12
Attention heads16
KV heads4
Head dim64
Routed experts8
Active experts per token2
Expert hidden dim512

Installation

git clone https://github.com/cneuralnetwork/nanosarvam
cd nanosarvam
pip install -r requirements.txt

Requirements: Python 3.11+, PyTorch 2.2+, a CUDA-capable GPU.


Quickstart

export WANDB_API_KEY=your_key_here        # or pass --wandb_api_key

python train.py \
  --tiny \
  --use_fp16 \
  --use_8bit_adam \
  --grad_checkpoint \
  --batch_size 1 \
  --accumulation_steps 16 \
  --max_seq_len 512

Expected VRAM usage: ~2.5 GB weights + optimizer, ~0.4 GB activations.

Train on a custom Hugging Face dataset

Any public or gated Hugging Face dataset works. Specify the repo ID with --dataset, the text column with --text_field, and the split names:

# OpenWebText
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "Skylion007/openwebtext" \
  --text_field text \
  --val_split none          # openwebtext has no validation split

# FineWeb (10 BT sample, gated — requires HF token)
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "HuggingFaceFW/fineweb" \
  --dataset_name "sample-10BT" \
  --text_field text \
  --val_split none \
  --hf_token YOUR_HF_TOKEN

# SlimPajama
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "cerebras/SlimPajama-627B" \
  --text_field text \
  --train_split train \
  --val_split validation

Full argument reference

Dataset

ArgumentDefaultDescription
--datasetroneneldan/TinyStoriesHugging Face dataset repo ID
--dataset_nameNoneDataset config name (e.g. sample-10BT for FineWeb)
--text_fieldtextColumn that contains raw text
--train_splittrainSplit name for training data
--val_splitvalidationSplit name for validation data; set to none to skip
--hf_token$HF_TOKENHuggingFace token for gated datasets

Tokenizer

ArgumentDefaultDescription
--tokenizerEleutherAI/gpt-neo-125MHuggingFace tokenizer repo ID

Model

ArgumentDefaultDescription
--tinyoffUse the ~300 M-param config instead of the full ~30 B config
--max_seq_len512Maximum context length in tokens

Training

ArgumentDefaultDescription
--epochs3Number of full passes over the training data
--batch_size1Per-step batch size
--accumulation_steps16Gradient accumulation steps (effective batch = batch × accumulation)
--lr1e-4Peak learning rate
--deviceautocuda or cpu
--num_workers4DataLoader worker processes

Memory optimisation

ArgumentDefaultDescription
--use_fp16offFP16 mixed-precision training (recommended)
--use_8bit_adamoff8-bit AdamW via bitsandbytes (~4× smaller optimizer state)
--grad_checkpointoffGradient checkpointing (saves activation memory, ~30% slower)

Checkpointing

ArgumentDefaultDescription
--save_dir./checkpointsDirectory for checkpoints and logs
--save_every500Save a checkpoint every N optimizer steps
--resume_fromNonePath to a .pt checkpoint to resume training from

Weights & Biases

ArgumentDefaultDescription
--wandb_api_key$WANDB_API_KEYW&B API key (prefer env var over CLI to avoid leaking in shell history)
--wandb_projectnanosarvamW&B project name
--wandb_run_nameautoW&B run name
--log_every10Log metrics every N optimizer steps

API keys and secrets

Never hardcode API keys in source files. nanosarvam reads credentials from environment variables and falls back to CLI args as a convenience for one-off runs.

# Recommended: set in your shell profile or a .env file (never commit .env)
export WANDB_API_KEY=...
export HF_TOKEN=...         # only needed for gated datasets

python train.py --tiny --use_fp16 --use_8bit_adam ...

If no W&B key is found, the run is logged offline to ./wandb/.


VRAM reference (tiny config, seq_len=512)

ConfigurationEstimated VRAM
FP32 + standard Adam~11.6 GB
FP16 + standard Adam~10.2 GB
FP16 + 8-bit Adam~6.0 GB
FP16 + 8-bit Adam + grad checkpoint~5.5 GB

Resuming a run

python train.py --tiny --use_fp16 --use_8bit_adam \
  --resume_from ./checkpoints/checkpoint_step_1000.pt

Project structure

nanosarvam/
├── model.py          # Model definition (RMSNorm, RoPE, GQA, SwiGLU, MoE)
├── train.py          # Training loop, dataset loading, CLI
├── requirements.txt
└── README.md

Contributors

cneuralnetwork/nanosarvam

A repo to train your own small sarvam-30b model

Python

77

1 commits

updated Mar 7, 2026

See the code

README

nanosarvam

nanosarvam architecture

A compact, from-scratch implementation of a Mixture-of-Experts (MoE) language model inspired by the Sarvam-30B and DeepSeek-V2 architectures.

Designed to be readable, hackable, and trainable on consumer GPUs.


Architecture

ComponentDetail
AttentionGrouped-Query Attention (GQA) with QK-Norm and RoPE
FFNSwiGLU dense block (layer 0) + MoE blocks (remaining layers)
MoE routingTop-K sparse routing with a shared always-active expert
NormalisationRMSNorm pre-norm throughout
Position encodingRotary Position Embeddings (RoPE)

Full config (~30 B parameters)

HyperparameterValue
Hidden dim4096
Layers19
Attention heads64
KV heads4
Head dim64
Vocab size262 144
Max sequence length131 072
Routed experts128
Active experts per token6
Expert hidden dim1024

Tiny config (~300 M parameters, fits on 8 GB VRAM)

Enabled with --tiny. Suitable for experimentation on a consumer GPU.

HyperparameterValue
Hidden dim1024
Layers12
Attention heads16
KV heads4
Head dim64
Routed experts8
Active experts per token2
Expert hidden dim512

Installation

git clone https://github.com/cneuralnetwork/nanosarvam
cd nanosarvam
pip install -r requirements.txt

Requirements: Python 3.11+, PyTorch 2.2+, a CUDA-capable GPU.


Quickstart

export WANDB_API_KEY=your_key_here        # or pass --wandb_api_key

python train.py \
  --tiny \
  --use_fp16 \
  --use_8bit_adam \
  --grad_checkpoint \
  --batch_size 1 \
  --accumulation_steps 16 \
  --max_seq_len 512

Expected VRAM usage: ~2.5 GB weights + optimizer, ~0.4 GB activations.

Train on a custom Hugging Face dataset

Any public or gated Hugging Face dataset works. Specify the repo ID with --dataset, the text column with --text_field, and the split names:

# OpenWebText
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "Skylion007/openwebtext" \
  --text_field text \
  --val_split none          # openwebtext has no validation split

# FineWeb (10 BT sample, gated — requires HF token)
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "HuggingFaceFW/fineweb" \
  --dataset_name "sample-10BT" \
  --text_field text \
  --val_split none \
  --hf_token YOUR_HF_TOKEN

# SlimPajama
python train.py --tiny --use_fp16 --use_8bit_adam \
  --dataset "cerebras/SlimPajama-627B" \
  --text_field text \
  --train_split train \
  --val_split validation

Full argument reference

Dataset

ArgumentDefaultDescription
--datasetroneneldan/TinyStoriesHugging Face dataset repo ID
--dataset_nameNoneDataset config name (e.g. sample-10BT for FineWeb)
--text_fieldtextColumn that contains raw text
--train_splittrainSplit name for training data
--val_splitvalidationSplit name for validation data; set to none to skip
--hf_token$HF_TOKENHuggingFace token for gated datasets

Tokenizer

ArgumentDefaultDescription
--tokenizerEleutherAI/gpt-neo-125MHuggingFace tokenizer repo ID

Model

ArgumentDefaultDescription
--tinyoffUse the ~300 M-param config instead of the full ~30 B config
--max_seq_len512Maximum context length in tokens

Training

ArgumentDefaultDescription
--epochs3Number of full passes over the training data
--batch_size1Per-step batch size
--accumulation_steps16Gradient accumulation steps (effective batch = batch × accumulation)
--lr1e-4Peak learning rate
--deviceautocuda or cpu
--num_workers4DataLoader worker processes

Memory optimisation

ArgumentDefaultDescription
--use_fp16offFP16 mixed-precision training (recommended)
--use_8bit_adamoff8-bit AdamW via bitsandbytes (~4× smaller optimizer state)
--grad_checkpointoffGradient checkpointing (saves activation memory, ~30% slower)

Checkpointing

ArgumentDefaultDescription
--save_dir./checkpointsDirectory for checkpoints and logs
--save_every500Save a checkpoint every N optimizer steps
--resume_fromNonePath to a .pt checkpoint to resume training from

Weights & Biases

ArgumentDefaultDescription
--wandb_api_key$WANDB_API_KEYW&B API key (prefer env var over CLI to avoid leaking in shell history)
--wandb_projectnanosarvamW&B project name
--wandb_run_nameautoW&B run name
--log_every10Log metrics every N optimizer steps

API keys and secrets

Never hardcode API keys in source files. nanosarvam reads credentials from environment variables and falls back to CLI args as a convenience for one-off runs.

# Recommended: set in your shell profile or a .env file (never commit .env)
export WANDB_API_KEY=...
export HF_TOKEN=...         # only needed for gated datasets

python train.py --tiny --use_fp16 --use_8bit_adam ...

If no W&B key is found, the run is logged offline to ./wandb/.


VRAM reference (tiny config, seq_len=512)

ConfigurationEstimated VRAM
FP32 + standard Adam~11.6 GB
FP16 + standard Adam~10.2 GB
FP16 + 8-bit Adam~6.0 GB
FP16 + 8-bit Adam + grad checkpoint~5.5 GB

Resuming a run

python train.py --tiny --use_fp16 --use_8bit_adam \
  --resume_from ./checkpoints/checkpoint_step_1000.pt

Project structure

nanosarvam/
├── model.py          # Model definition (RMSNorm, RoPE, GQA, SwiGLU, MoE)
├── train.py          # Training loop, dataset loading, CLI
├── requirements.txt
└── README.md

Contributors

Languages

Python

100.0%