Posts in Python (20 found)
Unsung 3 days ago

“In the face of ambiguity, refuse the temptation to guess.”

Guido van Rossum shared a remembrance of Tim Peters , an important member of the Python community, who passed away earlier this year. I do not use Python all that much, and I wasn’t familiar with Peters’s work, but among his accomplishments was the Zen of Python , which consisted of 19 principles: (The links come from Wikipedia’s version . I kept them because they provide nice context for non-programmers.) I have always been wary of design principles. Most fall pretty to the classic saying “Everything simple is false. Everything complex is unusable.” I find the vague ones uninspiring, and the specific ones too rigid to be useful – a lot of design sooner or later arrives at “it depends,” and that’s hard to capture in a pithy one-liner. But there is something about (some of) these above that feels different, and Wikipedia entry suggests people actually found them useful . Perhaps they’re more pragmatic than usual, many expressed as “X over Y,” rather than fluffy stuff like “Move fast and break things” (evil), “Make it as simple as possible, but not simpler” (easy to abuse), or “Design is not how it looks, it’s how it works” (a perversion of Jobs’s “Design is not just what it looks like and feels like. Design is how it works.”) Or maybe they’re as bad and I see them as interesting only because they’re exotic, coming from the coding realm rather than the design one? Either way, they made me think what my own design principles would be. I arrived at a few of the first kind… …but I have to think about this all more carefully. Maybe more importantly, I’m interested in principles of those principles . Should each principle have a solid example showing you exactly how it’s been helpful before? You can sense there’s a real war story behind “Now is better than never. Although never is often better than right now.” and it would be great to read it. This is a thread in progress and I will report back. In the meantime, maybe Peters’s list would be useful for you to think about your list, too? Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested . Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity , refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain , it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea – let’s do more of those! 1fps or 60fps, but nothing in between. True UX delight is fiber, not sugar . Design assuming your every user will become a power user. You can ignore motor memory, but motor memory will never ignore you.

0 views

Monads in Lean

This post demonstrates how to use monads in the Lean programming language (Lean 4, to be specific). If you're not familiar with Lean, this part of the language is very similar to other functional programming languages, like Haskell or OCaml. Suppose we want to write a simple numerical expression evaluator that supports numbers with addition and division: What happens when we encounter a division by zero? We'll want our evaluator to report this as a failure, which will be represented explicitly using the the Option type: With this in hand, the eval function can be written as follows: safeDiv returns an Option ; to propagate that possible failure to its caller, eval also returns an Option , and - moreover - has to perform lots of tedious checking for the possibility of a none value. Is there a better way? Note a common code pattern repeated here: We can extract it into a helper function: And rewrite our eval using this helper: This is already much better; we can make it even cleaner using operator overloading: Congratulations - we've pretty much invented monads! In simplified form, the Monad type class in Lean is defined as: In our code, pure is equivalent to some , and bind is equivalent to withSome ; in fact, the Monad instance for Option is something like: An operator akin to >>? for monads is already defined in Lean; it's called >>= , and picks up the bind method of the Monad type class. So we can rewrite our evaluator using the standard Monad instance, without defining withSome or the >>? operator [1] : We can go even further with the do notation, which is syntactic sugar around >>= that lets us rewrite the evaluator as: This notation should be familiar if you've seen Lean code dealing with I/O; we'll revisit I/O later in the post. Functional programming languages place a lot of emphasis on pure functions that are free of side effects. There's no question that such functions are easier to reason about, debug, and even optimize (by memoization). That said, the real world is messy and sometimes side effects are inescapable; monads help encapsulate side effects in functional programs. The core idea is: side effects are encapsulated inside a Monad , which wraps the value returned from a computation. The bind method (or the equivalent >>= operator) lets us take a wrapped value and push it into the next computation in the sequence. This may look familiar from continuation-passing style (CPS). Continuations themselves can also be modeled with a monad [2] . The definition of bind is: Here's a mental model to think about it: Chaining multiple bind s together is essentially a sequence of computations while keeping track of the side effects. A monad decouples what computations do from how they are sequenced . The programmer describes the sequence of computations and their dependencies, while the monad's bind implementation handles the bookkeeping necessary to combine their side effects. Our evaluator case study shows one example of side effects: early return from a computation with a none value. Let's see another idiomatic way of doing that, with the Except type that contains either a successful result or an error value (very similar to the Result type in Rust). We'll begin by writing an exception-returning version of safeDiv : Instead of writing a whole new eval variant for Except , we'll create a generic one that works with any Monad [3] : Now evalM can be used with safeDivExc to implement an evaluator where division returns Except ; used with safeDiv , it would be equivalent to the Option -specific evalDo we've written before. Let's look at a more advanced example: an evaluator that also logs the computation it executes in a linear log of strings. The challenge here is that we still have to combine that with Option to support the divide-by-zero case, so we'll start by creating a new structure to carry the state of the computation: This will be the result of one eval call; it produces an optional value, along with a list of strings (the log). Here's the Monad implementation for this type: The main idea is combining the stored log with the log of the next computation by appending them (thus accumulating a linear log). Here's our evaluator: Note how the code of evalLogged doesn't have to deal with the mechanics of logging too much (other than adding new log entries). All of that is hidden within the monad instance. LoggedOption is an example of the writer monad , which is a write-only version of the state monad . One of the most important use cases of monads in functional programming languages is modeling mutable state through a computation. A stateful computation is modeled as a function that takes an initial state and returns a tuple containing the result value and a new, updated state. In Lean notation: To demonstrate this in action, let's enhance our evaluator to support variable assignments and lookups. Our state is going to be an association list of name, value pairs: And we'll augment our expression enum with additional operations: This is going to be our state monad: Note the correspondence of the run function to the State signature above: This is its Monad class implementation: And finally, the evaluator: Operations that don't deal with variables directly (like .num and .add ) just do their work as before. .div only has to deal with the actual monad type to ensure that none is propagated in case of division by zero. Note also that this evaluator supports stores as expressions, since they separately return a value and the updated state; therefore, computations like this one will work: Producing the result some (16, [("x", 12)]) . In a language with mutable state, modeling side effects is easy - just assign some state (like a struct field or class member). In a functional language like Lean, however, we have to carry this state across the computations explicitly; monads help us do this with elegance - by hiding most of the mechanics of actually carrying the state around, the majority of the code remains free of bookkeeping. Perhaps the most well known example of a monad in functional programming languages like Lean and Haskell is IO . To anyone who's written a "real" program that interacts with the outer world, IO is very familiar. Here's a customized "Hello" program that's typically taught in the first 15 minutes of learning a new programming language: Note the do notation here, suggesting monads. As mentioned before, do is syntactic sugar for the monad's bind method, or the >>= operator; we can rewrite this code more explicitly as: In essence, IO is a state monad, where the state carried around represents the "outside world". IO operations like println act on that world, and its state is carried over using bind , like other state monads. Here's a version of our expression evaluator that logs directly to standard out, instead of collecting the log as a list of strings: The only unusual construct here is OptionT , which is a monad transformer that helps us compose Option (for propagating failure from safe division) with the IO Monad [4] . The IO monad also supports throw for Python-like exception behavior, but in this example we use Option explicitly; exceptions are a matter of programming preference, and using them inside library functions like eval doesn't feel right to me. Just like in Haskell, monads in Lean should obey certain laws . Those are: Left identity : wrapping a value in pure and immediately passing it to f with bind should be equivalent to just calling f on the value: Right identity : extracting a value from a computation and immediately wrapping it with pure again should not change the computation: Associativity : the grouping of operations doesn't matter, as long as their order remains the same: Let's see how Option obeys these laws. For left identity, pure v is some v and the bind implementation matches some x to next x , which is equivalent to f v . For right identity, m >>= pure just rewraps a some value in pure , leaving none alone - this is equivalent to keeping things as they are. For associativity, if m is none then both sides are none . If m is some v , the left side is f v >>= g , and the right side reduces to the same, so again they are equivalent. While Lean doesn't enforce that a Monad instance obeys these laws, it has a separate type class called LawfulMonad which does require Lean proofs; this is useful for Lean's main use case - proving theorems about programs, expressed through its powerful type system. But this is a topic for another day. Examine the value of an Option If it's none , return none without proceeding Otherwise if it's some result , continue the computation with result Take a value wrapped with potential side effects Take a computation that takes this value and may produce additional side effects Combine the results into a final wrapped value It takes the current state, which for our use cases is an association list carrying values for all defined variables. It returns an optional result which is a pair of some value (in our case, the result of the computation) and an updated state.

0 views
Simon Willison 1 weeks ago

Locating the source of a mysterious beep with Claude

Our house has a box room, full of boxes that we still haven't unpacked from our last move. A couple of weeks ago something in that room started intermittently beeping . The beeps were far enough apart that standing in the room and trying to determine the source of the noise was frustrating, and I really didn't want to dig through every one of those boxes. So I had Claude Code build Beep Locator , a software system for triangulating the source of a mysterious beep using multiple devices scattered around the room. Here's what Beep Locator looks like after it has been running for a while: You run Python web server to show the primary UI, and then use the QR code or URL to connect as many devices as you can spare to act as listeners - I was using two iPads, a phone, a MacBook Pro and a Surface Ultra. The devices then play noises to each other to help estimate their locations. This didn't work particularly well, so I added a "Rough mode" where you can drag their icons around in the space to provide rough locations which are then adjusted based on those sounds. Once that's set up, the devices all listen for the beep! I added a clapping mode too so I could test it by clapping my hands in different locations around the room - displayed as diamonds on the map. This helped me gain confidence that it was capable of locating a sound. Beeps show up on the map as an X, plus a line in the "Sounds located" log. You can replay these sounds (from each device in turn) to confirm they are the mysterious beep you are looking for, then click "This is the mystery beep" to mark them as such. Once you've confirmed the mysterious beep frequency the system will listen out for it, measure the interval between beeps, and use the triangulated locations to lock down the most likely location on the map. The system worked as intended. It gave me the position of the beep to within about 40cm, then I dug through that specific pile of boxes and found an ancient carbon monoxide detector that desperately wanted its batteries replaced. When I started working through this problem with Claude it quickly dug up BeepBeep: A High-Accuracy Acoustic-Based System for Ranging and Localization Using COTS Devices , a 2007 paper by Chunyi Peng, Guobin Shen, Yongguang Zhang, Yanlin Li, and Kun Tan. Here's that paper's abstract: We present the design, implementation, and evaluation of BeepBeep, a high-accuracy acoustic-based ranging system. It operates in a spontaneous, ad-hoc, and device-to-device context without leveraging any pre-planned infrastructure. It is a pure software-based solution and uses only the most basic set of commodity hardware – a speaker, a microphone, and some form of device-to-device communication – so that it is readily applicable to many low-cost sensor platforms and to most commercial-off-the-shelf mobile devices like cell phones and PDAs. It achieves high accuracy through a combination of three techniques: two-way sensing, self-recording, and sample counting. That sounded exactly like what we needed to build! Beep Locator runs a Python web application server that does most of the work. The listening devices then connect to that server via WebSockets and present a UI which requests browser microphone access. The listeners mainly work by recording a 60 second buffer of recent audio. They also run a simple beep detection algorithm (see detector.js ), which uses Fast Fourier Transform and a high-pass filter to identify potential beeps. It sends these events to the main server. When a beep is reported, the server has a device play a short chirp (the device with the lowest round-trip time to the server), then asks every listener upload a clip from about 0.6s before the beep to 0.8s after that chirp. This chirp allows the clips to be aligned with each other, a crucial step in locating the beep. I started this project using Claude Code Cloud via my iPhone, with Opus 5.5 running in Extra thinking effort mode. Here's that shared starter session , which began with this prompt against a newly created empty GitHub repository: That got me this problem.md file . As part of writing that up Claude found and read the BeepBeep paper, which is described in that file. The research looked good, so I told it: That got me to this point - most of the system was built, but nothing had actually tried running it yet. I cloned the new repository to my laptop and fired up Claude Code... and then Fable 5.2 was released , and this project seemed like an excellent opportunity to put that through its paces. I had Claude Code on my laptop start the server running, then made sure it could both see what was happening and make live changes to the software as it ran. This was already baked into the software: Opus 5.5 had built an installModule() method on the listeners that could be triggered over the WebSocket connection, meaning the admin server could execute arbitrary new code on any of its clients. On some devices, web pages that listen on the microphone request user permission any time the page reloads. The hot-swap module mechanism meant that we could deploy new code without having to manually interact with each of the listening devices in turn. From that point on my involvement was mainly to sit by the laptop chatting with Fable 5.2 about what was going on, and occasionally requesting new features. Here are some of the feature prompts I ran: This gave me the ability to drag listeners around the map. That added the thing where any time I clapped it would show on the map as a different symbol from the beeps. That made it easier to spot which symbol likely reflected which real-world sound. Now I could replay sounds, making it much easier to identify which recorded clip was the mysterious beep I was looking for. At this point I was getting close - I had a solid idea of where the beep was coming from, but wouldn't it be neat if I could reposition the listeners around that point to get an even finer location? And since I had one spare device, I then said: I think the most interesting part of this project is that I demonstrated it's possible to give Claude Code ears . Claude doesn't have native audio input (yet), but it can run JavaScript and Python code that can analyze audio captured by a microphone. I told it to run a web server with WebSocket connections to multiple listening devices, then had it both run a WebAudio microphone on those devices and hook them up so they could be sent fresh JavaScript code to execute via that WebSocket. Then I could pretty much leave Claude alone, hacking away at the problem, querying the audio logs, and reconfiguring its ears to help it solve the problem. I'm reminded of a similar hack I heard about at GitHub Universe a few weeks ago, where Martin Woodward told me he had been debugging the GitHub Universe Badge computers by plugging them into a computer via USB-C and then pointing a webcam at their screen, so his coding agent could tell if updates were working correctly or not. Figuring out ways to let coding agents perceive the world around them is a whole lot of fun. You are only seeing the long-form articles from my blog. Subscribe to /atom/everything/ to get all of my posts, or take a look at my other subscription options .

0 views
Sean Goedecke 2 weeks ago

LLMs are not superhuman at reading and writing neural network weights

A recent paper argues that frontier LLMs can work with neural network weights directly. This seems superhuman, but it isn’t. The paper shows that GPT-6 Astra can take a small neural network and interact with its weights directly, “well past what we’d expect from humans or conventional algorithms”. Specifically, Astra was able to identify what games a small network 1 was trained to play just by looking at the weights, and even tweak the weights itself. The most impressive result is Astra significantly improving a 0.8B Qwen LLM’s ability on mathematics by natively editing its weights. The reason to be excited here is that “superhuman ability to improve language models” is precisely the kind of thing that could cause recursive self-improvement. I think a smart human ML researcher could perform all of these tasks . Figuring out what game a model was trained to play based on the network sounds impressive until you consider three points: Here’s that calculation expressed as a heatmap in three lines of Python: And here’s the heatmap for each game: If someone showed you that heatmap without the game labels, I think you’d be able to immediately identify at least the first three games purely by noticing where the player is (e.g. for Breakout, in a horizontal line at the bottom) and where the moving objects are (e.g. for Pac-Man, in the distinctive Pac-Man maze). It’s neat 3 that Astra was able to calculate the norms in its head without executing Python, but not that impressive, and certainly not something that should shock anyone who’s been paying attention. I’m not going to go through each example 4 in the paper, so let’s skip straight to the most impressive one: fixing a 0.8B Qwen model’s ability to do mathematics. 0.8B is a lot of parameters, and “mathematics” is way more complicated than “guess what the game is based on how the player moves”, and editing weights is arguably harder than parsing them. What happened here? First, note that the Qwen model was not “bad at mathematics” in a pure capabilities sense. It had a specific problem where after 32k tokens it would get stuck in loops, so any mathematical task that needed more than 32k tokens would automatically fail 5 . If you had a model that looped like this, how would you update the weights to fix it? Personally, I would try steering : I would write some reasoning texts that looped and some reasoning texts that didn’t, calculate the difference between the looping and non-looping residuals, measure how much each weight contributed to that difference, then try manually trimming those top weights. This is basically the Heretic abliteration playbook. And this is exactly what Astra did! It wrote four pairs of texts, measured 6 the weights that contributed to looping, started cutting them down and testing if it worked, and ended up finding a patch that stopped the Qwen model from looping, thus making it able to work on mathematical problems for more than 32k tokens. Again, this is exactly what a competent human researcher could have and would have done. It’s cool that Astra was able to make direct weight updates. But we shouldn’t think of this like a radically new capability that will change how AI research is done. We should think of this as analogous to the ability of LLMs to emit machine code and tweak compiled binaries: it’s an impressive trick, but the best way to work with binaries is still to write source code and compile it. Likewise, the best way to update the weights of a model is to train it normally. To the extent that intelligent LLMs help with AI research, they will help by improving training , not by magically tweaking model weights directly. Around 17k weights. By taking the L2 norm of each input across the 32 weights in the first layer. Note that this is superhuman mental mathematics, not superhuman AI research. The most impressive one I’m skipping is hand-writing a neural network from scratch. While cool, if you can express a task as a simple program, we already know it’s possible to express that program as a NN , even by unaugmented humans . All the <32k token problems were solved successfully on the original Qwen model. Unlike with the toy game networks, it had access to Python. The input channels of the model directly listen to each 8x8 grid cell The input channels are labeled (e.g. “agent”, “moving objects”) It’s thus relatively trivial to calculate 2 which parts of the grid the first layer of weights cares about and why Around 17k weights. ↩ By taking the L2 norm of each input across the 32 weights in the first layer. ↩ Note that this is superhuman mental mathematics, not superhuman AI research. ↩ The most impressive one I’m skipping is hand-writing a neural network from scratch. While cool, if you can express a task as a simple program, we already know it’s possible to express that program as a NN , even by unaugmented humans . ↩ All the <32k token problems were solved successfully on the original Qwen model. ↩ Unlike with the toy game networks, it had access to Python. ↩

