Posts in Python (20 found)
Farid Zakaria Yesterday

Programming languages are for humans

tl;dr borrIR is a borrow checker, a zero-libc standard library ( ), and a bitcode package manager for raw LLVM IR. Try it live in the browser playground , and commit yourself to the agentic engineering way of life . Welcome AI disciples. This post is for you. We are just past the year mark when Opus 4.5 was released on November 24, 2025, when the way in which we craft and generate code changed overnight. We ushered in the era of agentic coding , where AI agents can autonomously generate, modify, and reason about code with minimal human intervention. Despite the loss of joy that comes with knowing the codebase inside and out or bickering with my friends about esoteric language features, there is no denying how much more prolific I have become by embracing the agentic engineering way of life . With the blindfolds on, the language du jour seems to be Rust for our dutiful clankers. Anthropic even made a large splash at how they rewrote their whole messaging system from Python to Rust [ cite ] for those sweet sweet performance gains. After numerous projects coded 100% by agents, where I have had 0 insight into the code itself: why are we even bothering with a language at all? Rust seems like a reasonable choice but it has its fair share of criticisms: complexity, slow compile times, and everyone seems to enjoy complaining about the generated build artifacts. Of course the popular opinion now is that the compile-time verification of Rust from the borrow-checker is what gives it the appeal. Coupling provable-verification with the stochastic reasoning of AI agents seems to be the current trend. Hear me out: a borrow checker does not require Rust. To commit to the agentic engineering way of life, we need the implementation to be so low-level that you are disuaded from even looking at it. We need the LLM agents to code directly in assembly, but not any ordinary assembly. We need a form of assembly that carries enough type information to allow the agents to reason about memory safety without human intervention. We need LLVM IR as our assembly language, with a borrow checker built on top of it . I built borrIR . It is a borrow checker for LLVM IR, designed to enforce memory safety at the assembly level. Check out the playground for an interactive demo. Wtf did I just build? 1 is a static analysis pass that sits in front of (assembler for LLVM IR). It parses textual LLVM IR (or disassembles bitcode via ), builds each function’s control-flow graph, tracks pointer provenance, and runs a forward fixed-point dataflow analysis to enforce affine ownership. All the fancy stuff Rust’s borrow checker does, but at the LLVM IR level. Here is the same use-after-move bug in Rust on the left and raw LLVM IR on the right: We can then run on the LLVM IR file and get a diagnostic equivalent to what Rust’s borrow checker would produce for the same use-after-move bug. Aside For those wanting the juicy compiler details: borrIR gets Non-Lexical Lifetimes (NLL) almost for free. In early Rust a borrow lasted until the closing of its scope, even if you never touched the reference again. Fixing that meant inventing MIR so the compiler could track where each reference was last used. LLVM IR has no scopes to begin with. Simplicity wins. As of the first release, the checker reports eight error classes ( – ) and one warning from use after move to laundering a pointer through . You can see the full list of error classes and the warning on the borrIR documentation . In the pursuit of pure blind agentic engineering zeal, I decided to abandon all libraries that might have been generated by higher-level languages and rely solely on our verified LLVM IR modules. includes a set of verified LLVM IR modules for common low-level operations, , such as memory allocation, I/O, and string manipulation, all of which pass the borrow checker itself. Think of these as the replacement for the standard libraries you would normally get from C or Rust: and friends. No , no , no dynamic linker. The binaries produced by this pipeline are fully static ELF executables, with no dependencies on or any other external libraries. They are incredibly small and self-contained, and the build process itself produces very little overhead or intermediate artifacts. Aside You actually have to ask LLVM to disable passes such as , otherwise LLVM will happily rewrite your hand-written loops into calls to standard library functions, which then fail to link if you don’t have . There is even a package-manager built into for handling pre-assembled packages, making it easier to share and reuse verified LLVM IR modules. Details are unimportant for this post but suffice it to say that we can build a complete ecosystem purely out of verified LLVM IR modules. This has been a nagging thought bugging me for the last few months as I have gotten more-and-more comfortable with having projects purely written by an LLM agent. I already trust the compiler to turn whatever language I write into correct, optimized assembly, and I never read that output. Having the agent write LLVM IR directly is the same trust, moved one layer up. The borrow checker is what makes that trust reasonable. It is a safety net for me and a feedback loop for the agent. Ownership is checked one function at a time, so the agent does not have to hold the whole program in its context to know who frees what. Try breaking the borrow checker in the live WebAssembly playground , or poke around the repo and run . Programming languages are for humans. Nobody asked the clankers if they wanted one. Yes, I am using I in the sense of “I, the author, built this tool.” even though it’s 100% LLM-generated code.  ↩ Yes, I am using I in the sense of “I, the author, built this tool.” even though it’s 100% LLM-generated code.  ↩

0 views
Max Woolf 2 days ago

Opus 5.5 and Fable 5.2 made my overoptimized Rust code even more overoptimized

