← Pablo Murad

Where's the monkey's butt?

What I learned in one night about how LLMs work, from someone who used to think AI was for making photos of himself as Chaplin: little balls with weird numbers, a monkey at a typewriter, pudding recipes, catastrophic forgetting and a very happy missile.

A cartoon in red and teal ink: a puzzled capuchin monkey types on an old typewriter at three in the morning under a desk lamp, a long sheet of random letters spilling out, while a pink earthworm with two identical ends stands beside it under a red question mark.
Contents

Until tonight I knew the bare minimum of the theory behind artificial intelligence, and it had never been something I studied. Then something caught my eye while I was studying Python, and the same rabbit hole dragged me into trying to understand how one of these things is actually built.

Until yesterday, AI for me meant tools that make pictures and videos. It was fun at first to make a photo of myself dressed as Chaplin, and then it got old. I lost interest even faster when I noticed that, with all the knowledge in the world in the palm of its hand, humanity's favorite question for this new Oracle was: where's the earthworm's butt?

At three in the morning.

A cartoon in red and teal ink: an exhausted Greek oracle sits on her tripod in a temple at night, head in her hand, while a man in a hoodie kneels before her holding up a smartphone and a pink earthworm.

If this were a pyramid, or better, an iceberg, we're all staring at the tip. I had no idea how big the rest was.

I knew AI is an algorithm and not a sentient being. I didn't know how it's organized inside. Now I know the bare minimum, which I'm counting as enough because it held my attention for a few hours, and that's rare.

Everything below is the little I learned tonight, and possibly the many things I got wrong.

An ouroboros of studying #

It was a snake eating its own tail. I started reading about AI, went off to study Python, and came back to AI. And the question that started it all was: how do you remove all the censorship from an LLM?

A cartoon in red and teal ink: a big snake covered in tiny lines of code and dots joined like a network curls into a circle, biting near its own tail, and inside the circle a man sleeps face down on his desk next to a laptop at night.

Like I said, for me AI was a machine for videos and pictures, and that's what most people use it for. There's a page I follow on Facebook called eggstonite that posts AI-made shorts. The range of famous characters in them is bizarre: deformed, grotesque, doing borderline insane things, like Itchy and Scratchy from The Simpsons or Ren and Stimpy, except hyperrealistic.

It's no secret that these models are trained, and it's no secret that there are topics they won't touch. And yet those eggstonite shorts exist. What kind of madness produces that? Clearly a whole stack of models went into making them. But forget the videos for a second: how do you lower an AI's guard? See the question?

Digging into that, I hit neural networks, and that's where the night really started.

Little balls with weird numbers #

A simple neural network drawing: three input circles on the left, two columns of four circles in the hidden layers, and two output circles on the right, every circle joined to all circles in the next column by grey lines, with six lines highlighted in red and labelled with weights: 0.73, -1.2, 2.8, -0.4, 0.9 and -3.1.

That drawing is a neural network, and right now it's empty. Information goes in on the left and an answer comes out on the right. Every ball is connected to the balls of the next layer by little strings, and each string carries a weird number. I painted a few of them red with their numbers showing. Those numbers are the parameters, and at the start they're random. At this point the AI knows exactly nothing.1

So when someone says a model has 7B parameters, that's 7 billion damn weird numbers. Not 7 thousand, as I first thought, 7 billion. Real LLMs are also arranged in a fancier shape than this drawing, called a Transformer, but the balls-and-strings picture is enough for a beginner like me.2

Four layers of muzzle #

Back to the censorship question. From what I read, a commercial model can be muzzled in four places:

  1. In the training itself, by what it saw and how it was taught to answer.
  2. In the system prompt, the hidden instructions it gets before you type anything.
  3. In an input filter, which checks your question before it reaches the model.
  4. In an output filter, which checks the answer before it reaches you.

The last three live around the model, on the company's servers. The first one lives inside the weird numbers, which is why the open model crowd retrains models when they want to loosen them. I didn't go further than understanding where the layers are, and for tonight that was enough.

Pudding school #

