Waitlist open Our new book, AI Engineering For Production, is coming before the end of 2026. Get the release date first.New book: AI Engineering For Production, coming before the end of 2026. Join the waitlist
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: pub@towardsai.net
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab VeloxTrend Ultrarix Capital Partners Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

The Rise of the SLMs: Building the Smallest Possible Language Model.
Latest   Machine Learning

The Rise of the SLMs: Building the Smallest Possible Language Model.

Last Updated on October 29, 2026 by Editorial Team

Author(s): Naimish Baranwal

Originally published on Towards AI.

The Rise of the SLMs: Building the Smallest Possible Language Model.

This is the first step toward building SLM(Small Language models).

This work replicates the findings reported in https://arxiv.org/abs/2305.077

The referenced research seeks to develop the smallest language model capable of processing English sentences. For coding, I took help from Andrej Karpathy’s nanoGPT repo https://github.com/karpathy/nanoGPT.

In this paper, researchers aim to create the smallest language model that can understand English words and generate fluent, consistent English text.

This is the first step towards building small language models, where I am pre-training the language model from scratch.

Why Small is the New Big in AI, and how to build one from scratch.

SLMs deliver faster inference, lower latency, and real-time performance ideal for edge devices and chatbots. They cut costs dramatically with reduced compute, energy, and memory needs, suiting SMEs and on-device AI. Privacy improves as they run locally without cloud dependency, and specialization boosts accuracy for targeted tasks.

I am using the dataset TinyStories, which is available on Hugging Face. Anyone can use the model directly from Hugging Face, available in different versions: https://huggingface.co/roneneldan/TinyStories-33M

  • TinyStories-1M/3M/9M/28M/33M

I pre-train my whole model on NVIDIA GeForce RTX 5050 8GB VRAM, which took approximately one hour for 20,000 iterations. Also, for better accuracy, I ran for 50,000 iterations, which took approximately 3 hours. You can use Jupyter Notebook’s T4 GPU; it might take the same time to run, or if you have RAM, you can reduce the iterations.

Also, I use the optuna library to do the hyperparameter optimization.

Data Preparation:

In the prepare_data() function, data is loaded from Hugging Face, split into train.bin and validation.bin files, and tokenized using the GPT-2 tokenizer from tiktoken. A memory-mapped function enables efficient RAM usage during processing, while datasets are downloaded in batches for optimized performance.

Write on Medium

In the get_batch() function, the batch size is set to 32 with a block size of 128. This means each iteration processes 128 tokens per sequence across 32 sequences, totaling 4,096 tokens per batch (32 × 128). Running 50,000 iterations processes approximately 204 million tokens—about 22% of one epoch from the TinyStories training set's roughly 900 million tokens—while still yielding decent results.

Model Architecture

The Block class implements a single transformer block comprising a LayerNorm layer, CausalSelfAttention mechanism, and a feedforward neural network (MLP).

Attention Mechanism

In the CausalSelfAttention class, causal masking is applied manually, while Flash Attention is utilized automatically when available (PyTorch 2.0+). The embedding size must be fully divisible by the number of heads; here, 384/6 = 64 dimensions per head.

Training Process

The estimate_loss() function employs gradient accumulation over 32 steps before updating weights. Every 500 iterations, it computes validation and training losses by averaging over 100 batches each.

GPT Model Assembly

The GPT class serves as the main container, combining token and positional embeddings, then passing them through 6 transformer blocks (Block class). Each block features 6 parallel causal attention heads that capture diverse perspectives—such as syntax, semantics, and local context—while the sequential blocks enable hierarchical learning.

Inference Optimization

The @torch.no_grad() decorator disables gradient tracking within inference functions for improved efficiency.

The Rise of the SLMs: Building the Smallest Possible Language Model.

Hyperparameter optimization

Optuna systematically explores the search space, learns from each experiment, and converges on optimal settings automatically using Bayesian-inspired optimization. I use it to find the best embedding size, number of attention heads, number of transformer layers, learning rate, and dropout.

Training Results

After completing the training iterations, the best model parameters are saved in a .pt file. During inference, the system automatically loads weights from best_model_params.pt to generate responses using the optimized mode.

Here are some responses from the model:

You can find all the code and details in the following repo:

GitHub – NaimishKB/SLM–TLM-from-scratch

Contribute to NaimishKB/SLM–TLM-from-scratch development by creating an account on GitHub.

github.com

Happy Learning!!

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI


Towards AI Academy

We Build Enterprise-Grade AI. We'll Teach You to Master It Too.

15 engineers. 100,000+ students. Towards AI Academy teaches what actually survives production.

Start free — no commitment:

→ AI Engineering For Production — our new book, coming before the end of 2026. Join the waitlist.

→ Agents Architecture Cheatsheet — 3 years of architecture decisions in 6 pages

Our courses:

→ AI Engineering Certification — 90+ lessons from project selection to deployed product. The most comprehensive practical LLM course out there.

→ Agent Engineering Course — Hands on with production agent architectures, memory, routing, and eval frameworks — built from real enterprise engagements.

→ AI for Work — Understand, evaluate, and apply AI for complex work tasks.

Note: Article content contains the views of the contributing authors and not Towards AI.