I like fast software. I like very fast software. A couple months ago, I published a blog post titled Writing Rust code that’s faster than state-of-the-art libraries by asking agents to make the code faster in which I listed techniques for using agentic LLMs to speed up the runtime execution of Rust software—of course, with extensive checks and balances to ensure good code quality, avoid regressions, and mitigate cheating by the LLMs. After enough iterations, the resulting Rust libraries are faster than existing state-of-the-art implementations with the same or better capabilities, even against those already written in Rust. The main bottlenecks for me open-sourcing the resulting Rust crates are a) doing comprehensive real-world testing to ensure the code works as advertised and b) I don’t want to release the code and then have another model release immediately find another 2x-or-more speed boost because that would be embarrassing. I’m not satisfied with my code merely being faster than state-of-the-art: I want my code to push against hardware limits even for “fun” software that may not require maximum throughput. I don’t want my benchmarks to be measured in milliseconds, I want them measured in microseconds , dammit. Who knows if some application in the future will require submillisecond word clouds or submillisecond ASCII art generations? In that blog post, I mostly used OpenAI’s GPT models for this agentic iteration pipeline. The day after publication, Anthropic announced Claude Opus 5.5 , which was met with skepticism as Opus 5 was underwhelming…and then it quickly turned out that Opus 5.5 was a step-change increase in the capability of agents with the ability to complete difficult technical tasks that neither OpenAI’s nor Anthropic’s other models could complete. I spent the $20/mo to try out Opus 5.5 on my agentic iteration pipeline after observing the hype…and after only two days, the results were impressive enough that I paid the $100/mo to get more usage quota. Through more testing over the past couple months, I can confidently say Opus 5.5 and its subsequent Fable 5.2 sibling did in fact result in significant performance breakthroughs that indeed push my Rust software to its limits. Lest people think that this post is an undisclosed #ad for Anthropic, I had grievances with Claude Code prior to Opus 5.5 which were the primary reasons I switched to OpenAI’s Codex . One such example is Claude ignoring AGENTS.md in favor of CLAUDE.md ( until very recently ), which was honestly petty enough to tip the scales. The main grievance with using Claude Code is deciding which harness to use—or, rather, the lack of decision. Although I was fine with using Claude Code in the terminal back in the halcyon days of Opus 4.5, Codex’s ability to use any harness, such as Zed Agent which allows using the Codex subscription natively, made it more convenient to keep everything in one place. In contrast, Claude Code infamously blocks third-party harnesses and has closed workarounds used to access it regardless. Therefore, I had to consider workarounds for using Opus 5.5 in a way that doesn’t require significant changes to my agentic iteration pipeline. Zed Agent has a workaround to use Claude Code by following the Agent Client Protocol , but there was a problem due to how Claude operates: Opus 5.5 loves spinning up background tasks and working asynchronously, and Zed Agent had poor support for background tasks so I had little idea what the agent was actually doing. This was made worse by Opus 5.5 never editing code files using Edit tools; instead, Opus 5.5 likes to write Python files which surgically find/replace the code. I tried using the Claude Code terminal application again but that made the ergonomic issues above even more difficult to manage. Claude editing a Rust file by writing a Python script. That said, the async nature can save time when spinning up subagents (in this case Haiku 5.5) to review the changes made, as the main Opus 5.5 agent can write code or run long benchmarks while the subagents simultaneously do their nonblocking review work. Therefore, my main harness for my Opus 5.5 work was the standard desktop Claude app —which will likely eliminate all my AI engineering street cred, but it is what it is. In addition to clearly listing background tasks in progress, the native app also lists current session and weekly usage which was a pain to constantly check when using Zed Agent or CLIs. Background task sidebar in the Claude Code desktop app. There are also two more usability perks of using Claude Code within the desktop app: images always appear inline when the agent reads them so I can tell specifically what the agent is reading, and Remote Control is unexpectedly useful for letting hours-long prompts run while I’m doing other things such as job hunting and touching grass (but failing because I really wanted to know how well the code is running). At first, I fed Opus 5.5 my updated Ur-Prompt for agentic iteration—typically a prompt with an explicit directive to improve the speed at which the benchmarks run by at least a specified amount without either causing regressions or cheating the benchmark results. With this new model (and a few tweaks to my AGENTS.md to address some peculiarities with Claude), that approach indeed worked, and in a single pass, Opus 5.5 achieved 1.2x - 1.5x speedups on multiple distinct projects which had already been optimized with GPT 6.1 Astra. That said, there are a few quirks with how Opus 5.5 works such as prompt queueing: with Codex/Zed Agent, I could queue a prompt such as such that it would only be sent to the agent after it was done with the current prompt (important as it is deliberately asymmetric information as telling someone to do a breakthrough while they are still working is counterproductive), but with Claude Code it will send any queued message when idle, e.g. while it’s waiting on background tasks such as benchmarks and subagents. My silly workaround to this behavior was to put in a Markdown file in another folder outside of the current environment (so Claude can’t accidentally find it when it examines the environment), then add to the prompt: This works, and Opus 5.5 indeed does not cheat by reading ahead of time, and the breakthrough commands do result in actual breakthroughs. One issue I have with Opus 5.5 is that it definitely writes more lines of code than the GPT models: in the case of Rust that’s not necessarily bad performance-wise since it’s a compiled language but it adds more technical debt than I would like. For example, many of my Rust projects rely on PNG image encoding and decoding through Rust’s png crate. However, when Opus 5.5 was instructed to make improvements on benchmarks where PNG processing is on the hot path, it consistently creates its own bespoke PNG module from scratch (with parallelism/streaming better-aligned to how the base code processes the data) that does achieve the desired 1.2x - 1.5x speedups without causing any regressions, so I’ll begrudgingly accept it. I very frequently run maintenance passes and even then it struggles to do so. Another issue with agentic iteration work specifically is that Claude Code obfuscates how it runs benchmarks. When running benchmarks with criterion , instead of displaying the benchmark results as they come in, they’re piped to a temporary file so I can’t view intermediate progress. It also doesn’t return results from the benchmarks until after they’ve concluded, despite my prompting explicitly asking it to, so I have to twiddle my thumbs a bit (again, good for attempting to touch grass). Agentic LLMs have mostly become homogenized in terms of how they work through their turns, with the difference between certain LLMs coming down to benchmarks which may be gamed, or worse— vibes . Overall, I have to give more trust to Opus 5.5, which I have mixed feelings about. That said, the trust has been rewarded, particularly with new approaches I found where Opus 5.5 excels where GPT models did not. In my prompts, I always added a suggestion about leveraging process profiling that the GPT models mostly ignored: Opus 5.5, in contrast, is extremely eager about profiling with samply to find the areas where code spends most of its time executing and will often do so as its first task, including reprofiling after each change to find changed hot paths for further improvements. Opus 5.5 profiling a Rust crate with a somewhat inscrutable command. Opus 5.5 also spends more time running experiments whereas GPT models edit the code first then ask questions later; both approaches have their merit but I think Opus 5.5 is more productive at it. While working on making my Rust software super-fast, I never put much thought into how much system memory it utilized. I figured it was unnecessary since a) Rust is already extremely memory efficient and b) writing to RAM beyond what is needed causes wasted system overhead which would inevitably be caught by the existing prompts to make the software faster. I was wrong. Very wrong. If I could get a ~20% reduction in peak memory without much code complexity change, then maybe it’s worth pursuing. Therefore I gave Opus 5.5 a simpler-than-usual prompt because I was too apathetic to prompt engineer it: The results on a couple projects: Memory decreases on my Rust HDBSCAN /clustering crate after the prompt. Memory decreases on my Rust text search project (in-memory, not CLI). I immediately used the same prompt on all my projects and achieved similar significant peak memory reductions (doing a second pass with resulted in even stronger reductions). In general, it achieved this through the traditional tricks used to explicitly manage memory such as streaming data and smarter specification of sizes. That said, I had hoped that this approach would result in speed improvements (i.e. the agent discovers an algorithm has no viable memory improvements and therefore it implements a better algorithm) but significant speed improvements were rare. Another hyped aspect of Opus 5.5 is its ability to better handle visual design and avoid the typical “AI Slop” aesthetic when designing web applications. This capability may not intuitively translate toward maximizing the speed of my Rust software, but it’s crucially important to balancing both speed and quality for my applications that rely on visual design, as visual design isn’t always subjective and “it looks ugly” can be a legitimate software regression. In my initial post about agentic iteration, I described implementing a UMAP algorithm with this approach, as UMAP is a useful-for-me dimensionality reduction algorithm (among many) that when used to project to 2D, it can automatically create intuitive visual clusters. Images of Digits clustered via umap-learn. via umap-learn docs In my original post, I noted that the Python bindings of my Rust UMAP algorithm beat umap-learn by 4x - 15x after several agentic iterations. Although it excelled at all the typical quantitative benchmark metrics, my UMAP algorithm apparently failed the most important benchmark: vibes. The visual clusters in cases such as the famous MNIST dataset of digit images were not semantically distinct compared to existing implementations such as umap-learn, PaCMAP , and TriMap : The Python bindings of my UMAP crate (top-left) are indeed ~12x faster than but that doesn’t matter if it produces indistinct clusters. So I asked Opus 5.5 iterate specifically to improve cluster distinctiveness compared against for the known good implementations while minimizing the speed tradeoff, along with making more apples-to-apples fairness tweaks: Download the video . Opus 5.5 also made the head-to-head video, which is unexpectedly hypnotic. The speedup relative to fell to about 4x, but cluster quality is very comparable now and 4x is still a good speedup. Another visual-oriented project I’ve been working on since Opus 4.5 is the fast and accurate automatic conversion of images from raster files to vector (SVG) files that can scale to any size. This isn’t a new concept: tools such as Inkscape that convert images to vectors/SVGs have been around for awhile. Rust itself has vtracer and img2svg , but I wanted to see if I could beat them not only in speed, but also a) visual fidelity between the vector and raster and b) output SVG file size, which requires deriving fewer and more efficient SVG Paths and Bézier curves . Take for example, this image of a pelican riding a bicycle. That is what everyone talks about with AI, right? A 393KB vector-art-style image generated with ChatGPT Images 2.5. Don’t think too hard about its left leg. This test case is deliberately tricky for raster-to-vector algorithms as pelicans are very curvy. Running the image through with default settings results in a 153KB SVG that’s unusably blocky. Prior to Opus 5.5, running the image through my Rust crate that went through the GPT agentic iterative optimization pipeline resulted in much better output than / for my crate, but still had enough errors such as color blotches and jagged “staircases” that were easily identifiable and would make the output vector SVG unusable, so I shelved the project entirely. Opus 5.5 in contrast is eager to zoom into the image, find staircases, construct comparison grids and image diffs, fix the underlying algorithms, and repeat until it’s fixed. Opus 5.5 iteratively examining output SVGs by creating comparison matrices of test outputs. With the guardrails and repeated Opus 5.5 iterations, my approach to raster-to-vector finally beats the existing options by considerable margins. For this pelican example, my crate beats both and in all of speed, size, and error. Here’s the pelican SVG output from the crate, reduced from the stated 25KB to 14KB after passing it through a separate SVG compression/refinement tool I also created and optimized with Opus 5.5 using similar techniques: It’s not 100% perfect but you really need to zoom in to see the defects. This pipeline has worked well with my other test images, but it still needs more real-world tests before I will release it. Yes, we’re going there. The release of Opus 5.5 specifically led to a new age of reverse engineering software using LLMs, from Reverse Engineering Anything allowing reverse engineering anything (duh), to drastically speeding up decompiling games . For my work making software as fast as possible, I didn’t read too much into it until I randomly saw one of my reasoning traces run objdump to try and figure out why a change did not result in an expected speed increase. So as an experiment, I gave this as a part of a dedicated variant Ur-Prompt in its own pass (since Opus 5.5 may avoid disassembly unless you specifically constrain it): The effectiveness of this approach legitimately surprised me…but don’t ask me to explain what’s happening. Speedup after a disassembly optimization for a Rust graph network crate. Speedup after a disassembly optimization for the Rust UMAP crate (w/ the visual constraints persisting). Somehow, Opus 5.5 is smart enough to make Rust code changes that propagate through LLVM to the resulting binary with fewer instructions without causing regressions—I would have called that impossible a year ago. One potential weakness of this approach is that it may overfit to specific hardware (my M3 MacBook Pro / ARM architecture) but the diffs appear to be more architecture agnostic. At the very least, it intentionally doesn’t write custom CPU instructions in Rust itself because doing so requires . You may have noticed I haven’t talked about Fable 5.2 yet despite giving it equal billing with Opus 5.5 in the headline. Fable 5.2 was released a couple weeks ago and its benchmarks were…ok. Not much better than Opus 5.5 on paper especially below effort, but much more expensive. I had spare quota, so why not put Fable 5.2 (on effort) through the same paces I did for Opus 5.5? I fed it the Ur-Prompt (and bumped the research subagents to Opus 5.5), and Fable 5.2 did not achieve the 1.2x - 1.5x speedup consistent with each successive model release. Fable 5.2 instead achieved a 1.5x - 2.0x speedup on many of my projects. Massive speedups for my word cloud project in both text parsing and generation. Given the benchmark results, I don’t get it but I am very much not complaining. One tool I’ve been experimenting with (particularly in this very post) but never talked about due to potential accusations of heresy is a next-generation grep replacement that is faster than the beloved ripgrep , but with additional features; this new Rust crate named byteseek . ripgrep, itself written in Rust and optimized for over a decade, is tough to beat speedwise without shenanigans, however Fable 5.2 was able to find massive speedups on synthetic benchmarks in-memory. Also massive speedups for byteseek; this is after I told Fable 5.2 to . ripgrep itself uses real-world datasets to benchmark (Linux source tree and English+Russian OpenSubtitles; Russian tests UTF-8) and does the benchmarks via the CLI which has significant overhead from opening files for scanning not present with in-memory benchmarks, so I ran an apples-to-apples CLI benchmarks comparing the two on both synthetic and real data: byteseek particularly excels at alternation/multiple query terms and case-insensitive searches. BTW I am also developing a new scientific data visualization library in Rust and wanted an excuse to dogfood it. Given the likely skepticism about its performance, I am officially open-sourcing byteseek on GitHub early as a research preview to demonstrate just what this type of overoptimized Rust code looks like. Since I have the speed headroom to do so, I also added more features such as pretty-printing output for humans, jq -like JSON searching (plus YAML/TOML), fuzzy and predicate matching, and Python bindings which unexpectedly beat the optimized pyahocorasick and orjson . A ripgrep-like output with but with more information and more pretty . In all, this is my new agentic iteration pipeline: The Opus 5.5 pass Typically done using my updated Ur-Prompt , with various constraints tweaked depending on the problem. (e.g. the target metrics for optimization and regression mitigation) The Opus 5.5 peak memory reduction pass Simple prompt, if there is a significant speed increase that implies performance has not converged. The Opus 5.5 disassembly pass Done with a dedicated variant Ur-Prompt , if there is a significant memory reduction. The Fable 5.2 pass Same as the Opus 5.5 pass, although I bump the subagents to Opus 5.5 to better match the model’s power. The (optional) Fable 5.2 disassembly pass …if I have Claude Code quota to spare: Fable only being able to be used for half of the Claude Code weekly quota is a bummer. My Rust software that I had already optimized with GPT-6.1 Astra now achieves a cumulative 4x speedup on average with much lower memory utilization, and this was reproducible across multiple projects. My word cloud generator—where I was overly excited about hitting 1 millisecond generation—now generates in 374 microseconds. This also generalizes to projects where speed is more meaningful, such as my Rust statistical modeling library and my Rust data visualization library. Per Opus 5.5, the performance for most of my Rust projects have now have hit theoretical hardware limits. Therefore I have little reason to continue procrastinating as new models likely won’t make the code meaningfully faster, so I should hopefully be shipping more quickly. That said, marketing the Rust projects has become increasingly difficult since my original post for a number of reasons, but that’s a discussion for another blog post. In the meantime, I should learn how compiler optimization in Rust actually works as there are likely more significant code speedup opportunities there… The Opus 5.5 pass Typically done using my updated Ur-Prompt , with various constraints tweaked depending on the problem. (e.g. the target metrics for optimization and regression mitigation) The Opus 5.5 peak memory reduction pass Simple prompt, if there is a significant speed increase that implies performance has not converged. The Opus 5.5 disassembly pass Done with a dedicated variant Ur-Prompt , if there is a significant memory reduction. The Fable 5.2 pass Same as the Opus 5.5 pass, although I bump the subagents to Opus 5.5 to better match the model’s power. The (optional) Fable 5.2 disassembly pass …if I have Claude Code quota to spare: Fable only being able to be used for half of the Claude Code weekly quota is a bummer.

0 views

Protect Your Web Forms Against Spam Bots

The comments form that appears at the bottom of every article in this blog is under constant abuse by spam bots. I added a CAPTCHA to it a few years ago and at the time it seemed to help some, but spammers have now figured out how to bypass them. As a result, my comments inbox has been getting out of control lately. In this article I'm going to share a solution that I built to help me reduce spam on this blog from 30-40 messages per day to just about 2-3 per month. It is based on the " proof of work " concept, and unlike CAPTCHAs, it does not rely on third-party services. It is also better for users, because it does not require them to solve silly puzzles or even know that they are being verified. I have implemented the solution in Python and Flask, because that is what this blog runs on, but once you understand how it works you should have no trouble porting it to other languages or frameworks.

0 views
Blog System/5 4 days ago

Entering the Geminispace