0 views
neilzone 2 weeks ago

Fixing the unavailability of Tasmota devices after HomeAssistant restarts

Earlier this year, I moved from running HomeAssistant in Python venvs to HomeAssistantOS . After an initial challenge with proxying , it has been working fine. I still don’t like using HAOS, but I can live with it. It seems to need updating a lot , and there is no - at least, not that I have found - automated way of doing this. So I am using an automation based on this template to automate updates . This works fine, but I have noticed that my Tasmota devices - of which I have quite a lot - are unavailable after HomeAssistant Core restarts. There are a lot of search results about this, so I am not the only one with this problem. I looked into a couple of the options ( to 0, and to 0), but I already had these set. Reloading the Tasmota integration did not do anything either. What seems to have worked, though, is an automation which tells all the Tasmota devices to restart, once HomeAssistant restarts . Mine looks like this: This seems - a bit more testing needed - to preserve the state of the device, so if it is off when it restarts, it remains off, and vice versa. I imagine that, because the Tasmota devices are restarting, if HomeAssistant tried to send a command to one or more devices during this restart window, the command would fail. Probably not an issue for me, but perhaps something to bear in mind.

0 views
spf13 2 weeks ago

Game Boy Color on My Conference Badge

After finishing the NES emulator , every NES game I tried played fine. I even beat the first few dungeons in Zelda on the badge. This all got me thinking that while I wanted to play Zelda on this, its form factor really looked a lot like a Game Boy. A lot more like a Game Boy than an NES. And there’s Zelda and Pokémon games on the Game Boy. I wonder how hard this will be as I don’t know really anything about Game Boy hardware. Turns out it was quite hard. So I teamed up with Gemini again to see if the same Badger board and RP2350 could run Game Boy and Game Boy Color. We had the same MicroPython Viper emitter and the same 8 MB of QSPI PSRAM, just a very different puzzle on the CPU and cartridge side. You don’t need an emulator background for this; I’ll explain each term as it comes up. I thought the SM83 would be simpler. It was not. On the NES, the CPU is a Ricoh 2A03, a trimmed MOS 6502 with three 8-bit registers ( , , ), one stack pointer, and 56 instructions. The whole core fit in local variables inside one loop over a fixed, unbanked memory map. The Game Boy has the Sharp SM83 ( ), an 8080/Z80 hybrid with eight 8-bit registers ( , paired as ), a stack pointer, a program counter, and 512 instructions: 256 base opcodes plus 256 behind the prefix, nine times the 6502’s count. While the CPU is more complicated, the display is simpler: 2.67× fewer pixels, 1.7× fewer scanlines. To get this to work within the constraints of MicroPython I had to implement five additional Viper tricks the original NES build didn’t have. On the NES that approach worked. The 6502 has three registers — , , — so , , , and a few pointers still fit in Viper’s four fast locals ( – ). Its 56 opcodes started as a 55-deep chain that collapsed into a five-level binary search to halve dispatch cost. One Viper loop, fixed memory map, compiled clean. The SM83 doesn’t fit. Eight registers ( , , , , , , , ) plus , , and cycle counters overflow those four locals — the Cortex-M33’s other registers are reserved for stack, exception frame, and runtime. That’s : the register file won’t fit in locals. The decoder doesn’t scale either. A tree that worked well for 56 opcodes needs ~500 branches for 512 (256 base + 256 -prefixed). What made the NES fast won’t even build for the Game Boy. That leaves two problems: where to keep eight registers if not in locals, and how to decode 512 instructions without 512 branches? Reading each opcode as three small numbers instead of one collapses 512 instructions into a handful of blocks. For it to index registers directly, the 8-bit register file had to move out of Viper locals and into flat memory: eight bytes at inside one ( ): Index is the exception: on the SM83, in the bitfield means indirect memory through instead of a register, so the real registers sit at . The Z80/SM83 designers worked on paper in octal . Read any opcode byte in base 8 and it splits into three octal digits ( , , ), which are the instruction set’s bitfields: All 64 instructions ( ) share , so they collapse into five lines of Viper: That single check covers sixty-four opcodes, with and picking the destination and source registers. When , those same bitfields map to all eight ALU ops on from ( , , , , , , , ), handling another sixty-four arithmetic instructions in one block. The 256 bit ops split the same way: is , is , is , and shifts, rotates, or swaps on . Fifty lines of bit math replaced hundreds of branches. On the NES I could cheat. RAM, PPU, APU, PRG-ROM, everything sits where it was wired, so a read is just an address check and you’re done. The Game Boy doesn’t do this. The CPU still sees 64 KB, but the cart is constantly swapping what lives behind that window: My first version checked the address on every access, if it’s in this range do this, else if it’s in that range do that: That’s readable, and it matches how the memory map is drawn in every doc. But the Game Boy runs at 4.19 MHz — double that in GBC double-speed, so that check runs millions of times a second. Again, running into the constraints of this limited hardware. Every is a branch the Cortex-M33 has to predict, and a miss stalls the pipeline. The trick is that every Game Boy address is 16 bits — four hex digits like . In binary that’s , where the left four bits (15–12) are the top nibble and the right twelve bits (11–0) are the position inside a 4 KB page. A page is 4 KB = 4,096 = 2¹² bytes, so shifting right by 12 ( ) drops the low twelve and leaves just that top nibble: 0 to 15. Sixteen values, sixteen pages, exactly covering 64 KB. Masking the other way ( ) keeps the low twelve as the offset 0–4,095 inside the page. → (page 13) + (offset 291). That top nibble already tells me which bank to use, no needed. I keep a 16-entry page table in (slots 32–47 of the ) with precalculated offsets into , indexed directly by that nibble: Switching banks is one store, no copy: And a read is four lines with no branches: Lookup, mask, add, load. Banking stopped showing up in profiles after that. NES cartridges in our library were 40 KB to 256 KB, small enough to read into RAM in one shot at boot. Game Boy Color cartridges are much larger: Link’s Awakening DX is 1 MB (64 banks of 16 KB) and Pokémon Crystal is 2 MB (128 banks). Reading 2 MB off QSPI Flash at launch freezes the badge for several seconds. When we pushed the RP2350 to to get extra frame headroom, the badge hard-locked on bank switches. USB serial died with it; only a power cycle brought MonaOS back. The bottleneck was the shared QMI bus: The RP2350 is rated at 150 MHz, and this badge’s firmware runs at 230 MHz (a 53 percent overclock). Per the badge hardware schematic and Pimoroni’s board config , the 16 MB Winbond Flash and 8 MB AP Memory PSRAM ( on ) share and with ( ). At 230 MHz, QSPI runs at: $$\frac{230\text{ MHz}}{2} = 115\text{ MHz}$$ Both memory chips are rated for 133 MHz max ( notes as the “Absolute maximum before a drop in PSRAM freq” ), so 115 MHz gives comfortable timing margin. At 300 MHz, QSPI hit 150 MHz — past the 133 MHz spec on both parts. The Cortex-M33 core survived, but burst-copying 16 KB banks from Flash ( ) into PSRAM ( ) over the shared QMI bus locked the hardware. Because the badge has 8 MB of PSRAM on the MicroPython heap ( reports bytes free), we didn’t need to evict banks or overclock the bus: That eliminated both the multi-second boot stall and mid-game Flash thrashing. The Game Boy LCD is 160×144 and the badge screen is 320×240. Not enough to double the size, but it can do 1.5× (240×216, repeating every other scanline ), which seemed like it was a nice compromise. On the screen it’s ok. It results in doubling up the width of some things and keeping others normal thickness. It has the advantage of taking up the entire height of the screen, but with the visual compromise of not actually what the game should look like. I kept in the scaler but made the default the native 1:1 : 160×144 centered on 320×240, one LCD pixel per badge pixel and just have a larger gutter around it. At 1:1 the pixel art replicates the original intent of the artists, but you might need glasses to actually read it. Reminds me of the old Game Boy screen magnifier which was just a magnifying glass that mounted to the Game Boy screen. Maybe someone can make one for the badge :) The Joyplus Handy Boy with its magnifier and stereo speakers. Photo: Thomas Bresson , CC BY 3.0 Centering a 160×144 viewport leaves 80 px gutters on the sides and 48 px on the top and bottom. Empty space beside a running game reads as a mistake, and a real Game Boy has plastic around its screen anyway, so I drew a bezel in twilight slate with gold pinstriping and cream lettering along the bottom (switching to for monochrome cartridges). The left gutter holds a small HUD for battery, frame rate, and a live capacitive D-pad and button visualizer; the right gutter shows and save-state indicators. The underlying hardware had a very long run — the original monochrome Game Boy launched in Japan on April 21, 1989 and the Color revision that doubled the SM83 to 8.4 MHz didn’t arrive until October 21, 1998, nine years later on the same 160×144 PPU. Nintendo kept the combined GB/GBC family in production until March 2003. By that tail end there were no untried registers left, so late-era GBC games lean on every trick the hardware allows, from mid-frame window layers to animated fonts streamed out of ROM. In Oracle of Ages , walking up to an NPC brought up the bottom dialogue box, and the overworld sprites bled right through it, drawing over the text. To draw a bottom dialogue box ( ), the game turns on the Window layer ( bit 5) via at scanline 80 and clears it again at VBlank. My first renderer only checked a single frame-level after scanline 143 had finished, judging all 144 scanlines by whatever state the registers held at the end of the frame. Movable rocks on scanlines acted as if the Window covered them, while sprites on drew over the text because VBlank had already cleared bit 5. Latching , , , , and into and on every scanline — and tracking the active Window line counter in during rendering — gives the renderer what the PPU actually saw on that line: Link’s Awakening DX had a weirder glitch: Link’s two-tile walk animation tore inside-out for a single frame on every step, but only when walking down, never left or right. Walking left or right keeps Link’s two 8×16 sprites in place. Walking down swaps their VRAM tiles ( / ) and toggles ( ) on both OAM entries ( / ) every 8 frames. Because Link’s Awakening DX runs in GBC double-speed mode ( bit 7), the CPU gets 228 M-cycles/scanline , not 114. Budgeting 114 starved the scanline midway between the VRAM tile write and the OAM flip, leaving Link half-turned for a frame: Giving double-speed mode its full 228-cycle scanline budget fixed the tear. When I booted Pokémon Crystal , Professor Oak’s intro and every menu border came up as empty rectangles. I did not know the hardware allowed what the game was doing here. To decompress 1bpp font and border tiles into 2bpp WRAM, Pokémon Crystal calls ( ), which points SP into banked ROM ( ) , loops to pull two bytes every 3 M-cycles, streams the result over HBlank HDMA ( ), and stops the transfer with on ( ). I had assumed always lived in RAM and was an ordinary bit op, which broke both steps. Routing through the ROM window when and treating bit-7 clears on as an HDMA cancel (not a 128-tile GP-DMA ) brought Oak and the borders back. Paired with a background renderer that skips empty tiles, render time in our serial timings sits around 1.5 to 2.8 ms per frame. From what we measured on the badge, CPU execution stays under 12 ms and rendering under 3 ms, keeping the loop inside the 16.6 ms budget for 60 Hz gameplay. Saving has to work too because it’s a conference badge. The code is open source at github.com/spf13/universe-2026-badge-hacks . To put it on a badge: Connect the badge over USB, open USB Disk in MonaOS, and mount the drive. Clone the repo and copy the app over: Copy your own legally dumped / files into (no copyrighted ROMs are distributed): Safely eject the drive, open the GBC launcher, flip your badge upside-down, and play. Building the Game Boy Color emulator ended up making the NES emulator faster too. Once those five Viper tricks worked on the SM83, I ported them back to : pointer-based CHR bank switching ( / into instead of copying 8,192 bytes into Python on every switch), keeping all 262 scanlines inside one Viper call instead of breaking out on , dirty-flagged Viper palette updates ( ), precomputed nametable row pointers with unrolled 8-pixel writes in , and tighter operand and wait-loop fast paths. Now I have a Game Boy Color hanging from my neck, running Link’s Awakening DX and Pokémon Crystal at 1:1. If you’re at Universe in San Francisco, come say hi. : 16 KB fixed ROM Bank 0 : 16 KB switchable ROM Bank (up to 125/128/512 banks under / / ) : 8 KB External SRAM (4 banks) : 4 KB fixed Work RAM Bank 0 : 4 KB switchable WRAM (Banks 1–7 via at ) : Echo RAM (mirror of ) Stay at the badge’s stock 230 MHz so the QMI bus stays at 115 MHz. Allocate the full cartridge arena once in PSRAM ( ) with , falling back to the 20-slot ring buffer only if triggers. Preload only Bank 0 and Bank 1 at launch so games boot immediately, then fault in each 16 KB bank on first visit ( ) and keep it pinned in PSRAM for the rest of the session. Holding or for 650 ms ( in , alongside a 60-second timer when no buttons are pressed) snapshots state and opens the pause menu for frame skip, scanline filters, scaling, and exit. Touching the rear capacitive HOME pad fires , calling to write the 84 KB arena and register state to flash before returning to MonaOS. Connect the badge over USB, open USB Disk in MonaOS, and mount the drive. Clone the repo and copy the app over: Copy your own legally dumped / files into (no copyrighted ROMs are distributed): ( Link’s Awakening DX ) ( Pokémon Crystal ) ( Dragon Warrior I & II ) ( Tetris DX ) ( Oracle of Ages ) ( Super Mario Land ) ( The Final Fantasy Legend ) Safely eject the drive, open the GBC launcher, flip your badge upside-down, and play.

0 views
Farid Zakaria 3 weeks ago

Dafuq is a deterministic VM?

