How to build an LLM from scratch

By

Updated

Tagged: AI

A practical guide for software engineers to build and train a small GPT-style language model on a Mac with Language Model Builder.

Paul Graham recently said that if he were 17 today, he’d learn how to build LLMs from scratch and train the strongest one his hardware could handle. I think that’s great advice, so in this guide we’re going to do exactly that: train a small GPT-style language model on a Mac, starting from random weights.

I’m a software engineer, not a machine learning researcher, and I write for other software engineers. You won’t derive equations, implement matrix multiplication, or spend weeks learning a machine learning framework here. Instead, we’ll treat the language model like any other software system you already know how to work on, with inputs, internal state, a processing pipeline, build artifacts, runtime settings, and failure modes.

We’ll use Language Model Builder, a free Mac app. You don’t have to write Python or download a finished model. We’ll train directly on the Mac, inspect the checkpoints, fine-tune the behavior, and test what comes out. I wrote a shorter overview in Build a language model on your Mac with Language Model Builder, and if you want to jump straight into the hands-on side with real training runs, fine-tuning, and DPO in the app, check out build a language model on your Mac.

What we are building

We’re building a small GPT-style language model. It takes a sequence of tokens, predicts the next one, appends it to the sequence, and repeats that loop to generate text.

Here’s what the inference path looks like:

text
  ↓
token IDs
  ↓
embeddings
  ↓
Transformer blocks
  ↓
next-token probabilities
  ↓
generated text

Training runs the exact same model and wraps a feedback loop around it:

prediction
  ↓
compare with the real next token
  ↓
measure the error
  ↓
update the weights

If you write software for a living, you already recognize most of these pieces under different names:

Software engineering conceptLanguage model concept
input encodingtokenizer
internal data representationembeddings
processing pipelineTransformer blocks
persisted application stateweights
versioned build artifactcheckpoint
held-out test fixturesvalidation data
runtime optionssampling settings

The analogy isn’t exact, of course, but it gives you a solid mental model before we open the app.

What “from scratch” means

Building a model “from scratch” doesn’t mean writing every layer of the stack by hand. Language Model Builder sits on top of MLX, Apple’s machine learning framework for Apple Silicon, which handles tensors, gradients, and the low-level math for us.

It’s the same way you build a web app without writing your own TCP stack, database engine, and operating system first. We use the framework to run the math, and we create the model itself:

  • a tokenizer selected for our data
  • a new Transformer architecture
  • randomly initialized weights
  • our chosen training data
  • checkpoints produced on our Mac

Since we aren’t importing pretrained weights, everything the model learns comes from our own training run.

What you need

To follow along with Language Model Builder, you’ll need:

  • an Apple Silicon Mac
  • macOS 15 or later
  • free disk space for datasets and checkpoints
  • time for a training run

The app is free, and you don’t need an account, an API key, a cloud GPU, or a Python setup. Grab it from languagemodelbuilder.com.

The Language Model Builder download page

Move it into your Applications folder and open it. You’ll see three options on the welcome screen:

  • Learn about models
  • Build a model
  • Open an existing project

We’ll be using the first two.

Define the experiment before pressing Train

Click Build a model to start a new project. I kept the default name, My First Model.

Hold off on starting the training run for a moment. Training takes hours, so spending five minutes upfront to decide what you want out of the run will save you a lot of guessing later. Start by writing down this goal:

Observe how a small Transformer changes during pre-training,
then test whether fine-tuning improves its responses.

Our little model isn’t going to compete with ChatGPT or Claude. All we want to see is whether it moves from random gibberish toward recognizable patterns from its training data.

Create three test prompts

Save these three prompts so we can test them against several checkpoints using the same runtime settings:

Once upon a time, a small fox
The robot opened the door and
Mia looked at the sky because

Before any training happens, the output will be complete nonsense, and that gives us our baseline.

Create a run log

Create a Markdown file called model-lab.md and start it with these headings:

# My First Model

## Goal
## Mac and app version
## Model configuration
## Tokenizer and dataset
## Training log
## Checkpoint samples
## Fine-tuning
## Final comparison
## Limitations
## Next experiment