On May 1st, 2020, Project Gemini made the rounds for the first time via a Hacker News discussion thread . I remember seeing the announcement back then, barely a month after the Covid 19 worldwide lockdown, and thinking it was a cool gimmick. But that was that. However, I’ve recently been seeing a few links here and there as footers in hand-crafted blogs, and I nerd-snipped myself to export this blog as a Gemini capsule that you can find at . The process has been fun, and I actually quite like the extreme minimalism of the resulting site. So what else would you expect from me? I had to write about it—hence this post. Today we’ll learn a little bit about what Gemini is, how I approached the blog export to its native gemtext format, and I’ll confess a couple of… sins I committed along the way. A terrible name, that is. Looking for information about Gemini these days is extremely hard, thanks to Google polluting the namespace with its own AI offering. Of course that’s not Project Gemini’s fault because Google’s thing came after them, but still, good luck finding stuff about this network. Joking aside, let’s look at Project Gemini’s barebones front page: Project Gemini's front page, displayed in the Lagrange browser. … and break down the introductory and only paragraph: Gemini is a new internet technology supporting an electronic library of interconnected text documents. You can think of Gemini as a way to access a bunch of text-only pages, with links among them, so you can find information and follow links to additional resources. Instead of using or URL prefixes, you use instead. That’s not a new idea, but it’s not old fashioned either. Exactly. Gemini is like the WWW , or “the web” in more colloquial/modern parlance. In fact, Gemini is a parallel community to the web. Obviously, that’s not a new idea because the web dates back to 1989, and we are now 37 years after that. The idea is not unique either because Gopher , a much lesser-known option, exists as well. Surprisingly to me, I realized that Gopher came after the web in 1991 while researching this article. I had always assumed Gopher was first and that the web came to replace it because of Gopher’s rigidness. But that’s not quite what happened. It’s timeless, and deserves tools which treat it as a first class concept, not a vestigial corner case. Humans have shared written documents since around 3400–3100 BCE (roughly 5,100–5,400 years ago) in ancient Mesopotamia and Egypt, and that’s probably (hopefully?) not going away. It’s true, though, that at this point, text sharing is not the primary thing that the web does, as you well know. We have morphed the web from a document distribution tool into an app platform, for better or worse. A little confession: I worked at Google for 12 years, starting right at the time they published Google Wave (2009), which to me marked the start of truly interactive web apps—more so than Gmail (2004) did. In the back of my mind, I knew I was helping turn the web into how we run apps, destroying the traditional desktop paradigm—a feeling I never liked. And… it happened. Obviously, it’d have happened without me, a little pawn in the game, but it bothered me regardless. Gemini isn’t about innovation or disruption, it’s about providing some respite for those who feel the internet has been disrupted enough already. (That comma splice hurts.) As we have established earlier, Gemini’s ideas are not new, so it’s indeed not innovative. And seeing how little people read these days, or even how unable to pay attention to long-form text they are, it’s not going to disrupt anything either. But respite is key: having a separate place where you know you’ll only find some sort of counter-culture sounds entertaining. Fun fact: I wasn’t quite sure what respite meant and originally took it to be similar to spite. That meaning would have worked equally well here, if not better? We’re not out to change the world or destroy other technologies. We are out to build a lightweight online space where documents are just documents, in the interests of every reader’s privacy, attention and bandwidth. Here is the interesting thing. Gemini claims that it has been designed to minimize the chances of becoming bloated, and I’m not exactly sure how you can prevent that. For example: articles can provide links to images, but images are not auto-loaded. OK, says who? The auto-loading part is something the client browser controls, and it’d be trivial to create a Gemini browser, or modify an existing one, to auto-load and render images. That’d go against the spirit of Gemini, but if enough people wanted it, it’d happen. Same story as the browser wars . And that’s the key: “enough people”. As long as Gemini stays under the radar and only like-minded people gravitate towards it, these properties will be maintained. But if for any reason it becomes more mainstream… unwanted changes will happen. Enjoying so far? Please take a moment to show me by subscribing to Blog System/5. It’s free! Gemtext is the native format of documents stored in the Gemini network, with a MIME type of and a extension. Gemtext documents are typically grouped in capsules —which is just another name for “website”. The format itself is like a super-diluted version of Markdown, supporting just these features: Three levels of headings. Paragraphs. Links as standalone lines, not as inline text. Preformatted text blocks, also not as inline text. Unordered lists. Blockquotes. Workable for sure, but weak. In my opinion, Gemini missed the boat of creating a truly semantical web, but for that you need additional primitives to represent more concepts. In any case, you can read through the long FAQ to know that this was discussed and eventually ruled against, so know that a lot of thought was put into its design. Yet another fun fact: just two days ago, I stumbled upon “Good morning and welcome to my idea of a new web” : the proposal of a “browser” that just renders Markdown documents. This feels quite similar to the idea behind Gemini, but using a better (not a great) format with more markup abilities. And I say fun fact because, as I was learning about Gemini, I was imagining developing this exact alternate idea. One curious bit is that Gemtext is also the format for subscription feeds. Sure, you can offer an RSS feed for your capsule, but RSS is a monster spec that feels out of place in a minimalistic network like Gemini’s. So you can abuse Gemtext to create a feed by creating a page that’s primarily links with a de-facto format. Again, it’s simple, and it works. The big benefit of Gemtext’s simplicity is that clients can also be super-simple. You can rest assured that all clients will be able to display the same content, consistently. So far I’ve tried Elpher within Emacs , Lagrange on the desktop , and Buran on my Android phone . All are simple. All display text in the same way. I definitely do not recommend using the Gemtext format to persist your original content, but that doesn’t mean you have to write in Gemtext. Which brings us to Markdown again. All of the content you are reading in this blog is authored and stored as Markdown documents. Like many other people who still maintain a blog in this day and age, I started with a hosted platform (Blogger) and then experimented with Medium. But as soon as Medium became riddled with noise, I ran away. Unfortunately, escaping was difficult: the format that Medium spit out was frigging awful—almost as if it were designed to provide the illusion that you could export content, even if the content was nearly useless after the fact. It was at that point that I committed to converting my golden copies to Markdown even though authoring in Markdown was more inconvenient. And believe me: it is inconvenient, especially when having to insert images. But now I own my content in a format that’ll survive for years to come. Which brings us back to Gemtext. The thought that crossed my mind when I stumbled upon Project Gemini again three weeks ago and that triggered this whole thing was: can I write a script to convert my Markdown docs into a capsule? And with “I” I really mean AI, because this is the kind of experiment I was not going to code myself. And of course I could. After just one simple prompt, I had a converted site that I could browse. Granted: the conversion Python script was literally awful, and the converted format was not great either, but having something I could play with inspired me to try harder. A run of my blog-to-capsule exporter. So I threw everything away and started over, again with AI, to write a conversion tool for my blog (codenamed for now) that takes the existing Hugo layout and spits out a capsule end-to-end in just 300 milliseconds while processing 1000 documents. The tool is obviously written in Rust, and by now supports enough configurable features that I’m increasingly tempted to throw Hugo away for the web version and create my own static site generator too. Because, you know, while Hugo works, it isn’t the greatest in usability and its recurrent incompatible changes are annoying. I’ll resist the urge to do that for now… I think. Let’s dive a tiny bit into . First of all, this second iteration is still entirely vibecoded. Oops, first sin. I have not looked at the code because it’s working for what I need it to do, it’s fast, and it’s not going to be used by anyone else… unless you want it, but then I’d probably rewrite it once more now that I know what the final feature set looks like. Now, for this second iteration, I was so close to running out of my $20 weekly OpenAI quota that I pivoted from my favorite GPT 6.1 Sol model to GPT 6 Luna to see how far I could go. Luna is so cheap that you can do a ton with it, and I actually got to work well enough within just a few iterations. But oh dear. Luna is cheap, but it’s also kind of crap for coding. It stops half-way. It doesn’t think through enough corner cases. It doesn’t produce enough tests. The plans it produces are very vague. You have to be extremely prescriptive when asking it to do things and even that leads to mixed results. Out of curiosity, when my weekly cap was reset, I asked Sol to review what Luna did, and oh boy did it have things to say. From design problems to important missing tests, passing through outright bugs. I let it fix those issues, and I continued building with Sol. Right now, I’m actually pretty happy with the results of . I can configure the mapping of pages to templates in a much more explicit way than in Hugo. I can use MiniJinja for templating. I can specify cross-site links. I can handle inline links, figures, and even tables. I can generate archives/feeds for the site, for each year, for each month. I can process blog posts, and also standalone pages. All in all, the results are very satisfactory given the close-to-zero effort I put into it. With the site exported to Gemtext, I needed a server. There are a lot of options out there, but the one that piqued my interest was Agate : a minimalistic Gemini server written, of course, in Rust. You run the binary pointing it at the directory containing the generated site and, voila, it works. Agate even takes care of auto-generating SSL certificates because all Gemini traffic is TLS-protected, and the fact that it’s automated is a relief because dealing with certificates is a pain. My new Gemini capsule shown by a Surface Go 2 running Lagrange. Artwork courtesy of Eva Merino. But running Agate once, interactively, and making it serve in the background are different stories. I am running FreeBSD on my server and I could have used the prebuilt package, but then I encountered a crashing bug and wanted to add a feature, so I had to pivot to building from source. And, as you can imagine, Cargo leaves a lot to be desired if you want to install the resulting product to a running system. Now, of course you can copy the built binary to, say, , but there is typically much more than a binary in a distribution: think about documents, examples and, for a server program in particular, startup scripts. Mind you, Agate’s source tree does include a FreeBSD rc.d script, but it was buggy, insufficient, and it also required manual copying. So I created a PR to revamp the installation system based on earlier experience with setting up similar infrastructure in other Rust services I run. I mentioned briefly above that I wanted to add a feature to Agate and that it was the reason I had to build from source. And that feature is… analytics, which are the second sin right there. “Oh no, ah-nah-ly-tics! Privacy enemy number one! How dare you add analytics to something in the Gemini network!?!” But wait a second. What are analytics? You do realize that Agate prints and saves a log of incoming connections (with IPs redacted by default), right? That’s par for the course for any Internet server out there, because in order to serve requests… well, the server actually needs to know what those requests are and where to send the responses to. So you can always analyze the log to gain some insights on traffic. And that’s pretty much what I did. I just wired this exact same information to my own analytics service for visualization. The only thing I see are the pages that are being downloaded, when they are downloaded, and the originating country (computed from the requester’s IP after truncating the last octet to mask it). Essentially… good old page counters from the 1990s. Live page views graph showing both https:// and gemini:// visits at once. The way I implemented this is generic though: I extended Agate to add optional support for an SSI-style URL inclusion primitive and then added such a call to the capsule-wide footer template given to my Gemtext generator. As a high-level primitive, it can serve other purposes, like sourcing comments for each page by making the footer download a pre-rendered chunk. I haven’t implemented that yet in my comments service, but it should be pretty easy. Sounds interesting? I might try to contribute this SSI feature upstream to Agate, but I predict that this collides with the goal of a lightweight server and that it’ll be rejected. But I’ll try anyway. I want to get the FreeBSD-related bug fixes and related improvements merged first, because those are helpful to everyone, I hope. That’s about it! If you are in the U.S. you are about to have 4 days off, so spend that time falling into the Gemini rathole. And if you are elsewhere, do the same! It’s entertaining. From now on, remember that you can also read this blog via gemini://capsule.jmmv.dev/ if you want a super-fast, distraction-free experience. To get started, visit the Gemini software page for a long list of clients to choose from and install. (Content also available at: ) Project Gemini's front page, displayed in the Lagrange browser. … and break down the introductory and only paragraph: Gemini is a new internet technology supporting an electronic library of interconnected text documents. You can think of Gemini as a way to access a bunch of text-only pages, with links among them, so you can find information and follow links to additional resources. Instead of using or URL prefixes, you use instead. That’s not a new idea, but it’s not old fashioned either. Exactly. Gemini is like the WWW , or “the web” in more colloquial/modern parlance. In fact, Gemini is a parallel community to the web. Obviously, that’s not a new idea because the web dates back to 1989, and we are now 37 years after that. The idea is not unique either because Gopher , a much lesser-known option, exists as well. Surprisingly to me, I realized that Gopher came after the web in 1991 while researching this article. I had always assumed Gopher was first and that the web came to replace it because of Gopher’s rigidness. But that’s not quite what happened. It’s timeless, and deserves tools which treat it as a first class concept, not a vestigial corner case. Humans have shared written documents since around 3400–3100 BCE (roughly 5,100–5,400 years ago) in ancient Mesopotamia and Egypt, and that’s probably (hopefully?) not going away. It’s true, though, that at this point, text sharing is not the primary thing that the web does, as you well know. We have morphed the web from a document distribution tool into an app platform, for better or worse. A little confession: I worked at Google for 12 years, starting right at the time they published Google Wave (2009), which to me marked the start of truly interactive web apps—more so than Gmail (2004) did. In the back of my mind, I knew I was helping turn the web into how we run apps, destroying the traditional desktop paradigm—a feeling I never liked. And… it happened. Obviously, it’d have happened without me, a little pawn in the game, but it bothered me regardless. Gemini isn’t about innovation or disruption, it’s about providing some respite for those who feel the internet has been disrupted enough already. (That comma splice hurts.) As we have established earlier, Gemini’s ideas are not new, so it’s indeed not innovative. And seeing how little people read these days, or even how unable to pay attention to long-form text they are, it’s not going to disrupt anything either. But respite is key: having a separate place where you know you’ll only find some sort of counter-culture sounds entertaining. Fun fact: I wasn’t quite sure what respite meant and originally took it to be similar to spite. That meaning would have worked equally well here, if not better? We’re not out to change the world or destroy other technologies. We are out to build a lightweight online space where documents are just documents, in the interests of every reader’s privacy, attention and bandwidth. Here is the interesting thing. Gemini claims that it has been designed to minimize the chances of becoming bloated, and I’m not exactly sure how you can prevent that. For example: articles can provide links to images, but images are not auto-loaded. OK, says who? The auto-loading part is something the client browser controls, and it’d be trivial to create a Gemini browser, or modify an existing one, to auto-load and render images. That’d go against the spirit of Gemini, but if enough people wanted it, it’d happen. Same story as the browser wars . And that’s the key: “enough people”. As long as Gemini stays under the radar and only like-minded people gravitate towards it, these properties will be maintained. But if for any reason it becomes more mainstream… unwanted changes will happen. Enjoying so far? Please take a moment to show me by subscribing to Blog System/5. It’s free! Gemtext Gemtext is the native format of documents stored in the Gemini network, with a MIME type of and a extension. Gemtext documents are typically grouped in capsules —which is just another name for “website”. The format itself is like a super-diluted version of Markdown, supporting just these features: Three levels of headings. Paragraphs. Links as standalone lines, not as inline text. Preformatted text blocks, also not as inline text. Unordered lists. Blockquotes.