The life of a system call inside Rewind VM. Since I started writing about Rewind VM , the question I get most from friends is not “does it work?” but “how does it actually work?” 🤔 D’uh! It is a virtual machine that only gets interrupted when it asks to be . That seems to not have helped much, so let’s go deeper. We will follow a tiny C program through the machine and, at each step, look at where non-determinism would have crept in and what Rewind does about it. Aside: If you have not seen Rewind before, start with a flaky build you only catch once . CPUs must be deterministic. If they were not, we would have a very bad time trusting them to do anything. Give a CPU the same registers, the same memory and the same instructions, and it computes the same result. What does change? Why are machines not deterministic? They are not closed systems. They interact with the outside world and that interaction is not deterministic. A timer interrupt can land at any instruction or a disk read can complete at any time. Aside: Computers can’t actually make random numbers. A deterministic machine can only fake it with pseudo -randomness: run the same algorithm from the same seed and you get the same numbers back. The real stuff has to come from the physical world. My favorite example is how Cloudflare keeps a wall of 100 lava lamps in its San Francisco office with a camera pointed at it, feeding its encryption keys. If we could capture all external influences, we could replay the external world and get the same run again. That is what Rewind does. Every source from the outside world is either removed or replaced with a value derived from a stored seed. Time, for instance, is a clock managed by Rewind. Interrupts arrive only at points we choose. ⏱️ One more outside influence is easy to miss: other CPUs. On two cores, which thread wins a race comes down to cache misses and pipeline stalls, so Rewind provides a single virtual CPU and the threads take turns on it. To control the outside world, Rewind needs moments where the software stops and Rewind can step in. At those moments it writes down what just happened, hands over the current time, or delivers an interrupt. So how do you stop the software at the same place on every run? One answer is to make the hardware do it. CPUs have performance counters that can interrupt after a set number of instructions. Unfortunately, the interrupt may arrive a few instructions late, and the amount varies. 1 Rewind uses a cooperative approach: let the software tell us when something happens! Rewind runs the guest under KVM, the hypervisor built into Linux. The guest’s code runs directly on the real CPU until it touches a device. The CPU then stops the guest and hands control to the program running the VM, Rewind’s monitor ( ). That hand-off is a VM exit . Rewind patches the guest kernel so that whenever it needs something only the outside world has, such as the time, a timer, or “I have nothing to do”, it makes an exit and asks the monitor. Reporting what happened, like a process starting or a line of output, is an exit too. Each exit the guest makes is called a step , and they are numbered starting from boot. If we assume the guest is deterministic up to step N , step N happens at the same instruction on every run. The monitor’s loop, sketched in Python: normal VM a different instruction each run run 1 timer run 2 timer Rewind step N, every run run 1 (recording) step N run 2 (replay) step N an exit the guest made: one step the monitor's interrupt each line is the guest's instructions, left to right This is true on the first run too. Nothing gets recorded, and a replay just runs the same inputs again. Three pieces make this work, and your program doesn’t need to know about any of them. A patched Linux kernel. The guest kernel is the piece that cooperates. A small patch teaches it to take its clock, its timer and its idle loop from the monitor instead of from hardware, and to report what processes do: exec, exit, output, files written. The monitor also hides the CPU features that would leak the outside world in, such as the hardware cycle counter and the random number instruction, so the kernel never uses them. rewind-init. The special PID 1 is a small program that mounts the input image (a Nix closure or a root filesystem), runs the command, reports its exit status and powers the machine off. The image is mapped straight into guest memory, so reading a file is reading memory, and there is no disk to finish a read at a random moment. rewind-vmm. The monitor owns time, decides when interrupts go in, and keeps the trace of everything the kernel reports. Inputs Nix closure or rootfs → erofs Guest VM · 1 vCPU on stock KVM Code runs natively on the real CPU Build / test processes nix build, make check rewind-init PID 1, mounts erofs Patched Linux + Rewind platform Clock, timer, idle and events go through the host VM exit = one step Interrupt only at an exit Host: rewind-vmm Owns time, ordering and memory Virtual clock exits + branch count Event trace processes, files, output Keyframes dedup page store Seeded randomness Same inputs + seed → same run The life of a system call Here is the program. It reads the clock, draws a random number, prints both with the address of a stack variable, sleeps for a second, then reads the clock again. On my laptop every run prints something new. In Rewind, every run prints the same thing, down to the nanosecond, until you change the seed: Same inputs, same run id, same 432 steps. Oh, and the program slept for a second, yet the whole VM finished in 0.39 seconds. 🤓 Normally, reading the time never enters the kernel: a bit of code in every process reads a hardware counter directly. Rewind hides that counter, so the read goes to the kernel, and the kernel asks the monitor. guest host hello user space guest kernel Rewind platform KVM host kernel rewind-vmm host process syscall no hardware counter read the clock an I/O port VM exit made by the guest count a step clock += 5 µs + work leave the time in memory timer due? interrupt run the guest again resume the guest return the time …400.001006990 Rewind hides the CPU’s random number instruction, so the only thing available to the guest kernel is the seed Rewind passes at boot. The kernel’s random number generator is seeded with that value, so every run of the same program with the same seed gets the same random numbers. Most system calls never leave the guest. The few that need the outside world make an exit, and the monitor writes down what happened. The guest kernel also reports when it is idle, so the monitor can jump its clock to the next timer interrupt. 2 Control those few doors and the guest is deterministic: the outside world shows up at the same step on every run. So, dafuq is a deterministic VM? Like I said at the start, it’s a VM that only gets interrupted when it asks to be. Hopefully that makes a bit more sense now. 😅 Intel’s counter is good enough that you can single-step the rest of the way to the exact instruction. I have an AMD laptop. 🙃  ↩ costs no real time. The monitor jumps its clock straight to the deadline and delivers the timer interrupt.  ↩ lock both reach the lock at once the winner depends on the cache Rewind: one vCPU vCPU A B A exits threads switch only at an exit the same order every run A step is a VM exit To control the outside world, Rewind needs moments where the software stops and Rewind can step in. At those moments it writes down what just happened, hands over the current time, or delivers an interrupt. So how do you stop the software at the same place on every run? One answer is to make the hardware do it. CPUs have performance counters that can interrupt after a set number of instructions. Unfortunately, the interrupt may arrive a few instructions late, and the amount varies. 1 Rewind uses a cooperative approach: let the software tell us when something happens! Rewind runs the guest under KVM, the hypervisor built into Linux. The guest’s code runs directly on the real CPU until it touches a device. The CPU then stops the guest and hands control to the program running the VM, Rewind’s monitor ( ). That hand-off is a VM exit . Rewind patches the guest kernel so that whenever it needs something only the outside world has, such as the time, a timer, or “I have nothing to do”, it makes an exit and asks the monitor. Reporting what happened, like a process starting or a line of output, is an exit too. Each exit the guest makes is called a step , and they are numbered starting from boot. If we assume the guest is deterministic up to step N , step N happens at the same instruction on every run. The monitor’s loop, sketched in Python: normal VM a different instruction each run run 1 timer run 2 timer Rewind step N, every run run 1 (recording) step N run 2 (replay) step N an exit the guest made: one step the monitor's interrupt each line is the guest's instructions, left to right This is true on the first run too. Nothing gets recorded, and a replay just runs the same inputs again. Three pieces make this work, and your program doesn’t need to know about any of them. A patched Linux kernel. The guest kernel is the piece that cooperates. A small patch teaches it to take its clock, its timer and its idle loop from the monitor instead of from hardware, and to report what processes do: exec, exit, output, files written. The monitor also hides the CPU features that would leak the outside world in, such as the hardware cycle counter and the random number instruction, so the kernel never uses them. rewind-init. The special PID 1 is a small program that mounts the input image (a Nix closure or a root filesystem), runs the command, reports its exit status and powers the machine off. The image is mapped straight into guest memory, so reading a file is reading memory, and there is no disk to finish a read at a random moment. rewind-vmm. The monitor owns time, decides when interrupts go in, and keeps the trace of everything the kernel reports. Inputs Nix closure or rootfs → erofs Guest VM · 1 vCPU on stock KVM Code runs natively on the real CPU Build / test processes nix build, make check rewind-init PID 1, mounts erofs Patched Linux + Rewind platform Clock, timer, idle and events go through the host VM exit = one step Interrupt only at an exit Host: rewind-vmm Owns time, ordering and memory Virtual clock exits + branch count Event trace processes, files, output Keyframes dedup page store Seeded randomness Same inputs + seed → same run The life of a system call Here is the program. It reads the clock, draws a random number, prints both with the address of a stack variable, sleeps for a second, then reads the clock again. On my laptop every run prints something new. In Rewind, every run prints the same thing, down to the nanosecond, until you change the seed: Same inputs, same run id, same 432 steps. Oh, and the program slept for a second, yet the whole VM finished in 0.39 seconds. 🤓 Normally, reading the time never enters the kernel: a bit of code in every process reads a hardware counter directly. Rewind hides that counter, so the read goes to the kernel, and the kernel asks the monitor. guest host hello user space guest kernel Rewind platform KVM host kernel rewind-vmm host process syscall no hardware counter read the clock an I/O port VM exit made by the guest count a step clock += 5 µs + work leave the time in memory timer due? interrupt run the guest again resume the guest return the time …400.001006990 Rewind hides the CPU’s random number instruction, so the only thing available to the guest kernel is the seed Rewind passes at boot. The kernel’s random number generator is seeded with that value, so every run of the same program with the same seed gets the same random numbers. Most system calls never leave the guest. The few that need the outside world make an exit, and the monitor writes down what happened. The guest kernel also reports when it is idle, so the monitor can jump its clock to the next timer interrupt. 2 Control those few doors and the guest is deterministic: the outside world shows up at the same step on every run. So, dafuq is a deterministic VM? Like I said at the start, it’s a VM that only gets interrupted when it asks to be. Hopefully that makes a bit more sense now. 😅 Intel’s counter is good enough that you can single-step the rest of the way to the exact instruction. I have an AMD laptop. 🙃  ↩ costs no real time. The monitor jumps its clock straight to the deadline and delivers the timer interrupt.  ↩

0 views
Ahead of AI 3 weeks ago

Building Reasoning Models from the Ground Up: A Full Video Course

I have written a lot about reasoning models here over the last two years on Ahead of AI, including a recent article on mechanisms to control reasoning effort levels in contemporary LLMs . Reasoning models are still as relevant as ever. In fact, almost all current-generation LLMs today are reasoning models or offer a reasoning mode. For those who are interested in how reasoning models work, including inference scaling, reinforcement learning, and distillation, I wrote my recent Build Reasoning Model (From Scratch), which implements these from the ground up in PyTorch, which, in my experience, is still the best way to understand and learn how things really work. Now, in the last few months, I also sat down and recorded accompanying lectures I wanted to share with you. So, below, you will find eight reasoning model-from-scratch coding videos (11 hours of content). We start with a pre-trained LLM and implement methods to evaluate and improve it in Python and PyTorch. So, if you enjoyed my Coding LLMs from the Ground Up course last year, this is essentially the sequel (but you can also watch it without the prior course as a prerequisite). I’m currently taking a short break and will be back soon with more exciting LLM research roundups next month. In the meantime, I hope you enjoy coding along! As a small side note, and since I often get asked how reasoning models relate to today’s AI agents, here’s a short section on this before getting started with the videos. A reasoning model is essentially an upgrade from a conventional LLM, that is, adding more post-training via reinforcement learning with verifiable rewards (and optionally inference scaling techniques) to make it more capable of solving more challenging problems. Classically, reasoning models are developed for math and code, but the capabilities can generalize to other problem domains as well. A reasoning model then functions as the engine inside an agent harness, where the agent harness is a software or tooling framework around the LLM/reasoning model to tackle even more challenging problems (bigger coding tasks, travel booking, and all other sorts of personal assistant tasks). The task of the harness is sophisticated context management and giving the LLM access to tools. Figure 1: An engine analogy for conventional LLMs, reasoning models, and agent harnesses. Figure from my Components of a Coding Agent article. In this analogy depicted in the figure above, the model is the engine, and the agent harness adds the machinery that lets us use it for various things (as an upgrade from a simple chatbot interface). An agent can use either a conventional LLM or a reasoning model, but reasoning models are the more typical choice as they are more capable. (As mentioned above, most current-gen LLMs are reasoning models with variable reasoning effort settings.) So, the bottom line is that reasoning models, as the “engine,” remain an important part of understanding modern LLM agents. The resources accompanying these topics shown above are: The Build a Large Language Model (From Scratch) book and videos The Build A Reasoning Model (From Scratch) book (and videos below) The Components of a Coding Agent article on Substack The videos below focus on developing the reasoning model that can power such a system. The reasoning-from-scratch videos focus on a small pre-trained Qwen3 model, where we implement the reasoning methods ourselves in Python and PyTorch. Starting with a pre-trained model lets us focus on the interesting part: evaluation, inference-time scaling, reinforcement learning, and distillation. Regarding the prerequisites, I recommend being comfortable with Python and PyTorch. I designed the reasoning materials as standalone content, so the previous Build A Large Language Model (From Scratch) content is recommended but not strictly required. Compute-resource-wise, you can work through the early text-generation and evaluation examples on a CPU. For the later experiments, especially training, a GPU makes the work much more practical. The first video covers the setup and some more recommendations; the repository also includes hardware and environment recommendations . Figure 2: An overview of the topics being covered. These videos accompany my book, Build a Reasoning Model (From Scratch) . If you like to read through the explanation in more detail and at your own pace, work through exercises, and so on, I recommend the book as a companion here. For the most in-depth learning experience, my suggestion is to read a chapter, work through its code alongside the corresponding video, and then try the exercises. The book is available from Manning and Amazon , and the print edition is in color! Figure 3: A random excerpt from the Build a Reasoning Model (From Scratch) print book. Thank you to everyone who has picked up a copy or recommended it to a friend. Your support helps me keep creating these materials. As a last, quick side note before getting to the main videos below: For a shorter, more conceptual overview, I also recommend my AI Reasoning Models course on LinkedIn Learning (it should be free for 24h when accessing it via the link there, which shouldn’t then require a LinkedIn Premium subscription). The course is about 90 minutes and explains how reasoning models work, covering the main ideas behind inference-time scaling, reinforcement learning, and distillation. It’s a good optional preview if you’d like the main ideas without working through the full implementations below. To get to the main part of this article, here are the eight main lecture videos. The first video starts with an explanation of the relationship between conventional LLMs, reasoning models, and agents. Next, the main topic of the video is setting up the coding environment. This includes installing the Python and PyTorch dependencies (with uv), among others. I also discuss hardware choices and common setup issues. Topics covered The relationship between conventional LLMs, reasoning models, and agent harnesses On the benefits of learning through code implementations The scope of this video series Installing Python dependencies Choosing hardware and checking CUDA or Apple Silicon support Using a remote GPU with VS Code and troubleshooting the environment Watch video 1 · Setup instructions Before adding reasoning methods in the upcoming videos, we need a working base model. Instead of training it from scratch, since that would be a whole other book (see Build A Large Language Model (From Scratch) ), we start with a pre-trained model. Here, we load the pre-trained weights of a Qwen3 0.6B model. Then, we implement the text-generation process via a streaming text generator and add KV caching and model compilation to make text generation more efficient. These implementations give us the baseline and base components we will evaluate and improve in the following videos. Topics covered Encoding text as tokens and decoding it back into text Downloading Qwen3 weights and loading the model on the selected compute device Going over tensor shapes, logits, and next-token predictions Implementing greedy decoding and streaming text generation Handling end-of-sequence tokens and measuring generation speed Adding a KV cache to reuse attention keys and values Combining KV caching with and comparing hardware performance Watch video 2 · Chapter 2 code In this lecture, we build a math-answer verifier step by step, from answer extraction to normalization and checking mathematical equivalence. We then use it to evaluate the model on MATH-500. We use this verifier to evaluate the base model’s performance on the MATH-500 evaluation dataset. However, the verifier also has a second job later in the series: providing the reward signal for reinforcement learning with verifiable rewards (RLVR). Topics covered Intro to verifiers and how they fit into LLM evaluation methods (other methods are covered in the book’s appendix) Reusing answer verification as a reward signal for RLVR (more on that in chapter 6) The verifier flow, including extracting final answers, normalizing answers and checking mathematical equivalence Building an answer grader and an evaluation loop for MATH-500 Comparing base and reasoning models on MATH-500 Watch video 3 · Chapter 3 code Now we explore ways to improve answers while keeping the model weights fixed. But before implementing specific inference-scaling techniques, we first implement methods to generate diverse answers from the same prompt (this is standard practice in proprietary LLM chatbots, such as ChatGPT). Concretely, we implement temperature scaling, multinomial sampling, and top-p filtering to generate diverse responses. Then we combine multiple responses through self-consistency, using majority voting over their final answers. We also examine the tradeoff between answer accuracy and the extra computation needed to generate more candidates. Topics covered Comparing how additional compute benefits model performance during training and during inference A gentle intro to inference-scaling through chain-of-thought prompts Implementing temperature scaling and multinomial sampling to generate diverse answers Adding top-p filtering to control the quality of the diverse answers Combining candidate answers through self-consistency, one of the most popular inference scaling techniques Evaluating MATH-500 accuracy against the cost of additional inference compute Watch video 4 · Chapter 4 code Building on the previous video, we implement scoring functions to compare multiple answers generated from the same prompt. We can also use these scoring methods to break ties in self-consistency (covered in the previous lecture). The scoring methods covered here include computing token and sequence log probabilities (this will also be relevant in the later reinforcement learning chapters). We then implement a self-refinement loop in which the model critiques an answer and attempts a revision. The evaluation lets us check how useful those additional steps are for our model. Topics covered Using scoring functions for comparing multiple answers and breaking ties Implementing a simple heuristic scorer Computing token probabilities and sequence likelihoods (also relevant for the following lectures) Using log probabilities for improved numerical stability Building a self-refinement loop for generating critiques and revised answers Evaluating self-refinement on MATH-500 Watch video 5 · Chapter 5 code In this lecture, we move on to implementing a training technique called Reinforcement Learning with Verifiable Rewards (RLVR). We first implement a simplified version of Group Relative Policy Optimization (GRPO), generate groups of responses, score them with our verifier, and use their relative rewards for the model weight updates during training. Topics covered Generating reasoning traces and understanding the relationship between answer lengths and problem-solving abilities Discussion and comparison of two important LLM post-training methods: Reinforcement Learning with Human Feedback (RLHF) and Reinforcement Learning with Verifiable Rewards (RLVR) Turning verifier scores into rewards and relative advantages Computing sequence log probabilities and a simplified GRPO loss Assembling the training loop with logging and checkpoint saves Evaluating checkpoints and checking training stability and memory needs Watch video 6 · Chapter 6 code Now that we implemented the training loop in the previous lecture, we can revisit it and analyze the training runs in more detail. Concretely, this video adds more training metrics for inspection and analysis, including entropy and advantage statistics, clipped policy ratios, KL loss term values, and formatted rewards. We then review the training logs and evaluation results to understand what these additions do and whether additions such as clipped policy ratios and KL loss terms are helpful. Topics covered Running longer training experiments and interpreting their logs Tracking advantages and entropy to understand training behavior Implementing clipping in the policy loss and analyzing its effects Adding a KL loss term and discussing reward hacking Understanding limitations of the simplified KL formulation Implementing format rewards and conditioning them on answer correctness Comparing checkpoints on MATH-500 and exploring further GRPO research Watch video 7 · Chapter 7 code Finally, we explore another way to train a small reasoning model, that is, learning from answers generated by a stronger (and bigger) teacher model. We discuss different forms of distillation, prepare reasoning data, and implement the supervised training loop. We finish this lecture and course by evaluating the distilled model on MATH-500 and comparing the results. This rounds out the series with an alternative to developing reasoning capabilities through reinforcement learning. Topics covered Comparing the different combination and approaches to distillation, including soft and hard distillation, and on-policy and off-policy distillation Creating and collecting teacher-generated answers for the MATH dataset (using DeepSeek R1) Preparing the distillation dataset, including tokenization and training/validation/test splits Computing answer-token log probabilities and understanding the cross-entropy loss Implementing supervised training and tracking training and validation losses Evaluating checkpoints on MATH-500 and comparing distillation results Watch video 8 · Chapter 8 code As you watch these lectures, I encourage you to pause occasionally and try a small experiment of your own if something interesting comes to mind. For example, feel free to change the sampling settings, inspect a few failed answers, or try variations of different ideas similar to the suggestions in the exercises. And if you would like the full written walkthrough, figures, and exercises alongside the videos, you can find Build a Reasoning Model (From Scratch) at Manning and Amazon . Thanks for reading and supporting Ahead of AI. I am taking a short break to regenerate, and I look forward to being back with the next round of LLM research articles next month. In the meantime, happy viewing and tinkering! Figure 1: An engine analogy for conventional LLMs, reasoning models, and agent harnesses. Figure from my Components of a Coding Agent article. In this analogy depicted in the figure above, the model is the engine, and the agent harness adds the machinery that lets us use it for various things (as an upgrade from a simple chatbot interface). An agent can use either a conventional LLM or a reasoning model, but reasoning models are the more typical choice as they are more capable. (As mentioned above, most current-gen LLMs are reasoning models with variable reasoning effort settings.) So, the bottom line is that reasoning models, as the “engine,” remain an important part of understanding modern LLM agents. The resources accompanying these topics shown above are: The Build a Large Language Model (From Scratch) book and videos The Build A Reasoning Model (From Scratch) book (and videos below) The Components of a Coding Agent article on Substack Figure 2: An overview of the topics being covered. The companion book These videos accompany my book, Build a Reasoning Model (From Scratch) . If you like to read through the explanation in more detail and at your own pace, work through exercises, and so on, I recommend the book as a companion here. For the most in-depth learning experience, my suggestion is to read a chapter, work through its code alongside the corresponding video, and then try the exercises. The book is available from Manning and Amazon , and the print edition is in color! Figure 3: A random excerpt from the Build a Reasoning Model (From Scratch) print book. Thank you to everyone who has picked up a copy or recommended it to a friend. Your support helps me keep creating these materials. The videos As a last, quick side note before getting to the main videos below: For a shorter, more conceptual overview, I also recommend my AI Reasoning Models course on LinkedIn Learning (it should be free for 24h when accessing it via the link there, which shouldn’t then require a LinkedIn Premium subscription). The course is about 90 minutes and explains how reasoning models work, covering the main ideas behind inference-time scaling, reinforcement learning, and distillation. It’s a good optional preview if you’d like the main ideas without working through the full implementations below. To get to the main part of this article, here are the eight main lecture videos. 1. Motivation and code setup The first video starts with an explanation of the relationship between conventional LLMs, reasoning models, and agents. Next, the main topic of the video is setting up the coding environment. This includes installing the Python and PyTorch dependencies (with uv), among others. I also discuss hardware choices and common setup issues. Topics covered The relationship between conventional LLMs, reasoning models, and agent harnesses On the benefits of learning through code implementations The scope of this video series Installing Python dependencies Choosing hardware and checking CUDA or Apple Silicon support Using a remote GPU with VS Code and troubleshooting the environment Encoding text as tokens and decoding it back into text Downloading Qwen3 weights and loading the model on the selected compute device Going over tensor shapes, logits, and next-token predictions Implementing greedy decoding and streaming text generation Handling end-of-sequence tokens and measuring generation speed Adding a KV cache to reuse attention keys and values Combining KV caching with and comparing hardware performance Intro to verifiers and how they fit into LLM evaluation methods (other methods are covered in the book’s appendix) Reusing answer verification as a reward signal for RLVR (more on that in chapter 6) The verifier flow, including extracting final answers, normalizing answers and checking mathematical equivalence Building an answer grader and an evaluation loop for MATH-500 Comparing base and reasoning models on MATH-500 Comparing how additional compute benefits model performance during training and during inference A gentle intro to inference-scaling through chain-of-thought prompts Implementing temperature scaling and multinomial sampling to generate diverse answers Adding top-p filtering to control the quality of the diverse answers Combining candidate answers through self-consistency, one of the most popular inference scaling techniques Evaluating MATH-500 accuracy against the cost of additional inference compute Using scoring functions for comparing multiple answers and breaking ties Implementing a simple heuristic scorer Computing token probabilities and sequence likelihoods (also relevant for the following lectures) Using log probabilities for improved numerical stability Building a self-refinement loop for generating critiques and revised answers Evaluating self-refinement on MATH-500 Generating reasoning traces and understanding the relationship between answer lengths and problem-solving abilities Discussion and comparison of two important LLM post-training methods: Reinforcement Learning with Human Feedback (RLHF) and Reinforcement Learning with Verifiable Rewards (RLVR) Turning verifier scores into rewards and relative advantages Computing sequence log probabilities and a simplified GRPO loss Assembling the training loop with logging and checkpoint saves Evaluating checkpoints and checking training stability and memory needs Running longer training experiments and interpreting their logs Tracking advantages and entropy to understand training behavior Implementing clipping in the policy loss and analyzing its effects Adding a KL loss term and discussing reward hacking Understanding limitations of the simplified KL formulation Implementing format rewards and conditioning them on answer correctness Comparing checkpoints on MATH-500 and exploring further GRPO research Comparing the different combination and approaches to distillation, including soft and hard distillation, and on-policy and off-policy distillation Creating and collecting teacher-generated answers for the MATH dataset (using DeepSeek R1) Preparing the distillation dataset, including tokenization and training/validation/test splits Computing answer-token log probabilities and understanding the cross-entropy loss Implementing supervised training and tracking training and validation losses Evaluating checkpoints on MATH-500 and comparing distillation results