Note your Mac chip, unified memory, macOS version, and app version, then paste your goal and test prompts into the file. Keeping your inputs, settings, sample outputs, and notes in one place makes it easy to compare checkpoints and reproduce what you did later.

Do not import a base model

In the Base models section, you can import existing models like SmolLM2 or Qwen2.5. That’s handy when you want to fine-tune an open-weight model, since it already comes with a tokenizer, architecture, and trained weights.

The Language Model Builder catalog of existing base models

Skip that section for this guide. Here we want to start from random numbers and watch the weights take shape on our own Mac.

Use the embedded guide as architecture documentation

Open Learn about models. Language Model Builder ships with an interactive guide that takes around 90 minutes to work through.

The introduction in the interactive Language Model Builder guide

My advice is to go through it once before you kick off a multi-hour training job. You don’t need to turn into a machine learning researcher, just pay attention to how data moves across the system:

  • how text becomes model input
  • what representation moves through the model
  • where context is combined
  • what the model returns
  • how training changes persisted state

Next, let’s walk through each of those pieces in plain software-engineering terms.

The tokenizer is the input layer

A language model never sees raw strings. A tokenizer splits text into reusable chunks and assigns each chunk an integer ID.

For example, take this string:

the little cat played

A tokenizer might split it into pieces like this:

the | little | cat | play | ed

Those integer IDs are what go into the model. Think of the tokenizer like a codec or parser sitting at the boundary of your system, where both sides have to agree on the format.

Language Model Builder comes with a byte pair encoding playground. It starts with tiny pieces and repeatedly merges the most frequent pair of adjacent tokens. At zero merges, every character gets its own token:

The tokenizer playground before learning any token merges

Click Run next merge a few times and watch common character sequences collapse into single tokens. Try running 10 or 50 merges and compare how the text breaks apart:

The tokenizer playground after learning 65 token merges

A bigger vocabulary lets the model represent familiar text in fewer tokens, which helps with context length. The catch is that the model has to compute an output score for every single entry in that vocabulary, so the output layer gets larger and heavier to train.

One rule you can’t break:

A checkpoint only works with the tokenizer and token IDs used to train it.

If you swap the token mapping later, the saved weights won’t line up with the right tokens anymore.

Fig 1 · 1/6Next token
input text · the model does not receive a string directly

Embeddings are the internal representation

Token IDs are just lookup numbers, so two IDs being close numerically doesn’t mean the words are related. An embedding maps each token ID to a vector, which is a list of learned numbers that acts as the model’s internal data representation.

During training, tokens that show up in similar contexts gradually end up with similar vectors. The app projects a 50-dimensional embedding space down to two dimensions so you can inspect it visually:

The Language Model Builder embedding map grouping related words

You can see animals, colors, places, and family words clustering together, even though nobody hardcoded those categories. Those groupings came straight from usage patterns in the training data. Just keep in mind that the map is a debugging view, because squashing 50 dimensions down to 2 always distorts some of the distances.

The Transformer is the processing pipeline

The Transformer is the pipeline that processes the sequence of token vectors. It’s a stack of blocks running one after another, and each block combines an attention step with a small feed-forward network.

Attention lets each token pull in information from other relevant tokens in the context. Look at this sentence:

The book did not fit in the bag because it was too large.

To make sense of it, the model has to look back at earlier tokens, and attention is how it connects that context. Because a text generator works left to right, it can’t peek ahead at future tokens. Each position can only look at itself and what came before it. That restriction is called causal attention.

Putting those steps together gives you the full processing path:

token IDs
  ↓
token and position embeddings
  ↓
repeated Transformer blocks
  ↓
one score for every possible next token
  ↓
probabilities

At the end of the pipeline, the model outputs a probability distribution over every possible next token rather than a single stored answer.

The weights are persisted application state

The architecture defines the code path and the shapes of the data flowing through it, while the weights are the numbers that change during training. They hold everything the model picked up from the dataset.