0 views
Sean Goedecke 1 weeks ago

Why output caching doesn't work

LLM inference economics depends on caching 1 model inputs, to prevent the entire conversation history being recomputed on each message 2 . Should we cache model outputs in the same way? As it turns out, no. First, here’s why we might think caching outputs is a good idea. We cache inputs to prevent repeated work, but LLMs do a lot of repeated work in their output as well: In all of these cases 3 I could go and read the files myself, but I don’t. Agents produce such a volume of output, and reading agent output is tiresome, so it’s better to simply ask for the key points. It’s an obvious waste of tokens 4 to repeat all of this content. In fact, it’s worse than the input caching situation, because it’s a waste of output tokens, which are significantly more expensive to produce 5 than input tokens are to ingest. If you want to prevent this, you’d have to get the model to avoid repeating itself. For instance, you could fine-tune or prompt a coding model to output “src/script.py:12-15” instead of simply regurgitating those lines of the file. More generally, you could fine-tune a model to reference segments of its own conversation history instead of repeating them. The harness could then trivially expand those references with the actual content, so all of this is transparent to the user. Unfortunately none of this is a good idea, because it only optimizes visible output . I don’t think models repeat themselves often in their internal chain of thought 6 . I can’t read frontier chains of thought, but my sense from open models and general principles is that they shouldn’t need to, because that information is already available to them. So optimizing repetition only optimizes the segment of model output that is visible to the user. How much is that? Based on my own agent histories, it’s about 6%. 50% of output tokens are reasoning tokens, and the remaining 44% are tool calls 7 . So we’re running headlong into Amdahl’s law : even if you can save two-thirds of the tokens in visible output (a ridiculously optimistic estimate), you’re still only saving 4% of total output tokens. If you want to save output tokens, you need to reduce the 94% of output tokens that are invisible, which largely depends on intelligence . The smarter the model 8 , the fewer reasoning tokens and tool calls it needs to get to the right answer. This is why we see a strange phenomenon 9 where more expensive models are actually cheaper to use: they might be 5x more expensive per-token, but they can get to the right answer with 6x fewer tokens, so the overall cost is less. In the KV cache. Including tool calls. Coding agents often used to repeat tokens in tool calls (e.g. by re-outputting the entire file content for each edit) but I think this behavior has mostly been replaced with more efficient find-and-replace editing tools. I’m pretty sure that most mature inference providers already do speculative decoding based on previous ngrams in the input, which would at least exploit output repetition to deliver a speedup. The reason, broadly speaking, is also the reason why transformers are so important: because of the attention mechanism, input tokens can be ingested in parallel, while output tokens must be generated one-at-a-time. I’m only moderately confident about this. Some open-source reasoning models (particularly early ones) do, but those models also use way more tokens than frontier models for the same output, so my guess is that powerful frontier models don’t loop in their chain of thought very often. It’s possible that tool calls involve some repetition as well, if agents are composing content in the chain of thought and then repeating it in the tool. Any readers who have done a lot of coding with open-source models (or who work at a frontier lab) and thus know the answer to this, please email me if you can — I’m curious. And the better the harness, though I remain convinced that there isn’t that much comparative advantage in harness quality because everyone can copy each other. This applies to real life too, and is the reason why you shouldn’t hire the cheapest plumber you can find. When I get agents to write PRs I often ask them to repeat and explain relevant code snippets in the conversation Long-running agent investigations produce lots of evidence docs, but also need to quote from those docs when they respond to the user Every time I’ve played around with automated AI research I’ve asked the agent to repeat some sample model outputs so I can make my own qualitative check In the KV cache. ↩ Including tool calls. ↩ Coding agents often used to repeat tokens in tool calls (e.g. by re-outputting the entire file content for each edit) but I think this behavior has mostly been replaced with more efficient find-and-replace editing tools. ↩ I’m pretty sure that most mature inference providers already do speculative decoding based on previous ngrams in the input, which would at least exploit output repetition to deliver a speedup. ↩ The reason, broadly speaking, is also the reason why transformers are so important: because of the attention mechanism, input tokens can be ingested in parallel, while output tokens must be generated one-at-a-time. ↩ I’m only moderately confident about this. Some open-source reasoning models (particularly early ones) do, but those models also use way more tokens than frontier models for the same output, so my guess is that powerful frontier models don’t loop in their chain of thought very often. ↩ It’s possible that tool calls involve some repetition as well, if agents are composing content in the chain of thought and then repeating it in the tool. Any readers who have done a lot of coding with open-source models (or who work at a frontier lab) and thus know the answer to this, please email me if you can — I’m curious. ↩ And the better the harness, though I remain convinced that there isn’t that much comparative advantage in harness quality because everyone can copy each other. ↩ This applies to real life too, and is the reason why you shouldn’t hire the cheapest plumber you can find. ↩

0 views
Max Bernstein 1 weeks ago

Inside PyPy: first contact with RPython

I get restless now and then and I want to implement a programming language. Then after mustering the resolve, I stew, for there is no good implementation language. 1 What am I to do, build my own programming language so that I can then use it to implement the first language? So I go back to modifying an existing implementation instead. There do exist established general-purpose tools for building fast programming language implementations: And more nascent ones such as Deegen , which was used to reimplement Lua. They each take different approaches: While none of these spark joy , they do each have benefits, including accomplishing the primary goal of offloading a lot of the language runtime choices and nasty details. In this post we will take a first look at RPython because it is the kind of VM implementor’s programming language that I keep thinking about. More on that later. Before we continue, please heed this warning: RPython is an implementation detail of PyPy. It has not had the years of polish that the rest of the system has had. Please do not badger maintainers. We’re going to build a little program in RPython. I am mostly following along with the docs , specifically Getting Started with RPython . There’s a little more ceremony than you might be used to and that’s because we’re going to run this file in two modes: normal Python 2 interpreter and compiled to C. This is the weirdness of RPython. If you don’t have installed, you can install PyPy, which helpfully still implements Python 2. If this all went fine, you will see it print . None of this is RPython yet . For that, we need a hint more ceremony. This is when we clone the PyPy project, in which we will find RPython. Now edit the Python program. Below the definition, add the following function: This function looks unused, but it is actually a hint to RPython: this is where the compiler should start translating. Let us now compile this program. Either inside the PyPy directory or with , run: If all goes well, you will see a whole mess of output, including a partially rendered Mandelbrot fractal. Finally, you will see something like: This is the RPython compilation process. In it, RPython is analyzing types, removing memory allocations, monomorphizing functions, and generating C code. Then it hands this C code off to a C compiler to compile. You should have in your current directory an executable named , which you can run like . It should also print . So far, this is not so different from Python. But let’s try something Pythonic. Let’s see what happens when we also use to mean string concatenation. Under normal Python 2, this will work just fine, printing and then . Under RPython, though, you get this inscrutable error (again, rough edges): and are unceremoniously dropped into the debugger, Pdb (hit Ctrl-D or type ). From this message you are meant to intuit that RPython did not enjoy that two different types flowed into the function. It helpfully tells you that there was a when trying to reconcile the and types that flowed into the function’s first parameter. It then gives you a pointer to the offending line and an IR dump. This happens because RPython requires function parameters to be monomorphic. Though the variables are syntactically untyped, RPython computes a type analysis to discover what type each variable should be. When and both flow into , boom, complaint. 2 To get around this, we do what all good C++ programmers do and we templatize the function. The RPython spelling of this is, as with many other features, a function annotation: You will find now that RPython happily compiles the program. This works because it makes a new copy of for every input type of the first ( ) argument. “Hey wait a minute,”, you might ask, “doesn’t this mean it stops being a valid Python 2 program?” Great question. No. You can still run the program as long as you provide the location of the RPython libraries via (as before): This runs ~instantly, which is a big relief. Developing an interpreter project with a 30 second or more turnaround time for each compile would be really frustrating. This has been a taste of RPython, both great and somewhat frustrating. I intentionally made it about RPython as a programming language rather than being so focused on RPython as a programming language implementation tool because I want some of its features to exist in a general purpose programming language… that then also might be used to implement other programming languages. I bring it up because I want to rehash the stuff that I occasionally grumble about in the vicinity of PLDI but for some reason have not written about online. Perhaps writing about it will encourage people. I think there is a lot of good stuff in RPython: I wish some stuff were different, or at least modifiable: I will probably add more to this list as I continue to remember some years of these conversations. Wouldn’t this be great? I don’t really have the time, energy, or expertise to build such a thing. There are so many design decisions along the way. It would probably accidentally grow to be huge and ossify along the way, and what a bummer that would be. If you have any pointers to existing projects or a way to implement such a thing in a really lightweight form (read: sub 10k lines, portable ideas), I would be very interested. Here are some pointers to other projects in the neighborhood: Thanks for CF Bolz-Tereick first for allowing me to talk their ear off about this for years and second for reviewing this post. I don’t want to implement atop Racket. C++ and C give me endless nightmares and are completely DIY. Yes, yes, I have built large VMs on C++ and C before. One time I posted so hard about the frustration that my tech lead unfollowed me on Twitter. I don’t really want to try to think about GC in Rust.  ↩ I initially thought any variable had to be monomorphic but I could not get an error from programs such as .  ↩ RPython, which has PyPy (Python) as its primary success story but also can claim Topaz (Ruby) and a couple of other smaller ones Truffle, which is the foundation of TruffleRuby, GraalPython, GraalJS, and even Sulong (LLVM) Deegen requires you to write your bytecode interpreter and type system in a C++ DSL. From this it generates an interpreter, a baseline JIT compiler, and, hopefully eventually, an optimizing JIT compiler. Truffle requires you to write an AST or (newly) bytecode interpreter in an Annotation-based Java DSL. From this it specializes guest language code before emitting Graal IR, which uses aggressive partial evaluation to generate optimized code. RPython requires you to write an interpreter in a restricted dialect of Python 2 that acts more like Java or Go than Python. The RPython compiler will then analyze your code, translate your “Python” program into C code bundled with RPython IR, and then “tier up” from the C code to JITed code at run-time. In order to go from “random RPython program” to “JIT compiler”, you need to participate in its meta-tracing , which requires annotating where your interpreter loop loops. Compile to native AOT with additional JIT. Seems like this provides good start-up performance with (optional!) tier-up as the runtime system observes the system’s behavior. Automatic memory optimization. There is no good way to syntactically express how an object should be allocated—Python is, after all, a very high-level language—so Python programs are profligate allocators of memory. RPython programs would be the same except that the AOT compiler does a whole-program analysis to try and remove these allocations. The JIT does too, but via a different mechanism. The JIT is provided to you. You don’t have to think about program analysis; the PyPy authors think about it for you. It is possible to do manual memory layout via so that you can write better data structures than Python would otherwise let you express. It provides a garbage collector for you. Furthermore, it handles all the stack scanning stuff and “oop maps” so you don’t have to build handles/ /… yourself. RPython does its partial evaluation and automatic JIT creation via meta-tracing . It is one of the last surviving tracing JIT compilers (alongside LuaJIT and, kind of, HHVM). For a lot of programs, method-based compilers seem to have produced better, or at least more predictable, results. I kind of want to see what a meta-method-JIT would look like. The user experience leaves something to be desired. I want better error messages, faster compiles, and less output. I want thorough docs. I want better performance feedback. This is in line with the rest of my ramblings about mechanical sympathy: the runtime should tell you what is wrong. I (or CF) shouldn’t have to stare at IR in traces and go “hmmmmm…” It requires writing a lot of your tooling anew. Even if I had, for example, a JavaScript parser written in Python, it likely wouldn’t be in Python 2 and it likely would not work well with RPython’s special rules. Runtimes such as JRuby get around this by compiling parsers (Prism) to WebAssembly and then bundling a WebAssembly interpreter written in Java. Along these lines, I would like more help with lexing and parsing, for which I have so little patience. I think it would be neat if it had a way to pause and save an “image” of the heap. After all, RPython is in control of all the memory and the code. It would be neat if, in addition to a JIT, it also helped you build an AOT compiler for your guest language. What if your language is statically typed? Should the toolkit provide functionality for type checking? Type inference? Some solution for C code. You can call it and stuff just fine but there’s no Sulong equivalent so it’s a totally opaque barrier to optimization. Don’t write your runtime helpers in C, sure, but at some point you have to interact with outside code. Weval, which turns an interpreter into a baseline AOT compiler. Its current implementation requires the interpreter to be compilable to Wasm and then its heap snapshottable with Wizer. One can imagine this technique being used instead to implement a JIT instead of an AOT, thereby also sidestepping the snapshot requirement. One might also imagine this applying to another IR than WebAssembly. Say, LLVM… semPy, which is an executable semantics for Python. Zig and other languages such as the more nascent k1 have the ability to run and generate code at build-time. Perhaps someone could implement a VM toolkit in one of these languages. I think a lot of the effort would still go toward something like GC handles if you want a moving GC. I don’t want to implement atop Racket. C++ and C give me endless nightmares and are completely DIY. Yes, yes, I have built large VMs on C++ and C before. One time I posted so hard about the frustration that my tech lead unfollowed me on Twitter. I don’t really want to try to think about GC in Rust.  ↩ I initially thought any variable had to be monomorphic but I could not get an error from programs such as .  ↩