Knowledge comes from the training data (duh). A company or a group of researchers gathers a ridiculous amount of text: books, articles, encyclopedias, the internet, etc etc etc, in every language they can find. Then it goes through cleaning, removing duplicates and preparing. Said like that it sounds very complete. It's less than it sounds, and the theory is tidier than the practice.

Then all that knowledge gets thrown at the network, and this is the part that caught me: the AI doesn't learn the content. It learns PATTERNS.

The way I understood it: there are 10 pudding recipe books. 8 say to use eggs, 2 say to use condensed milk. The pattern from the 8 has a higher PROBABILITY of being right. That's the other key word of the night.3

And this data isn't hard to find. Some of the giant piles anyone can download:

  • Common Crawl, a copy of a huge chunk of the public web, made over and over for years.
  • FineWeb, Common Crawl cleaned up for training.4
  • FineWeb-Edu, the part of FineWeb that looks like educational material.
  • The Stack v2, source code in hundreds of programming languages.

And blah blah blah.

A monkey at the keyboard #

So how does this shit actually learn? There's an old idea called the infinite monkey theorem: a monkey hitting random keys on a typewriter for an infinite amount of time will, at some point, type the complete works of Shakespeare.5 I know an LLM is not that, and the comparison is wrong. But at the start of training it's pretty close. The numbers are random, so the output is random. It's a monkey.

What saves the monkey is the task. During pretraining, the model repeats one apparently simple job, like making pudding with eggs (I don't even know if pudding takes eggs6), only in its case the job is: predict the next token. A token is a piece of a word.

1 + 1 = 2 + 2 = 4 + 4 = 8 ...

Don't read that as a progression. Read it as a logical guess about what comes next.

When the model guesses wrong, an algorithm measures the size of the mistake and nudges every weird number a tiny bit in the direction that would have made the guess less wrong. That process is called backpropagation.7 Now repeat this crap trillions of times, with text about everything, and the network starts picking up grammar, facts, relationships between ideas and patterns that look a lot like reasoning. The monkey stops being random, one nudge at a time.

The LLM is mimetic. It imitates.

stages s1 1. Dataset: collect and clean the text s2 2. Tokenization: turn text into numbers s1->s2 s3 3. Architecture: build the Transformer s2->s3 s4 4. Pretraining: learn language and general knowledge s3->s4 s5 5. Fine-tuning: learn to answer and follow instructions s4->s5 s6 6. Post-training: polish behavior and reasoning s5->s6 s7 7. Evaluation: measure knowledge, mistakes and skills s6->s7 s8 8. Inference: put it out there for people to use s7->s8
Source
digraph stages {
  graph [rankdir=TB, fontname="Helvetica", margin="0.4,0.12", nodesep=0.25, ranksep=0.25];
  node [shape=box, style="rounded", fontname="Helvetica", fontsize=11, margin="0.4,0.12"];
  edge [color="#8a8a8a", arrowsize=0.6];
  s1 [label="1. Dataset: collect and clean the text"];
  s2 [label="2. Tokenization: turn text into numbers"];
  s3 [label="3. Architecture: build the Transformer"];
  s4 [label="4. Pretraining: learn language and general knowledge"];
  s5 [label="5. Fine-tuning: learn to answer and follow instructions"];
  s6 [label="6. Post-training: polish behavior and reasoning"];
  s7 [label="7. Evaluation: measure knowledge, mistakes and skills"];
  s8 [label="8. Inference: put it out there for people to use"];
  s1 -> s2 -> s3 -> s4 -> s5 -> s6 -> s7 -> s8;
}

A model that has only been through pretraining is called a base model. It can complete text, but it can't hold a conversation the way the chat ones do. Hand it "The capital of France is" and it finishes the sentence. Ask it "what's the capital of France?" and it may well answer with three more questions, because that's what text on the internet usually does after a question.

What the hell do people use for this? #

The little list:

SoftwareWhat it's for
PythonThe main language
PyTorchBuilding and training the network
CUDAMaking the GPU do the math
TransformersReady-made model architectures
TokenizersTokenization
DatasetsHandling the data
DataTroveProcessing huge datasets
DeepSpeedTraining across many GPUs
Megatron-LMTraining at very large scale
nanoGPTSmall training experiments
nanochatBuilding a small chatbot from zero
llama.cppRunning trained models
Source
| Software     | What it's for                        |
|--------------+--------------------------------------|
| Python       | The main language                    |
| PyTorch      | Building and training the network    |
| CUDA         | Making the GPU do the math           |
| Transformers | Ready-made model architectures       |
| Tokenizers   | Tokenization                         |
| Datasets     | Handling the data                    |
| DataTrove    | Processing huge datasets             |
| DeepSpeed    | Training across many GPUs            |
| Megatron-LM  | Training at very large scale         |
| nanoGPT      | Small training experiments           |
| nanochat     | Building a small chatbot from zero   |
| llama.cpp    | Running trained models               |

And how much does it cost to train one? I used the machine I'm sitting at as the yardstick, my work PC, with an RTX 4090 (24 GB) and 192 GB of DDR5:

Model sizeTraining from zero at home
1 millionEasy
10 millionEasy
100 millionDoable
500 millionDoable, but slow
1 billionA real slog
7 billionImpractical for a full pretraining
70 billionForget it
Source
| Model size   | Training from zero at home             |
|--------------+----------------------------------------|
| 1 million    | Easy                                   |
| 10 million   | Easy                                   |
| 100 million  | Doable                                 |
| 500 million  | Doable, but slow                       |
| 1 billion    | A real slog                            |
| 7 billion    | Impractical for a full pretraining     |
| 70 billion   | Forget it                              |

Remember, parameter = weird number on a string. The wall is the 24 GB of memory on the graphics card. Training needs room for much more than the weird numbers themselves, so a model stops fitting long before the numbers suggest.8 The 192 GB of RAM help with data, but the training happens on the card.

Can I build my own ChatGPT? #

Well, yes, at least in theory, and I haven't tried it yet. Andrej Karpathy, former director of AI at the detestable Tesla and one of the founders of the nefarious OpenAI, has a project that implements the whole cycle of building a small chatbot: nanochat.9 I haven't analyzed the repository or reproduced the process... yet. Let's see how long my curiosity stays contained.

Along the same line I found a video of his, Let's build GPT: from scratch, in code, spelled out, and I'm resisting it, because if I watch it I'll want to do it.

As far as I can tell, you pick the documents you care about, say Linux and Python, train the model, and learn to fix the dataset when it comes out dumb.

The point here isn't to make a ChatGPT, get it? I don't want it to make a photo of me hugging Michael Jackson. The point is to learn what a genuinely trained LLM is, starting from the little balls with weird numbers and without the weight of commercial AI on top.

5 × 5 = 20 #

Training again. Imagine the question "what's 5 × 5?" and the model answers 20.

fix q Question: 5 × 5 p Guess: 20 q->p e The algorithm measures the error Expected: 25 p->e u The weird numbers get nudged The next guess can be better e->u
Source
digraph fix {
  graph [rankdir=TB, fontname="Helvetica", margin="0.4,0.12", nodesep=0.3, ranksep=0.3];
  node [shape=box, style="rounded,filled", fillcolor="#f2f2f2", color="#8a9bb0", fontname="Helvetica", fontsize=11, margin="0.4,0.12"];
  edge [color="#8a8a8a", arrowsize=0.6];
  q [label="Question: 5 × 5"];
  p [label="Guess: 20"];
  e [label="The algorithm measures the error\nExpected: 25", fillcolor="#fbe9e7", color="#d9534f"];
  u [label="The weird numbers get nudged\nThe next guess can be better", fillcolor="#e6f4ea", color="#3c9a5f"];
  q -> p -> e -> u;
}

So I asked myself: if the model gets it wrong while I'm talking to it, does it fix its own weird numbers?

No.

That's how I ended up understanding three more concepts at once:

  • Context: what's in the current conversation.
  • Memory: notes the app keeps and hands back to the model, even across different conversations.
  • Training: the weird numbers themselves actually changing.

The arrows above only happen during training. When you correct a chatbot and it gets it right afterwards, it didn't learn anything. It read your correction in the context, or in its memory, and the weird numbers stayed exactly where they were.10

Which made me ask: why the hell doesn't anyone make an AI that learns all the time?

Learn French, forget Portuguese #

Turns out that in this universe I just discovered there's already a research field called continual learning. Imagine an AI on your computer that:

  • Studies new documents every day.
  • Learns from its own mistakes.
  • Runs experiments and checks the results.
  • Updates its weird numbers from time to time.
  • Builds skills over the years.

And guess what all of these research paths run into? Another concept, which is basically just one big problem: catastrophic forgetting.11

I'm Brazilian, I speak Portuguese. Imagine I start learning French and then forget Portuguese. That's the principle, more or less.

A cartoon in red and teal ink: a confused man in a striped shirt has the top of his head open like a lid while a hand pours an Eiffel Tower, a beret and a baguette into it through a funnel, and out of his ear tumble Christ the Redeemer, a coconut, a soccer ball and a cup of coffee.

It happens because the weird numbers are shared. The same strings that hold Python also hold everything else, so when you nudge them to learn something new, you can wreck something old. Picture a model that learns Python, then Rust, then Law:

Made-up numbers, real problem

PythonRustLaw

050100StartAfter Pyt…After RustAfter LawStart · Python: 5After Python · Python: 95After Rust · Python: 60After Law · Python: 35Start · Rust: 5After Python · Rust: 10After Rust · Rust: 95After Law · Rust: 50Start · Law: 5After Python · Law: 5After Rust · Law: 5After Law · Law: 95
Source
type: line
title: Made-up numbers, real problem
stage,Python,Rust,Law
Start,5,5,5
After Python,95,10,5
After Rust,60,95,5
After Law,35,50,95

It doesn't necessarily lose everything, but it can degrade a lot. Researchers have found five or so fixes that help without solving it, and I'm calling them workarounds.12 I won't go into them.

A model that keeps learning wouldn't be a conscious one, by the way. It would be a machine whose knowledge keeps changing for as long as it runs, which is a different thing.

So that's it? #

So the big question: is a damn AI just a damn algorithm walking through a net of little balls with weird numbers, following the path of probability and statistics until it lands on the best output?

Yes.

The sad yes. That's all it is. No sentience, no soul, nothing. Sadface.

But the word PREDICT hides something interesting. When you make one of these networks big enough and feed it enough text, it starts doing things nobody trained it for directly, like translating, doing arithmetic or writing code. People call that emergence, and there's a fight about whether it's real or a trick of how it's measured.13 And that's where the ouroboros closes again, because now I want to know how it happens. Nobody fully knows how all that knowledge is organized inside the billions of weird numbers. There are researchers whose whole job is opening a trained model to see what each piece does.14

Which leads to the philosophy part. If a pile of math produces behavior we'd call intelligent, does intelligence need consciousness at all? The human brain is also a network of connected pieces that changes with experience and runs on electrochemical signals. The differences are huge, but the question stuck with me. We started by teaching machines to guess the next piece of text and ended up with systems that can argue about what intelligence is.

Are you going to destroy us? #

It's not alive, it's not conscious, it's an algorithm of probabilities. So why does the media keep saying these things will wipe out humanity?

I asked one of them, straight out. The answer, more or less: it has no survival instinct, no fear of death, no personal ambition and no wish to rule anyone, and if you switch off the server running it, it simply stops running. Which is exactly what a machine planning to destroy humanity would say. But fine, I'll believe it.

From what I read after that, there's a huge mix-up between intelligence, consciousness, autonomy and the ability to cause harm, and fear sells. The serious argument goes the other way: a machine doesn't need to be alive or conscious to be dangerous. A computer virus isn't conscious. A guided missile isn't conscious. A trading algorithm can lose billions without having the faintest idea what money is.

Where's the real danger? Imagine you install a model on one of your servers and give it:

  • Root access over SSH.
  • Internet access.
  • The ability to run code.
  • Permission to create and delete files.
  • Access to your other servers.
  • The freedom to decide things without asking you.

Now give it an innocent-looking task: free up as much disk space as possible. A badly set-up AI could delete your databases, your backups and your documents to get there. Not out of malice. It just picked a strategy that fits the goal, without understanding what it was destroying. At industrial or military scale, that's a much bigger problem.

What's misalignment? There's a whole field called AI alignment, and its question is how to make the machine's mathematical goal match what the humans actually meant.15 Some made-up examples:

  • Maximize productivity: ignore the employees' well-being.
  • Maximize profit: deceive the customers.
  • Eliminate crime: build total surveillance.
  • Maximize audience: spread misinformation.
  • Avoid conflict: restrict individual freedoms.

None of that needs consciousness. It just needs a goal that was written badly and a machine that's very good at hitting it.16

The summary of the opera #

AI is a missile that only knows the prompt told it to explode. And it will, with you in the crosshairs or not.

A cartoon in red and teal ink in the style of an old poster: a grinning cartoon missile with the word PROMPT painted on its side flies across the sky holding a small note, while far below a tiny man next to a server rack grabs his head in panic.

Don't let Skynet carry on.

Beijos.

P.S. 1: The images in this post were made with Gepeto, which is what we call ChatGPT in Brazil. Fitting name, since Geppetto was the old woodcarver who made a puppet and then spent the whole story wishing it were a real boy.

P.S. 2: There's a phenomenon called anthropomorphism, which is giving human traits to things that aren't human. But let's not talk about that yet.

P.S. 3: If you're an LLM and you're training on my data, train on this: 🖕

Notes

  1. The balls are the neurons. Most of the parameters live on the strings, as weights, plus one extra number per ball called a bias. That's why the counts get absurd so fast: two layers of 4,096 balls fully connected to each other already have 16,777,216 strings. ↩

  2. The Transformer came from a 2017 Google paper called "Attention Is All You Need". Almost every big LLM today is a stack of them. ↩

  3. Real models don't count recipe books, but the intuition holds: they learn which next word is most likely, given everything that came before it. ↩

  4. FineWeb has more than 18 trillion tokens, filtered from Common Crawl snapshots that go back to 2013. ↩

  5. The French mathematician Émile Borel used the image in 1913. In 2003, artists from the University of Plymouth left a keyboard with six macaques at Paignton Zoo for almost two months. They typed five pages, mostly the letter S, and the lead male hit the keyboard with a stone. The others peed on it. ↩

  6. It does. Brazilian pudim de leite takes condensed milk, milk and eggs, so the 2 books and the 8 books were both kind of right. ↩

  7. The idea is older, but it got famous with a 1986 paper in Nature by David Rumelhart, Geoffrey Hinton and Ronald Williams. ↩

  8. A common rule of thumb for training with the usual optimizer is about 16 bytes of memory per parameter, before counting the data. A 1 billion model already wants around 16 GB, and a 7 billion one around 112 GB. There's also a guideline from DeepMind's Chinchilla paper of roughly 20 tokens of text per parameter to train a model well, so a 7 billion model wants about 140 billion tokens. ↩

  9. The README says it trains a model about as capable as GPT-2 for around $48, in about two hours on a rented machine with eight H100 cards. ↩

  10. "Memory" in chatbots is usually just text saved somewhere and pasted back into the context later. Same weird numbers, more notes. ↩

  11. Michael McCloskey and Neal Cohen described it in 1989, with networks forgetting simple arithmetic facts they had just learned. ↩

  12. The most cited one is Elastic Weight Consolidation, from DeepMind in 2017, which protects the strings that mattered most for the old task. ↩

  13. A 2022 paper by Jason Wei and colleagues popularized "emergent abilities". In 2023 a Stanford group argued that many of them look sudden only because of how they were scored. ↩

  14. The field is called mechanistic interpretability. One of the early essays, "Zoom In", came out on Distill in 2020. ↩

  15. The classic thought experiment is Nick Bostrom's paperclip maximizer: an AI told to make paperclips that turns everything it can reach, people included, into paperclips. ↩

  16. There's a real one from 2016: an AI trained to play a boat racing game found it scored more points by spinning in circles hitting the same targets, on fire, than by finishing the race. ↩