At the start, every weight is a random number. On every step, the training loop does five things:

  1. reads a batch of token sequences
  2. predicts the next tokens
  3. compares those predictions with the real tokens
  4. measures the error
  5. adjusts the weights slightly

That error measurement is called the loss. You don’t need to write gradient math yourself to understand what’s happening: the framework takes the loss and nudges the weights in a direction that lowers it.

It helps to keep the two phases separate in your head. Training is an offline job that builds a model artifact, and generation is the runtime that loads that artifact and predicts tokens.

The model blueprint is a compatibility contract

Head back to your project and open Project setup. Here’s the blueprint I used for this run:

tokenizer       GPT-2 BPE
vocabulary      50,261 tokens
context         512 tokens
embedding width 256
blocks          8
attention heads 4
parameters      about 19.3 million
weights on disk 36.8 MB

The project setup for my 19.3-million-parameter language model

Those settings fix the exact shapes of the data moving through the model. The vocabulary size sets how many input embeddings and output scores the model has, and the context length controls how many recent tokens it can see at once. The embedding width is the size of each token’s internal vector, the number of Transformer blocks sets how deep the pipeline is, and the attention heads let the model track several attention patterns in parallel.

Put all of those numbers together and you get the parameter count. Once you save a checkpoint, you can’t change those dimensions and load the old weights into the new shape, just like you can’t change a serialized file format without writing a migration. Write the full blueprint down in model-lab.md before you move on.

Choose the tokenizer before training

Language Model Builder recommends Fast 10K BPE for a smaller first model. For the run in these screenshots, I picked GPT-2 BPE instead, which has a vocabulary of about 50,000 tokens and makes both the input and output layers much bigger.

That single choice bumped my model from roughly 9 million parameters up to 19.3 million, and it made training noticeably slower. If you want a quicker first experiment, stick with Fast 10K BPE. Either way, log your choice in model-lab.md and don’t change it once training starts.

Treat the dataset as an input dependency

Head over to Pre-training data to pick what your model will learn from.

The Language Model Builder dataset catalog with TinyStories 2 selected

The built-in catalog gives you TinyStories, WikiText, Simple English Wikipedia, scientific abstracts, poetry, and a few other collections. Pick TinyStories 2. It’s made of short stories with a small vocabulary, which gives a tiny model a realistic target it can start picking up on a single Mac.

Before you hit download, take a minute to inspect the dataset. Look at its source, license, and size, and scan a few sample records for repeated boilerplate, broken text, or private or unwanted content you wouldn’t want baked into the weights.

A model can only pick up patterns that exist in its training data. Feed it stories and you get a storyteller; feed it scientific abstracts and you get a completely different voice. That’s why the dataset matters just as much as the model architecture. Later on, if you bring your own data, keep the exact files or a versioned manifest alongside your project, or you won’t be able to reproduce the run.

Pre-training is a long-running background job

Switch to Pre-training and double-check the summary against your notes before you kick things off. Make sure the dataset, tokenizer, parameter count, number of steps, and estimated duration all match what you expect.

The pre-training screen before starting the 20,000-step run

The recommended run is 20,000 steps. On my M4 Pro, the app estimated somewhere between one and four hours, though your estimate will vary depending on your model, tokenizer, and Mac. Plug your Mac into power and click Start pre-training.

Training won’t start right away. First, the app has to pull down the dataset files. In my run, it downloaded about 2.1 GB of TinyStories 2 data from Hugging Face.

Language Model Builder downloading the TinyStories 2 dataset before training

Keep in mind that this is only the training dataset, not a pretrained model, so we’re still starting from random weights. Once the download wraps up, the app prepares the training data and encodes the source files with the tokenizer you picked.

Language Model Builder encoding the downloaded source file before training

The step counter only starts moving once that encoding finishes. From here on, treat the run like any long-running background job: keep an eye on progress metrics and checkpoints, know how to pause it, and log enough detail to pick up where you left off if anything interrupts it. Jot down the start time, initial loss, validation loss, and tokens processed per second.

Read the metrics like an engineer

Once training is underway, the screen plots two live loss curves.

My model during pre-training with live training and validation loss