0 views
Simon Willison 1 weeks ago

Running the full server-side Datasette Python app in the browser with service workers and Pyodide

Datasette Lite is my port of the Datasette Python application to run directly in the browser using WebAssembly and Pyodide . I've released a complete rewrite of Datasette Lite using service workers, and it's now almost indistinguishable from the real server-side application. You can now do all of the following, using a carefully crafted URL to lite.datasette.io : The ability to load specific Datasette references, plugins, and SQLite versions makes this a fantastic tool for linking to demos of work-in-progress features or bug reproductions, without needing to spin up a full web server to serve that demo. As an example, consider the following URL: https://lite.datasette.io/?install=datasette-maplibre&url=https://gist.githubusercontent.com/simonw/39fa5d399465766039549912e2b3d291/raw/f6dfba99a75cbb8b5d9386223220eb52272767ee/demo.db&metadata=https://gist.githubusercontent.com/simonw/39fa5d399465766039549912e2b3d291/raw/f6dfba99a75cbb8b5d9386223220eb52272767ee/metadata.yml#/demo/capitals_and_countries%23map=0/4.2/180&color=continent Follow that link and, after a short loading screen, you'll find yourself on a page that looks like this: That's Datasette running the new datasette-maplibre plugin, loading up a database of GeoJSON shapes of countries and displaying both a combined map and individual boundary maps in a table. Let's break down that URL to see what it's doing: The installs that additional plugin from PyPI. You can pass as many times as you like to load more plugins. loads that SQLite database from the provided URL. These URLs need to have open CORS headers - I host files like this in Gists , because they provide an easy way to get open CORS headers on a web-hosted file. loads this metadata.yml file . The metadata file adds HTML descriptions to various tables, and to the Datasette homepage. Visit that homepage here for a guided tour of the other features of that plugin, all defined in the metadata file. is a fragment hash that turns into a location within Datasette - here it's loading the SQL view, then appending another fragment hash to it ( is a URL-encoded ) which tells the map plugin to zoom to a certain location and to set the color of the shapes on the map based on the column in the data. That URL is doing a lot of work! I wrote more about this trick for building URL-addressable software in URL-addressable Pyodide Python environments last year. The full set of supported URL arguments is described in the Datasette Lite README . I've already started using Datasette Lite as part of the Datasette development process. Here's a recent issue describing a pagination bug - I posted a comment there demonstrating the old, broken behavior and the new fix using links to Datasette Lite: Demo of the bug: https://lite.datasette.io/?ref=1.0a42&sql=https://gist.github.com/simonw/75ececf61d50e6e8d50f0c150150ee81#/data/scores?_size=2&_sort=score - click next and the second page is empty. Here's that same page with the bug fixed (running on 1.0a43): https://lite.datasette.io/?ref=1.0a43&sql=https://gist.github.com/simonw/75ececf61d50e6e8d50f0c150150ee81#/data/scores?_size=2&_sort=score Datasette Lite is not a new project. I launched the first version back in 2022 , originally as a bit of a joke (running server-side apps in the browser is pretty funny) but one that quickly started proving its value. The problem with that initial version is that it was a hack . It worked by running Datasette in a Pyodide web worker, simulating requests through that stack, then injecting the resulting HTML back into the top level page using . This worked for basic Datasette, but meant that any feature that used JavaScript failed to work, because script tags in don't execute, and the web worker tricks it used failed to load additional JavaScript or CSS files. The new version takes a completely different approach based on Service Workers . These allow JavaScript to intercept HTTP requests for new pages and resources and serve them from client-side code instead. Datasette Lite registers a service worker for the entire domain. The parent page then creates an iframe that sends requests for Datasette pages to URLs that look like this: Those are regular Datasette URLs, but with a prefix. What's that about? The prefix is necessary because of multiple tabs. Consider the URL above, which loads the demo instance with the plugin. That URL defines a full, custom Datasette instance. You might have that one running in a tab, then one of my other demo links running in another. The service worker for is shared between all of those tabs. If it routed to a single instance of Datasette then every tab would share that underlying instance, no matter what plugins or other settings their URL attempted to configure. Instead, the parent page generates a random session ID and uses it as a prefix for all of the subsequent hidden asset and page loads. The service worker can then use that session ID to route those requests back through the parent page to a web worker running a dedicated Datasette instance for that particular session. (We still need a web worker because Pyodide in a service worker would not be able to maintain state beyond around 30 seconds, depending on the browser. There are a lot of moving parts here!) I had Claude Fable 5.2 generate several SVG diagrams to help explain this. Here's my favorite of those, now embedded in the Datasette Lite README: This system started life back in May as an AI research spike generated using Claude Opus 4.8. It wasn't until November (and Claude Fable 5.2) that I felt familiar enough with how it all works to confidently ship it to production! I added this feature last night as an off-shoot of investigating a potential bug in SQLite . Datasette is meant to work against any released version of SQLite since 3.25 (released in September 2018). There have been 87 further releases since then. Being able to fire up Datasette against a specific version of SQLite is really useful for demonstrating new SQLite features and debugging weird issues. In the past I've used various tricks to get different SQLite versions running with Python on my Mac, but it's not a trivial process. WebAssembly is perfect for this. I can load up a custom SQLite build entirely in my browser, test it there, then discard it when I close my tab. datasette/pysqlite3-wasm-wheels is my new repository which contains WebAssembly compiled Python wheels for pysqlite3 for 163 different SQLite versions. Each version gets a file with a name like this: That's for SQLite 3.54.1, the most recent version. Datasette Lite now takes a special URL parameter, which will accept a version number like , resolve the path to the corresponding wheel file, then fetch that wheel and install it into the Pyodide environment and configure Datasette to use it. Once I'd built the wheels, I decided to have Claude Fable 5.2 build me [this bonus tool]( https://datasette.github.io/pysqlite3-wasm-wheels/?versions=3.54.1,3.54.0&sql=select+json_object(%27a%27%2C+(select+json_array(1%29%29%29) for comparing a SQL query across any selected versions of SQLite. Here's an example showing how differs between SQLite 3.54.0 and 3.54.1: Nothing about how Datasette Lite works is unique to Datasette. Almost any Python application should be able to pull the same trick - running entirely in the browser using WebAssembly and Pyodide, as a cheap way to provide preview environments, demonstrate features, and recreate bugs. C and Rust extensions used to be a blocker for this kind of thing, but any good coding agent can compile those to Pyodide-compatible WebAssembly now. You can even publish them to PyPI as of PEP 783 in April 2026. One catch is databases. SQLite is no problem at all, but running PostgreSQL or MySQL in WebAssembly, while possible, is still a path less trodden. I'd love to see WebAssembly preview environments like these become a common pattern across the Python ecosystem. For Hacker News: Full server-side Datasette Python app in the browser with service workers 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 . Load client-side Datasette to browse any SQLite database, JSON file, CSV file or SQL script Select a released version of Datasette to load from PyPI Load a specific commit, tag, or branch name from the Datasette GitHub repository Pick from over 100 versions of SQLite to use with Datasette Install additional Datasette plugins from PyPI or URLs to wheel files, including JavaScript visualization tools

0 views

The NVIDIA Bubble