0 views
Giles's blog 3 weeks ago

RMSNorm

Normalisation is an essential part of LLMs. In the GPT-2 code, we use LayerNorm in a bunch of different places -- in each Transformer block, we do it just before we feed our incoming context vectors into the multi-head attention module, and then again before we feed the result through the FFN: ...and we also do one more round just before we project our context vectors into vocab space via the output head. We do that to make the model more trainable; it helps to prevent vanishing or exploding gradients, by constraining the vectors going into our attention, feed-forward and output head modules so that they have a reasonably stable set of statistical properties. And when ( as part of my black-box reimplementation of GPT-2 in JAX ) I tried training an almost-complete model without LayerNorm, training completely failed after about 100 steps -- the loss went up to the kind of level that I'd expect from an uninitialised model, and stayed there despite another 700 or so training steps. (Later on in this post I'll show results from a similar run.) So, normalisation is important. But it doesn't have to be LayerNorm specifically -- if you look at the currently-popular open models, a lot of them use something called RMSNorm instead, and I wanted to look into why that might be. In this post I'll go through the differences between LayerNorm and RMSNorm, and show the results of training a few GPT-2 small style models using each. RMSNorm was introduced in a 2019 paper by Biao Zhang and Rico Sennrich 1 , which is a surprisingly easy read. They note that most people at the time felt that a critical part of LayerNorm -- which they are explicitly comparing their new system to -- is that it does mean normalisation. But they were less sure that it was the important bit, and felt that scale normalisation was its real benefit. Let's dig into what that means. Firstly, a refresher on LayerNorm. Our normalisation layer in the diagram above is being fed with a bunch of context vectors -- one for each token in each sequence in our batch. LayerNorm deals with each of them separately 2 . For each one, it performs two steps: Let's work through that. We'll go through the normalisation first; say you start with a context vector of Its mean is ( 2 + 4 + 6 ) / 3 = 4 . If you subtract that from each element, you get ...which has a mean of ( − 2 + 0 + 2 ) / 3 = 0 . So that sorts out the mean part of it. I'll call this "re-centring" below -- hopefully it's obvious why! To make the variance one, we need to divide each element by the standard deviation (SD) of the whole vector (see my previous LayerNorm post for details as to why). The SD is the square root of the variance, and the variance is calculated by squaring each item's difference from the mean, adding them all together, and then dividing it by the number of elements 3 . Now, there's a neat trick that you can do here. As we have already set our mean to zero in the previous step, each number in our vector is already exactly equal to its difference from the mean. So we can just square them element-wise, and take the average of that, which will give us our variance: Again, SD is the square root of the variance, so here it's 2 2 3 ≈ 1.63 . Dividing our already-recentred numbers by that gives us a normalised context vector of We can sanity-check that the result has a variance of 1 -- remember it's just the average of the elements squared: So, that's the normalisation part of LayerNorm. We've recentred our context vector on its mean, and made it have a variance of one. Now that we've normalised our context vector, we need to scale and shift it. Intuitively that feels a bit like undoing the careful work we've done to fix the mean to zero and the variance to one. But it's worth remembering that what we're trying to do with our normalisation is make the results have stable statistical properties; what the ideal specific properties might be is something that the network should be learning. So the first phase gets everything into a well-known state, then the shift/scale goes from there to the shape that the network learns that it actually needs. Both of these operations are done with trainable vectors of the same size as the context vectors -- that is, the scale vector is d emb long, and so is the shift vector. They're applied element-wise. So let's say our scale vector was After normalisation, our original context vector was So we multiply that element-wise by the scale vector, and we get: ...and that's the scaling done. Similarly, if our shift vector was ...then applying it to the scaled vector would be: ...and with that, we've completed our LayerNorm. But it took quite a lot of calculations; let's list them out: So in total we have, per context vector in our batch: Let's look at RMSNorm next to see how it compares. The idea behind RMSNorm is to try to get away with doing fewer calculations. In particular, we skip working out the mean -- we don't even try to re-centre our context vectors. Instead, we just scale them down to the same length. To do that, we work out an average length for each vector -- specifically, the Root Mean Square (RMS, of course) -- and then divide each number in it by that. That done, we do the same scale trick that we did with LayerNorm, but not the shift -- more about that later. Let's work through that in numbers again; we can start with the same context vector: The mean square of that is, as you might expect, the mean of the squares of all of the numbers in it: The root mean square is the square root of that, which is about 4.32, so we divide through by that: You might intuitively expect the RMS of that resulting vector to be one, and of course it is; the mean square is: ...and again, we square root that to get RMS which is again 1. So you can see that by dividing by the RMS, we're going to re-scale all of our context vectors so that they have a new RMS of one. But their means can be all over the place -- we've not tried to do anything to fix them. That's our abbreviated normalisation; once that's done, just like with LayerNorm, we apply an elementwise scaling operation by a trainable scale vector -- but we don't shift it. Interestingly, in the original paper, they give equations both with and without the shift -- equation (4), in which they first present it, doesn't have a shift, but equation (5), which they call a general form, does. It's not clear to me which one they actually used in their tests, but it's worth noting (and thanks to GPT-6 Astra for digging this up for me) that the code on GitHub posted by one of the authors has an optional that is switched off by default. Anyway, the fashion these days appears to be to use RMSNorm without a shift, and to me that makes intuitive sense; we've normalised the scale of the values in our context vector via the division by the RMS, so "fixing" that to get desirable statistical properties makes sense. But we didn't normalise the means, so the numbers coming out do not have a stable baseline for us to adjust with a shift. We could add one anyway of course, but there's no intuitive need to add a "new mean" back in to replace an old one that was never removed in the first place. It's a bit fuzzy, perhaps, but it makes some kind of sense. So let's stick with the popular version without shift: how many calculations do we save by doing RMSNorm? So that gives us a total of: In terms of differences with LayerNorm we have: So, it's certainly cheaper -- significantly fewer addition/subtraction operations. The question is, is that saving in training time worth it? In the paper, they train various models of various sorts (including an early Transformer model) and come to the conclusion that it is; they got similar, or in some cases better, loss with RMSNorm than with their LayerNorm training runs. And, of course, the fact that it's widely used in current open LLMs suggests the same. Would it work well for my own models? And what kind of performance improvement would I get, if any? It was time to write some code and train some models. The PyTorch code for RMSNorm was pretty trivial: Our incoming batch of context vectors is shaped b × n × d emb , where b is the batch size and n is the sequence length. In the method, just as in the worked example above, we get the square of everything, then work out the mean across that last d emb dimension so that we have per-context-vector means, keeping the dimensions stable with that so that we wind up with a b × n × 1 result rather than a b × n one. We then take the square root to work out the RMS, but we add on a tiny ϵ first so that it will never be zero (which would cause a divide-by-zero in the next step). And finally we divide the incoming numbers by that adjusted RMS, multiply by our trainable scaling vector, and we're done. One thing that is worth noting; to me it would be a bit more natural to add on the ϵ in the division, like this: However, I had the LayerNorm code from the book in front of me as I wrote it, and noticed that it adds on its own ϵ before the square root, like this: ...so I decided to keep it consistent. When I later looked at the docs for PyTorch's built-in RMSNorm class, I saw that it did the same thing as mine, so it seemed to be the "right" way to do it. The two alternatives have very different behaviour when numbers get close to zero, so it was important to be consistent. And having mentioned PyTorch's built-in RMSNorm, let's dig into that a bit. A little while ago, I noticed that by using PyTorch's built-in GELU module rather than the hand-rolled one from the code in Sebastian Raschka 's book " Build a Large Language Model (from Scratch) ", I got a significant speedup when training on my local machine -- from 21,000 tokens/second to 25,000. PyTorch also has its own built-in and modules. Now, while I felt that the book could actually have used the PyTorch GELU, it 100% made sense that it showed you the code for LayerNorm -- after all, "Build a Large Language Model (by Bolting Together Random Bits of PyTorch)" doesn't have the same ring to it. And likewise in this set of experiments I wanted to try running my own RMSNorm. But given that the point of RMSNorm is meant to be speeding up training, it felt like it would be worth seeing how that speedup might compare to using built-in modules rather than hand-rolling our own. After all, the built-in modules can use fused kernels, and that can be a huge advantage. Rather than doing each of the separate steps in the Python code above by dropping down into CUDA, doing the calculations, and then returning to Python to find out what the next step is, the whole thing can be coded in a single CUDA routine that can be run in one go. Even better, that routine can be optimised as a whole -- stuff that's used frequently can be kept in registers, things can be laid out so that the cache is used efficiently, and so on -- whereas with the Python implementation, everything would need to be in the main VRAM at the end of each step. Definitely a win. My guess is that this is a large part of why the built-in GELU is faster, so I expected serious speedups from using PyTorch's normalisation classes. That meant that I wanted my code to be able to switch easily between different kinds of normalisation. As I mentioned at the start of this post, the original GPT-2 code used LayerNorm in three places: The code for the Transformers bit looked like this: ...and the output head bit like this: That code is essentially the same as Raschka's from the book, with a couple of (inactive in this post's experiments) tweaks to support mixture-of-experts models . I wanted a config flag -- in that dictionary -- to control the kind of normalisation we used. It seemed pretty clear that so long as the various classes we wanted to use in place of the existing implementation were compatible with it, we could just swap them in. So I replaced the existing lines that created with: ...and defined like this: That gave us the option for the original "hand-rolled" LayerNorm from Raschka, my own RMSNorm implementation, their respective PyTorch implementations, and a no-normalisation option that I felt would be worth running a test against. The explicit setting of for the PyTorch implementations made sure that they would be as similar as possible 4 . I set for the PyTorch out of an abundance of caution -- it's the default value anyway. One thing I was initially concerned with, but which turned out to be a non-issue, was weight initialisation. In many of my tests I've found that the models I've been training can perform significantly better or worse just based on the random weights they get prior to training. If you change which modules make up your model -- say by swapping out a LayerNorm for an RMSNorm -- then if those modules consume different amounts of randomness when they're being created, all subsequently-created modules will get different random number results when their weights are initialised and the results of your tests will be polluted by that. However, on looking at the code again, I realised that there was nothing to worry about here. Raschka's LayerNorm and my own RMSNorm do not use any randomness, because their trainable parameters are set to ones and zeros -- and the PyTorch implementations do the same. I was actually a little sad about that because it meant that I couldn't use a bit of code I was rather proud of, but it did simplify things. 5 That all seemed to work -- I did short test training runs with each of the settings locally to confirm that loss dropped. It was time to test things out. I was, as usual, going to train models from scratch that were based on GPT-2 small, with two differences: These models come out at roughly 163M parameters, which is very small, but was hopefully large enough to show interesting results. For the training runs, I would: Training models is expensive -- for others I've been doing with models of this scale, it takes about 2 days to train them locally on my RTX 3090, or costs about US$40 if I use DDP to train them on an 8x A100 machine with 40 GiB/GPU (which takes about 2h30m). So I didn't want to train tons of them, and decided that a sensible minimum set would be: I also wanted to do a quick test with no normalisation just to confirm that training failed. I did these all on Lambda -- there were some issues with instance availability, but once again proved its usefulness. I was able to start three instances and spread the training runs across them. All tests were run with the usual set of commands to make sure that the library versions and so on were the same: ...with set to each of the training run configurations I'd created: Each configuration was identical apart from the , plus a small extra difference for the no-norm test, which (conveniently enough) we'll look at now. Let's look at the no-normalisation test first. From previous experience, I suspected that it was likely to go bad fast, so I set it to checkpoint and log training loss every 10 global steps instead of every 617. And, indeed, by step 530 it started logging a consistent loss of on every training step, so I force-quit it at step 640. The training loss looked like this: You can see that loss started rising at step 500, and then after that it didn't even try to log it. Gradients also zoomed off the top of the chart: So, that was reassuring! As expected, training a Transformer-based LLM without any kind of normalisation doesn't work well. The other training runs were much less eventful -- they all completed normally, and I downloaded the models, and ran my normal held-back test set through them to get a comparable quality metric. Here's what I got: The links go to the models themselves on Hugging Face. These are really interesting! Let's look at training speed first. What we're meant to be looking into here is the performance characteristics of RMSNorm versus LayerNorm, so let's compare like vs like. The hand-rolled RMSNorm was indeed a bit faster to train than the hand-rolled LayerNorm, but only about 2.5% faster, both in terms of training time and tokens per second. For the runs using the built-in PyTorch modules it was an even closer-run thing -- only 0.5% improvement for RMSNorm. Without doing tons of extra training runs I can't say safely what the noise level is for this kind of thing, but my gut feeling (based on having trained more than 60 of these models now) is that the 2.5% difference is probably real, while the 0.5% one could well just be noise. In particular, it's worth noting that both of the "hand-rolled" training runs happened on the same instance (by chance), though the PyTorch ones were on different ones, which makes the 2.5% number more trustworthy. But on to the elephant in the room: the difference between the fused PyTorch implementations and the hand-rolled ones is much bigger. With LayerNorm, it took 11% less time to run. The speedup for RMSNorm was a little smaller, at just less than 10%. That is definitely not noise, and completely eclipses the speedup from switching the kind of normalisation! 6 Now let's take a look at the quality of our models. Again, we'll start with the like vs like comparison. Hand-rolled RMSNorm got a test loss that was 3.601292 − 3.595336 = 0.005956 worse than the hand-rolled LayerNorm. That's a tiny difference. Similarly, the PyTorch RMSNorm got 3.572383 − 3.571158 = 0.001225 worse loss than the PyTorch LayerNorm. I'm tempted to say that those numbers were within the noise. However, I don't have any numbers to back that up -- when I looked into noise previously I did measurements for variations in weight initialisation, and for runs with the same initial weights but different random seeds for the post-model-initialisation steps, but those runs used dropout, which the ones in this experiment did not. In theory, my training loop should be entirely deterministic; no randomness is used after the initial weight initialisation. A while back I did two training runs on 8x A100 machines with the same config, months apart, and the Safetensors files were identical bit-for-bit. But what we did here was start with a specific set of initial weights, and then see what happened when we trained them with different normalisation settings. It's certainly conceivable that some initial weights might be "in a better place" for training with LayerNorm while others were in a better place for RMSNorm. So while the fact that both were a little bit worse with RMSNorm is interesting, I'd really need to train a bunch of different models to get any certainty here. Best to chalk it up to noise for now. Now, back to that elephant... Once again, the big difference here is not between LayerNorm and RMSNorm, but between hand-rolled and built-in PyTorch implementations. For LayerNorm, the PyTorch version got 3.595336 − 3.571158 = 0.024178 lower -- better! -- loss than the hand-rolled one. And for RMSNorm, the difference was 3.601292 − 3.572383 = 0.028909 . Those are not super-small differences. Based on the various interventions I tested against the GPT-2 code, that's larger than the improvements I got from switching to full-fat 32-bit rather than using Automatic Mixed Precision (AMP -- at 0.012558), more than I got from adding on gradient clipping (0.013209), and more than adding on bias to the QKV weights (0.022141). I'd need to do significantly more training runs in order to find out if this was due to some kind of noise, and I'll not spend that time and money now. It feels like there are two possibilities: On the one hand, the fact that the results were consistent is interesting. If the PyTorch models had both been better than the hand-rolled ones but by different amounts, then that would be easy to ascribe to chance (I make it a 25% probability, though you could argue for 1/6). But the fact that the improvements were so similar is harder to explain. On the other hand, a systematic difference would be really weird , at least to me. I'm confident that my hand-rolled implementations match the PyTorch ones in terms of the maths -- not only have I checked and double-checked the code, but the LayerNorm one was written by someone expert in the field, and I've also run them past both Claude Opus 5.5 and GPT-6 Astra, both on high thinking levels, to check that there are no differences 7 . So while I can't rule errors out, I've done a lot to try to eliminate them. For now, I think I'll loosely chalk this up to noise too. I've seen weird coincidences crop up before -- regular readers might remember that in my post on LoRE , the loss delta of using it on the input side only, when added to the delta of adding it to the output side only, was almost exactly the same as the delta for adding it to both ends. That repro'd over two separate random seeds and really looked like it was a thing -- only to disappear with a change to a part of the code that should not have affected it if it had been a real additive effect. More Tests Needed. I think an interesting set of experiments to test that would be not only to try with different random seeds, but also to try with different weight initialisation strategies entirely. What would these results look like if, instead of using PyTorch's default initialisation, we used the one they describe in the GPT-2 paper? (More on that in an upcoming post.) But back to this experiment: what can the results that we have right now tell us? I started this set of experiments with two goals: to understand how RMSNorm works, and to see if I could show similar results to the original paper -- that it gets comparable loss to LayerNorm, with a noticeable saving in training time. I'm happy with the first part of that -- and hopefully if you're reading this, the "how it works" part is clear for you too! The loss was, I think, also as expected. Again, I'd need to do a much larger-scale experiment with various starting weights to be sure, but the fact that the difference between RMSNorm and LayerNorm was so small was certainly reassuring. The training speed was a much less impressive result. With hand-rolled code, the 2.5% speedup looked potentially real, but it pretty much vanished when I switched to PyTorch's built-in classes. The big difference, of course, was that between PyTorch's built-in classes and the hand-rolled ones. The speedup from using fused kernels for this stuff was not such a big surprise, especially after the similar improvement from using the built-in GELU. It would certainly be interesting to see if using narrowed the gap, though. But the improved loss was definitely interesting. Again, I'd need to do a ton of training runs to see if that was real or noise. It seems most likely that it was noise, but the fact that the effect was positive for PyTorch in both cases, and was by such a similar amount, keeps nagging at me. One remaining question aside from that, though: RMSNorm wasn't obviously significantly faster, especially if you use fused kernels, and while it wasn't obviously worse than LayerNorm, it didn't appear to be better -- so what explains its popularity in so many open weights models? The first thing I thought was that maybe it's something that becomes more effective in terms of cost reductions as models get larger. However, having thought it through, I think that exactly the opposite is true -- its effects get even smaller as we scale up. Remember that -- in terms of calculations -- RMSNorm saved 3 d emb additions/subtractions for each context vector. That would scale smoothly as d emb was increased, and of course the number of RMSNorms would increase proportionally as the model gained more layers. So I think that the absolute compute reduction in terms of calculations saved would scale roughly linearly with each of width and depth. But other aspects of the model's cost scale more than linearly with width. For example, in GPT-2, our FFNs map from d emb to 4 d emb and back again; that means that the number of calculations scales as O ( d emb 2 ) . More modern implementations use SwiGLU, but I believe that the scaling is of the same order. And that's not even to mention the fact that modern models have longer context, and while the norms scale linearly with the sequence length (and the RMSNorm savings do too), full attention is O ( n 2 ) on that. So if we're only getting, say, 0.5% improvement for these tiny 163M parameter models with a 1,024 token context length, it would be an even smaller percentagewise improvement for larger ones. Even if that wasn't the case, the amount is pretty small: DeepSeek V3 was widely reported to have cost US$6M to train (excluding R&D and a bunch of other stuff, but that's actually the correct number to use here). So even if we ignore all of the above and use it directly, that would just be a US$30,000 saving from using RMSNorm. And that's basically an upper bound -- we'd expect it to be significantly less. Another possibility, though, is that it's an architectural thing. These open models have a bunch of differences to the GPT-2-style code I've been using here. They use RoPE for position encoding, and SwiGLU for the feed-forward networks. Mistral has multiple differences in the attention mechanism. On the face of it, I don't see any obvious reasons why those might speed up RMSNorm, but I can certainly imagine that they might "prefer" one form of normalisation over another, resulting in better loss. So perhaps that's what people have found. But there are plenty of other possibilities. If people have generally found that it's just as good as LayerNorm, then perhaps it's just a fashion -- one model uses it, then the next one has no particular reason to move back, and so on. And there is a general move towards dropping biases from LLMs (for example, from the QKV weights), and RMSNorm would fit that. And anyway, it is a bit simpler! Whatever the reason: if RMSNorm is that little bit simpler than LayerNorm, by skipping the recentring aspect of normalisation, is there something even simpler that could work even better? While discussing the subject with Claude Opus 5.5, it mentioned "Transformers without Normalization" 8 , which is a really interesting paper -- one of the authors has a neat intro on GitHub . They noticed that the transformations that normalisation layers tend to learn wind up looking a bit like the S-shaped mappings you get from the tanh function, so tried using that instead with a system they called Dynamic Tanh (DyT) -- and got good results! The first sentence in this post was "Normalisation is an essential part of LLMs". Was that wrong? I suppose that depends on what you mean by "normalisation" -- could you regard their tanh trick as being normalisation of some kind? -- though given that Yann LeCun was a co-author on the paper I should probably be a bit hesitant to disagree with his definition of it ;-) I think their DyT system is something for a follow-on post, though. For now: RMSNorm seems to be essentially the same in terms of model quality, and maybe slightly faster than LayerNorm for the models I've been playing with, at least if you don't use the fused modules. But using the fused PyTorch modules instead of hand-rolling our own normalisation is a huge win for speed. The loss improvement that came with it in this experiment is very interesting, but I'd certainly want to do quite a lot of extra experiments before claiming it was real! For now, I think I'll say that I'm happy that I learned how RMSNorm worked, but I don't think I'll add it in as a standard part of my training runs. And the further experiments can go on the pile with the hundreds of other things I'll look into later. Once I've learned about RoPE, and SwiGLU, and all of the rest of it... Thanks for reading! Linkrot-safe citation: Biao Zhang, & Rico Sennrich. (2019). Root Mean Square Layer Normalization.  ↩ There was an earlier normalisation technique called BatchNorm which operated across the whole batch, but that seems to have dropped out of favour. The paper has some discussion of why that was.  ↩ Or by the number of elements minus one if we're using Bessel's correction . I'll use the version without in this post, but the maths works out either way.  ↩ Raschka's LayerNorm implementation does not use Bessel's correction, which makes it compatible with the original GPT-2 code; specifically, it uses the kwarg: Per the PyTorch docs for , this is the pre-PyTorch 2.0 way of saying: From the docs for The variance is calculated via the biased estimator, equivalent to . So that matches nicely.  ↩ Just in case I want to use it in the future, here it is: With that, you can wrap anything that might draw variable amounts of randomness from the various random-number generators in a block, and you can be sure that the state will be stable afterwards regardless. Using that in some of my earlier code would have been much easier than the various contortions I went through to ensure that different routes through the code drew the same amount regardless of the model's configuration.  ↩ One possibility that occurs to me: the fact that the LayerNorm got more of a speedup might be due to an inefficiency in the hand-rolled code having been addressed in the PyTorch implementation. Remember, what we started with was written as educational code to explain how LayerNorm works, so it does this: Now, remember that in the explanation of LayerNorm above , I noted that once you've recentred the vector, you can re-use that to work out variance, because the recentred vector is already a list of differences from the mean. So you could rewrite the above more efficiently as: That would save us two calculations of the mean and the differences from it, so would hopefully speed things up. Or, of course, it could have just been noise, or something completely different :-)  ↩ I was going to put a defensive "FWIW" against the "I got an LLM to check it out" bit there, but these days, for this kind of thing, I think it's unnecessary.  ↩ Zhu, J., Chen, X., He, K., LeCun, Y., & Liu, Z. (2025). Transformers without Normalization. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .  ↩ Normalises the context vector so that its mean is zero, and its variance is one. Scales and shifts (aka biases) the resulting normalised vector by trainable amounts. Working out the mean: for a context vector of length d emb , we have d emb − 1 additions, then one division. Recentring on the mean: d emb subtractions. Working out the variance: we can use our recentred vector for the differences, so that's done, but we need to get the squares of all of the numbers, which is d emb multiplications, add them together using d emb − 1 additions, and then do one division. Variance to standard deviation: one square root. Dividing it all by the SD: d emb divisions. Scaling by the scale vector: d emb multiplications Shifting by the shift vector: d emb additions Additions/subtractions: d emb − 1 + d emb + d emb − 1 + d emb = 4 d emb − 2 Divisions: 1 + 1 + d emb = 2 + d emb Multiplications: d emb + d emb = 2 d emb Square roots: 1 Working out the squares of all of the numbers: d emb multiplications. Averaging them to get the mean square: d emb − 1 additions, then one division. Getting the RMS from that: one square root Dividing all of the numbers by the RMS: d emb divisions Scaling by the scale vector: d emb multiplications Additions/subtractions: d emb − 1 Divisions: 1 + d emb Multiplications: d emb + d emb = 2 d emb Square roots: 1 Additions/subtractions: ( 4 d emb − 2 ) − ( d emb − 1 ) = 3 d emb − 1 fewer Divisions: ( 2 + d emb ) − ( 1 + d emb ) = 1 fewer. Multiplications: 2 d emb − 2 d emb = 0 difference Square roots: 1 − 1 = 0 difference. Twice in each Transformers block: before the MHA and before the FFN. At the end, just before the output head. No weight tying. No bias on the QKV matrices. Use no dropout. Schedule the learning rate: a warmup over the first 5% from zero to 0.0014, then a cosine decay down to 0.00014. Train for the Chinchilla-optimal ~20 tokens per parameter. One with the old LayerNorm. One with the PyTorch LayerNorm. One with my hand-rolled RMSNorm. One with PyTorch's RMSNorm. It's noise due to numerical differences -- some kind of rounding thing, for example. Imagine a tiny difference right at the start of training -- a single parameter gets updated to 0.11892473 with the hand-rolled code, but to 0.11892474 with the fused code. That slightly changes the results from the next training step, so the gradients are different, and now the model diverges a bit more. As we continue over 33,000 training steps over 3.2B tokens, you can imagine that the models could diverge quite a lot. We're on a choppy ride over the loss landscape, always trying to head downwards, and a small change near the start can drastically change where we end up. Alternatively: maybe there's something systematic that makes the PyTorch implementations better in this case? Linkrot-safe citation: Biao Zhang, & Rico Sennrich. (2019). Root Mean Square Layer Normalization.  ↩ There was an earlier normalisation technique called BatchNorm which operated across the whole batch, but that seems to have dropped out of favour. The paper has some discussion of why that was.  ↩ Or by the number of elements minus one if we're using Bessel's correction . I'll use the version without in this post, but the maths works out either way.  ↩ Raschka's LayerNorm implementation does not use Bessel's correction, which makes it compatible with the original GPT-2 code; specifically, it uses the kwarg: Per the PyTorch docs for , this is the pre-PyTorch 2.0 way of saying: From the docs for The variance is calculated via the biased estimator, equivalent to . So that matches nicely.  ↩ Just in case I want to use it in the future, here it is: With that, you can wrap anything that might draw variable amounts of randomness from the various random-number generators in a block, and you can be sure that the state will be stable afterwards regardless. Using that in some of my earlier code would have been much easier than the various contortions I went through to ensure that different routes through the code drew the same amount regardless of the model's configuration.  ↩ One possibility that occurs to me: the fact that the LayerNorm got more of a speedup might be due to an inefficiency in the hand-rolled code having been addressed in the PyTorch implementation. Remember, what we started with was written as educational code to explain how LayerNorm works, so it does this: Now, remember that in the explanation of LayerNorm above , I noted that once you've recentred the vector, you can re-use that to work out variance, because the recentred vector is already a list of differences from the mean. So you could rewrite the above more efficiently as: That would save us two calculations of the mean and the differences from it, so would hopefully speed things up. Or, of course, it could have just been noise, or something completely different :-)  ↩ I was going to put a defensive "FWIW" against the "I got an LLM to check it out" bit there, but these days, for this kind of thing, I think it's unnecessary.  ↩ Zhu, J., Chen, X., He, K., LeCun, Y., & Liu, Z. (2025). Transformers without Normalization. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) .  ↩

0 views
Farid Zakaria 3 weeks ago

Who wrote this byte?

git blame for your build’s bytes. 🔍 A build is bit reproducible when the same inputs give the same bytes. Why does reproducibility matter? They provide certainty that software is genuine and has not been tampered with. See reproducible-builds.org . Nix is infamously not bit reproducible, but rather input-addressed : the hash of a package is calculated from the inputs rather than the output. We still prefer though to have bit reproducibility, because it allows us to verify that the package we downloaded is the same as the one built from source. It is something many packages aspire to achieve. When the outputs differ, you want to know why. The first step is to find the bytes that differ, and the second is to find the program that wrote them. Finding the cause of a difference has traditionally been the challenging part of process making builds reproducible…until now! I have been building Rewind VM , a deterministic virtual machine that can record and replay builds, and it now has a new command to find the program that wrote a byte that differs between two runs: . Aside: I wrote about Rewind VM first in a flaky build you only catch once , and then about properties . Let’s see how it works, first with a small example. Let’s start with a made-up library, , that writes its pkg-config file with a short Python script. 1 The script collects the packages the library links against into a : Python iterates a set of strings in an order drawn from its hash seed , which is random for every new process. In Rewind the seed is an input: decides every random number the build draws. Let’s build under eight seeds: The third column from the end is the start of the output’s hash (i.e. ), and the last is the run id. We did eight builds and got five different outputs. 😬 Our build is not reproducible. shows what differs between two runs, without leaving Rewind: You could ascertain this from tools like diffoscope but would be left to figure out what program wrote the differing bytes. does that for you. takes two runs and a file, and names the program that wrote the first byte that differs: The output is a little long, but it is all relevant and the first line has the answer: wrote that byte at step 2,909. 2 The rest of the text is how the tool determined the provenance of the byte change. The tool highlights that the difference was made inside python3, and we know that the seed is the one input that changed. 🎯 $out/…/tiles.pc differs at byte 178 install copied it, step 3,157 its source already differed: not the cause /build/tiles/tiles.pc python3 wrote byte 178, step 2,909 the first writer: the difference starts here python3 gen-pc.py same command line same gen-pc.py in both runs → the cause is inside python3: its hash seed The fix is straightforward, we wrap the list with , and every seed then builds the same . 🙌 How can the command deduce the lineage of a byte? The trick is that blame does not have to search for the write. The run already recorded it.😯 Every Rewind run records each program’s starts, exits, opens for writing and renames, each at its step. 3 For , the guest’s Linux kernel also keeps two kinds of record: The records are written to a buffer in the guest kernel’s memory, a 1MiB buffer, and Rewind copies them into at the intervals it has stop the VM anyways. This keeps the runs identical and performant. write open step step step buffer buffer buffer trace.bin: the records, saved with the run I measured the cost of the records in Rewind 0.9.0, and it is small enough to leave them on for every run. With the records, blame finds the write that set the byte by reading the trace, without replaying either run. It only replays to read a file’s contents at a step. The Rewind app shows the same thing visually. Open the two runs side by side: The Compare tab now lists the files that differ between the two runs: We can also click a file to see it from both runs. Here that is step 2,909, with in the process tree and its command in the build log: At that moment, we can explore the complete VM state: the files as they were, the process tree, a fork, or gdb. The app shows the same information as , but visually and interactively. In order to capture possibilities of non-determinism, we need to vary any input that can change the output. The seed decides random numbers. also varies the schedule , the order threads take turns, which is how parallel and end up with different outputs. Turns out there is a third input that can change the output: the order of directories. The order of files in a directory is not guaranteed to be the same across machines, or even across runs on the same machine although many builds assume it to be. We can also vary the order of directories in Rewind which helps catch even more non-determinism with . This is useful for builds that depend on the order of files in a directory. writes an index of the plugins it ships, in the order returns them. It builds the same output under every seed, but not under every directory order: 4 We have four directory orders, and four different outputs. Each one lists the same five plugins in another order: The fix is the same as before: , and every key builds the same index. Look closely and both examples are the same bug. Python iterates a set in hash order, and ext4 lists a directory in hash order. Change the seed behind the hash and the order changes with it. Finding the cause of a difference has traditionally been the challenging part of process making builds reproducible. Many tools exist to help detect nondeterminism but few actually give you the root cause. Lowering the barrier to making builds reproducible is a goal of Rewind VM, and is a step in that direction. Rewind VM is purpose built to work in the Nix ecosystem and helping make more Nix packages reproducible is a worthy goal. If you want a deeper dive on this subject, check out the reproducible builds tutorial , which walks through both examples step by step, including the directory-order one. If you maintain a package that does not reproduce and you do not know why, try blame on it, and tell me what it finds. I would love to add it to the leaderboard . 🏆 nixpkgs sets that circumvents this bug.  ↩ The output is real, with long lines wrapped to fit and the store path shortened.  ↩ A step is a moment the virtual machine stops and hands control to Rewind, such as when a program starts or writes to the terminal. Step 2,909 is the same moment every time you replay the run.  ↩ It is the second example in the reproducible builds tutorial .  ↩ The file in was copied there by . The file it copied from already differed, so the copy is not to blame. That file, , was first written by pid 112. It was still when it opened the file for the redirect, and then became . One write of 227 bytes set byte 178. had the same command line in both runs, and the only file from the build it read, , was the same in both runs. install copied it, step 3,157 its source already differed: not the cause /build/tiles/tiles.pc python3 wrote byte 178, step 2,909 the first writer: the difference starts here python3 gen-pc.py same command line same gen-pc.py in both runs → the cause is inside python3: its hash seed The fix is straightforward, we wrap the list with , and every seed then builds the same . 🙌 How it knows How can the command deduce the lineage of a byte? The trick is that blame does not have to search for the write. The run already recorded it.😯 Every Rewind run records each program’s starts, exits, opens for writing and renames, each at its step. 3 For , the guest’s Linux kernel also keeps two kinds of record: a write record for every write to a file: which thread, which file, where in the file and how many bytes; an open record for every file a program opens, for reading or for writing. step step step buffer buffer buffer trace.bin: the records, saved with the run I measured the cost of the records in Rewind 0.9.0, and it is small enough to leave them on for every run. With the records, blame finds the write that set the byte by reading the trace, without replaying either run. It only replays to read a file’s contents at a step. In the app The Rewind app shows the same thing visually. Open the two runs side by side: The Compare tab now lists the files that differ between the two runs: We can also click a file to see it from both runs. Here that is step 2,909, with in the process tree and its command in the build log: At that moment, we can explore the complete VM state: the files as they were, the process tree, a fork, or gdb. The app shows the same information as , but visually and interactively. Beyond seeds In order to capture possibilities of non-determinism, we need to vary any input that can change the output. The seed decides random numbers. also varies the schedule , the order threads take turns, which is how parallel and end up with different outputs. Turns out there is a third input that can change the output: the order of directories. The order of files in a directory is not guaranteed to be the same across machines, or even across runs on the same machine although many builds assume it to be. We can also vary the order of directories in Rewind which helps catch even more non-determinism with . This is useful for builds that depend on the order of files in a directory. writes an index of the plugins it ships, in the order returns them. It builds the same output under every seed, but not under every directory order: 4 We have four directory orders, and four different outputs. Each one lists the same five plugins in another order: stock order sharpen rotate resize crop blur dirents=1 sharpen crop blur rotate resize dirents=2 sharpen resize crop rotate blur sorted() blur crop resize rotate sharpen The fix is the same as before: , and every key builds the same index. Look closely and both examples are the same bug. Python iterates a set in hash order, and ext4 lists a directory in hash order. Change the seed behind the hash and the order changes with it. Try it Finding the cause of a difference has traditionally been the challenging part of process making builds reproducible. Many tools exist to help detect nondeterminism but few actually give you the root cause. Lowering the barrier to making builds reproducible is a goal of Rewind VM, and is a step in that direction. Rewind VM is purpose built to work in the Nix ecosystem and helping make more Nix packages reproducible is a worthy goal. If you want a deeper dive on this subject, check out the reproducible builds tutorial , which walks through both examples step by step, including the directory-order one. If you maintain a package that does not reproduce and you do not know why, try blame on it, and tell me what it finds. I would love to add it to the leaderboard . 🏆 nixpkgs sets that circumvents this bug.  ↩ The output is real, with long lines wrapped to fit and the store path shortened.  ↩ A step is a moment the virtual machine stops and hands control to Rewind, such as when a program starts or writes to the terminal. Step 2,909 is the same moment every time you replay the run.  ↩ It is the second example in the reproducible builds tutorial .  ↩

0 views
Sean Goedecke 3 weeks ago

Software is slow because of bad design, not slow languages

Many people are saying that AI will make software faster by rewriting it in faster languages, but this isn’t generally true. Most programs cannot be meaningfully sped up by rewriting them in C or Rust. How can this be true? Some languages are orders-of-magnitude faster than others: for instance, C can be fifty times faster than Python. Won’t rewriting my Python program in C thus make it fifty times faster? No, it won’t. Software performance is usually dominated by I/O, not the speed of the language. Where language speed matters, most slow languages already have popular libraries that allow them to unlock C-like speed. In general, performance is a matter of design , not of language choice. Consider a simple CRUD website with a database. For any given request, 50% of the request time 1 might be spent querying the database: to fetch the current user, the record being asked for, any relevant user memberships or settings, and so on. Rewriting that website in C can only speed up that other 50%, which puts a hard ceiling on the improvements you can make 2 . At best, you’ll make requests twice as fast (probably closer to 1.5x in practice). That’s not bad, but it’s nowhere near an order-of-magnitude speedup. In other words, most real programs are “I/O-bound”: they spend most of their time waiting for data to be input or output somewhere, as opposed to “CPU-bound” programs that spend most of their time actively doing things. I/O-bound programs don’t just have to rely on a database. Often programs have to wait on some third-party API, or on writing or reading data to disk. You could speed the code in up by 100x and you probably wouldn’t even notice, because spends all of its time waiting on the network. What about work that is obviously not I/O-bound? For instance, wikis have to turn stored markdown into renderable HTML 3 . Wouldn’t rewriting that in a faster language cause a massive speedup? It would! That’s why applications that do that use libraries like cmark-gfm that call out to fast languages for markdown rendering. In general, most slow languages can write very fast programs by invoking this kind of library. Python is famously a slow language, but it’s a competitive choice for CPU-bound workloads like machine learning and mathematics, because it has a healthy set of libraries that let it offload these workloads to fast C code. If a Python program spends 80% of its time doing matrix multiplications on a GPU, you are very unlikely to be able to speed it up by rewriting it in C, because those matrix multiplications are already happening in tightly-optimized C or assembly code. Of course, some programs do in fact do a lot of CPU-bound work in slow languages. If a program has not had much engineering attention, there will probably be a lot of low-hanging fruit . But these programs are often unimportant: if they were important, someone would have gone in and optimized them already, before AI made it (relatively) easy. That doesn’t mean it’s impossible to find a useful program to rewrite. Actual Computer recently rewrote tiktoken in assembly, providing a significant 4 speedup. However, you’re not going to revolutionize some field of computing like this. Even fast tokenization is only useful on the margins, because time spent in tokenization is a fraction of the time spent in inference. Despite all this, I think most software is far slower than it could be. I’m optimistic about the potential (with or without AI) to significantly speed up commonly-used software. But I think most of these speedups will come from redesigning the program, not rewriting it in a faster language. In a 2018 post , Bryan Cantrill described trying to rewrite a C program into Rust. It was difficult because the carefully-optimized design of the C program did not play well with the Rust borrow checker. Giving up, he simply wrote the program in Rust in the naive way, expecting a 20% slowdown or worse. Instead, it was 30% faster . The reasons boil down to Rust’s internal preference for a B-tree over a binary search tree, which happens to be a more cache-efficient data structure. So even in a largely CPU-bound workload, in the hands of someone very skilled at writing fast C, performance is dominated by design, not by language speed. This matches my own experience in higher-level languages. When I think of the significant speedups I’ve managed, they’re almost exclusively redesigns of the software to do less work: All of these strategies are completely unrelated to how fast the language is. In fact, writing in a slow higher-level language can make it much easier to optimize the code, because you can see at a glance what the program is doing. If (for some reason) I had first rewritten the web server in assembly, I would have a much harder time noticing the N+1 query, or the fact that we could move an API call into a job, and so on. Right now everyone is asking their AI agents to rewrite programs in Rust or C or assembly. This is fun, but it’s not a serious attempt at optimization. The set of programs that can be meaningfully sped up by this kind of rewrite is very narrow. If you want to make everything faster with AI — and you should! — you ought instead to be asking your agent to profile programs, identify hotspots, and suggest ways to redesign what the program does. Occasionally you may run into a hotspot that is truly CPU-bound and cannot be refactored to do less work. In these rare cases, rewriting that section in a faster language will help. But simply rewriting from the start will be far less successful than most people imagine. There are many good reasons to rewrite software in a different language: portability, efficiency, maintainability, and so on. But in terms of raw speed , you’re better off focusing on the program’s design. This might seem ridiculously high (if you typically work with slow languages or CPU-bound workloads), or ridiculously low (if you don’t). In my experience it’s at least in the ballpark for interpreted languages. This is formally called Amdahl’s law . Why not just store the HTML? You can, but sometimes the content of the HTML differs per-user (and even if you store the HTML you have to convert it at least once). They claim 4-23x faster than tiktoken and it was indeed ~5x faster on my laptop — though arguably this speedup comes from a redesign to avoid the dependency on regex, not on any intrinsic slowness of Rust with Python bindings. Caching a slow operation (typically an external API call) Performing slow operations asynchronously, either in a background job or out of the request/response lifecycle Performing operations in parallel instead of sequentially (sometimes breaking up large operations in order to do this) Replacing a set of SQL queries with a single SQL query (fixing N+1 problems) Replacing a slow SQL query with a fast SQL query Skipping unnecessary slow operations (e.g. in a paginated view, only fetch ancillary data from entities that are on the current page) This might seem ridiculously high (if you typically work with slow languages or CPU-bound workloads), or ridiculously low (if you don’t). In my experience it’s at least in the ballpark for interpreted languages. ↩ This is formally called Amdahl’s law . ↩ Why not just store the HTML? You can, but sometimes the content of the HTML differs per-user (and even if you store the HTML you have to convert it at least once). ↩ They claim 4-23x faster than tiktoken and it was indeed ~5x faster on my laptop — though arguably this speedup comes from a redesign to avoid the dependency on regex, not on any intrinsic slowness of Rust with Python bindings. ↩

0 views
spf13 3 weeks ago

Zelda on My Conference Badge

As one of the GitHub Stars and a member of the GitHub Creators program, I got a package a few days before GitHub Universe: my conference badge, early, with a little note card tucked in that said hack this . As soon as I saw it I thought — man, this has a game controller on it, and it’s kind of perfect. Hanging from a lanyard around your neck, you can just grab it, hold it up, and play. I wonder if I can get The Legend of Zelda on it. So I backed up the flash, mounted the filesystem, and verified the restore came back clean — the whole badge is recoverable from USB, which is why every experiment below ships as you can delete if you want every byte back. With that safety net I started working out how much of the badge I’d have to give up. This year’s badge is called Badger , and it’s a nice piece of hardware: an RP2350 (dual-core ARM Cortex-M33 running at 230 MHz), a 320×240 IPS panel, 16 MB of QSPI flash with about 9.76 MB free for user apps out of the box, 8 MB of QSPI PSRAM, an accelerometer, Bluetooth Low Energy, and an infrared transceiver. It runs MonaOS 4.0, a custom MicroPython environment with hardware-accelerated graphics primitives ( ), a dual-core software 3D rasterizer ( ), and LED control ( ). The obvious approach is to flash a bare-metal C NES emulator as a image. That takes about twenty minutes, and it works. It also turns the badge into a Nintendo emulator that used to be a badge which ruins the entire point. You lose MonaOS: the BLE contact exchange, the venue IR scavenger hunt, the two-player games, the tilt-controlled 3D Mona launcher. All of it. I didn’t want a dedicated emulator. I wanted Zelda , Super Mario Bros. , and Tetris to be an ordinary app inside MonaOS, sitting at , launching from the carousel, and dropping back to the OS when you tap the HOME pad on the back. Which means running inside MicroPython. And running an NES inside an interpreted language on a microcontroller runs into serious performance issues. I love a challenge like this. An NES needs three things: Standard MicroPython bytecode manages somewhere around 100,000–200,000 interpreted opcodes per second on a Cortex-M33. Full-speed NES needs roughly ten times that. Writing a native C module was an option but not one I was really interested in. Custom dynamic native modules on MicroPython are an ABI and symbol-matching gamble against a vendor firmware image. It just felt too risky and fragile of an option. If it breaks on someone else’s badge, it breaks in a way they can’t fix. So with a healthy amount of curiosity and with Gemini 4 Argon we went to work. The model drafted the inner loops from prompts describing the 6502, PPU, and mapper contracts — instruction decode, sprite evaluation, and bank switching. I set the four-pointer architecture around , , , and , shaped the Viper kernels, and measured every number below on hardware over USB serial. The remaining bugs ( , calls, the frame budget) are the kind you only get from running it. Other pure-Python NES emulators I tried allocate objects on every instruction and ran at less than half a frame per second on the badge in my quick test. So Gemini and I built our own NES emulator from scratch ( , ~1,100 lines): a custom 6502 CPU core, scanline PPU renderer, and Mapper 0 ( ), Mapper 1 ( ), Mapper 2 ( ), and Mapper 3 ( ) bank switcher engineered specifically around RP2350 . The thing that makes this possible is . Regular MicroPython, and even , still dispatches through the object model. Viper doesn’t. It compiles typed Python syntax directly into raw ARM Thumb-2 instructions at import time, and it works on unboxed values: machine-word integers and raw pointers ( , , ). So when you dereference , you get a single 16-bit Thumb-2 or . No heap allocation, no dictionary lookups, no garbage collector pressure. That one decorator closes most of the performance gap. The catch is that Viper comes with some fairly unforgiving constraints. Writing non-trivial emulation in Viper means living with the ARM Architecture Procedure Call Standard: So we packed CPU work RAM, OAM, palette RAM, VRAM, and the cartridge save window into a single contiguous 32 KB ( in the emulator, with PRG ROM banked in separately): The badge has no speaker, so there is no APU, and isn’t emulated — this is a picture-only port. The emulator’s own registers (program counter, accumulator, X, Y, stack pointer, status flags, cycle counters, PPU latches, MMC1 shift registers) all live in a 64-element 32-bit integer array ( ). Four pointers ( , , , ) are enough for the entire 6502 core and PPU to run without spilling. The panel runs in 16-bit RGB565. MonaOS exposes the underlying buffer as . Rather than rendering into an intermediate frame buffer and paying for a full-screen blit, the PPU scanline renderer writes directly into display memory: The NES screen is 256 pixels wide and the badge is 320, so centering it leaves a 32-pixel gutter on each side. Leaving that dark seemed like a waste. The left gutter now carries the mark, a live FPS counter (around 32 FPS in Zelda in this post-optimized build with the sidebar and HUD), and a controller input visualizer. The right gutter has the button mapping and a indicator that lights up whenever battery SRAM hits the disk. Flipping the Badge Upside-Down Turns It into a Handheld When the badge hangs from a lanyard, the 8-channel capacitive controller ( ) sits at the top of the board, above the screen. Genius design. It means you can grab the badge, keep the lanyard around your neck and play it like a gameboy as you rotate it 180° and the touch array lands under your thumbs, which is exactly where a handheld wants it. The only issue is the badge’s orientation is now inverted, so the logical mapping of the D-pad and action buttons is upside-down. The fix is simple: The first build that actually booted Zelda on hardware gave us 72.9 ms per frame: 31.9 ms in the 6502 core and 41.0 ms in the PPU renderer. That is 13.7 FPS, about 22% of real-time NES speed. Ok. This is awesome. We got it working, Zelda on my conference badge. Once running the next goal was to make it playable. Four changes took 49 ms off every frame, a 3.1× speedup, down to 23.7 ms in Zelda (about 42 FPS) and 10.9 ms of work per frame in Tetris : A tight read loop used for timing rather than waiting can skip cycles it needed. That is why the compatibility list below is fourteen titles I actually played rather than a claim of universal NES support — the mapper set and optimization are tuned to those. I’m sure other titles play and I’m sure some don’t. The emulator is open source, so you can try your own ROMs and see what works and since we live in the age of agents, have them help patch it for your favorite NES game. Zelda uses battery-backed RAM at to persist quest data (only when you die or open the save screen), while Metroid saves by password; Final Fantasy and Dragon Warrior also rely on battery-backed saves. Most NES classics ( Super Mario Bros. , Tetris , Contra , Castlevania , Mega Man 2 ) have no battery-backed save at all. Because the entire machine state is a 256-byte register array ( ) plus one contiguous ( ), full save states were nearly free to add. They sit next to the battery SRAM image on the badge’s LittleFS partition, as and . One more caveat: the save inherits the write risk — back up anything you care about over USB, or let’s be honest, if you care about it don’t do it on a conference badge. The 60-second auto-save timer is deliberately lazy to be gentle on flash. in the ROM list means a save-state file was found for that title — the list’s marker for “there’s a restore here.” Turn-based RPGs and handheld classics are a natural fit for a lanyard badge you carry between conference sessions. Alongside action staples ( The Legend of Zelda , Super Mario Bros. , Tetris , Contra , Castlevania , Mega Man 2 , Metroid , Donkey Kong Classics , Pac-Man , Galaga , Excitebike , Dr. Mario ), we added full MMC1 + battery SRAM + instant save state profiles for Final Fantasy ( ) and Dragon Warrior ( ). Tetris Mega Man 2 Final Fantasy (NES, MMC1 + save states) Two-Minute Install The NES emulator ( ) and the Hardware Lab ( ) are open source: github.com/spf13/universe-2026-badge-hacks Mount the badge as USB storage. Plug it in over USB-C and launch the USB Disk ( ) app from the MonaOS menu. It shows up as a removable drive ( on Windows, on macOS). Clone and copy : macOS (zsh): Badge not at ? Run to find it — some Macs mount it as or . Windows (PowerShell): Drive letter varies — check File Explorer if doesn’t exist. Add your own ROMs that you’ve dumped yourself and legally obtained. No ROMs are included or linked: Eject & play. Safely eject the drive (macOS: right-click → Eject or ; Windows: system tray → Safely Remove), pick NES from the MonaOS menu, turn the badge upside-down so the capacitive pad sits under your thumbs, and go. Conference badges used to be glorified flashing name tags. Today they’re dual-core ARM computers that compile native machine code at import time, and the interesting part of this project was finding out how far that actually gets you. Today it’s far enough for a playable NES. If you’re heading to GitHub Universe 2026, I look forward to seeing you there. Just remember to save your game before the keynote. (Since it felt like a Game Boy I then wondered if I could get it to run Game Boy Color games too. See the follow-up post: Game Boy Color on My Conference Badge .) An emulated 8-bit Ricoh 2A03 (a 6502 core) at 1.789773 MHz, about 29,780 CPU cycles per frame at 60 Hz. A Picture Processing Unit rasterizing 240 scanlines of background tiles and up to 64 hardware sprites. 61,440 pixels written to the display buffer every frame. Four arguments, maximum. Viper functions take through . A fifth argument is a compile-time error. No working Viper-to-Viper calls. Calling one Viper helper from another boxes the arguments back through the MicroPython runtime, or fails to compile with on Cortex-M33. Every hot kernel, especially, has to inline its own memory reads, writes, and bank switches into one self-contained function. Explicit casts. Reading a byte out of into a typed local needs an explicit , or the on-device compiler stops with . No dynamic structures. No dicts, no objects, no tuples in the inner loop. Primitive arrays and pointer arithmetic only. : 2 KB internal CPU work RAM (mirrored up to ) : 256 B object attribute memory (sprite OAM) : 32 B active palette RAM : 4 KB VRAM and nametables : 8 KB pattern table and CHR RAM window : 8 KB battery-backed save RAM ( on the 6502 bus), mapped when the cartridge claims it : 8 KB spare tail reserved for cartridge expansion Eight buttons, NES-shaped: four D-pad channels, two right-hand action pads ( for A, for B), and two pads in the middle ( for START, for SELECT). All eight are touch channels, and the firmware exposes them as logical actions rather than fixed GPIOs. Automatic rotation ( ): the IMU notices the inverted orientation, flips the screen buffer 180°, and the logical mapping swaps and . Bypassing the display compositor at 230 MHz. We initially experimented with , which worked for smaller ROMs in internal SRAM but pushed the shared QSPI Flash/PSRAM bus ( ) to 150 MHz and locked up the QMI bus on larger cartridges. Keeping the badge’s stock 230 MHz clock (already a 53% factory overclock over the RP2350’s 150 MHz spec, keeping the QSPI bus at its 115 MHz ceiling) and configuring , , and gave us a rock-solid, low-overhead display path. Removing runtime division. Even inside Viper, or emits calls to the C helper, 7,680 of them per frame. Replacing all tile coordinate math with bit shifts ( , ), pre-populating the universal background color into palette slots for branchless lookups, and fast-pathing empty 8-pixel tile rows ( ) cut + from 41.0 ms to 9.4–12.1 ms. That is 3.4×. One Viper call per scanline instead of per instruction. Moving the entire scanline instruction loop ( ) inside Viper reduced ~10,000 Python-to-Viper transitions per frame down to 262 (one per scanline, returning briefly so Python can service bank switches). Caching , , , , , , and the PRG bank offsets in local ARM registers, and replacing the 55-deep linear opcode chain with a balanced five-level binary search tree, roughly halved dispatch overhead. Fast-forwarding idle spin loops, then frame pacing. Zelda and Super Mario Bros. spend dozens of scanlines spinning in two- and three-instruction loops waiting for a sprite-0 HUD split ( , ) or the VBlank NMI flag ( ). When we see a taken backward branch ( in ) that lands on a pure read, the emulator fast-forwards the rest of that scanline in one step. went from 32.0 ms to 11.6 ms (3.0 ms in Tetris ). Then stepping two logic frames per rendered frame whenever wall-clock delta exceeds 18 ms keeps game logic at 60 Hz. Rendering is honest about its limits: about 42 FPS uncapped in Zelda (23.7 ms/frame), 32 FPS with the FPS counter and sidebar drawing, 58 FPS in Tetris (10.9 ms of work per frame), which is smooth enough to play. Idle auto-save. Every 60 seconds, as soon as you briefly let go of the buttons (so a flash write never interrupts a jump or a sword swing), the emulator snapshots CPU registers, PPU latches, VRAM, and SRAM to flash in about 160–390 ms and flashes in the right gutter. Save on pause, exit, and HOME. Holding A + B (or START + SELECT) for 650 ms saves and opens a pause overlay: , , , , , . The HOME pad on the back fires an IRQ ( ) that saves and returns cleanly to the MonaOS launcher. Relaunching a game marked restores the exact frame and position in 14 ms. Mount the badge as USB storage. Plug it in over USB-C and launch the USB Disk ( ) app from the MonaOS menu. It shows up as a removable drive ( on Windows, on macOS). Clone and copy : macOS (zsh): Badge not at ? Run to find it — some Macs mount it as or . Windows (PowerShell): Drive letter varies — check File Explorer if doesn’t exist. Add your own ROMs that you’ve dumped yourself and legally obtained. No ROMs are included or linked: macOS: drop any file into ( , , , , , , , , , etc.) — Finder drag-and-drop works too. Windows: same files into . Eject & play. Safely eject the drive (macOS: right-click → Eject or ; Windows: system tray → Safely Remove), pick NES from the MonaOS menu, turn the badge upside-down so the capacitive pad sits under your thumbs, and go.

0 views
James Stanley 3 weeks ago

Coding agents are the ultimate sandbox game

It turns out the Environment Agency have done a LiDAR scan of England . They provide point clouds with 1 metre lat/lon resolution, showing the measured height of the terrain at each point, across the entire country. They provide both a DTM ("digital terrain model") and DSM ("digital surface model"), where the DTM has been somehow processed to only tell you actual terrain, while the DSM tells you heights including vegetation and buildings etc.; there is also a combined point cloud that gives you DSM heights but includes a classification of each point to say whether they think it is ground or vegetation or a roof. James Nation recently posted a 3d reconstruction of Bruton Dovecote , using the Environment Agency LiDAR data to provide the shape of the surrounding terrain, this is how I found out about the LiDAR data. So this sounds like an incredibly powerful dataset, but what can we do with it? I started trying to just make a viewer so that I could explore the point cloud dataset and hopefully think of something cool to do, and you know how it is with LLM coding agents, one thing led to another and before I knew it I was flying a biplane around Somerset. Flight simulator This is a game using the Godot engine, plus a Python script that takes in Environment Agency point clouds and OpenStreetMap data, and constructs meshes of the terrain suitable for Godot. I currently only have a small area of the country, I'd love to do the whole thing but it is 60 gigabytes of Godot assets already. About 15 years ago I tried to play FlightGear , and found I didn't really get on with it. It was super slow on my PC, plus you have to spend a million years pretending to switch on magnetos and fuel pumps etc. before you can even fly the plane. I had much more fun playing GL-117 . It is visually a much less impressive game, but you get to experience the joy of flight with less faffing around. It has a crosshair controlling the "stick", and you basically just point the mouse where you want the plane to fly. So I copied that interaction model for my game. The ultimate sandbox game I realised while I was playing with this that the flight simulator is not the real game here. I briefly harboured the delusion that I was making a flight simulator that I might some day release, but I now realise that that is not what it's about. It's never going to be "finished". Adding things to the game and then flying around the local area is the game , for me. Treating it as a finished work that is just played as-is is missing most of the fun. Plus it's 60 gigabytes, and bulk-downloading the Environment Agency data is super inconvenient, they make you download it in 5km chunks and have some anti-bot stuff that makes it difficult (not impossible) for the LLM to download them automatically. All this stuff is just annoying for other people to have to deal with. (But apparently there is an easier way to get it ). So I think "finishing the game" and "releasing it" are not worthwhile. If you want to play the game I've been playing, start up your favourite coding agent and get started. The joy is in making your own. Traditionally a game involves a "gameplay loop", which is a sequence of things that take place within the game that are (intended to be) fun for the player. For example in Mario you run through the level collecting coins and avoiding enemies and trying to reach the end, and repeat that for every level. In my flight simulator the gameplay loop is to fly around in the game, have an idea occur to me, ask Codex to implement it, and then fly around some more now with the benefit of the cool new feature. It's a very personal type of gameplay. I also realised that a lot of the joy I have got from programming over the years has been this kind of "gameplay", it's just that before coding agents I had to focus much more on the programming and much less on the new ideas. 4 years ago I wrote in The future of virtual reality about this kind of thing being possible, although it isn't (yet?) playing out how I expected. I expected that you'd have some kind of AI-powered 3d world model that would behave more like an image generation model that you can walk around, and that the coding agent would have to do only a tiny amount of work in plugging together pre-existing parts. That's not really what's happened. Instead coding agents have been absolutely wildly successful, to the point that they just implement everything you ask for by hand and you don't need an AI involved at runtime. The biplane in the game is not even an asset I downloaded from somewhere, I just asked the bot for a cartoon-style biplane and it made me one. I didn't know whether it made a static triangle mesh or whether it was constructing it at runtime. (As it happens, it's made at runtime out of Godot primitives for spheres, cylinders, and boxes, with procedural shaders for fabric and metal seams). My flight simulator is still in the realm of "classical games programmed by AI" rather than "AI games" as such. I still think that an AI-driven world will be a material step-up in capabilities, but the required models don't exist yet, and end-user hardware wouldn't currently be able to run them anyway.

0 views
Blargh 4 weeks ago

Inspecting RustRadio and GNU Radio streams dynamically

When building software defined radio flowgraphs it’s common to want to inspect the live data as it flows through various stages. In GNU Radio, and RustRadio, the handoff points are very clear. They are the streams between the blocks. In GNU Radio you can stop the graph, click a bit in gnuradio-companion, and have a new time sink (or whatever you need) added, and then start the graph up again. But it makes for a lot of stopping and starting. There’s also the drawback that it assumes that the GNU Radio flowgraph is graphical in the first place, and not running headless on a raspberry pi somewhere. And for large graphs, preemptively adding GUI elements for everything you may possibly want to read at runtime can clutter things up, and waste CPU processing and rendering data you’re not interested in. Another use case is if you have a constantly running RF sniff process using an SDR, to get a second reader of the same data, to help develop the next version without shutting down the one already running. So clearly, what you want is to be able to connect to the flowgraph over the network, and start streaming any and all streams in the flowgraph. I showed a screenshot of this in my previous post . After adding the ability to sniff streams it looks about the same, but instead of needing to tee off every stream that may be interesting, and wasting the CPU resources when the UI is not connected, I’ve now changed it to sniff the streams by name. RustRadio has a pretty easy way to sniff the streams by name using , and add other stream metadata. E.g. this is most of the receiver for my IKEA sparsnäs decoder : But I’m not restricted to using a fixed UI. The RustRadio UI crate has an example UI application that can connect to anything, and lets you show a waterfall of any I/Q stream. When I told a friend of mine about this he thought it was very cool. Then he got disappointed when I said it was just for RustRadio, not GNU Radio. Well, let’s see if an LLM can make it happen. Yup, a few tokens later it works on GNU Radio too. Now, the code is probably not suitable for merging at all , but it’s just a demo. It’s fine if it’s throwaway code. Note the “IQ Stream Server” block, which can be used for dedicated sinks, and can also “import” all streams in the whole graph. My demo does not let me add the true sample rate, though, so imported streams get a default fake sample rate. I can query the available streams at runtime: And I can use the same example I/Q waterfall UI to plot waterfalls from this graph: There are more streams in that dropdown than there are blocks. That’s because the Channel Model block is actually a GNU Radio Python hierarchical block, and we’re seeing all the underlying blocks’ streams. Video demo: This is built into RustRadio , with the WASM-based UI code in rustradio UI . The vibecoded changes to GNU Radio are in this hooks branch , and then the IQ streaming blocks using the hooks in the hooks branch of gr-iqstream .

0 views

UUIDv7 doesn't have the properties you think it does

I’m going to call it. UUIDv7 is weird. Most blog posts about UUIDv7 tout these benefits: But none of these properties are strictly held. Certain RFC compliant implementations of UUIDv7 violate these properties to extreme degrees. The only useful property UUIDv7 appears to strictly provide is uniqueness and therefore collision resistance. I’ve already discussed how UUIDv7 IDs can be guessable , so this post explores the other properties. Superficially, it seems that embedding a timestamp in the ID can remove the need to track the creation time in a separate database column, providing marginally more efficient database operations. If you need to list things ordered by creation time very often, it’s useful if the primary index gives that behavior, removing the need for another index. Unfortunately, the timestamp embedded in a UUIDv7 ID may not relate to the object creation time. The Postgres docs for helpfully warn that “the extracted timestamp is not necessarily exactly equal to the time the UUID was generated”. RFC 9562 allows implementations to alter the timestamp field, using values that aren’t strictly derived from the system clock. This relates to the tension between UUID monotonicity and timestamp accuracy. In certain scenarios, the difference between the timestamp and the current time can be arbitrarily large. Implementations MAY alter the actual timestamp. — RFC 9562 §6.1 This specification makes no requirement or guarantee about how close the clock value needs to be to the actual time. — RFC 9562 §6.1 … implementations MAY increment the timestamp ahead of the actual time … — RFC 9562 §6.2 Incrementing the timestamp ahead of the system clock is an interesting problem. If the generator is seeing so much load that a counter field is regularly overflowing then the timestamp could accelerate into the future. Using a sufficiently large counter would be wise and the RFC says the minimum size SHOULD be 12 bits. A counter overflow would require a pretty aggressive creation rate, over 4,096 IDs per millisecond per node, which is beyond the limits of many systems. This overflow becomes relevant, however, if the timestamp freezes; which I’ll discuss in a later section. One prominent implementation that increments the timestamp is the Python standard library’s UUIDv7. The increment happens only in certain circumstances, like when the counter overflows. Unfortunately, the generator can get stuck in an increment cycle if the clock ever jumps backwards and the timestamp can race ahead of the system time by an arbitrarily large amount. Here’s a simple example: Which gives: We expect the difference to be 3600 seconds (one hour) as the implementation refuses to allow the embedded timestamp to jump backwards and we expect the difference to decrease as the system clock catches up to the frozen timestamp. But when the load is above one ID per millisecond the difference will increase without bound. At lower loads it will take longer for the system clock to catch the timestamp, but we don’t see the runaway effect. The related issue shows Python developers reasoning that this is consistent with the RFC, is consistent with other implementations, and that there isn’t “much we can do” on a “flawed system”. I think these points are correct as I see this same behavior in other implementations. Nevertheless, it would be helpful if existing UUIDv7 implementations could handle system clock jumps without runaway behavior. There are many real-world examples of clocks jumping backwards, even decades out of sync in time-sensitive environments. Embedding the timestamp in the ID means that you cannot share the ID without also sharing the timestamp. It’s pretty difficult to think of an example where this really matters. One example could be a user profile page that doesn’t disclose when the account was created, but the UUIDv7 ID in the URL leaks the high-precision timestamp. This issue would typically be very low on my list of security concerns because I find much more severe problems when I do security assessments. Nevertheless, there are contexts where this matters and engineering resources would be focused on addressing it. If you’re in the latter camp, be wary of UUIDv7 leaking metadata. This section is even more pedantic, so skip ahead if you’ve had enough. Briefly: UUIDv7 IDs provide some sort of rough order, which may be suitable for your requirements. When I was reading the UUIDv7 RFC I was surprised to see it describing a method for creating IDs across different nodes that are monotonically ordered. This was proven impossible back in the 1970s , and lead to the development of vector clocks and similar technology. At a high level, the problem is that system clocks cannot be synchronized to a suitable precision. Ordering things by timestamp only works if you know precisely what time it is. Any uncertainty in the time results in uncertainty of event ordering. Succinctly: Timestamps are only time-ordered if you know what time it is and you don’t know what time it is. For this reason, similar ID formats claim to be nearly sorted. It seems odd that UUIDv7 makes a stricter claim and does not deliver on them. At the very least, the challenges of synchronizing clocks across systems make the millisecond and especially the sub-millisecond timestamps quite suspect. But even on a single node, using a single implementation, UUIDv7 IDs are not strictly monotonic. The easiest way to get out-of-order UUIDv7 IDs is to use an implementation that uses a millisecond timestamp without a counter. This approach trivially generates out-of-order IDs inside a small for loop . So no, there’s nothing in the UUIDv7 specification that would ensure the IDs are strictly monotonically increasing. Specific implementations may do better than others (with sub-millisecond timestamps, counters, well-synchronized clocks, etc), but we’ve known since the 1970s that this problem is not strictly solvable. In UUIDv7’s favor, roughly ordered IDs are still quite useful. So don’t rip UUIDv7 out of your systems just yet. Just be wary of what assumptions you have. The RFC has lots of discussion about the handling of clocks that jump backwards. Timestamps are only time-ordered if clocks tick forwards, so special care is needed. We’ve already discussed one mitigation: tracking the last generated timestamp to ensure that an earlier timestamp is never used. To do this safely you’ll need to write the last used timestamp to persistent storage, such that you can read it again after a system reboot or a process restart. I’ve looked at several UUIDv7 implementations I couldn’t find one that writes timestamps to persistent storage. So implementers seems disinterested in addressing the issue and they generate out-of-order IDs when a process restart follows a clock jumping backwards. Looking at real-world clock synchronization problems, you’ll find many examples of clocks getting set to future dates . When this happens, the backwards jump would align the timestamp to the actual time, but a last-used-timestamp guard would force timestamps to use keep using that incorrect timestamp until the system clock catches up. If the system clock takes a long time to catch up, you may start experiencing counter rollovers. My mental model for UUIDv7 is that it’s a mash-up of a bunch of different ideas which implementations are free to choose as they see fit. There’s a wide variance of properties that UUIDv7 implementations can provide, with varying degrees of certainty they can successfully provide those properties. If you’re building your own implementation you can likely build something that has the properties you need. But most of us want to reach for an off-the-shelf version, especially when standard libraries provide an implementation, so we’re generally at the mercy of someone else’s implementation decisions. Implementations can change over time, making broad changes to their behavior while still being RFC compliant. Distributed systems may have multiple implementations across their subsystems, each with distinct properties. The only thing you can really expect is strong collision avoidance and ID uniqueness. Be sure to ask these questions when picking a UUIDv7 implementation: Unfortunately, this sort of analysis is much more difficult than building an RFC compliant generator. Authors of UUIDv7 generators may not know the answers to these questions and may themselves be surprised that the RFC does handle this for them. Hello! I'm Robert Alexander, a DevSecOps consultant available for contract work . This blog features some of my work and thoughts on software, the cloud, and security. You can subscribe to my posts with your favorite RSS client and follow me on Mastodon . If you'd like to show your appreciation and help support my writing, you can do so via this link. monotonically increasing IDs a helpful timestamp of when the object was created; and unguessable IDs Is the implementation compliant with the RFC? What additional properties does this implementation guarantee? Under what limits can those guarantees be met? Are there any assumptions required for these properties to hold, such as having an accurate system clock? Under what conditions will the implementation alter the timestamp? How guessable are the generated IDs?

0 views
Farid Zakaria 1 months ago

Always, sometimes, never

Exit 0 means your program exited 0. That’s it. That’s all it means. 🍞 I have been working on a deterministic VM called Rewind VM , where “a run” (i.e. test, command etc.) is a function of its inputs including the thread schedule. The determinism comes from the tool recording every step which lets you replay it exactly. This alone is a pretty good way to find flaky tests: run the test under Rewind, then runs it under many different thread schedules, with some slight latency added, and failures often crop up. 🐛 Feedback however was that it was not enough: the tool could find a failing schedule, but it could not tell you if that schedule was actually a bug. It only knew that the run ended differently than the original schedule, which could be a crash, a timeout, or just a different exit code. That is not enough to say “this is a bug”. Someone pointed out that I had built most of a property-based testing tool, but I only had one property: matching exit codes. What is property-based testing ? If you have used QuickCheck or Hypothesis , you have already used the idea. You write a property, or constraint, that must hold for every input. The tool generates lots of inputs, and when one breaks the property, it shrinks it down to the smallest input that still fails. already did the generating and the shrinking. The inputs are thread schedules, and narrowing shrinks a failing schedule down to the one step that causes the failure. The only property though was “the run ends the same way schedule 0 did”: the same exit code and the same outputs. That’s a pretty low bar, but easy to improve. 🙃 Rewind now lets specify properties that must be true for every run, or must be true for at least one run, or must never be true in any run. Let’s keep the bank from last time : two tellers deposit into one account from two threads, without a lock . This time the example is in Java as a JUnit 5 suite to appeal to my Enterprise brethren. 1 A teller that runs between the other’s read and store writes a stale balance over the other’s deposit. 💥 We include a “typical” test suite: one teller, two tellers concurrently, and a new account being empty. We run it and see all tests pass and head home for the day. 🍺 Is the code correct? Let’s use Rewind to dig further. Before even looking at the balance, Rewind knows a lot about what a run did . Every open, write, rename, close, fork and exit is in the trace, with the step it happened at. Rewind ships properties computed from the trace alone: Let’s throw a few at the bank and only run schedule 0: Interesting! writes its performance counters to 2 . It has nothing to do with our bug, but I included it because I learned something new and it could have been a bug if it did not include the process ID. The file properties shine for bugs between processes. The properties tutorial has a program that rewrites its config in place while another process rereads it. Its own test fails only when a read lands between the truncate and the last write, but flags it on the very first run. 😲 The bank’s real invariant is not in any syscall though. It lives in memory in our example: the balance variable must add up . For that there is the Rewind SDK , a tiny library you call from your program. Each call writes one line to , a device in Rewind’s VM, and the trace keeps it with the step, process and thread that wrote it. 3 must be true every time the program reaches it. is its opposite: a run that reaches it at all fails. These are your typical , except we get the whole replay if it fails. is the one I find the most interesting and tough to think through at times. 🤓 It tests the search: its condition must be true in at least one of the runs check tries, and it never fails a run. In model-checking terms, is a safety property (nothing bad happens in any run) and is a reachability property (some run gets there). Here it asks whether any run had both tellers inside at the same time. Look at the output above again: The suite passed under schedule 0, but one teller always finished its deposit before the other started. That pass told us nothing about the race. 🤷 Let try its default 64 schedules: That took 40 seconds on my laptop 4 and we found that two deposits went missing. The first line is the again: of the 17 runs check tried before it found the failure, 11 had both tellers inside at once. The fix is the obvious one: hold a lock from the read to the store. Every schedule passes, but is that enough to make us feel warm and fuzzy? The line is what gives me the warm embrace: in 42 of the 65 runs the tellers ran concurrently, but the lock prevented the bug. ✅ 5 A condition that is only true when the bug happens can never be true once the bug is fixed. 💡 Java developers though love writing JUnit tests. Fear not my FizzBuzzEnterprise colleagues, Rewind has you covered: the SDK has a JUnit 5 extension. Put on the test class and it marks each test’s start and result. If you can’t touch the code, reads the XML reports the runner wrote instead: Maven’s surefire, Gradle, pytest’s , whatever writes the format. The Rewind app shows the timeline of a run, with the tests and the build log. The failing test is red, and the event card names the assertion that failed. The strip under the timeline has a span per test: green passed, red failed. Each include a helpeful tooltip with the test name and the steps it ran. All the other Rewind features can then be used to help isolate the cause: the source panel, gdb on a fork at any step, the thread lanes and Check from here. There is a SDK for many languages already included in the Rewind repository. They are tiny, and the only dependency is the Rewind VM itself. The SDK is a single file or two per language, and you can copy it into your project. 6 The properties tutorial goes through each piece step by step, and the advanced tutorial has script properties and a file of properties to keep beside your tests for the more adventurous. If you happen to find any interesting bugs with Rewind let me know. I am keeping track of a small leaderboard of the best ones. 🏆 It is in the Rewind repository, next to the C version.  ↩ turns it off.  ↩ Outside Rewind the device does not exist and every call does nothing, so the calls can stay in your code.  ↩ The JVM is chatty: 148,479 steps for three tests, where the C equivalent takes about 4,500.  ↩ This counter must sit outside the lock. With , the second teller would wait before it reaches the counter.  ↩ The SDK’s README has the format instrunctions if you want to write one for another language.  ↩ C and C++ : , Go : and for Python : , and a pytest plugin that loads itself Java : and the JUnit 5 extension It is in the Rewind repository, next to the C version.  ↩ turns it off.  ↩ Outside Rewind the device does not exist and every call does nothing, so the calls can stay in your code.  ↩ The JVM is chatty: 148,479 steps for three tests, where the C equivalent takes about 4,500.  ↩ This counter must sit outside the lock. With , the second teller would wait before it reaches the counter.  ↩ The SDK’s README has the format instrunctions if you want to write one for another language.  ↩

0 views
Simon Willison 1 months ago

Hello Python 3.15, goodbye 3.10, and now I can use 3.11

Python 3.15 is here ! Here's the essential What's new in Python 3.15 guide, this year curated by 3.14 and 3.15 release manager Hugo van Kemenade. As someone who builds open source software that works in every supported Python version, I get to say goodbye to Python 3.10 and start embracing features from Python 3.11. First, some highlights from Python 3.15. I'm most excited about Explicit lazy imports from PEP 810 . These let you import modules like so: The module will then be imported the first time those symbols are used in the code that follows. My LLM CLI tool implements plugins. I had to recommend manual lazy imports in the plugin author documentation, because simply installing plugins that used heavy dependencies such as could add multiple seconds to every invocation of the command. Lazy imports directly address this startup cost. The new unpacking syntax is neat. Here's an illustration lifted from the documentation : PEP 798: Unpacking in Comprehensions by Adam Hartz and Erik Demaine proposed this as an extension of the unpacking syntax from PEP 448 , which landed in Python 3.5 back in 2015. Python's existing tracing profiler has been renamed from to profiling.tracing , and has been joined by an exciting new sampling profiler called Tachyon, aka profiling.sampling . Sampling profilers work by periodically capturing stack traces from running processes, then using those to calculate which functions have the most time spent inside of them. They're very low overhead and can provide a deep insight into running systems, without needing to instrument those systems first. I've previously used tools like py-spy for this. Now this capability is baked into the standard library. If you have the PID of an existing Python 3.15 process you can start gathering samples by running this (I had to use on macOS): Interact with the main program a bit, then hit Ctrl+C to stop gathering and see a report, which looks something like this: It can also produce flame graphs like this and heat maps like this , and can even output a format that can be viewed in the Firefox profiler UI. Miguel Grinberg investigated How fast is Python 3.15? the other day against the 3.15.0rc3 release and found performance to be mostly the same as 3.14, with the exception of the experimental JIT. The JIT gave a 1.2x boost over the standard 3.15 interpreter (on a Fibonacci test), the first time Miguel observed a meaningful JIT performance increase. Miguel's explorations of 3.14 last year found significant boosts against Python 3.13 across many more categories. I used the following sequence of commands to get to use Python 3.15 on my Mac. First I had to upgrade itself to ensure it knew about the new release: Then I installed the stable 3.15 release: And told that I wanted that to be the default for every command, unless the project itself pinned a different version: Now the following reports 3.15 as the version: I already have a bunch of tools installed using . I reinstalled them to use Python 3.15 like this: Then I can confirm the version like this: The release of 3.15 means that Python 3.10 (released in 2021) is officially no longer supported . My policy for my main open source projects is to keep them working in every supported Python version. I can now drop 3.10 and start using features that were introduced in 3.11. Here's the What's new in Python 3.11 document. I finally get to rely on tomllib being available! Datasette makes extensive use of . 3.11 adds TaskGroup and timeout() , and several more new features. is a new in 3.11 alias for . Python's SQLite support got some significant upgrades in 3.11, including: Plus a whole bunch of improvements to Python's typing system . I plan to land Python 3.11 improvements to a bunch of my projects over the next few weeks. Here's my first Datasette PR removing that workaround. I've also updated my click-app , datasette-plugin , python-lib , and llm-plugin cookiecutter templates to test against Python 3.11 through Python 3.15. You are only seeing the long-form articles from my blog. Subscribe to /atom/everything/ to get all of my posts, or take a look at my other subscription options . setlimit() and getlimit() expose a mechanism for setting SQLite runtime limits from Python. create_window_function() lets us create custom window functions in Python, as a class with , , , and methods. blobopen() provides an efficient mechanism for partial reads and writes of large binary values stored in a SQLite row. You can now call to remove a SQLite authorizer. Datasette had a workaround for this!

0 views
Shayon Mukherjee 1 months ago

A versioned filesystem for disposable sandboxes

livedraftsandbox 1$ python sync_leads.pysandbox 2$ node enrich.jssandbox 3, days later$ python report.py41424344reads 43branch/mainfork, nothing copiedbranch/drafta sandbox on the draft$ python score_v2.pyEach sandbox commits a new snapshot to the volume, live keeps moving forward, and a draft forks off snapshot 43 without copying anything. At Tines we built 3B around a simple idea, which is that every step in a workflow is a computer. A step’s code, whether a person or an agent wrote it, runs inside a fresh Linux sandbox that gets its credentials through a proxy, does its work, and then gets thrown away so no leftover state can cause security issues later.

0 views
Nicky Reinert 1 months ago

System Monitor Widget for iTerm2

Did you know that you can build your own toolbelt-widgets in iTerm2 ? What’s iterm2 anyway? It’s one of the most powerful if not the most powerful terminal emulator for macOS . It’s neither bloated, it’s free, it feature-rich and I am a huge fan of it. However, there is this cool feature called “ Toolbelt ”: A sidebar with a colection of small productivity tools… notes, code snippets, history… but one thing is missing. something most admins and sysop-dudes and dudesses probably need occasionally or regularly: a system monitor widget . And iTerm2 supports custom widgets using Python ! So I built my own system monitor widget for the toolbelt and it has a lot to offer: There is a lot of interactivity. You can click process to see further details or “focus” on a specific process to see only this processs network activity, disk usage and cpu utilisation. It’s open source: https://github.com/nickyreinert/iTermSysMon And installation is quite easy: Put the Python-file into this folder: (Create if not existing) Restart your app or do to open iTerm2’s “script monitor” where you can reload custom scripts (and watch their output). CPU and memory usage, splitted into CPU usage per kernel and memmory usage splitted into usage per type (used, swap, cached, free) of course a list of running apps, processes and services of course a network usage overview showing processes’s up- and download, including per-process request details of course a list of open ports and the services listening on them of course a disk activity monitor showing what files are being touched, modified, created and so on a watch list for folders and their sizes - to keep track of where your disk storage is being used, allowing you to clean up cache, temp or folders easily

0 views
Simon Willison 1 months ago

A new feature for my blog, built using my voice

I shipped a new feature for my blog today: the Newsletters page, which offers an index of all of the newsletters I've sent out, both my free weekly Substack and my monthly sponsors-only updates. I built the feature almost entirely using my voice, chatting away to my laptop while I cooked dinner. I used the ChatGPT desktop app for this, in the Codex tab, using the voice conversation mode, running against a local development environment. Here's what that looks like: I started the session against my local simonwillisonblog checkout by typing: This gave me a preview of the site that it would be working on, and meant that I could later ask it to show me the new pages so I could visually track its progress. Then I clicked the "Start new voice chat" button - that's not the microphone button, it's the one to the right of it - and set my laptop up in the kitchen so I could talk to it while I cooked. I had a pretty good idea of what I wanted to build, and it's a simple enough Django feature that I was certain the model (in this case GPT-6 Astra High) would be able to do it. A new model, a migration, some view code, templates, and a couple of import functions to populate the database from external sources. Here's an extract of my voice transcript that was captured by Codex: Um, they do not. Um, this is going to be a new type of content. Um, it's not going to show up... Oh, hold on. Yeah, no- I do not want this to show up in my, um, tag pages and date archive pages and... Actually, no, I think... I don't want it on the tag pages. I don't want it on the, um, blog index page. But I think I do want it to show up on the date-based pages. You know, if you navigate to September the 19th, and I sent a newsletter on that page, I think I want that to show up. So... this is- so I think we probably need a new model. The other thing is that I want them searchable, uh the Substack ones are not searchable, because those are actually just copies of other s- on content on my blog. These monthly ones do contain unique content, and spe- and once they're... published, like once they're made public a month after they've gone out, I want them to show up on my search results. Apparently this was clear enough that the model knew what I wanted to build! You can read the full transcript, disfluencies and all, in this Gist . We went on like this for about half an hour (the time it took to cook dinner). The model would reply and occasionally ask clarifying questions, then get to work modifying the code. We got a surprisingly long way entirely by voice: It was almost ready to ship. The catch was the imports: Astra offered to export data from my local copy so I could import that into production, but I wanted it to work like my other import scripts. Since some of the data lived in a private GitHub repository, this would involve creating a new API key, and for that I knew I'd have to sit at the keyboard for a while. Once I had finished cooking and judged it mostly feature-complete, I had Codex create a branch and open a pull request. I reviewed the code in the GitHub PR interface. It was nearly what I needed, except it had chosen to use Git in a subprocess for one of the import scripts. I needed one of the imports to pull from a private Git repository, so I figured the API would be a better bet. I switched to typing and had Codex swap that out for an API-based import instead. You can see the changes I made during the review in the extra commits on the PR . I fixed the import mechanism and made a few tweaks to the display of those public pages. It took an additional half hour of typing-based prompting to get to the point where I was happy to deploy it to production by landing the PR. You can see the end result at the new newsletters index page , or view the page for a previous monthly newsletter . The index page shows my most recent Substack weekly newsletters and GitHub sponsors monthly newsletters mixed together in reverse chronological order. Further down the page are links to my by-year archive pages. GPT-6 Astra designed the page, and then tweaked that design based on my vocal feedback from glancing at the local preview across the kitchen. OpenAI love using voice-driven demos like this one for things like DevDay - and they do work well in that environment. I don't think this is going to be a daily driver for me though. I've written before about how much "work" I get done using ChatGPT voice mode on my phone while walking the dog - mostly research and brainstorming, but occasionally actual development work by having ChatGPT write and test out snippets of code. This feels different. The addition of the visual preview, plus being able to type or paste things in via the keyboard when I need to communicate something that doesn't work vocally, makes this a much more powerful way of interacting with a coding agent. I still switch back to typing once I get down to the details of things though. Being able to paste in examples and error messages, or directly highlight the code or feature that needs changing, remains more efficient than trying to describe it in words. I mainly work from home, which is good because there's no way I'd want to talk to my computer like this in a shared workspace! The killer feature for me is the ability to multi-task. I usually cook with a podcast or TikTok running; now I can actually build stuff instead. You are only seeing the long-form articles from my blog. Subscribe to /atom/everything/ to get all of my posts, or take a look at my other subscription options . A new model and migration to represent imported newsletters in Django, plus Django Admin configuration for that Four working imports: The most recent Substack items via RSS Every other Substack item via their undocumented API, which GPT-6 Astra knew about (it tried directly) and then ran a search to figure out how to paginate it and found this article by Karen Spinner All of my published monthly newsletters from my simonw/monthly-newsletter-archive GitHub repository My most recent private sponsors-only newsletter from a private repository The /newsletters/ and /newsletters/2026/ public archive pages Newsletters showing up on day and month archive pages too, but not on tag pages or my homepage Weekly Substack newsletters link to Substack; archived monthly newsletters have their own pages Integration with my site search engine

0 views