The blue line is training loss, which tracks prediction error on the batches currently updating the weights. The orange line is validation loss, which measures error on held-out data that never touches the weights. When both curves trend down together, the model is learning patterns that carry over to unseen text. When training loss keeps dropping while validation loss climbs, the model is memorizing the training set instead of generalizing. That’s overfitting.

Don’t panic over a single spike. Look at the overall trend across many measurements, and keep an eye on the other live counters too:

  • current step
  • learning rate
  • tokens per second
  • elapsed time
  • estimated time remaining

Tokens per second tells you how fast your Mac is crunching through batches, and loss tells you how accurately the model predicts tokens in the dataset. To see whether the generated text reads well, you have to inspect real samples, which we’ll do in a moment.

Now comes the waiting. My run took more than two hours to finish, so start it when you can leave your Mac plugged in and working for a stretch. That said, you don’t have to sit through all 20,000 steps before trying the rest of the app. Wait until a few checkpoints show up in the Sample timeline, then hit Pause.

Pausing pre-training after the model has produced several checkpoints

With the run paused, you can jump over to Sampling and test the latest checkpoint to see how the whole loop fits together. Whenever you’re ready, head back to Pre-training and resume.

Checkpoints are versioned build artifacts

A checkpoint is a snapshot of the model’s weights saved at a specific training step. Having checkpoints lets you:

  • pause and resume a long run
  • compare earlier and later versions of the model
  • roll back to an earlier state if later training overfits
  • pick a specific base state for fine-tuning

For every checkpoint you decide to keep, write down the step number, training loss, validation loss, and a few sample outputs. The latest checkpoint isn’t automatically the best one, especially if validation loss started creeping up near the end.

If a run is going to take several hours, wait until at least one checkpoint has been saved before closing the app. Then reopen the project and verify the checkpoint history is there before you count on being able to resume.

Sampling is runtime configuration

Open Sampling, pick a checkpoint, and try your first baseline prompt:

Once upon a time, a small fox

Sampling text from a checkpoint after pausing pre-training

The checkpoint decides the probabilities for the next token, while the sampling controls decide how the app picks from them. Tweaking these sliders doesn’t retrain the model. They work like runtime flags for the same build:

  • Temperature controls how strongly generation favors the most likely tokens.
  • Top-k limits the pool to the k strongest candidates.
  • Top-p keeps the smallest group of candidates whose combined probability reaches your chosen threshold.
  • Min-p drops candidates that are way too weak compared to the top choice.
  • The random seed makes a run reproducible as long as the checkpoint, prompt, and other settings stay unchanged.

Whenever you’re comparing two checkpoints, leave all of these settings locked so you’re only measuring the model itself.

Decide when the run is good enough

There’s no magic loss number that tells you a model is done. Instead, look at three signals together:

  1. validation loss
  2. the gap between training and validation loss
  3. sample outputs from fixed prompts and settings

As long as validation loss and your sample outputs keep getting better, extra steps can still pay off. Once validation loss flattens out, running longer usually wastes time or pushes the model into overfitting on the training set.

Keep your expectations realistic for a 19.3-million-parameter model. It’s going to stay limited, so the goal here is steady, visible progress you can explain from your notes.

Pre-training does not define product behavior

Pre-training only teaches the model to continue text, not how to behave like a chat assistant. A pre-trained checkpoint might continue a prompt structured like this:

User: Tell me a short story.
Assistant:

Even when it plays along, it wasn’t trained to treat the first line as a user request and the second as a clear boundary for its reply. Teaching that back-and-forth takes a separate training stage.

Supervised fine-tuning teaches the interaction contract

Supervised fine-tuning (SFT) trains the model on pairs of prompts and desired replies. Open Fine-tuning data and look through a conversational dataset to see how it’s structured. Most examples contain three parts:

  • a system instruction
  • a user message
  • an assistant response

Reserved chat tokens mark where each role begins and ends, which teaches the model the exact turn-taking format we expect at runtime.