If you liked this piece, you should subscribe to my premium newsletter, and you can subscribe on the following links: $70 a year , $18 a quarter , or $7 a month . In return, you get a weekly premium newsletter that dives deep into the finances of the AI bubble. Over the past few months, I’ve published a two part guide to the world of AI debt, an analysis of the (dubious) impact of generative AI on the global economy , deep analyses of the biggest players in the AI infrastructure space like NVIDIA (part one and two ) and Oracle (part one and two ), and the role private credit is playing in funding AI data centers , and how private equity, reeling from years of successive failed software acquisitions, is doubling down on the AI bubble .  Last week’s piece was a 13,000-word deep dive into Megaspeed — the shady firm at the heart of Jensen’s downfall, which somehow bought billions of GPUs despite being, just a few years ago, an unsuccessful developer of free-to-play mobile games. It’s all very weird, and I spent a lot of time making sense of it all.  On Friday, I’m going to share how we fix the tech industry, and how we stop the next bubble before it even starts.   If you want to get in touch — and especially if you have any juicy information about Anthropic, OpenAI, or any other companies in the AI bubble — hit me up on Signal at ezitron.76. I’m also on IB on your Bloomberg Terminal.  This weekend, thousands of horrible little men cried out for the return of their pervert emperor, demanding that NVIDIA restore disgraced CEO Jensen Huang, who resigned after it leaked that he’d had multiple affairs , one of which (as described in my free newsletter last week) was with a woman called Alice Huang who may or may not have been a Chinese spy, but was most certainly selling restricted AI chips to Chinese companies through a company called Megaspeed ( covered in depth in my premium last week ).  Within the space of a week, illegal chip sales routed through Alice Huang’s empire went from $4.8 billion to “at least” $7.5 billion , to $12 billion between March 2024 and June 2025 according to the Wall Street Journal.  The Information also reported that companies connected to Alice Huang invested in DeepSeek, the famed Chinese AI lab that spooked the world back in Q1 2025 for, ironically, suggesting that we didn’t need to buy as many NVIDIA GPUs. Let’s be clear about something: Jensen Huang resigned and is not coming back. To paraphrase Semafor’s Rohan Goswami , NVIDIA’s board was packed with allies , deliberated at length about what to do (and didn’t really want to do it) , and has both let him walk and done nothing to retain him, I’d personally guess because the probe the board is running already has some idea of wrongdoing such as, I dunno, the giant illegal smuggling ring that has been covered at length by basically every media outlet. NVIDIA has also said it was not considering bringing him back . Even now, a week into this bizarre crisis, few are truly reconciling with the allegations raised in May 2026 by Culper Research’s short report , namely that 20% or more ($43bn+) of NVIDIA’s FY 2026 sales came from selling through China. Even two profiles of Culper in the New York Times and Wall Street Journal fail to substantively discuss the material of the guy they’re god damn profiling. That’s because, to paraphrase Culper’s own work, Megaspeed is just the tip of the iceberg. As I covered last week , Culper directly connects Megaspeed to popular AI server manufacturer Supermicro , whose co-founder and board member Wally Liaw was arrested with several co-conspirators back in March for trying to sell over $2.5 billion in chips to a Chinese passthrough entity Culper believes is a Megaspeed affiliate. Liaw had previously resigned in 2018 due to an accounting scandal ( per short seller Hindenburg ), only to be rehired in 2021 as a consultant and reinstated to the board in 2023. Let me spell it out for you: a co-founder and member of the board of one of the largest manufacturers of AI servers was arrested for selling chips to China, specifically to a company affiliated with the very same smuggling operation that Alice Huang ran.  Supermicro is a huge, publicly-listed company with a history of accounting scandals. 70% or more of its revenues come from selling AI servers powered by NVIDIA GPUs, and back in August 2024 — months into Megaspeed’s $12 billion purchases of eventually-smuggled GPUs — Supermicro was NVIDIA’s third-largest customer, around that it was facing allegations of accounting manipulation and sanction evasion by Hindenburg that never went anywhere because our markets are broken and our SEC is trash. Anyway, my point is that this story is just getting started, and that those in the Copium dens are trying to reframe this as a “guy who made a mistake” rather than a philanderer that appears to have overseen the GPU equivalent of Iran Contra. Whatever rumors you may have read about a potential Jensen comeback appear to be peddled by the most desperate of AI boosters who, based on reports on CNBC , do not appear to be aligned with what Huang himself has said.  And really, why do they want Jensen back so bad?  It’s simple: Jensen Huang’s value has nothing to do with GPUs or AI, and everything to do with keeping the AI bubble inflated. Perhaps it’s more appropriate to call it the NVIDIA Bubble , because without it, the AI industry doesn’t really make much sense.  As I’ll make clear later in this piece, NVIDIA played an active role in keeping the wheels of the AI bubble turning — funding model labs, buying startups, and backstopping compute for Neoclouds, thereby allowing them to raise debt. Its interventions didn’t merely sustain the industry-wide spending spree, but amplified it. In the process, NVIDIA transformed the AI bubble to something that attached itself to the personal wealth of ordinary people — often without them realizing it.   As the stock prices of NVIDIA (and the rest of the Magnificent Seven) became engorged on AI-related hysteria, the exposure of ordinary (and unwitting) savers to the AI bubble grew. Investors who followed the mantra of “don’t buy individual stocks, just buy index funds” ended up in a position where, due to the top-heavy nature of the S&P 500 , and the predominance of mega-cap tech stocks, a significant chunk of their wealth is gambled on the question of whether AI is a bubble or not. And that’s without mentioning other factors — like how insurers and pension funds are exposed to the AI bubble (and, in particular, the AI infrastructure buildout), either directly or indirectly through their investments in private credit.  Or, put succinctly, if NVIDIA sneezes, the retirement savings and personal investments of ordinary retail investors will catch a cold. And if NVIDIA catches the flu, we’ll see the wealth of retail investors contract the fiscal equivalent of pneumonic plague — the type that Soviet scientists cooked up in a Siberian lab during the Cold War, and that gives Annie Jacobsen nightmares .  Despite many saying “NVIDIA isn’t NVIDIA without Jensen,” in truth it’s still selling the same chips, has the same fab space and supplier agreements, and outside of his horrible personality (and cult of personality ) seems virtually identical. Back in August, NVIDIA said that it expected 70% year-over-year growth in Fiscal Year 2028 (starting February 2027) , which suggests — unless something has materially changed! — that NVIDIA had clear expectations and agreements to hit those targets. CEO Colette Kress should, if you believe everything that’s been said over the last few years about “insatiable demand,” have absolutely no problem selling just as many GPUs at just as fast a rate… …unless, of course, there’s another reason that “NVIDIA isn’t NVIDIA without Jensen.” The truth is that what people actually mean is that “NVIDIA isn’t NVIDIA without Jensen using its balance sheet to grow at a high pace involving constant, quasi-legal-to-illegal dealmaking involving channel stuffing and illegal smuggling.” The Wall Street Journal reports that Jensen Huang had told his finance team ( in August, the very same month it raised guidance) that the company was facing a glut of GPUs and had over-ordered capacity at TSMC and with memory manufacturers, necessitating further circular financing: I dunno man, I’m no securities lawyer, but I feel like worrying that you have an oversupply of chips and then telling investors that you actually expect to sell more chips than ever feels like some sort of stock manipulation, and it wouldn’t be the first time NVIDIA’s done it in the last year. Back in September 2025 , it announced it would invest $100 billion in OpenAI to build 10GW of data center capacity, with Jensen Huang saying live on CNBC that there had “never been an engineering project of this complexity and this scale ever,” referring to a deal that he would dismiss as “ never a commitment ” five months later, because it was only ever a “ letter of intent .” The truth is that Jensen Huang lied. You can dress it up in terms of “memoranda of understanding” or “letters of intent” not actually meaning “a contract has been signed,” but Jensen Huang went on CNBC and did everything he could to convince you that NVIDIA was investing $100 billion in OpenAI to build 10GW of data centers, much like he went on CNBC a few months ago to convince you that (and I quote the headline) “NVIDIA [had lined] up $500 billion in financing” despite these being A) memoranda of understanding and B) no money ever changing hands or being raised by anybody to do anything and, to quote Bloomberg , said $500 billion figure having “no obvious provenance.” There is no other way to interpret this other than intentional manipulation of the markets perpetuated by the mainstream business and technology press, all because nobody would ever push back on Jensen Huang.  And that’s because everybody knows, deep down, that we’re all living in an NVIDIA Bubble — a financial mania manufactured, maintained and sustained using NVIDIA’s credit rating and cash to brute-force the markets and the media into believing in anything. While the AI bubble is relatively young, the NVIDIA bubble has been inflating for over a decade. I don’t even mean that derisively! Jensen Huang and NVIDIA were formative to the entire AI bubble, both in creating the infrastructure, demand, and even the underlying research that eventually led to the LLM boom.  Way back in August 2016, Jensen Huang delivered “the world’s first AI supercomputer” — the DGX-1 — to a small AI lab called OpenAI that had recently raised money from yCombinator’s Sam Altman and Tesla/SpaceX’s Elon Musk . Three months later, OpenAI announced it was moving to Microsoft Azure , training on NVIDIA Pascal GPUs in the earliest days of AI compute. A few years later, NVIDIA found itself in flux, with a beat on earnings in February 2019 clouded by a decline in both hyperscale and cloud sales , but Jensen Huang was already working on an acquisition that would change everything, agreeing to buy Israeli high-speed networking firm Mellanox that March for $6.9 billion in cash , outbidding both Microsoft ( which was already using its tech at Azure ) and Intel for the InfiniBand technology that would eventually allow NVIDIA to network together clusters of AI servers.  Four months later in July 2019 , Microsoft would invest a billion dollars into OpenAI “...to build “new Azure AI supercomputing technologies.” Four months later in November 2019 , NVIDIA and Microsoft would announce that Azure would now offer a “a new kind of GPU-accelerated supercomputer in the cloud on Microsoft Azure,” networking together up to 800 NVIDIA V100 GPUs using Mellanox’s InfiniBand tech, and the first time I can find where you could rent out massive clusters of AI GPUs. Microsoft and NVIDIA engineers even trained their own conversational AI model called BERT . The deal itself wouldn’t close until April 2020 , and a month later in May, Microsoft and OpenAI would announce that they had built a 10,000 GPU “supercomputer” together, with sources telling The Register that it was likely made up of AMD CPUs and NVIDIA V100 GPUs.  The same month, NVIDIA would release its A100 GPUs , which remain somewhat of a workhorse for AI Compute, and were a huge commercial success. Another significant milestone came two months later in July 2020 , when NVIDIA would publish a blog about how OpenAI researchers had released a paper describing how they’d trained GPT-3 using its Volta-era V100 GPUs ( released in 2017 ).  In August 2020 , NVIDIA’s data center revenue would outpace its gaming revenue for the first time in the company’s history, “aided largely by the Mellanox acquisition” per Holger Mueller of Constellation Research.  In other words, Jensen Huang and NVIDIA were far more foundational to the AI bubble than Sam Altman or Elon Musk, quite literally buying and building the company and the infrastructure necessary to build large language models.  While June 2017’s Attention Is All You Need paper absolutely kicked off the transformer-based model boom, NVIDIA and Baidu’s late 2017 research into mixed precision training that allowed model developers to use nearly half as much memory during training without losing accuracy, and also train faster on NVIDIA’s newer chips, a technique that became the standard in the early days of LLMs, shouldn’t be overlooked. In August 2021, OpenAI would launch Triton , a Python-esque coding language specifically built to make it easy to write code that ran on GPUs that would become foundational to the entire AI boom. Three months later, Microsoft announced that OpenAI’s GPT-3 was now available on an invite-only basis to customers via its new Azure OpenAI Service . Then came 2022 — a rough year for everybody, per my second Hater’s Guide To NVIDIA :  NVIDIA’s Q3 FY23 (November 2022) earnings were rough , missing on analyst expectations , though not as rough as Q2 FY23, when it had to pre-announce that it had missed on guidance by a little under $2 billion .  While NVIDIA had started shipping its H100 GPUs with data center sales eclipsing its gaming revenue by about $2.2 billion, it had yet to fill the hole caused by the post-pandemic dropoff of PC and graphics card sales or, more aptly, the hole left by the collapse of cryptocurrency mining.  And then a mere two weeks later, Sam Altman announced the launch of ChatGPT , creating the greatest sense of FOMO in the tech industry’s history. Per the New York Times , “...the entire agenda of [Google] had changed” as a result of ChatGPT, and Satya Nadella was “gleefully” ordering billions of dollars of NVIDIA GPUs.  By March 2023, every major hyperscaler was now offering NVIDIA H100 chips , and a month later in April 2023, NVIDIA would invest in the Series B round of CoreWeave , a former Ethereum miner backed by Magnetar Capital, which was famous for backing dodgy CDOs during the Great Financial Crisis .  Somewhere in early 2023, CoreWeave got a new customer — NVIDIA itself, according to The Information . This deal was part of a wider strategy dubbed “Project Osprey,” wherein NVIDIA would spend $1.3 billion over four years to rent back its own GPUs for whatever reason, making it the second largest customer behind Microsoft, who was renting capacity for OpenAI. That Microsoft deal would eventually lead to the creation, per The Information , of the first GPU-backed financing led by private equity firm Blackstone, emphasis mine: This deal would, as The Information notes, become the template for basically all data center financing, rationalizing the notion of lending unprofitable, debt-filled neoclouds like CoreWeave billions of dollars to build data centers as long as some sort of other counterparty agreed to rent capacity in the future. And when lenders needed further justification — by which I mean proof of cashflows — they’d happily tick the box because NVIDIA had agreed to pay its customers to rent back the GPUs that all that debt was being raised to buy. In September 2023, Bernstein analyst and alleged professional Stacy Rasgon attacked “Twitter randos” for suggesting, and I quote , that it was a conspiracy theory to believe the following: Three years later, Rasgon has now downgraded NVIDIA , and worries about the following: Stacy was, of course, talking about Jack Gamble (AKA JG_Nuke) who had repeatedly critiqued CoreWeave as a pump and dump inflated by NVIDIA in its earliest days in 2023.  I mention this because I believe analysts and the mainstream media have been critical to inflating the NVIDIA Bubble, and in laundering the reputations and rationalizing the inherent lunacy of the AI bubble. As long as NVIDIA “beat and raised” — as in beat analyst expectations and raised guidance — everybody was happy and looked away from the many, many things wrong with this picture. And 2023 was the year that NVIDIA’s circular financing took off, with the company investing in Cohere , Synthesia , Runway , Hugging Face (which it would eventually acquire), Perplexity , Together (an inference company that also buys GPUs), and Mistral . At this point, NVIDIA’s bubble had begun to inflate, with a landgrab to invest in anything AI related and to buy as many GPUs as possible, per me in Part 2 of my Hater’s Guide To NVIDIA: What was missing, of course, were revenues. But none of that mattered! A captured media ecosystem and a brainless market credited AI with basically any related revenue growth for anybody who bought NVIDIA GPUs.  Behind the scenes, Jensen was doing everything he could to keep growth going, making sure CoreWeave was able to raise more than $10 billion in debt from a handful of very specific bankers that he’d conned into believing the idea that building endless AI data centers would create infinite cash.  By February 2024, the sudden influx of demand led to Jensen ruefully discussing the “fairest” way to decide who gets its GPUs , and a month later he’d announce Blackwell , the next-generation NVIDIA GPUs that cost tens of thousands of dollars more depending on the configuration , specialist cooling and entirely new racks, massively increasing the cost of data centers and, in turn, increasing NVIDIA’s revenues.  In June 2024 , Jensen would claim that “the more you buy, the more you save” under what he called “CEO Math,” but I would call “complete bullshit”, per Business Insider: That, by the way, is about as much “skepticism” as you’ll find in this era, and why the bubble was allowed to inflate. At no point can I find any substantive conversation about the actual benefits of buying NVIDIA GPUs , or any of the financial returns , or really anything other than…well…fluff.  You see, everybody loved the AI bubble. Liking AI allowed you to talk about something new and exciting , and nobody would argue with you if you said you thought it was going to make everybody a bazillion dollars. They would, however, attack you viciously if you dared to suggest anything was wrong — something they still do to this day! — because, as Jensen realized, AI had become load-bearing for the entire stock market, even though the only people making money on AI were NVIDIA and other semiconductor companies. And somewhere between 2023 and 2024, Jensen met Alice Huang (no relation) , and between March 2024 and June 2025, per the Wall Street Journal , Megaspeed would buy “nearly $12 billion worth of top-of-the-line NVIDIA chips” and send them to Chinese firms, including Blackwell chips that it claimed had demand that was “well above supply” in August 2024 and by October 2024 was “ sold out for the next 12 months ,” partially as a result of Jensen Huang creating that demand via CoreWeave and in his dealings with Megaspeed. In 2024 alone, NVIDIA would invest in data center firm Applied Digital (CoreWeave’s landlord), as well as neocloud Nebius and Stargate Abilene data center builder Crusoe . In 2025, it would anchor CoreWeave’s IPO ( which couldn’t have proceeded without NVIDIA’s help ), agree to pay neocloud Lambda $1.3 billion over four years to rent back its GPUs , invested twice in British neocloud Nscale, invested in Crusoe again , and extended its deal with CoreWeave to pay it $6.3 billion . In August 2025 , CFO Colette Kress would sing the praises of “extraordinary” and “soaring global demand,” and in October 2025, Jensen would claim ( and Reuters would report ) that there were “$500 billion in bookings for its AI chips.” What did that mean? Who knows. Nobody asked. Nobody dared harsh the flow. Would NVIDIA make $500 billion in that period? No. Huang would claim in NVIDIA’s Q3 Fiscal Year 2026 earnings ( November 2025 ) that “compute demand keeps accelerating and compounding across training and inference — each growing exponentially.”  All of this was part of the kabuki theater of NVIDIA — claims that there was “astonishing demand” for AI GPUs at a time when it was doing everything it could to inflate that demand by funding companies explicitly to raise debt and buy GPUs. The first sign of desperation began in September 2025, when Jensen Huang would go on CNBC and announce that non-existent deal with OpenAI . Per the Wall Street Journal , talks never progressed past their earliest stages. This did not stop anyone from reporting the deal as done for literally months — its intention was entirely to create the imaginary sense of “demand” that would mean you have to do whatever Jensen needs to get his GPUs.  And, of course, to continue fooling the media into believing that there was “incredible demand for AI.” In a December 2025 piece, TIME would mention that Jensen Huang was “unhappy,” because NVIDIA “had to publicly declare that its China revenue had shrunk to $0,” leading to him lobbying the Trump administration to change chip export rules that NVIDIA was at the time vigorously violating. By the end of 2025, NVIDIA had also agreed to around $27 billion worth of cloud compute agreements in total — literally agreeing to rent back its GPUs from its customers — and as of its last earnings report, these agreements had grown to a remarkable $36 billion. Not once during these three years did we ever learn what revenues Microsoft, Google, Amazon, or Meta made from renting out NVIDIA GPUs, but we didn’t need to, because the media was all too happy to claim that Microsoft and Google’s bets on AI had paid off as early as 2024. It didn’t matter that OpenAI or Anthropic lost billions, it didn’t matter that CoreWeave was a time bomb , it didn’t matter that NVIDIA was literally paying its customers to buy its GPUs , it didn’t matter that NVIDIA was effectively stepping in whenever anyone had any doubts about the AI bubble , as long as hyperscalers — and most importantly NVIDIA — kept beating on estimates and raising guidance. Even though, as I’ve mentioned, the actual revenues from AI are nowhere to be seen. Thanks to Bloomberg , we eventually found out that Microsoft’s Fiscal Year 2026 AI revenues were around $34 billion, with $24.1 billion coming from OpenAI, meaning that $265 billion in capital expenditures since 2022 (at the time) had bought Microsoft a single-digit AI business outside of feeding itself money by investing in OpenAI. As we can see in hindsight, it’s clear that there never was “insatiable demand” for AI chips outside of Jensen Huang’s pressure tactics, some of which involved claiming there was “limited availability” of chips that he himself made sure were in limited supply, mostly by making sure that NVIDIA-incubated customers bought them using either NVIDIA’s investment or debt raised using that investment, like when NVIDIA put in at least a billion dollars into an SPV that raised money for Elon Musk to buy NVIDIA GPUs in January 2026 . And the most-damning proof we’ve had of there being no real “demand shortage” is that NVIDIA has been forcing customers like Amazon to take billions of dollars of GPUs months in advance of when they’d need them as part of an “early rack receipt program,” with Business Insider revealing one crucial piece of information: In other words, Jensen Huang said that if you don’t buy the chips now — even though you have “no clear forecasted path” to install them — you won’t get them when you “need” them. As I’ve said recently, based on analyses of earnings statements and documents viewed by this publication, I believe there are over $200 billion worth of NVIDIA GPUs that are sitting in warehouses waiting to be installed as a result of artificial demand pressures created by Jensen Huang and NVIDIA.  This is how NVIDIA has beaten expectations and raised guidance basically every fucking quarter for the past two years — circular financing, illegal chip smuggling and channel-stuffing.  The most important rule of living in the NVIDIA Bubble was that everybody kept in line, saying there was always more demand for GPUs, always more demand for AI, and that everybody was making lots of money… even though none of that was actually true. Back in August, I used analyst notes to prove that the vast majority of AI demand — 70%+ of revenue and 80%+ of compute demand — was from Anthropic and OpenAI buying compute, and the sheer power of the NVIDIA Bubble was such that people simply ignored it because it was uncomfortable to think about. Last week, Sam Altman said the quiet part out loud at a Samsung conference , emphasis mine: One particularly-childish view that I’ve heard is that if NVIDIA falters, AMD or Broadcom could potentially “pick up the slack” and “capture the demand,” as if said demand was not entirely a result of Huang’s dealmaking and his aggressive use of NVIDIA’s balance sheet. Your open source model company fails to close a financing round? NVIDIA will pay $6 billion to “license” its tech and take some of its employees . A shitty AI search company that nevertheless buys hundreds of millions of dollars’ worth of compute starts running out of money? No problem, NVIDIA’s got billions to make sure Perplexity keeps chugging . CoreWeave’s landlords get worried about it not making its lease payments? No problem, NVIDIA has backstopped the leases . Anthropic needs another $10 billion to make prepayments on its compute? No problem, NVIDIA is kicking $10 billion into its IPO .  There’re also very few other companies out there like NVIDIA, which had twelve-month trailing free cash flows of $127 billion through its latest quarter, second only to Apple, which had $136 billion.  As of its latest quarter, NVIDIA also had about $99.4 billion in total liquidity — more than AMD ($15.8 billion) and Broadcom ($24 billion) combined, with better credit (AA versus A and A- respectively), lower net debt, and an interest coverage ratio (IE: how many times it could pay its interest expenses with its operating income) of 435x compared to Broadcom’s 17x and AMD’s 65x. Additionally, NVIDIA has significantly more capacity booked with TSMC and the memory cartel, largely as a result of being able to afford it and justify it with upcoming revenues, even if said revenues were artificially inflated with circular deals. In other words, NVIDIA has more cash, better credit, a better balance sheet, and spent three fucking years building hype, FOMO and funding its own customers so that by 2025 there were entire companies that existed functionally to either buy or rent NVIDIA GPUs.  This is a plan that took years — or a decade, depending on how you think about it — to execute, and its collapse was inevitable, because it’s clear that despite his bravado and confidence, Jensen Huang was desperate and would do literally anything to keep the beat-and-raise machine alive.  The Chinese smuggling was and is one of the single-most brazen acts I’ve seen in the history of capitalism — a flagrant, well-documented campaign of export control violations perpetuated at times in broad daylight, ignored by much of the press, to this day referred to by some as a “conspiracy theory” despite GamersNexus’ smuggling report from August 2025 , the New York Times reporting in October 2025 , Bloomberg’s reporting in December 2025 , Wally Liaw of Supermicro’s arrest in March 2026 , and Culper’s massive short report in May 2026 proving in vast detail that NVIDIA is absolutely involved in illegal smuggling of GPUs to China. Yet the most-damning part of all of this is how willing everybody was to ignore the circular financing, and no, I’m afraid that all the grab-bag articles saying “wow, NVIDIA sure has invested in a lot of its partners!” don’t count.  The media rubber-stamped every single circular deal throughout the AI bubble because there were hundreds of millions or billions of dollars attached — even if they weren’t real! — from NVIDIA or one of NVIDIA’s customers, all without any consideration or discussion of how unstable it was or, more importantly, how NVIDIA was inflating its revenues by creating these circular relationships. While the cries to restore Jensen Huang have fallen on deaf ears, even if he were to return, it’s clear that the circular financing era was coming to an end regardless of who was wearing the leather jacket.  And it’s important to measure how incredibly large a loss that is. Per The Wall Street Journal : That means 27% of all venture capital funding in 2026 flowed from NVIDIA, and those that didn’t lock down their funding are incredibly worried, including Nscale, which, per the FT , needs more money to complete its massive contract with Anthropic: Bloomberg also reports that NVIDIA invested $2 billion in Nscale in September — a billion more than we knew — but apparently said billions weren’t sufficient, and it’s unclear what’ll happen next, much like it’s unclear what happened to NVIDIA’s supposed offer to buy Reflection AI, per the WSJ, or its investment in Thinking Machines: Huh, that’s weird. Why would NVIDIA invest in or buy AI labs?  Ohhh. Right. The NVIDIA Bubble might get pricked if anyone buying AI compute — even those who quite literally can’t afford it! — blinks for even a second about the prospect of buying more.  And that’s been the core of the Jensen Huang hustle — NVIDIA invests, NVIDIA rents, NVIDIA backstops, or NVIDIA introduces you to Microsoft, Anthropic, OpenAI, or Meta, one of whom is a customer of basically every single AI lab, which should tell you about how much demand for AI there really is. The Journal’s piece ends with a gutpunch that tells the entire story of the AI bubble:  Without Jensen, there is no AI bubble, because if anybody else acted like Jensen they’d look like a fucking lunatic, mostly because the NVIDIA Bubble’s purpose was to rationalize the irrational and provide justifications for basically anything. If you worried that your customer couldn’t pay you, Jensen would invest. If you worried that you couldn’t pay your vendors, Jensen would backstop your leases.  And despite the constant threat of demand outstripping supply, Jensen could always get you more GPUs — and, per Elon Musk , many of his deals were “a handshake” rather than a “written contract,” with a “purchase order coming together at some point later.” One has to wonder how many of the “deals” announced by NVIDIA in the last few months — or any of that egregious forward guidance — was based on Jensen’s “handshakes,” or his ability to mobilize suppliers and vendors and financing under the banner of “insatiable demand for AI.” Except…it’s very clear that era is over. Per the WSJ , Jensen was warning as much at a conference in October, emphasis mine: This is three very specific warnings baked into one: While the third point is obviously bollocks, the first two suggest both tightening financing conditions and NVIDIA’s unwillingness to bankroll its own bubble, and a suggestion that with or without Huang, the end was already approaching at high speed. And without Jensen — and the central bank of AI — there’s very little keeping this entire thing afloat. While hyperscalers might have been afraid of pissing off Jensen and getting put in Jensen Jail , I don’t see Amy Hood (CFO of Microsoft) being intimidated by the meager presence of Colette Kress demanding that she (and other hyperscalers) take billions of GPUs in advance.  Without Jensen, NVIDIA loses its don (credit to Michael Burry for that one) and its ability to use mob-like tactics to push around its customers or constantly provide, per the New York Times , questionable deals that nevertheless made bankers billions of fees: Huang’s cachet was so significant that he was able to bully the CEOs of effectively every major private equity firm into lying on television about a non-existent $500 billion deal to fund data centers, emphasis mine: Jensen’s presence was not just finding the deals , but calling up the right bankers at the right time and giving them explicit or implicit guarantees that NVIDIA’s balance sheet would hold up the other end of the deal. And without Jensen, the NVIDIA Bubble bursts, leaving behind an industry that must reconcile with the consequences of its destructive mania. Whatever value you may or may not think AI has, it is not paying for itself. It is a continual drain on the debt markets and the venture capital industry.  Anthropic has $141 billion in cash, wants to raise another $70 to $90 billion, and will not be cash-flow positive before 2030 according to underwriter Goldman Sachs . It also has $895 billion in compute commitments, which is the real reason NVIDIA is investing $10 billion at its IPO — Jensen doesn’t care if the chips ever get rented, he cares that somebody has a reason to buy them, or issue debt to the company doing so. In reality, the “demand” for AI GPUs was manufactured by Jensen Huang and the hype cycle he created through exploiting the desperation of a flailing tech industry. The industry’s lead cheerleader and House Whip was also its central bank, an evil Michael Clayton figure that loved profiting off of bullying, monopolization, and legal cons that only made sense because he was going to do anything he could to keep you from not paying for AI, which required keeping as many companies alive as possible.  Anyone else doing this in literally any context would be considered a lunatic. Perhaps Jensen was one too.  In any case, nobody else has the balance sheet, credit rating, assets, cashflow and psychopathy to do the same. Jensen spent 33 years inflating the NVIDIA Bubble, and it took less than a week for it to collapse.  I want you to think deeply about why you think there’s “demand” for AI, and how much of that belief is built upon a fantasy concocted by Jensen Huang: Even Anthropic’s demand appears to be slowing, with growth ( per Ramp ) trending to around 15% to 25% quarter-over-quarter in Q4 2026, down from 47% in the quarter before and over 140% in the quarter before that.  One has to wonder how Anthropic — or OpenAI’s — customers will be able to afford those tokens if there’s a generalized sense that the money has run out. Remember: it’s not just that Jensen invested , but that everybody ultimately relied on the idea that Jensen would always be there if somebody else couldn’t invest. There was always the sense that NVIDIA had everybody’s back, mostly because, well, NVIDIA has, up until recently, had everybody’s backs as part of a giant, quasi-legal circular financing operation that the media applauded right up until it sputtered. As I’ve explained for years, the entire tech industry has become obsessed with growth-at-all-costs thinking — or what I call The Rot Economy — which inevitably dragged it into an era that was defined not by delivered value but by speculation on what might happen if we all put another few trillion dollars into something.  In reality, buying NVIDIA’s GPUs was always a shitty deal, though nowhere near as bad a deal as renting them. Hyperscalers won’t share their AI revenues because their AI revenues suck, and they’ve spent $1.4 trillion or more on what appears to be less than $100 billion worth of revenues, with the future theoretical hundreds of billions contingent on hyperscalers spending hundreds of billions more. OpenAI made up 11% of Microsoft’s total revenues in Q1 Fiscal Year 2026 , which suggests that Microsoft’s overall revenues are in decline and that its AI revenues aren’t filling the gap outside of an AI lab that lost $10.9 billion in Q3 2026 and raised only $11 billion of the $30 billion it wanted in its latest funding round at $1.25 trillion , which was also lower than expected. CoreWeave, Nebius, IREN, and every neocloud is woefully unprofitable, with the justification being that if they just stopped raising money and finished all of these data centers they might one day have positive margins, somehow. Braindead analysts are now suggesting that “customer prepayments will help instead of debt,” which is contingent on companies that rent AI compute making prepayments, most of whom are unprofitable.  While hyperscalers could fill the gap, hyperscalers are already in an overbuild situation, mostly driven by Jensen Huang’s pressure campaign.  Demand for AI services has never, ever made sense, with Anthropic and OpenAI making up 89% of all AI startup revenues and both of them being both unprofitable and agreeing to spend over $1.3 trillion in the next seven years , most of which is contingent on continual funding and debt. We do not know the revenues of effectively any other AI startup, only annualized run rates that tell us very little about the actual financial conditions of the company and the occasional reporting that tell us a dog like Cognition would burn $800 million in 2026 alone .  Even with the best possible read of those annualized run rates, these startups raise hundreds of millions or billions of dollars’ worth of funding to make tens or hundreds of millions of dollars in revenue, and need to do so every few months due to the remarkable cost of renting NVIDIA GPUs, which despite being multiple generations in do not seem to be getting more efficient for the end customer. In many ways Jensen Huang created the perfected form of Jack Welch’s GE Capital , manipulating the markets, the media and the banking system into affirming his every decision by making sure that everybody had somebody else to pay or get paid by, even if the entire system was terrifyingly brittle.  And the worst part is that Jensen never really cared about whether there was demand for AI outside of its ability to justify further debt or cash for buying AI GPUs. The majority of the backstops that NVIDIA has provided — like its leases for Oracle, Anthropic, and OpenAI — require the data center capacity to be built before NVIDIA pays a dime, punting any theoretical time at which he or his heir would have to “backstop” anything into a time so far in the future that it doesn’t really matter.  Every CoreWeave or neocloud debt deal follows the same path — a customer agrees to buy unbuilt capacity, the debt is raised, the GPUs are bought, and then nothing happens until the data center is actually finished, which may take years, but none of that matters as long as NVIDIA got paid. Who knows what happens in NVIDIA’s earnings today. Perhaps they beat and raise again, with Colette Kress coasting off of the previous three months’ worth of circular financing deals that kept the machine alive.  Then again, the amount of stories in the past week that have said something to the effect of “Colette Kress and NVIDIA do not want to do circular financing anymore” suggest that the company may be getting ahead of something — such as pulling or lowering revenue guidance, perhaps blaming everything on the “challenging transition” rather than “the collapse of the circular financing economy.” In any case, the NVIDIA Bubble has popped. Jensen Huang is done. NVIDIA is no longer the circular financing titan, and anybody depending on its theoretical backing for future financing or funding is shit out of luck. There is no longer a well-funded boob-signing billionaire playboy left to beguile the press, con financiers, and pump the most wretched of bags in an endless conga-line of dodgy deals with goal of goosing NVIDIA’s revenues by any means necessary, even if the eventual data centers never actually get bought. The NVIDIA Bubble inflated at the perfect time, with Jensen capitalizing on the industry-wide knowledge ( as I wrote back in the Rot-Com Bubble ) that tech was flat out of hypergrowth ideas. NVIDIA offered hyperscalers and their brainless executives a panacea — a magical chip that allowed them to monopolize both the software layer and the infrastructure underpinning it, if only they’d just buy enough GPUs and build enough data centers to house them. All that mattered to Jensen was keeping them believing in the dream. Unfortunately, the vast majority of people do not want to pay for AI, and the vast majority of those who pay for AI compute can’t afford to do so. Those buying NVIDIA GPUs refuse to explain how much money they’re making from renting them out, or what it costs to do so. We do not know how many active AI GPUs there are in the world, and hyperscalers like Microsoft have taken great pains to mislead us into believing they have gigawatts more in capacity than they actually have .  There’s a reason that NVIDIA has $36 billion in compute commitments — because the actual demand for AI compute is much, much smaller than the demand he created for his GPUs. None of this mattered because Jensen Huang always made sure that nobody thought about it too much. The moment NVIDIA’s growth slows, it’ll be all that anybody can think about.  If you liked this piece, you should subscribe to my premium newsletter, and you can subscribe on the following links: $70 a year , $18 a quarter , or $7 a month . If you want to get in touch — and especially if you have any juicy information about Anthropic, OpenAI, or any other companies in the AI bubble — hit me up on Signal at ezitron.76. I’m also on IB on your Bloomberg Terminal.  You’re gonna need customer prepayments to buy GPUs, which will require cash up front from your customers, who are for the most part functionally in default. You’re not going to be able to raise debt without being able to do so, if at all. Bring me cash or I’m not going to guarantee I can sell your GPUs, which are in tight supply, honest. There’s massive demand for AI GPUs . Is there? Jensen Huang pushed customers to take billions of dollars’ worth of chips months in advance, with $200 billion or more of them sitting in warehouses thanks to a lack of capacity or power to install them. That “demand” appears to be a result of channel-stuffing, and if it’s not, why the fuck did they have to pay for the chips and take them earlier than they need them? There’s massive demand for AI compute . Is there? The vast majority of AI compute is sold to either Anthropic or OpenAI. The vast majority of Microsoft, Google, Oracle, CoreWeave, Nscale, Lambda, Amazon and Firmus’ backlogs come from OpenAI, Anthropic, Meta, or a hyperscaler buying capacity for OpenAI and Anthropic. There’s massive demand for AI tokens. Is there? 80% of Anthropic and OpenAI’s revenues come from 1% of their customers, the vast majority of which are unprofitable AI startups , with the largest purchasers of these tokens — like Perplexity, Cursor, and Reflection AI — all funded by NVIDIA.

0 views
Unsung 2 weeks 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 2 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 3 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 1 months 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 1 months 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 1 months 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 1 months 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 1 months 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 1 months 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 1 months 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 1 months 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