DEV Community

Rajesh Phulwaria
Rajesh Phulwaria

Posted on AI-assisted

Building ADAM GPT From Scratch: When My 48 MB Dataset Crashed Python

What building a small GPT model taught me about tokenization, memory management, and the realities of training language models on limited hardware.

It started with a simple question

What actually happens inside a GPT model when it generates the next word?

We use AI assistants every day. We ask questions, write code, summarize documents, and generate ideas. But behind those simple interactions are tokenizers, embeddings, attention mechanisms, and neural networks trained on enormous amounts of text.

I wanted to understand these components beyond just using existing libraries.

That curiosity led me to build ADAM — Artificially Designed Autonomous Mind, my own GPT-style language model built from scratch.

You can explore the project here:

The goal wasn't to build another chatbot by connecting an API. I wanted to understand the underlying pipeline: how text becomes tokens, how a Transformer learns patterns, and how a model uses those patterns to predict what comes next.

I thought the hardest part would be implementing the Transformer.

I was wrong.

Chapter 1: Teaching a machine how to read

Before a GPT model can learn from text, that text needs to be converted into numbers.

This is the job of a tokenizer.

For ADAM, I experimented with a custom implementation of Byte-Pair Encoding (BPE). Instead of treating every word as an indivisible unit, BPE learns frequently occurring combinations and merges them into larger tokens.

The tokenizer starts with 256 possible byte values. It then repeatedly finds the most frequent adjacent pair and combines it into a new token.

For example, frequent character combinations may gradually become word fragments, complete words, or patterns containing spaces and punctuation.

I implemented the process myself, including pair counting, merging, encoding, decoding, and saving the vocabulary and merge rules.

My first experiments used Tiny Shakespeare. Later, I wanted to expose ADAM to a broader range of everyday language, technical terminology, names, numbers, and factual writing. Wikipedia looked like a promising next step.

I downloaded a dataset containing approximately 6.4 million English Wikipedia articles.

That was when the experiment became more complicated.

Chapter 2: Three thousand merges and nearly thirty minutes

I trained my tokenizer with 3,000 merge operations.

The result was a vocabulary of 3,256 tokens: the original 256 byte tokens plus 3,000 learned tokens.

The training logs showed how the algorithm progressed. The frequency of the selected pair decreased from 64,725 in the first merge to 69 in the final merge.

Some of the learned patterns included fragments and words such as oun, again, 2020, Japanese, and building.

The tokenizer had successfully learned recurring patterns from the training text.

But the training process took approximately 1,733 seconds—almost 29 minutes.

That raised a new question: if 20,000 articles took around half an hour, what would happen if I tried to process millions of articles?

A simple linear estimate suggested roughly 6.7 days for 6.4 million articles. However, that estimate assumes the workload scales linearly. My implementation repeatedly counted pairs and rebuilt sequences, so the actual runtime could be considerably longer.

The lesson was clear: a working algorithm is not necessarily an efficient algorithm.

Chapter 3: The crash that came without an error

Then came one of the most confusing moments in the project.

I was working inside my local WSL terminal, running Python from my ADAM project directory. The process stopped unexpectedly.

There was no useful Python traceback. No friendly exception explaining what went wrong. The process simply disappeared.

At first, it was difficult to tell whether the problem came from Python, WSL, the tokenizer, or the machine itself.

So I checked the Linux kernel logs.

The logs contained the message:

Out of memory: Killed process ... (python)

There it was.

The Linux kernel had terminated Python because the system ran out of memory available for the workload.

The logs recorded two separate out-of-memory events, one involving a Python process with approximately 630 MiB of resident memory and another involving approximately 1.32 GiB.

My WSL environment reported around 2.79 GiB of total memory in a later diagnostic.

The failure wasn't an ordinary Python exception. It was a resource problem severe enough for the operating system to kill the process.

And that led to another surprising discovery.

Chapter 4: How can a 48 MB file consume so much memory?

My corpus file, train.txt, was only around 48 MB.

That seemed small enough. So why was Python running out of memory?

The answer was in how my training script represented the data.

The script loaded the entire text file into memory. It then created training and validation text splits, encoded those splits using my tokenizer, and converted the resulting token IDs into PyTorch tensors.

My tokenizer also used Python lists to represent sequences of individual token IDs.

A Python list is not a compact array of raw bytes. It stores references to objects, and those objects can introduce considerable overhead. During tokenization, temporary lists and other intermediate representations can increase peak memory usage further.

In simplified form, the pipeline looked like this:

Text file → Python string → Python token lists → PyTorch tensors → model training

Several representations of the same underlying data could exist during processing.

The original file's size therefore did not tell me how much RAM the entire operation would require.

This was an important distinction. The 48 MB file wasn't necessarily the problem by itself; the way the program loaded, represented, and transformed its contents contributed to the memory pressure.

It also reminded me that an out-of-memory log identifies the resource failure, but doesn't automatically identify the exact line responsible for every allocation.

I had to look beyond the file size and examine the complete data pipeline.

Chapter 5: Moving tokenizer experiments to Google Colab

I needed a practical way to continue experimenting without repeatedly exhausting the memory available to my local WSL environment.

I moved the larger tokenizer training experiments to Google Colab, where a separately provisioned runtime can provide additional memory and, when available, GPU acceleration.

The plan was to train the tokenizer in Colab, save the vocabulary and merge rules to Google Drive, and reuse those artifacts in ADAM.

This separated two tasks that I had initially been thinking about together:

  1. Tokenizer training: learning how text should be represented as token IDs.
  2. GPT training: learning to predict the next token using those IDs.

The distinction matters because my ADAM training script loads an existing tokenizer. It does not automatically train a new BPE vocabulary just because I pass a merge-count argument.

Moving tokenizer training to Colab also taught me something important about hardware acceleration: a GPU does not automatically make an algorithm efficient.

My BPE implementation still performs repeated pair counting and sequence rebuilding. Moving those operations to tensors can help with some workloads, but it doesn't remove the algorithm's computational bottlenecks or guarantee that the complete corpus fits in memory.

For larger datasets, I will need to improve the implementation, use incremental pair-count updates, or evaluate a specialized BPE trainer designed for performance.

Colab gives me a more suitable environment for these experiments, but the code itself still needs to scale efficiently.

Chapter 6: From tokens to a Transformer

Once the tokenizer is trained and its artifacts are saved, the next stage is teaching ADAM to predict tokens.

The model receives a sequence of token IDs and learns to predict the next token in that sequence. Its Transformer architecture uses attention to help represent relationships between tokens within the context window.

My training script uses a configurable Transformer with embeddings, multiple attention heads, Transformer layers, and dropout. It trains using next-token prediction and evaluates both training and validation loss.

This is where tokenizer quality and model quality meet.

A tokenizer that represents text efficiently can reduce sequence lengths. But that doesn't automatically mean the model will generate better text.

The model still needs sufficient training data, an appropriate architecture, effective optimization, and enough training steps to learn useful patterns.

A vocabulary of 3,256 tokens is a useful experimental baseline for ADAM. Whether a larger vocabulary would help needs to be tested through compression measurements, validation loss, and generated samples rather than assumed.

The goal is not simply to maximize vocabulary size or the number of training merges. It is to find a practical balance between token efficiency, model capacity, computational cost, and output quality.

What this experiment taught me

Building ADAM has been as much a lesson in engineering as it has been a lesson in machine learning.

Here are the lessons I am taking forward:

1. Implementing an algorithm is only the beginning.

A custom BPE tokenizer can work correctly on a small corpus and still become impractical at a larger scale.

2. File size and memory usage are different things.

Data representation, temporary allocations, and redundant copies can make an apparently small dataset expensive to process.

3. Tokenizer training and model training are separate stages.

The tokenizer defines the vocabulary and merge rules; the Transformer learns patterns over the resulting token IDs.

4. GPU acceleration is not a substitute for algorithmic efficiency.

A GPU may accelerate tensor operations, but repeated full-corpus work and unnecessary data movement can remain bottlenecks.

5. Experiment incrementally.

Small benchmarks, runtime measurements, memory monitoring, and round-trip tests help identify problems before committing to a much larger run.

6. Preserve artifacts and make experiments reproducible.

Saving the vocabulary, ordered merge rules, configuration, and model checkpoints makes it easier to continue experiments without repeating expensive work.

7. Evaluate what the model learns, not just what the tokenizer builds.

A larger vocabulary or a successful training run does not prove that a language model generates coherent text. Validation loss and generated samples are essential.

What's next for ADAM?

The next stage is to improve the efficiency and reliability of the pipeline.

I want to benchmark different vocabulary sizes, measure how effectively the tokenizer compresses representative text, and reduce the memory overhead of corpus encoding. I also want to make larger experiments more reproducible by saving intermediate artifacts and avoiding unnecessary repeated work.

On the modeling side, the focus remains on training and evaluating the Transformer, understanding its limitations, and improving its generated text.

ADAM is still an experiment and a learning project. It is not intended to compete with large production language models at this stage. Its value is in helping me understand the mechanisms and engineering decisions behind them.

Final thoughts

When I started building ADAM, I expected to learn about attention, embeddings, and Transformer layers.

I did learn those things. But I also learned that machine learning doesn't happen in isolation from the systems running it.

A tokenizer can learn thousands of merges and still be too expensive to scale. A text file can occupy just 48 MB on disk and contribute to a multi-gigabyte memory workload. A Python process can disappear without a traceback because the operating system—not Python—decided it could no longer continue.

These aren't reasons to abandon the experiment. They're reasons to understand it more deeply.

For me, the most valuable part of building ADAM is not just getting a model to generate text. It is discovering what happens at every stage between raw text and the model's next-token prediction—and learning how to make each stage more reliable.

The project is still evolving, and this is one step in that journey.

Explore the project

If you're building your own language model from scratch, start small, measure everything, and don't underestimate the tokenizer. Sometimes the most useful lesson comes from the part of your code that unexpectedly stops running.

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

Rajesh, the part that will stick with me is the 48 MB file killing Python — the file size was never the problem, the representation was, and the kernel log is what proved it. Your 1,733 seconds for 20,000 articles turning into a 6.7-day estimate for 6.4 million is the honest scaling check most build-from-scratch posts skip. One concrete next step worth trying before the Colab runs: swap the token ID lists for a compact array (or stream the corpus in chunks) so you stop paying the per-object overhead on every ID — that is the exact gap between your 48 MB file and the OOM kill. Which fix are you trying first, the incremental pair-count updates or chunked tokenization — and did the 6.7-day number change the vocabulary size you are aiming for?

Collapse
 
rajesh_phulwaria_7a8f4a4c profile image
Rajesh Phulwaria •

Thanks bruhh! I’m planning to tackle chunked tokenization and compact token storage first, then look into incremental pair-count updates for the BPE trainer. The 6.7-day estimate definitely made me reconsider scaling before optimizing.. I’m keeping 3,256 tokens as my baseline for now rather than increasing the vocabulary blindly. although I want to compare compression and model validation loss before deciding on a larger vocabulary. Still experimenting, but that’s the fun part of building from scratch.