Open Supervised fine-tuning, pick the checkpoint with the best validation result, and stick with the recommended settings. Once SFT saves a new checkpoint, run your three baseline prompts again with the exact same sampling settings, and note down what got better and what got worse. Keep in mind that SFT reshapes how the model answers, while all its underlying knowledge still comes from what it saw during pre-training.

DPO is an optional policy-tuning stage

Direct preference optimization (DPO) trains the model on pairs of preferred and rejected answers. Open Direct preference optimization, and the app will run the same prompt twice so you can pick the response you like better. For each round, it saves:

  • the prompt
  • the chosen answer
  • the rejected answer

Four pairs are enough to launch a run and watch the mechanism work, though steering real behavior takes many more. Be consistent in what you reward, because contradictory picks send mixed signals to the optimizer.

If this is your first run through the pipeline, you can safely skip DPO. Pre-training plus SFT already covers the core workflow.

Use chat as an integration test

Open Chat with your model and select whichever checkpoint you want to test: pre-trained, SFT, or DPO. Start with prompts that stay close to the training data, like these:

Tell me a story about a brave little boat.

Once you see how it handles normal prompts, try pushing it outside the happy path:

  • a malformed request
  • a request outside the dataset’s domain
  • a long conversation near the context limit
  • a prompt with unusual names or symbols

Write down the exact system instruction and sampling settings you used. The chat interface makes the model feel familiar, even though underneath it’s still running the same next-token prediction loop one token at a time.

X-ray mode is the debugger

Click X-ray in the chat toolbar to inspect what happened under the hood. The reply splits into individual tokens, with stronger colors showing higher sampling probabilities. Click any token to see the runner-up candidates the model considered at that spot.

This view is especially handy when a reply catches you off guard, because you can immediately tell whether one token completely dominated or several options were nearly tied. Those probabilities are all the model has at each step, so treat the view as a probability readout rather than a window into a thought process.

Beside it, the transcript panel shows the raw role tokens and messages sent to the model, and the context meter tracks how much of the 512-token window you’ve used. Once a conversation grows past 512 tokens, the runtime has to drop older tokens from the active input. Every chat app built on an LLM runs into that hard ceiling and has to work around it.

Build an evaluation instead of judging by vibes

To compare your checkpoints fairly, run the exact same three prompts against your pre-trained, SFT, and DPO checkpoints while holding all of these settings constant:

  • temperature
  • top-k
  • top-p
  • min-p
  • maximum tokens
  • random seed
  • system instruction

Save every output, including the bad ones, and add a comparison table to model-lab.md using a template like this:

| Prompt | Pre-trained | SFT | DPO |
| --- | --- | --- | --- |
| Small fox | | | |
| Robot door | | | |
| Mia and the sky | | | |

Score things you can check directly in the text:

  • complete sentence
  • repetition
  • stays on topic
  • follows the requested format
  • unsupported claims

Paste the raw outputs right below the table so you can always see what a score refers to. Then pick the checkpoint you want to keep and write one concrete reason backed by your results.

Exporting a model means exporting an artifact

Language Model Builder exports your trained weights in the safetensors format. On their own, those weights aren’t enough to run the model. Any compatible runtime also needs:

  • the architecture definition
  • the tokenizer
  • the vocabulary and token mapping
  • the expected chat format
  • the sampling configuration

Store the Language Model Builder project and model-lab.md right next to the exported weights so that six months from now you can still trace exactly how that file was built.

How I would use this as a software engineer

The whole point of building a small model like this is to take the mystery out of the stack. You won’t ship it as a customer-facing assistant, because it’s too small and too narrow, and turning it into a competitive general model on your own would cost way too much time and money.

What you get instead is a clear mental model. When an AI feature misbehaves in production, you stop guessing and start isolating where things went wrong:

  • the tokenizer split the input poorly
  • important context didn’t fit in the context window
  • the model never saw that domain during training
  • the fine-tuning data taught the wrong response style
  • the prompt is vague
  • the sampling settings are too aggressive
  • your app didn’t validate the output

Each of those is a different bug, and each one takes a different fix.

