In this video, learn how to build your own Small Language Model (SLM) from scratch using Python, PyTorch, and Hugging Face datasets. We’ll walk through every step — from data collection and preprocessing to tokenization, transformer architecture, and model training.
You’ll discover how a compact 10–15 million parameter model can still generate coherent and meaningful text, using concepts inspired by GPT models. This tutorial simplifies complex AI topics like embedding layers, attention mechanisms, loss computation, and next-token prediction — all explained clearly with working code examples.
🔹 Topics Covered:
What are Small Language Models (SLMs)?
Using the TinyStories dataset from Hugging Face
Tokenization with OpenAI’s tiktoken library
Creating .bin training files for efficient processing
Building a Transformer architecture step-by-step
Implementing GPT-like attention blocks
Training configuration and hyperparameter tuning
Generating text from your trained SLM
🎯 Perfect for AI researchers, ML engineers, and enthusiasts who want to understand how GPT-style models actually work under the hood — without requiring massive GPUs or billion-parameter setups.
0:06 Introduction to Small Language Models (SLMs) and Project Overview
0:50 Data Selection: Using TinyStories for Training
1:25 Data Preprocessing: Tokenization and Efficient Storage
2:37 Preparing Data for Training: Batching and Input-Output Pairs
3:39 Model Architecture: Transformer Blocks and Embeddings
5:30 Configuring the SLM: Key Parameters and Design Choices
6:36 Training the SLM: Optimization, Loss, and Monitoring
7:36 Inference and Text Generation: Output Control and Final Results
In the current landscape of artificial intelligence, a small language model, or SLM,
is typically defined as any language model with fewer than 1 billion parameters.
This is a stark contrast to giants like GPT-3, which boasts around 175 billion parameters,
or the rumored GPT-4, which may reach a trillion. But why focus on small models?
The answer lies in efficiency and accessibility. SLMs can be trained and deployed with far
fewer resources, making them ideal for research, edge devices, and specialized applications.
In this video, we'll walk through the entire process of building an SLM,
from scratch, from data selection to inference.
The first step in building an SLM is selecting the right data set. For this project,
we use TinyStories, a synthetic data set of short stories generated by GPT-3, 5, and GPT-4.
TinyStories is designed for simplicity, containing language that a typical 3- to 4-year-old can
understand. This makes it perfect for training small models that still need to produce coherent
English. The data set is available on HuggingFace and contains 2 million training samples and 20,000
validation samples. With this foundation, we're ready to move on to data preprocessing.
Once we have our data set, the next step is tokenization. Tokenization is the process of
converting raw text into numerical tokens that a model can understand. For this SLM,
we use the GPT-2 subword tokenizer, which breaks down text into smaller pieces and assigns each
a unique ID. Each story is transformed into a sequence of token IDs, and these are stored in
a dictionary format. This conversion is crucial because neural networks operate on numbers,
not words. After tokenization, all token IDs are merged into a large corpus,
ready for efficient storage and processing. Handling large data sets requires efficient
storage solutions. Instead of keeping everything in RAM, which can quickly become unmanageable,
we store tokenized data in binary files on disk. Using NumPy's memmap, we can map large files
directly into memory, enabling us to process data sets larger than available RAM. This
approach also allows for batching, which speeds up both reading and writing operations. The result
is two key files, train, bin, and validation, bin, each containing millions of token IDs,
ready for model training. With our data stored efficiently, we now need to prepare it for
training. This involves creating input-output pairs. For language models, the task is next
token prediction. Given a sequence of tokens, predict the next one. We divide the token IDs
into chunks, where each chunk becomes an input, and the output is the same sequence shifted by
one token. This setup allows the model to learn language patterns and context, forming the basis
for generating coherent text. Batch processing is essential for efficient model training.
By grouping multiple input-output pairs into batches, we can leverage parallel computation
and optimize memory usage. Each batch contains several sequences, and the model processes them
simultaneously. This not only speeds up training, but also stabilizes the learning process by
averaging gradients across multiple samples. The batching strategy is a cornerstone of
modern deep learning workflows. Before feeding data into the model, we convert token IDs into
embeddings. An embedding is a dense vector representation of a token, capturing its
meaning. In RSLM, each token is mapped to a 768-dimensional vector. These embeddings are
learned during training, and form the foundation for understanding relationships between words.
Additionally, positional embeddings are added to provide information about the order of tokens,
which is crucial for language understanding. The core of RSLM is the transformer block.
Each block consists of multi-head self-attention and feed-forward neural networks. Self-attention
allows the model to focus on different parts of the input sequence, capturing dependencies
regardless of their position. The feed-forward network processes these representations further,
enabling the model to learn complex patterns. Drop-out layers are included to prevent
overfitting, ensuring the model generalizes well to new data. Within each transformer block,
the feed-forward neural network plays a vital role. After self-attention processes the input,
the feed-forward network applies additional transformations, allowing the model to capture
non-linear relationships. Shortcut connections, or residuals, are used to help gradients flow
through the network, preventing issues like vanishing gradients. This design enables deeper
models and more effective learning. Multi-head attention is a key innovation in transformer
models. By splitting the attention mechanism into multiple heads, the model can focus on
different parts of the sequence simultaneously. Each head learns to capture unique relationships,
such as syntax or semantics. The outputs are then combined, providing a rich, multi-faceted
understanding of the input. This mechanism is essential for the model's ability to generate
coherent and contextually relevant text. Now, let's assemble the full model architecture.
The SLM consists of stacked transformer blocks, each containing self-attention and feed-forward
layers. The input passes through token and positional embeddings, then through each
transformer block, and finally through a layer normalization step. The output is projected to
the vocabulary size using a linear layer, producing logits for each possible next token.
This modular design makes it easy to scale the model up or down as needed. Configuring the model
is a critical step. Key parameters include vocab, size, block, size, n, layer, n, head, n, md, and dropout.
Vocab. Size defines the number of unique tokens. Block. Size sets the maximum context length.
N. Layer is the number of transformer blocks. N. Head is the number of attention heads. N. Mbd
is the embedding dimension, and dropout helps prevent overfitting. These settings balance
model capacity and computational efficiency, tailored for small language models. Training the
SLM involves several steps. Selecting a learning rate, setting the number of iterations, defining
batch size, and choosing an optimizer. We use AtomW for optimization, with gradient accumulation
to update parameters after several steps. Learning rate schedulers help the model converge smoothly,
starting with a warm-up phase and then decaying. During training, we monitor both training and
validation loss, saving the best model based on validation performance. The loss function
measures how well the model's predictions match the target outputs. For language modeling,
we use cross-entropy loss, calculated across all tokens in a batch. Gradients are computed
and accumulated, then used to update the model's parameters. Gradient clipping is applied to prevent
exploding gradients, ensuring stable training. This iterative process continues until the model
achieves satisfactory performance on the validation set. After training, it's time to run inference.
The trained SLM can now generate text by predicting the next token given a sequence. The model loads
the best saved parameters and uses the generate function to produce new text. Temperature and
TopK sampling control the creativity and diversity of the output. The result is a small,
efficient language model capable of producing coherent English, demonstrating the power and
flexibility of SLMs built from scratch.