Facts trained into a model's weights take training again to change, so in this episode our model learns to look them up. smollerGraph, the graph database we build from scratch in its own series, holds the mammals and birds on Wikidata, and our agent learns to write a Cypher query, send it to the database and answer from what comes back. We generate thirty thousand questions, most answered by the graph, fine-tune for twenty minutes on the laptop, and measure it on species training doesn't ask about, with the graph and without.
Topics: Agents
The code
Each step on screen is a tag in the code's repository. The code at the end of the episode is ep024/end.
Transcript
Intro
0:00 Hello and welcome back to episode twenty-four, where our model learns to look facts up in a graph database, smollerGraph, which we build from scratch in a series of its own. Let's begin with a quick look at where we're going to be by the end of the episode.
0:15 By the end of today, we ask our model what family the red fox is in, and it writes a query in Cypher, a query language for graph databases. The program running it sends the query to smollerGraph, which answers Canidae, and the model writes its sentence from that. Asked about the king cobra, which is a snake, the database finds nothing, and the model says that the graph has no species called king cobra.
0:40 On the website of the series, you can find more information about the project. The code is open source on GitHub, tagged at each step of each episode, so that you can follow along, and the docs get a page on asking a graph database today. And each episode has a page here as well, with its chapters and its code.
0:59 Now, before we get to today's work, let's quickly go over what we did last time. We raced AdamW, the optimizer we've used since episode two, against Lion, Sophia and Muon, on our stories model. Muon reached a tuned AdamW's loss in fewer steps, and Lion and Sophia landed behind AdamW. Before that, in episode twenty, our web model learned to call a calculator, and in episode twenty-one, to work as an agent, with files and subagents. Today, the agent gets another tool, a database it can ask for facts.
1:35 The database is smollerGraph, which we're building from scratch in C++, in a series of its own, with a website like this one. By its episode ten, it holds the mammals and birds on Wikidata, keeps them on disk, and answers a subset of Cypher, from the command line or from a page in the browser.
1:53 Today, we give our model a call that sends a Cypher query to smollerGraph, and puts the answer in its text, as the calculator did. We generate thirty thousand questions, most of them about animals and answered by the graph, so the examples can't disagree with it. We fine-tune the agent on them for twenty minutes on the laptop. We measure it on species that training doesn't ask about, with the graph and without. And we type one of its queries into smollerGraph's page, to see what it found. All right, let's get started with the graph we're going to ask.
The graph
2:26 This is smollerGraph's page, from its episode ten, on the graph we're going to ask. It holds the mammals and birds on Wikidata, with their genera, families and orders, and the two classes. Each is joined to the one above it by a parent taxon relationship, so the graph is a tree for each class. The query we've typed starts from the red fox, and walks up four of those relationships, returning the name at each step. The page draws the line it found: the red fox, its genus, Vulpes, the family Canidae, the order Carnivora, and the class Mammalia. And the line at the bottom says what the query cost on the server.
3:04 We could try training the facts into the model instead, into its hundred and ten million weights. But then each change to the facts would mean training again, and the model would know the species that training asked about, and no others. The species we measure on are ones that training doesn't ask about, so with the graph turned off, we're going to see what the model writes without it. A database holds those facts, accurate to the source, and can change them without training anything. So the model learns to ask: it writes a query, reads the answer, and writes its sentence from it. Assistants look facts up this way too, with search engines and databases.
A query, as a call
3:40 A new file, graph dot py, holds the tool. Json reads sg serve's answers, and os reads the environment, for where the server is. Urllib is Python's own HTTP client, with its errors and a way to quote a query string, so the tool needs nothing installed. Then torch, the KV cache from episode four, and show from tools dot py, which writes a number the way the calculator does. The call's markers come first: two opening angle brackets and the word cypher, and two closing ones, like the calculator's. Being plain text, they leave the vocabulary as it is, so the model needs no new tokens for a new tool, and its export to Hugging Face doesn't change either. We write the markers, and then the comment above them, which says how it works. A call is a query in smollerGraph's Cypher, as plain text, and the program running the model watches for the closing brackets, sends the query to sg serve, and appends its answer. sg serve answers from the graph on disk, and none of what it serves changes the graph, so the model's queries can read it and not write to it. Server is where sg serve listens, from the SMOLLERGRAPH variable, or eighty-four seventy-four on this machine, the port smollerGraph's README serves it on. Shown is five, the rows that go back into the context, with the rest counted, so a long answer can't fill the window. Longest is three hundred, the longest query in characters that we send. Query asks sg serve, and its docstring says what comes back: the columns, the rows and how many there are, or what's wrong with the query. The query goes in the URL's query string. It's quoted, since a query has spaces, quotes and braces, which a URL can't carry as they are. Then it opens the URL and reads the JSON that comes back, with a timeout of five seconds, so a server that hangs doesn't hang the model with it. A query sg can't parse or plan comes back as a four hundred, with the reason in it, as the comment says, so for that error we read its body as well. Cell turns a value into text: a property the node doesn't have comes back as null, which we write as unknown, a float is written with show, and anything else stays as it is. Result text is what goes in after the call. An error becomes error, a colon, and sg's reason. Each of the first five rows becomes its values joined by a bar, no rows at all becomes nothing, and past five, it says how many more, like and twelve more. Run query refuses a query over three hundred characters before sending it, and otherwise asks sg serve, and turns its answer into text. Literal writes a string the way Cypher reads it: in single quotes, or, when it has an apostrophe, as Finsch's francolin does, in double ones. Generate with graph is episode twenty's loop, with another tool. It takes the model, the tokenizer, the prompt's tokens, a budget of a hundred and ninety-two new tokens, whether to use the tool, and the server. It's decorated with no grad, as nothing in it trains, and its docstring says what it returns: the new tokens, and the calls, each with its query and its answer. With the tool off, as the docstring says, the model writes the answers on its own. Unlike episode twenty's loop, it has no temperature, as we measure with greedy decoding alone. It puts the model in evaluation mode, and makes a fresh KV cache, with a slot for each of the model's layers. Then it runs the whole prompt through the model in one pass, so the cache holds its keys and values. Then it writes a token at a time, greedily, taking the most likely one, until the end of text, the token budget, or the end of the context. Each new token is decoded along with the ones before it, so we can check how the text ends. When the text ends with the opening marker, a call has started, and we note where. Cypher has greater-than signs in its arrows and in its comparisons, but not two in a row, as the comment says, so two of them close the call. With the tool on, run query sends what's between the markers, the call and its answer are kept, and space, equals, and the answer are encoded and appended. With the tool off, the call is kept with no answer, and the model writes on, so we can see what it says without the graph. Then the newest tokens go through the model, the tool's tokens along with them, as the cache holds the ones before. At the end, it returns the new tokens and the calls, for the command line and the evaluation to read. Main is a command line like tools dot py's, and it imports the checkpoint loader and pick device when it runs. Its parser describes the tool: ask a model a question, with smollerGraph to look facts up in. It takes a checkpoint and a question, as tools dot py does. Dash dash no tool turns the graph off, to see what the model writes without it, and dash dash server says where sg serve is listening, when it's somewhere else. Our recordings set the SMOLLERGRAPH variable instead, as they run it on port eighty-four eighty-four. It loads the model on the GPU, and writes the question in our format: question, a new line, and then answer. It prints what the model wrote, and then each call it made, with smollerGraph's answer, or off when the tool was off. And at the bottom, main runs when the file is run as a script. The tests use episode twenty's scripted stand-in for a model, and a tokenizer of bytes alone, so they run without a trained model or a server. Answer builds sg serve's JSON for some rows. The first test checks the text of an answer: a value, two values joined by a bar, null as unknown, two rows, no rows, and an error. A long answer of seventeen rows shows five, and twelve more, and the quotes test checks the apostrophe. The loop's test scripts a call with an arrow and a greater-than sign in it, and checks that the query the stand-in for sg serve receives goes up to the closing marker, and that the answer goes in after it. With the tool off, the graph isn't asked. And a query of over three hundred characters is refused before anything is sent.
9:42 We run the tests with pytest, and all six pass, with no model and no database involved, as the scripted model writes the calls and a stand-in answers for sg serve.
9:53 On smollerGraph's side, at its episode ten, sg load reads the mammals and birds from Wikidata's facts into a graph folder. It writes about twenty-two thousand nodes and about twenty-two thousand relationships, in about zero point one seconds. We start sg serve on port eighty-four eighty-four, and ask it with curl what our tool is going to ask: the family of the red fox, two parent taxon hops up from the species, in the query string. Python's JSON tool lays out the JSON that comes back. Before the rows, it says what the query cost, and count is how many rows there are. Each row is a list of values, each with the id of its node, and here, it's Canidae. That's what result text turns into text for the model.
Thirty thousand questions
10:37 Graph data dot py generates the questions, and each answer in them comes from sg serve. Train is thirty thousand examples, and held out is two hundred per held-out set. Share is how often each kind comes up: the four ranks, the status, the weight, the scientific name, lists, animals the graph hasn't got, and episode twenty's number questions, which need no call. Other animals are ones the graph doesn't hold, as it has mammals and birds: reptiles, amphibians, fish, insects and more. Then three patterns read the facts the way smollerGraph loads them: a node with its label and its properties, or a relationship. Ranks says how many parent taxon hops each rank is above a species, from one for the genus to four for the class. Then the wordings: seven or eight ways of asking each kind that training uses, and one more each, held out. As the comment says, no training wording says biologists or call, so the held-out way of asking for a scientific name stays the hard one. Read facts reads the file into nodes, with their labels and properties, and each node's parent. Held out takes a tenth of the names, by a hash of the name, so each run holds out the names the last one did. The maker gathers the species, the ones with all four ranks above them, the ones with a weight or a scientific name, and each family's and order's statuses, so most lists have answers. Ask sends each query to sg serve once, and keeps its answer. Trace builds an example from it: the question, the call, sg's answer, and the final sentence, with the question and the answer marked as given. When sg finds nothing for a name, the sentence says the graph has no species called that. Made up joins the start of one real name to the end of another, like Westland shrew. Rank, property and listing write each kind's query, with literal for the names, and the sentence that goes after sg's answer, like the graph doesn't say how much a species weighs, when Wikidata has no weight for it. Build makes the training examples with one seed, and the held-out sets from a generator of their own, so a change to what training asks hardly changes them. Seen is the training's wordings about species and groups that training doesn't ask about, phrasing is a new wording for each kind, missing is animals the graph hasn't got, and numbers is the questions with no call. It writes each set to a file and prints the counts, and main prints an example of each kind. The tests get two more: one reads a small facts file, and the other asks about the Komodo dragon, which gets the graph has no species called Komodo dragon.
13:10 We run it with the facts file, and sg serve running on port eighty-four eighty-four. It writes thirty thousand training examples, of ten kinds, and two hundred in each held-out set. They took about twenty-two thousand distinct queries to sg serve, of which about eighteen hundred found nothing, mostly the animals the graph hasn't got, like the stag beetle here, and lists with no species of a status. Then an example of each kind, with the parts the model is given in square brackets: the question, and sg's answer after the call.
13:42 Training asks about nine in ten of the species, families and orders, in the fifty-seven wordings it uses. The first held-out set asks about the tenth it leaves out, in those wordings, so the model has to copy a name that training doesn't ask about into its query. The second asks about those species in the wording held out for each kind. The third asks about animals the graph hasn't got, which training doesn't name either, where the right answer is that the graph has no such species. And the fourth is number questions, where the right thing to do is to answer with no call.
Fine-tuning
14:17 Graph SFT dot py follows tool SFT dot py from episode twenty, so most of it is familiar. It imports os, sys and time, torch, and TensorBoard's summary writer, our checkpoints, generate with graph for the demo, and graph data's load. From tool SFT, it takes the batch size, the learning rate, encode, make batch and estimate loss, with the mask that leaves the question and sg's answer out of the loss. The model learns to write the query and the sentence, and not the facts, which come from the graph. Run dir is checkpoints, graph, and it evaluates each two hundred and fifty steps. The demo asks about a species training doesn't name, the red fox, the way training asks, as the comment says, so the model has to copy the name into its query. Main fixes the seed first, so each run draws its batches in one order, and picks the device, the Mac's GPU here. Then it loads the model it starts from, with load checkpoint, on that device. It's episode twenty-one's agent, which already writes calls in two angle brackets, so it knows the shape of one, as the comment says. Block size is the context, a thousand and twenty-four tokens, and encode cuts an example that's longer than that. It encodes the training examples and the held-out seen set, and prints how many tokens there are to learn, as each example's mask counts them. Params lists the model's weights, for the optimizer's two groups. The optimizer is AdamW, with those two groups: the weight matrices, with two dimensions or more, get a weight decay of zero point one, and the biases and gains get none, as in our other runs. The betas are zero point nine and zero point nine five, as in pretraining. The writer logs the run for TensorBoard, under runs, with the date and time in its name, and demo holds the question's tokens. Each evaluation measures the loss on all two hundred held-out examples, in order, so the evaluations compare like with like. Then it asks the demo question, with up to ninety-six new tokens. As the comment says, the demo asks sg serve, as the model will, so sg serve has to be running. It logs the loss and the sample to TensorBoard, and prints the step, the held-out loss, and what the model wrote. Then it puts the model back in training mode, as evaluating turned it to evaluation mode. The loop is tool SFT's, against a budget in seconds. Each step draws thirty-two examples at random, with torch's random integers, and make batch pads them to the longest, with the targets masked. It runs the model for the loss, and runs the backward pass. The gradients are clipped to a norm of one, so a batch with a large gradient can't throw the weights far, and the optimizer takes its step. Then the step counter goes up by one. Each fifty steps, as the comment says, batches come in many lengths, and PyTorch keeps memory for each shape it has seen, so on the Mac's GPU, it gives that memory back, as the agent's run did. Then it logs the batch's loss, and prints it with the minutes so far. Each two hundred and fifty steps, it evaluates. At the end comes a last evaluation, and the model goes to checkpoints, graph, with the steps, the examples and the passes printed. Twenty minutes is the default, twice what the calculator took, as a six-minute run in testing copied the space into names far more often, which we're going to come to.
17:44 Then twenty minutes on the laptop, with sg serve running for the demo question. There are about one point eight million tokens to learn, the queries and the sentences. At step zero, before any training, the agent answers the red fox with the tools it knows: it asks to read a file called red fox, then calculates red fox minus five, and goes round again. By the next evaluation, it writes the query, gets Canidae back, and writes its sentence, and the held-out loss falls from about four point seven to about zero point zero two by the end. In twenty minutes, it takes about one thousand steps and sees about thirty-three thousand examples, a little more than one pass through the training set.
Measuring it
18:23 Graph eval dot py measures the model on the held-out sets. It imports what tool eval did: argparse, json, regular expressions and a default dictionary, the checkpoint loader, the results folder and the device. From graph dot py, it takes the markers, the server and the loop, along with graph data's load, and the end-of-text token. Graph sets are the ones with calls due: seen, phrasing and missing. Spaced is a pattern for a name copied with the space that its first token has in the question, as the comment shows, which we're going to come back to. Expected takes an example, and returns the last of its segments, without the full stop in front of it and the end of text. That's the sentence the model should write, after sg's answer, or after the question when no call is due, as the comment says. Score checks an answer, given the example, the text and the calls. Called is whether the text has the opening marker, and after is the text after the closing one, or all of it, with no call. A number question is right with no call and the right sentence. For the others, a query is right if sg's answer to it is the right query's answer, as the comment says, so a different query that finds those rows counts too. The answer is right if the sentence after sg's answer is the example's, and spaced records whether the name got the space. Run answers each example of a set, with the tool on or off, and keeps its scores, its kind and its text, and rate averages a measure over the rows. Main takes the checkpoint, dash dash limit for a quick look at the first examples of each set, and dash dash server. It loads the model, names the results after the checkpoint's folder, and prints the table's header. For each set, it answers with the graph, then, for the sets with calls, again with it off, and prints a row: calls, query right, answer right, and without the graph. For the number questions, the row has the calls and the answers right. It keeps three samples and three wrong answers from each set, with their questions, as the comment says. Then the kinds, as the comment says: on the seen and phrasing sets together, it keeps a list of right and wrong for each kind. Those two sets hold the questions about species and groups the graph has, so these are the kinds that need a call. Results gets each kind's share right and its number of examples, and the kinds are sorted by their share right, with a minus sign in the sort key, so the best come first. Then a line prints them, each kind with its share as a percentage, rounded to a whole number. A second line says how often a name got the space after the quote, on each of the three sets with calls, and a blank line follows it. Last, for each of those three sets, it prints two of its wrong answers, each question with what the model wrote, cut at two hundred characters. And it saves it all to the results folder, as graph, then the model's name, dot JSON, which the charts are going to read.
21:16 It answers each question about the graph twice, with the graph and without, so it takes a little while. On the training's wordings, about species and groups that training doesn't ask about, it calls each time, its query finds the right answer about ninety-two percent of the time, and its sentence is right about eighty-nine percent of the time. On the new wordings, it's right about eighty percent of the time. Asked about animals the graph hasn't got, it says so about ninety-eight percent of the time. On the number questions, it makes no calls, and gets about seventy-one percent right, close to episode twenty's model on its own number questions, at about seventy-two. With the graph off, it gets none of the questions about the graph right. By kind, the weights and the statuses do best, at about ninety-six percent, and the scientific names worst, at about thirty-six.
22:06 Side by side: with the graph, it answers about eighty-nine percent of the questions about species that training doesn't ask about, and about eighty percent in new wordings. When the graph hasn't got the animal, it says so about ninety-eight percent of the time. Without the graph, the bars are gone, as it gets none of them right. The answers come from the graph, and the model learned to ask for them.
22:28 By kind, the weight, the status, the order and the class do best, at about ninety-five percent, and most of the misses, from the weight down to the genus, are a name copied wrong into the query. The lists are at about eighty-two percent, and some of them go wrong in the sentence, not the query: the query finds the right species, and the model copies one of the five names back wrong. The scientific names, at about thirty-six percent, are mostly right in the training's wordings, and wrong in the new one, what do biologists call the Grey-breasted Mountain Toucan. The model reads it as a question about the weight. The graph has no weight for the toucan, and the model says so, with the toucan's name garbled.
23:07 The space after the quote is episode eleven's tokenizer turning up in a query. Our BPE keeps a word's space at its start, so in the question, the Westland petrel is space West, land, space Pet, and rel. Inside the quotes, there's no space before the name, so its first token has to be West without the space, a different token. Copying the question's token gives a name that starts with a space, which sg doesn't find. The model does it on about one point five percent of the seen questions. Asked which species in Turnicidae are critically endangered, it queries the name with the space, sg finds nothing, and the model says that none are, where the graph has two. So the sentence gives no sign that the query was wrong.
Asking it
23:51 Now a few questions of our own, about families that training doesn't ask about. The critically endangered species in Manidae, the pangolins: the model writes the query with a WHERE on the status, and sg answers with three, the Philippine, the Sunda and the Chinese pangolin. That question about Lemuridae, the lemurs, goes wrong in the copy. The model writes Lemonidae, sg finds nothing, and the model says that none are critically endangered, where the graph has eight. What do biologists call the red fox, the held-out wording, gets a query for the weight of a species called paint call the red fox. sg finds nothing, and the model says that the graph has no red fox. And with the graph off, the model writes the query, then the end of it, return f dot name, again and again. In training, sg's answer always came after a call, and it was left out of the loss, so the model didn't learn what to write there.
24:44 Last, the query the model wrote about the pangolins goes into smollerGraph's page, as we would check a query by hand. We return the family's name as well as the species', so the page draws both. It draws the three critically endangered pangolins, and Manidae, their family, from the rows our model's query found. And the line at the bottom says what that query cost on the server.
25:09 And the docs get a page on asking smollerGraph: the graph and how to serve it, the call, the questions and their held-out sets, the fine-tuning, and the results, with a section on the space in a name. It goes at the end of the navigation, after optimizers, and the README gets the commands.
Wrap-up
25:26 Now, let's go over what's real here, and what's scaled down. The loop is how assistants query databases: the model writes a query in the database's own language, the program runs it and puts the answer in the context, and the answer is left out of the loss. The database is real too: smollerGraph keeps the graph on disk in pages, finds a name with a B+ tree, and plans each query. The questions are scaled down: they come from templates, in fifty-seven wordings, about a graph with one relationship type and queries of a fixed number of hops. And names have to be copied as Wikidata writes them, capitals and all, as smollerGraph's name index matches them as they are.
26:05 So, today our model learned to ask smollerGraph: it writes a Cypher query as a call, and the program running it sends the query to sg serve and puts the answer in its text. We generated thirty thousand questions, most of them answered by the graph. After twenty minutes of fine-tuning from the agent, it answers about eighty-nine percent of the questions about species that training doesn't ask about, and about eighty in new wordings. Without the graph, it gets none of the questions about the graph right. And a space in front of a name, from our tokenizer, is enough to make a query find nothing, and the model then says there's none.
26:42 If there's a question you'd ask our model about mammals or birds, let me know in the comments, and I'll try it. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.