Going through this once also makes hosted model APIs much easier to work with. An API hides the training pipeline, the weights, and most of the runtime, yet those same boundaries are still sitting underneath every request. If you’re weighing local models against API calls, I ran the numbers in Running LLMs locally vs paying for an API.

For real production software, my advice is to start with an existing model and put solid engineering around it:

  • validate inputs before sending them
  • manage what goes into the context window
  • ask for structured output whenever you can
  • handle business rules with normal, deterministic code
  • test against a set of real prompts
  • log failures without leaking private user data
  • keep the model provider easy to swap out

Every one of those habits makes a lot more sense once you’ve seen how fragile a raw model is up close.

Try one controlled change next

Once your first default project finishes cleanly, spin up a second project and change a single variable.

A good first experiment is keeping the architecture, tokenizer, and step budget identical while swapping TinyStories for text you own, like your public blog posts or product docs. Clean the files before you train, though. Strip out duplicated pages, navigation menus, broken encoding, secrets, and anything you don’t want the model repeating back to you.

When the run wraps up, compare the two projects side by side:

  • how the tokenizer handles the text
  • training speed
  • validation loss
  • outputs on the exact same test prompts
  • the failure patterns that keep showing up

Since the dataset is the only thing you touched, you’ll know right away what caused the difference. After that, you can run the same kind of one-change-at-a-time test on context length, Transformer depth, embedding width, the tokenizer, or how long you train.

Common software-engineering mistakes in this experiment

Don’t start with the biggest model your Mac can fit in memory. A larger model slows down every feedback loop, and your first run is mainly about getting comfortable with the workflow. Finish one small run from start to finish before you scale anything up.

Whenever you change a setting, start a new run instead of reusing the old one. Give each run a clear name like starter-tinystories-20k and save the full configuration right next to its checkpoints. Two weeks from now, you’ll be glad you can trace every checkpoint back to the exact settings that produced it.

It’s tempting to watch only the training loss, since that number usually keeps dropping nicely. The catch is that your model can get worse on unseen text at the same time. Keep an eye on validation loss too, and run your fixed prompt set at each checkpoint.

Lock down your runtime settings whenever you compare two checkpoints. If the temperature, seed, prompt, or system instruction changed between samples, you’re testing the settings rather than the model.

Save the bad outputs along with the good ones. Cherry-picking one great answer is fine for a screenshot, while honest testing means looking at the weak replies and the mistakes that keep repeating.

Finally, training locally keeps your data off cloud servers, but you still need the rights to train on it. Stick to material you own or have permission to use, and leave out private, copyrighted, or restricted data.

How this differs from a production LLM

Under the hood, this tiny model runs through the same core pipeline as big GPT-style models:

  • tokenization
  • embeddings
  • causal attention
  • Transformer blocks
  • next-token prediction
  • gradient-based training
  • supervised fine-tuning
  • probabilistic sampling

Where things diverge is pure scale. Production models pack billions of parameters and train on massive datasets across distributed accelerator clusters, backed by huge evaluation suites. Even running a finished model at that size locally takes serious hardware, which I broke down in How much VRAM do you need to run an LLM locally?.

Language Model Builder shrinks everything down so it fits on a single Mac. You strip away the cloud clusters and the budget, and you’re left with the exact same moving parts and trade-offs you’ll run into with production models.

What you built

When you look at the whole workflow, you started with random weights, picked a tokenizer and architecture, prepared a dataset, ran a long training job, tracked metrics across versioned checkpoints, adjusted the behavior with fine-tuning, and checked the output against fixed prompts. Broken down like that, it looks a lot like any other software project, except the output is a language model.

Every LLM API you call sits on top of that same pipeline:

architecture
  + tokenizer
  + data
  + learned weights
  + behavior training
  + runtime sampling
  + application code

If you want to try this yourself, download Language Model Builder and start with the smallest recommended run. You won’t build ChatGPT on a laptop, of course, but watching a 19-million-parameter model climb from random noise to coherent sentences takes the guesswork out of working with larger models in your own apps. For a full walkthrough with real numbers from a complete run, head over to my Language Model Builder guide.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: