Views
No views yet
Model42M-V1) is a lightweight, efficient, and educational GPT-style decoder-only language model built completely from scratch in PyTorch. Trained on over 1.5B tokens and aligned with high-quality structured instruction datasets, VaghLM is designed to deliver rapid, structured, and helpful responses on consumer hardware.1graph TD
2 UserQuery[User Prompt] --> Tokenizer[SentencePiece BPE Tokenizer]
3 Tokenizer --> SpecTokens[Sequence: BOS + USER + tokens + ASSISTANT]
4 SpecTokens --> Model[VaghLM-42M Block Layers]
5
6 subgraph Blocks ["8 x Transformer Blocks"]
7 Model --> LN1[LayerNorm]
8 LN1 --> SDPA[Causal Multi-Head Self-Attention]
9 SDPA --> Add1[Residual Connection]
10
11 Add1 --> LN2[LayerNorm]
12 LN2 --> GELU[FFN: Linear -> GELU -> Linear]
13 GELU --> Add2[Residual Connection]
14 end
15
16 Add2 --> LNFinal[Final LayerNorm]
17 LNFinal --> TiedHead[Tied LM Head Output Projection]
18 TiedHead --> Sampler[Nucleus / Temp / Repetition Sampler]
19 Sampler --> OutputToken[Next Token Prediction]| Parameter / Configuration | Value / Details |
|---|---|
| Model Name | VaghLM-42M (Model42M-V1) |
| Active Parameters (Tied) | 42,615,808 (~42.6M) |
| Total Parameters (Untied) | 59,000,000 (~59M) |
| Vocabulary Size | 32,000 |
| Context Length | 2,048 tokens |
| Transformer Layers | 8 |
| Attention Heads | 8 |
| Embedding Dimension ($d_{model}$) | 512 |
| Feed-Forward Dimension ($d_{ff}$) | 2,048 |
| Weight Tying | Enabled (Input embeddings shared with output projection) |
| Positional Embeddings | Learned Absolute Positional Embeddings |
| Normalization | Pre-LayerNorm (standard nn.LayerNorm) |
SentencePiece library, with specialized tokens for structuring conversational turns (<user>, <assistant>, code, system, etc.).scaled_dot_product_attention (compatible with FlashAttention kernel executions).autocast and GradScaler) for memory-efficient and stable training.1VaghLM-42M/
2├── assets/ # Visual diagrams and assets (Mermaid models)
3├── checkpoints/ # Saved weights (.pt files)
4├── data/
5│ └── tokenized/
6│ └── all_tokens.bin # Binary file of pre-tokenized training data (1.6B tokens)
7├── examples/
8│ ├── generate_example.py # Simple, self-contained inference script
9│ └── load_model.py # Model inspection and validation script
10├── inference/
11│ └── generate.py # CLI interactive chat application script
12├── model/
13│ ├── __init__.py
14│ ├── attention.py # Multi-Head Causal Self-Attention block
15│ ├── config.py # Hyperparameter configurations (VaghLMConfig)
16│ ├── embeddings.py # Learned Token + Positional embeddings
17│ └── transformer.py # Main VaghLM Transformer model implementation
18├── tokenizer/
19│ └── vocab/
20│ ├── tokenizer.model # SentencePiece BPE model file
21│ └── tokenizer.vocab # Vocabulary list file
22├── training/
23│ ├── __init__.py
24│ ├── dataset.py # NumPy memmap training dataset & dataloader loaders
25│ └── trainer.py # Core pretraining & evaluation training script
26├── .gitignore # Git exclusion rules
27├── CHANGELOG.md # Release version history
28├── CITATION.cff # Citation metadata YAML
29├── CODE_OF_CONDUCT.md # Contributor Covenant Code of Conduct
30├── CONTRIBUTING.md # Developer contribution guidelines
31├── data.md # Instruction dataset distribution & 500 seed examples
32├── generate_data_md.py # Script to validate and compile seed instruction examples
33├── gradio_app.py # Gradio chat web server script
34├── INSTALL.md # Comprehensive install steps for Windows & Linux
35├── LICENSE # MIT License
36├── requirements.txt # Python library dependencies
37├── upload.py # Hugging Face hub folder upload script
38└── USAGE.md # Detailed model execution & sampling controls guide1# Clone the repository
2git clone https://github.com/Heet24/VaghLM-42M.git
3cd VaghLM-42M
4
5# Create and activate virtual environment (Windows)
6python -m venv venv
7.\venv\Scripts\activate
8
9# Create and activate virtual environment (Linux)
10# python3 -m venv venv
11# source venv/bin/activate
12
13# Install requirements
14pip install -r requirements.txt1from huggingface_hub import hf_hub_download
2import os
3
4os.makedirs("checkpoints", exist_ok=True)
5hf_hub_download(repo_id="Heet24/model42M-v1", filename="finetuned_v2_best.pt", local_dir="checkpoints")python inference/generate.pypython gradio_app.pyhttp://127.0.0.1:7860 in your web browser.1import torch
2import sentencepiece as spm
3from model.config import VaghLMConfig
4from model.transformer import VaghLM
5
6# Load model configurations
7config = VaghLMConfig()
8device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
10# Load model
11model = VaghLM(config)
12checkpoint = torch.load("checkpoints/finetuned_v2_best.pt", map_location=device)
13model.load_state_dict(checkpoint["model_state"])
14model.to(device)
15model.eval()
16
17# Load Tokenizer
18sp = spm.SentencePieceProcessor(model_file="tokenizer/vocab/tokenizer.model")
19
20# Format prompt
21prompt = "Explain Newton's third law of motion."
22input_ids = [config.bos_id, config.user_id] + sp.encode(prompt) + [config.assistant_id]
23x = torch.tensor([input_ids], dtype=torch.long, device=device)
24
25# Simple greedy inference loop
26generated = []
27with torch.no_grad():
28 for _ in range(150):
29 logits, _ = model(x)
30 next_token = torch.argmax(logits[:, -1, :], dim=-1, keepdim=True)
31 if next_token.item() == config.eos_id:
32 break
33 generated.append(next_token.item())
34 x = torch.cat([x, next_token], dim=1)
35
36print("Response:", sp.decode(generated))1flowchart TD
2 RawData[Raw English Text Corpus] --> Tokenize[SentencePiece Tokenizer Train]
3 Tokenize --> BinaryTokens[Convert Corpus to uint16 Binary File]
4 BinaryTokens --> Pretraining[Pretraining Loop: Cosine LR Decay + Warmup]
5 Pretraining --> PretrainedWeights[Base Model Weights: best_checkpoint.pt]
6
7 PretrainedWeights --> InstructionTuning[Instruction Alignment: XML Prompts]
8 InstructionTuning --> FinetunedWeights[Aligned Model Weights: finetuned_v2_best.pt]1@software{Rana_VaghLM-42M_A_42,
2 author = {Rana, Heet},
3 title = {{VaghLM-42M: A 42.6M Parameter Decoder-Only Transformer Trained From Scratch}},
4 url = {https://github.com/Heet24/VaghLM-42M},
5 version = {1.0.0},
6 year = {2026}
7}