Full Width [alt+shift+f] Shortcuts [alt+shift+k]
Sign Up [alt+shift+s] Log In [alt+shift+l]
SplitDuck.com Use A/B testing to increase revenue
1

How I Handletter

from Daniel Marino [alt+shift+b] in programming

When I first got into hand-lettering, I had a hard time finding people who shared their full process—especially the digitizing phase. So here’s a look at how I typically work. Everyone’s process is different, and a lot depends on your style and how you plan to present the piece. For me, since I don’t have the steadiest hand, I tend to embrace rough, scrappy, distressed looks. Most of my work ends up digital anyway, so mistakes can be fixed later. Here’s a short process video I made a while back. Thumbnails & Sketching Start with quick thumbnail ideas on scrap paper. Refine the chosen direction with a pencil on Bristol Paper. If possible, I use a drawing pencil (softer, lighter lead makes cleanup easier). After inking, I clean up with an art gum eraser. Inking My go-tos are Microns in different thicknesses. In the video I sharedI used a .08 for outlines and Graphic 1 for filling letters. I used a Gelly Roll 10 to add cut-outs, create depth, and fix small mistakes 😬. Digitizing I scan the inked artwork using Scanner Pro on iOS. Clean up in Pixelmator Pro. Add textures for distress and wear (I’ve collected a bunch of texture packs over the years). Where I’ve Used This This is basically the same process I followed for my State Motto series, and most of my other lettering projects. Don’t be afraid to lean into your natural tendencies (like a scrappier style if your hand isn’t steady) and use the digital phase to enhance or correct. Trial and error is a huge part of it.
19th Sep 2025

Stay updated

Get a weekly newsletter with the top 5 articles worth reading every week.

More from Daniel Marino

Letting Claude Teach Me

Now that I use AI regularly to help write code and complete tasks, I find myself in a position where I’m not learning as much as I used to. That feels a bit crummy. Fairly often, Claude writes code I don’t fully understand. For example: I know enough TypeScript to be dangerous, but I’m definitely not an expert. Recently I had Claude take some typing I thought was overcomplicated and drastically simplify it. The new version was clearly better — I just couldn’t tell you why. So I asked Claude to explain it in simple terms. Sure enough, it did. I guess that’s a silver lining to using AI: it can at least explain why it did what it did. A coworker mentioned he has Claude write one-off explanations with examples whenever this happens, and I liked that idea. So I built a skill around it. The skill looks at my uncommitted code, breaks it down, and writes a short blog article for me to read. I’m a fan of Josh Comeau’s blog and the way he uses interactive examples to teach a concept, so I made that part of the skill too — Claude generates interactive examples alongside the explanation, then packages everything up in a small Vite environment. The first iteration was expensive to run. At least 3 minutes, and roughly 10K tokens. I’m fine burning tokens, but I’m also thrifty 😬. The second iteration kept the Vite environment and styles already wired up, so Claude only had to write the article and the examples. That brought it down to about a minute and 7K tokens. Better — though I’d still like to get the token usage lower. The blog format is great, but it’s a lot of work (for Claude) to generate all of this just to delete it when I’m done reading. It’d be nice to have these articles persist somewhere I could revisit later, or share with other people. That brought me to my current iteration. It’s an Astro project that lives on GitHub. The skill works roughly the same way — review uncommitted code, generate a post complete with interactive examples — but now it publishes to a TIL subdomain where I can read the articles at my leisure or pass them along. It’s all vibe coded, and that feels appropriate. I’m up front about it on the site itself: Things Claude changed that I didn’t understand — explained… by Claude. I’ll probably keep tinkering to bring the token usage down further, but it was a fun project to put together, and I’m happy to let Claude teach me what it’s doing.

4th May 2026 • 1 votes
What I’m Using in 2026

This is an updated list of what I’m using in 2026. I’m only sharing what’s changed since last year’s list. Applications Chrome — Chrome was on my list last year, but I’m mentioning it again because I actually used Brave for most of 2025. I like Brave, and honestly I can’t even remember why I switched back to Chrome 🤷🏻. ChatGPT — I hate that I’m listing AI tools, but if I’m going to be transparent, it has to be here. I use it a bit for code, but mostly for rewording messages or rubber-ducking ideas. Claude Code — I wrote about my thoughts and reluctance to embrace AI for coding. My company pays for it, so I use it. Endel — I’m neurodiverse and have been trying to be more intentional about using tools that help me stay focused. Endel is super cool and has a lot of genuinely helpful features. Hyper — I was previously using iTerm2, but switched to Hyper mostly because it feels prettier. That’s probably a dumb reason since I could have customized iTerm2, but I installed Hyper on my new machine and never felt the need to switch back. Retcon — My team is pretty opinionated about Git history, and rewriting history via the command line or VS Code started to feel tedious. Several coworkers use LazyGit, but I didn’t want another terminal-based tool. Retcon does exactly what it promises and lets me handle more advanced Git workflows without having to be a Git super-nerd. Notion — I was using Bear for notes, but didn’t feel like I was getting enough value out of paying for it. That’s not a knock against Bear—it’s a great product. Notion’s free plan works just fine for me. I also tried Obsidian this year and liked it, but parts of it felt quirky. It also seemed like a bigger time investment to make it feel as polished as Notion or Bear. VS Code — I tried Zed for a bit, and there are things I really like about it. That said, I ran into a few weird and buggy behaviors that I just couldn’t get past. Equipment I got a 2025 M4 MacBook Pro when I started my new job this year. It’s more than powerful enough for anything I need to do.

4th Jan 2026 • 1 votes
The Money Filter

One of the biggest challenges I’ve faced as a web designer is how often people expect a website for next to nothing. Somewhere along the way, the perception formed that a website is a commodity—quick, cheap, and interchangeable. So when someone asks what I charge (for a very basic marketing site), I usually reply, “That’ll cost around $5,000.” That number isn’t a gimmick—it’s a filter. It immediately reveals who understands the craft behind the screen, who values quality, and who’s serious about investing in their own business. It separates those looking for something fast and inexpensive from those seeking something purposeful and crafted. It used to frustrate me when people balked at the cost. Now? I see it as a helpful sorting mechanism. It shows me who I actually want to work with. The Cost of “Cheap” There’s no shortage of DIY website builders promising professional results at a low price. And honestly—sometimes that’s fine. If you just need something quick and functional, a template might be all you need. But a boutique website is something entirely different. When you hire me, you’re not buying convenience—you’re investing in craft. A boutique site is designed and engineered specifically for you. It’s not a template dressed up with new colors. It’s built intentionally, shaped around your goals, your audience, your brand’s personality, and the experience you want people to have. And cheap solutions often come with hidden costs: lost conversions poor usability and performance accessibility issues a generic, forgettable brand presence The value of a bespoke website isn’t just in what it does. It’s in how it’s made—and what it communicates about you. Why Bespoke Work Matters When I build a custom website, it’s not just about aesthetics. It’s about alignment—making sure every part of the experience supports your story, your content, and your clients’ needs. Every choice—typography, layout, semantics, performance—is intentional. Anyone can make a website that looks good. I handcraft websites that feel right and function beautifully. As a design engineer, I don’t hand off a static mockup and hope the final result captures the original intent. I design with the intent to build, carrying the project from concept to code so the final experience is cohesive, thoughtful, and true to the vision. That’s what boutique design is: every pixel and every line of code has purpose. The Bottom Line If you only need a website, you don’t need me. But if you want a boutique digital experience—something that reflects your values, your vision, and your commitment to quality—then I’m the right fit. You’re not paying for a website. You’re paying for craftsmanship, collaboration, and care. And while not everyone values that, the right clients do. My pricing isn’t just a number—it’s a filter that helps me focus on the people who appreciate the work, the craft, and the impact it can create.

30th Nov 2025 • 1 votes
Vibe Coding and the Existential Dread of Progress

Does anyone else hate the term vibe coding? I’ve been pretty resistant to incorporating AI directly into my development workflow. I use it all the time to clean up emails, Slack messages, and blog posts (including this one). It’s helped me plan vacations, write my cover letter for Planning Center, and even gain insights from journaling. But coding? That felt like crossing a line. At first, I confined AI to repetitive tasks—formatting long word lists into arrays, deciphering cryptic console errors, or exploring how to integrate Vite into a Rails codebase still using Sprockets. All helpful, but I steered clear of anything that touched “real” engineering. Still, AI isn’t going anywhere. And as much as I hate admitting how much I rely on it, it genuinely makes my life easier. So I gave vibe coding a shot. Spoiler: I’m sold—with a few caveats. Vibe Coding an Alfred Workflow I’d played with basic Alfred workflows before, using the built-in UI or tools like Alfy. But I had an idea for something more complex—and neither the time nor the motivation to learn how to build it from scratch. The Problem At Planning Center, our design system has 300+ tokens (and counting). To grab one, I’d open our Storybook instance, scroll to the search bar, type in a few characters, click to copy, then return to my editor to paste it. Repeat that a few dozen times a day, and the friction starts to add up. The Solution An Alfred workflow that lets me search tokens via fuzzy matching, press Enter to copy, and paste directly—eliminating multiple steps and speeding up my flow. Using Claude Code I’ve tried ChatGPT and GitHub Copilot. They both work well (though I find Copilot’s integration with VS Code a bit invasive). I’m not ready to pay out of pocket, so I started using Claude Code through Planning Center’s access. Setup took less than 10 minutes. Anthropic’s documentation is clear, and their tips on effective usage are actually helpful. Building the Workflow with Claude Code I kicked things off with a prompt: I want an Alfred extension where I can enter “tt” followed by characters, and tokens from URL redacted will be shown using fuzzy search. Claude generated a Python script… that didn’t work. It produced a workflow Alfred couldn’t import. So I responded with: The Alfred extension fails to import. Claude replied something like, “You’re right, let me fix that,” and, impressively, it did. After about three hours of iterative prompts and debugging, I had a fully functional Alfred workflow that: Stores design tokens as a JSON database Caches data locally Refreshes if unused for over an hour Fuzzy-finds tokens on input Displays color swatches for color-based tokens I also used Claude to: Generate 100+ color swatches (since Alfred can’t use data URIs) Write a Bash script that builds the workflow with semantic versioning I don’t know much Python, but I know enough to skim the output and feel confident in the structure. And because this was a small, siloed project, I wasn’t concerned about maintainability or codebase conventions. The Cost Aside from the monthly AI access fee, the entire three-hour build process cost around $10 in usage tokens. That’s ~$3.33/hour—far below the value of my time. And now, every use of the workflow saves me 10+ seconds. That adds up quickly. If I’d tried to build this from scratch, it easily could’ve taken 10+ hours and been half as effective. That’s not even accounting for generating the color swatch images. I did spend about an hour trying to get Claude to scrape the tokens directly from the design system site, but that turned out to be unreliable. Still, the final solution works and required zero extra effort from the rest of my team. The Pros and Cons of AI in the Workflow Pros Efficiency Boost: Great at handling menial but necessary tasks—JSON formatting, token lookups, error decoding, etc. Rapid Prototyping: I built a working Alfred workflow in a single evening. Even if it were only a prototype, it would’ve been valuable. Creative Leverage: Designers and PMs can use AI to sketch out ideas and flows, helping engineers jump into development faster. Cons Skill Stagnation: Over-reliance on AI could erode problem-solving ability or deeper understanding of frameworks and languages. Job Displacement: AI is replacing some roles. At Planning Center, leadership has been clear AI won’t replace people—only support them. But the broader industry picture is less certain. Environmental Cost: Running large AI models consumes a lot of energy. Price Tag: Even if it saves time, AI access and usage can get expensive—especially if you’re footing the bill. So Why Do I Still Feel Icky? It took me a while to name the feeling, but I got there: I’m grieving the loss of what it means to be an engineer. I’ve spent over 20 years solving problems, building UIs, and turning ideas into code. I’ve always taken pride in being able to take a design and bring it to life. But now, what it means to be an engineer is changing—and that’s uncomfortable. I don’t want to become just a prompt wrangler. But I also don’t want to be the person who gets left behind because they refused to adapt. The logic is clear: why pay one engineer for 10 hours of work when another can produce the same result in two with AI? Finding the Sweet Spot I think the answer lies somewhere in the middle. Engineers should still understand their craft—be able to reason through problems, write maintainable code, and build features from scratch when needed. But AI should be a tool we use intentionally to reduce toil and accelerate progress. We don’t call it cheating when someone uses code completion. Why should this be any different?

19th Jul 2025 • 1 votes

More in programming

The GradScaler implosion: how filtered-out NaN gradients became NaN weights

I noticed something odd when I was training some models the other day -- something that went against my understanding of how PyTorch's Automatic Mixed Precision (AMP) training tools worked. In particular, I believed that the GradScaler class filtered out non-finite gradients -- that was based on this comment in the AMP recipe page: # ``scaler.step()`` first unscales the gradients of the optimizer's assigned parameters. # If these gradients do not contain ``inf``s or ``NaN``s, optimizer.step() is then called, # otherwise, optimizer.step() is skipped. However, I was finding that the weights of a model I was training were all being set to NaNs, and while I could see ways that could happen even with finite gradients, none of those appeared to be happening. Understanding your tools properly is an essential part of engineering, so I decided to dig in and find out what was happening -- in particular, what I was misunderstanding about what was going on. This post has the details, but so as not to bury the lede, while the GradScaler does not let non-finite gradients through, that's more a side-effect of its real purpose -- and if it gets into a sufficiently degenerate state, it will actually filter non-finite gradients, but respond to good, finite ones by trashing your weights! The good news is that it's only likely to do this if your model is in such a messed up state that your training run is probably doomed anyway. I don't think it can reasonably be called a bug, as a well-designed training run should have errored out before it kicks in. Here's how it works. The problem I was training a weight-tied model as part of my yak-shaving trajectory towards exploring the logit lens. Weight-tied models are fiddly to train -- you need to get your hyperparameters and the like just right, or they head off into infinite loss territory. But I'd spotted that the weights -- not just the loss -- in the last checkpoint for one of my failed training runs were all NaNs. Now, I was using AMP, which -- as I said -- I believed would be filtering out non-finite gradients, so I was initially quite surprised by that. I was sometimes getting NaN for my loss, which would have led to NaN gradients, but those would have never been applied to the weights; only the finite gradients would. How could finite updates to finite weights make them non-finite? Only one possibility came to mind: a non-finite value can wind up in a float because it overflowed. So you can imagine (slightly handwavily) that the training run might wind up in a regime where it kept bumping weights up using finite gradients, step after step, and eventually they would all overflow. As a mechanism, it seemed plausible, so I decided to see if it was happening. I added a new optional training parameter, log_model_norms, and if it was set, in rank zero just after the code to step the optimiser and the learning rate scheduler, we'd log the current model norms to a JSONL file: if log_model_norms and rank == 0: with torch.no_grad(): norms = {name: p.norm().item() for name, p in model.named_parameters()} with open(run_dir / "model-norms.jsonl", "a") as f: json.dump( {"global_step": global_step, "norms": norms}, f ) f.write("\n") So: we'd log the L2 norm for each named parameter in the model. A named parameter in this sense is a parameter tensor: an unbiased linear layer would have just one, the weights matrix, while a biased one would have two, one for the weights and one for the biases. The L2 norm of a set of numbers is the square root of the sum of their squares, so it is a good proxy for the size of the numbers that make up each tensor. With that, I kicked off another training run, ran it until it diverged, then asked Claude for some charting code to plot the norms over time for everything, treating their initial values as 100 so that they all worked in the same chart. Here's what happened: So that was entirely different to what I'd expected! All of the norms grew steadily but appeared to be settling down, but then it looked like they all blipped up to NaN on the same step. I checked the raw numbers to be sure -- and indeed, prior to step 17,186, the norms were finite, and then they all switched over to NaN in one go. How could that happen if non-finite gradients were being filtered out by the GradScaler? The answer lies in what the scaler is actually doing under the hood. How the GradScaler works Up until this point I'd been treating the GradScaler pretty much as a black box. By following the recipe, I knew that in order to use AMP, you would change a training step like this: logits = model(inputs) loss = torch.nn.functional.cross_entropy( logits.flatten(0, 1), targets.flatten() ) loss.backward() optimizer.step() ...to this: scaler = torch.amp.GradScaler() # ...into the training loop with torch.amp.autocast(device_type=device.type, dtype=torch.float16): logits = model(inputs) loss = torch.nn.functional.cross_entropy( logits.flatten(0, 1), targets.flatten() ) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() The torch.amp.autocast context manager would do calculations in 16-bit floating point in cases where that would be relatively harmless, and in 32-bit if needed -- and the scaler would... do something to make that work smoothly. I'd not really dug into what. That felt like a gap! Unfortunately the PyTorch docs are very light on what happens. There's the recipe I linked to above, which just says how to use it, and the API docs for the GradScaler itself, which just define the signature of the constructors for two deprecated versions of it, both of which look like this: class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True) See torch.amp.GradScaler. torch.cuda.amp.GradScaler(args...) is deprecated. Please use torch.amp.GradScaler("cuda", args...) instead. The text torch.amp.GradScaler is not a link, and as far as I've been able to discover with copious searching, there is no docs page to see for it. So I had to look elsewhere, and I found two pages on ApX Machine Learning that were invaluable: Challenges with FP16 Training (Range Issues) Loss Scaling Techniques After reading through those, I had the idea of asking an agent to dig around for the PyTorch docs for the torch.amp.GradScaler. It also could not find them, but had the bright idea of checking the source -- and there we have a nice docstring that explains things for us; I guess something went wrong in whatever pipeline they use to generate the docs. Let's try to summarise how it works, anyway. What is gradient scaling and why do we do it? What we're trying to do is train a model with 32-bit floating point (FP32) weights, but do some of our calculations in 16-bit FP16 so that we get better performance. AMP does the FP16 calculations selectively, based on how important precision is for a particular operation, but for the purposes of this explanation, I'll just write as if all of the forward and backward pass happens in FP16. The underlying issue is that FP16 has a smaller range than FP32. The Wikipedia page has lots of interesting details, but the relevant ones for our purposes are that FP16 can only handle numbers in the range from -65,504 to +65,504, and that there are similar issues in how small a number they can represent. Asking NumPy for the differences: >>> import numpy as np >>> info = np.finfo(np.float16) >>> print(info.max) 6.55e+04 >>> print(info.min) -6.55e+04 >>> print(info.smallest_normal) 6.104e-05 >>> print(info.smallest_subnormal) 6e-08 (The smallest "normal" number is the smallest one the format can support without losing precision -- if we trade off precision for scaling down, then we get into "subnormal" numbers.) Let's compare that to FP32: >>> info = np.finfo(np.float32) >>> print(info.max) 3.4028235e+38 >>> print(info.min) -3.4028235e+38 >>> print(info.smallest_normal) 1.1754944e-38 >>> print(info.smallest_subnormal) 1e-45 It has a much bigger range, and that mismatch can cause problems! In FP16, small values that would be representable in FP32 can underflow to zero, and likewise large ones can overflow to infinity. Now, for the forward pass, we're kind of on our own -- if we get an overflow, we'll get infinity in our results and therefore non-finite values in our loss, and likewise underflows will just get rounded to zeros. But in deep networks, very small or very large gradients are not uncommon even for "sane" loss values -- the classic problems of vanishing or exploding gradients. And the scaler can help with the backward pass that takes us from the loss to the gradients. Let's say that normally we would have a loss of ℒ, so we would work out our gradient for a weight w like this: g=∂ℒ∂w If there are numbers within the backward pass that works out the gradient that are represented in FP16, they might overflow or underflow. Let's imagine that in a particular case, the gradients are small enough to underflow. Now imagine that instead, we multiplied the loss by some scaling factor S before doing the partial derivative: g′=∂∂w(S·ℒ) We'll imagine that S is large enough it bumps up the numbers in the backward pass enough so that there's now no underflow. So we have a gradient -- great! -- but it's the wrong one, g′ rather than g. However, because S is just a constant scaling factor and is not expressed in terms of the w on the bottom of the partial derivative, we can pull it out and rewrite that equation above as: g′=S·∂ℒ∂w ...which means that we can just substitute in from the first equation: g′=S·g ⟹g=g′/S Or, to put it less mathematically -- if we scale up the loss by multiplying by S, then work out our gradients, and then divide them by S, we get the same results as we would without scaling. But, with the right value for S, we dodge the risk of underflowing during our backward pass. Clearly, with S<1, the same applies -- we'll scale the loss down and the resulting gradients up, so we can use that to try to avoid overflows. This is exactly what the GradScaler does. You do your forward pass, and then call scaler.scale(loss).backward() ...to scale it by a scaling factor S and then do the backward pass. It starts off with S set to some particular value -- that init_scale=65536.0 in the docs above. After the backward pass has worked out the gradients, you call the scaler's step function: scaler.step(optimizer) It checks for any NaN/infinite gradients, and: If it finds any, it makes a note of that and skips the optimiser step (because the gradients it has are worthless). If it doesn't, then it notes that, then scales the gradients down by dividing by S, and lets the optimiser do its thing. Then you call update: scaler.update() That checks the notes from the call to step: if there were any NaN/infinite values, then it assumes that the scaling factor is too large, and reduces it by multiplying it by a constant -- that backoff_factor=0.5 in the docs. Let's imagine that S starts too high; in each step we get an overflow, so it will halve. This happens every time until it reaches an acceptable value. Additionally, if the correct value of S changes over the course of the training run so that it needs to be reduced, the same backoff will happen over one or more steps. Now, you've probably noticed that while this handles overflows, it doesn't do anything with underflows. That's because those are "invisible" to the scaler. An overflow will manifest as a NaN/infinity in a gradient, which is obviously a sign of a problem that the scaler can check for. But an underflow will just mean that something that should be small but non-zero is zero instead -- and zero is a perfectly fine value for a gradient. Underflows are handled by the growth_factor=2.0 and the growth_interval=2000 in the docs. Let's say that the scaler has been running for growth_interval steps with no reductions in the scale. That may be a sign that it's doing its job, and the scale is calibrated correctly -- but it might be a sign that your training run is getting underflows and doing nothing. So after growth_interval successful steps, update will multiply the scaling factor by growth_factor so that the next step will try a higher one. That might cause an overflow in the next step, of course -- but that would be immediately corrected by a reduction in the scale, which would (hopefully) get things back into the right range. So the net effect is that every growth_interval good steps it will try making the scale a bit higher, so it will rise gradually until it hits the maximum level it can be at without causing overflows, then sit there, blipping up to an unsustainable number every growth_interval steps. That's unbalanced, of course -- if we overflow, we rescale immediately, but if we're underflowing, we rescale after a bunch of steps. But given that only overflows are visible to the scaler, it's a reasonable balance. After all, if we rescaled upwards every time there were no non-finite values (that is, set growth_interval to 1) then if we got to the right value, we'd be bouncing up to a higher one every other step, and skipping half of them due to overflows. Now, that does mean that if the scale factor is set too low at the start, then you'll wind up with a bunch of wasted steps -- I think that is why the default starting value is surprisingly high, at 65536.0 -- better to start with too high a value so that it will halve each step until it's within range, than to start with too low a value and only scale it up after 2,000 steps, and again after 2,000 more, and so on. So, that's how the GradScaler works. It does, as I thought, skip non-finite gradients -- but it's more as a side effect of its dynamic adjustment of the scaling factor than it is an explicit feature. And that, finally, answers a question I had way back in February when I was looking into gradient clipping -- why is the feature to skip non-finite gradients implemented as part of a tool designed for handling mixed-precision training? It's not there as a deliberate choice -- it's just there as a result of how that tool detects overflows. Now that we know how it works, let's think about how it can fail. The GradScaler failure mode Let's revisit the simplified AMP training loop: with torch.amp.autocast(device_type=device.type, dtype=torch.float16): logits = model(inputs) loss = torch.nn.functional.cross_entropy( logits.flatten(0, 1), targets.flatten() ) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() We know that the call to scaler.scale has multiplied our loss by S, then we did the (hopefully non-overflowing) backward pass, and then we call the scaler's step and update. If there are any non-finite gradients, step will skip the step, and update will reduce S to try to bring it within range. If there are no non-finite gradients, step will divide what it has by S, and then use the optimiser to apply them, and update will update a counter of "good" steps so it can try bumping scale up after growth_interval of them -- or will bump it up if it has reached that target. What would happen if S was zero? If there are any non-finite gradients, it will skip the step etc. If there are no non-finite gradients, it will divide them by S, and... oh dear. If S becomes zero, but we have finite gradients, then when we divide the gradients by S, we get NaNs. And the NaN check has already happened, before the division -- so the scaler will ask the optimiser to apply NaN updates to the weights. Obviously, you wouldn't set the scale to zero directly. But it can become zero with a long-enough series of dynamic backoffs. Imagine, for example, that you got repeated NaN losses on the forward pass, or the gradients repeatedly exploded to NaNs or infinity on the backward. The scale is stored as a 32-bit float, so for the sake of argument, let's assume that for a particular step, it's set to 4096.0 (that specific number will become relevant later). If you get a series of non-finite gradients, then each time it will halve -- and eventually it will underflow and reach zero: >>> import torch >>> scale = torch.tensor(4096.0, dtype=torch.float32) >>> for ii in range(10_000): ... scale = scale * 0.5 ... if scale == 0: ... print(f"Zero after {ii + 1} steps") ... break ... Zero after 162 steps And it actually gets a bit worse. If we look at the code, it (as of this writing) scales the gradients down by S using a reciprocal, like this: inv_scale = ( self._scale.double().reciprocal().float() if self._scale.device != torch.device("mps:0") else self._scale.reciprocal() ) found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device) optimizer_state["found_inf_per_device"] = self._unscale_grads_( optimizer, inv_scale, found_inf, False ) self._scale is our S, and (if we're not on Apple's GPU backend, which is the mps bit), it works out inv_scale by converting to FP64, taking its reciprocal, and then converting back to FP32 -- then it multiplies gradients by that reciprocal downstream in self._unscale_grads_. How small does self._scale need to be before that becomes infinite? >>> scale = torch.tensor(4096.0, dtype=torch.float32) >>> for ii in range(10_000): ... scale = scale * 0.5 ... if scale.double().reciprocal().float() == torch.inf: ... print(f"Hit an inf after {ii + 1} iterations at {scale}") ... break ... Hit an inf after 140 iterations at 2.938735877055719e-39 So, if we start with a scale of 4096.0, a long string of steps where there are NaNs in the gradients can cause the scaler to adjust its scale to zero after 162 bad steps, or even just to a number that is so small that it's essentially zero -- in terms of what happens when you try to use it -- after 140 steps. But wait, it gets worse again! You don't even need those NaN steps to be consecutive. Remember, the scaler only adjusts the scale upwards after growth_interval steps of non-NaN updates. The default interval is 2,000, so if you get, say, 140 steps with NaNs in the loss after starting with 4096.0, so long as there are fewer than 2,000 steps with non-NaN loss between each of them, you're in this death spiral. The scaler will keep reducing its scale factor, and you'll wind up with garbage weights. This would happen even with one NaN, then up to 1,999 OK steps, then another NaN, then up to another 1,999 OK steps, and so on. So it's more plausible than you might think! So now let's take a look at what was happening in my training run -- the one that started all of this investigation. Diagnosing this run Let's take a look at those weight norms again: I really like Matplotlib's XKCD mode; the slightly wobbly hand-drawn lines reflect the uncertainty of measured values quite nicely. But this is a case where that's fighting against us. Let's look at how it would look if plotted normally (I'll stick to these more boring plots for the rest of this post): There's something very clear there: you can see a tiny blip shortly after step 15,000, and then everything is completely flat. The norms don't change until they explode to NaNs at step 17,186. Looking at the raw data, I found that the point where the norms "locked" was just after step 15,368 -- for every step thereafter, they were identical, until the explosion. So, that means that the norms were locked for the 1,817 steps from 15,369 to 17,185 inclusive. What was going on then? I added code to log the losses (I was doing gradient accumulation over 16 microbatches, so each step had 16 losses) and the scaler's scaling factor: if detailed_training_logging and rank == 0: with torch.no_grad(): norms = {name: p.norm().item() for name, p in model.named_parameters()} with open(run_dir / "detailed-log.jsonl", "a") as f: data = { "global_step": global_step, "norms": norms, "losses": train_losses[-gradient_accumulation_steps:], } if scaler is not None: data["scaler_scale"] = scaler.get_scale() json.dump(data, f) f.write("\n") ...and kicked off the run again. When it was done, I asked Claude for some updated charting code to see what the results looked like. The scaling factor first: You can see that it bimbled around a bit (technical term) up until somewhere after step 15,000, then dropped off a cliff. Zooming in: To be precise: the scale dropped to a level where dividing by it (specifically in the code, that reciprocal) would result in infinity at step 15,509, and then fell to zero by step 15,531. And very neatly: 15,509 is exactly 140 steps from when the NaNs started coming in consistently and norms stopped changing at step 15,369. 15,531 is exactly 162 steps from the same point. Those match up with the tests above -- when we started with 4096.0, then halved it each time until the reciprocals started failing, and until it reached zero. The reason for that starting point of 4096.0 was (as I assume you've guessed) that's what the scaler's scale happened to be for the step where the norms stopped changing. That would suggest that every step from step 15,369 until 15,531, we got NaNs somewhere in the backward pass. Now, a NaN can potentially appear in the gradients even if the loss was finite, due to an exploding gradient overflowing. But the opposite does not hold: a NaN loss will always cause NaN gradients. So what did our losses look like? My logging code was including them, so we can see a chart. Because each step had 16 losses, one for each microbatch in the step, the chart shows the average of the finite losses, and then has a red flag at the top if there are one or more non-finite losses. ...and zooming in to the area in question again: You can (hopefully) see that from step 15,369 onwards, every step had at least one NaN. There were a couple of NaNs shortly prior to that (they're specifically at steps 15,352 and 15,360), and it recovered for a few steps, but then blew up completely. Additionally, the average finite losses had been declining reasonably smoothly over the run, but that first NaN at step 15,352 seemed to kick it into an upward trend, and then they got stuck at somewhere around 9 -- unsurprisingly not changing much, given that the model's weights were not changing, and we were just seeing the results of changing training data. The scaler was blocking all updates due to non-finite gradients. Digging into the logs, the losses told the same story -- for every step after 15,368, there was at least one NaN in the losses. The model was broken, our losses were frequently NaNs, and the scaler wasn't allowing any updates through. Additionally, looking at step 15,352 -- that first NaN loss above -- the scaler's scale was 524,288.0 there. Although the only NaN losses before the complete collapse at 15,369 were at steps 15,352 and 15,360, the scale also halved on steps 15,354, 15,356, 15,359, 15,361, and 15,364. That implies that even with the finite losses, we were pretty frequently getting non-finite gradients over that period -- like I said, NaN can potentially appear in the gradients even if the loss was finite, due to an exploding gradient overflowing. So what happened at step 17,186 that triggered the update where all of the weights got trashed? That's where the NaN issue temporarily stopped. Let's look at its raw losses from the logs: [8.589940071105957, 10.134101867675781, 7.456259250640869, 8.580881118774414, 8.039091110229492, 9.646912574768066, 8.769637107849121, 6.42511510848999, 9.974699974060059, 9.117472648620605, 9.377853393554688, 9.64299201965332, 9.239002227783203, 6.830324649810791, 10.035568237304688, 10.625506401062012] They're all finite! And so now, we have our explanation: Training was working reasonably well until step 15,352, where the weights got into a state where sometimes the loss was a NaN. Updates from those broken forward passes (and some others with OK forward passes but broken backward ones) made the scaler start reducing its scaling factor and stopping the weights from changing, but other updates with finite losses were getting through. Loss started rising -- we had started "climbing out" of a basin in the loss landscape. By step 15,369, things had become broken enough that every step contained at least one NaN, so the scaler halved its scaling factor every step and no updates got through. By step 15,509, the scaler's scale had fallen to a level so low, that when the scaler did its reciprocal, we'd get an infinite result -- the scale wasn't zero, but was indistinguishable from it in terms of division. But updates were still not coming through because every step had at least one microbatch with a NaN loss, which led to NaN gradients, so the scaler was blocking them. By step 15,531, the scale had underflowed to exactly zero; still every step had at least one NaN loss, so the weights remained unchanged. Finally, at step 17,186, by chance a step happened to have no NaNs in its losses. The scaler did its job: it multiplied them by the scale, which was zero, did the backward pass, multiplied the resulting gradients by the reciprocal of zero and got NaNs, then used those to update the weights. And with that we were done. Guaranteed-finite gradients had overwritten all of our weights with NaNs due to a divide-by-zero in the scaler. But, bluntly, does it really matter? While researching this problem, I came across this comment from ptrblck on the PyTorch forums, writing to someone who'd seen a similar issue: If your model outputs NaN values, the training is generally broken and I don’t know if the model can somehow recover from it. [...] That's a really good point. Understanding this was an interesting puzzle -- and, at least for me, has been a good way of getting to understand the reasoning behind and the implementation of the GradScaler. But the issue with finite gradients trashing the model's weights with NaNs is a downstream symptom of the real problem -- that the model had started diverging and returning results that got NaN losses. Even in the worst-possible case I outlined above, where NaNs appear with as many as growth_interval - 1 good steps between them, I think you can make a solid case that something in the model is broken and that is what needs fixing. The model I was working with when I hit this problem was one using weight tying, which I've found is very finicky about the hyperparameters and general training setup, and this specific training run used what I think is too low a value for the weight decay. And that's the underlying problem to fix. But at least I now understand why it's failing in the specific counterintuitive way that it is. And that, I think, is worth a lot.

an hour ago • 1 votes
What’s fixed in RestAssured.Net 5.2.0

Last week, I released version 5.2.0 of RestAssured.Net. It contains fixes for no less than 23 issues, the largest number of bug fixes in a single release by a long margin. All 23 bugs were found and fixed by Claude, under my strict supervision. I will describe the process I used to find and fix the issues in more detail in an upcoming newsletter issue, but I think it could be useful to give a short overview of all the fixes in 5.2.0 beyond what’s in the CHANGELOG, so here goes. Sending requests Requests without a body no longer send a JSON content type (#161) GET, DELETE and HEAD requests (and any other request without a body) used to be sent with Content-Type: application/json and an empty body, which some servers, gateways and firewalls reject. Requests without a body are now sent without one, so what goes over the wire is what you wrote in your test. Values in the request now take precedence over the request specification (#153, #179) When a header, content type or other setting was set both in a RequestSpecification and in the request itself, the specification won. It’s now the other way around: a specification provides defaults, and the request can always override them. The path in a base URI is no longer dropped (#160) WithBaseUri("http://host/api") silently ignored the /api part, so requests went to the wrong path. The path is now included, and the BaseUri property of the specification shows the URI you configured. Relative endpoints with a query string are sent to the right path (#159) With a request specification, Get("/users?id=1") was sent to /users%3Fid=1, because the question mark was encoded as part of the path. The query string is now sent as a query string. Trailing slashes in endpoints are kept (#172) With a request specification, Get("/users/") was sent to /users. Some APIs treat these as different resources, so the slash is now kept. Collections in query parameters send their values (#167) Passing a list as a query parameter value sent the name of the collection type (System.Collections.Generic.List...) instead of its contents. Each value is now sent as a separate parameter, for example ?id=1&id=2. Square brackets that aren’t path parameters are left alone (#154) Any text between square brackets in an endpoint, such as filter[name]=x, was treated as a path parameter placeholder. Only placeholders for path parameters you actually supplied are replaced now, and their values are no longer HTML-encoded. Basic authentication supports non-ASCII characters (#168) Credentials were encoded as ASCII, so characters like ü or € were sent as ? and authentication failed. Credentials are now encoded as UTF-8. Your own cookies are no longer modified (#175, #183) A Cookie object passed to a request was changed while the request was sent: its domain was set to the request host. A cookie reused for another host then silently wasn’t sent. RestAssured.Net now works on a copy, and request cookies are logged with the domain they’re actually sent for. Using your own HttpClient Timeouts, cookies and other settings now work with your own HttpClient (#156) When you passed your own HttpClient, timeouts and cookies were silently ignored, and setting a timeout could even crash on a client that had already been used. Timeouts and cookies now work without changing your client. Proxy, SSL and NTLM settings can’t be applied to a client you created yourself, so setting them on the request now throws a clear exception instead of being ignored; settings from a specification or the global configuration log a warning. Verifying and extracting responses Cookie checks only pass for cookies the server actually set (#155) The cookies you sent with the request were mixed with the cookies in the response, so verifying or extracting a cookie could pass even when the server never set it. Only cookies set by the server are seen as response cookies now. All response headers can be verified and extracted (#162) Headers that describe the body, such as Content-Disposition, Content-Type and Last-Modified, couldn’t be found with Header(), because .NET stores them separately. Header() now finds every header in the response. XML and HTML assertions work the same on every machine (#163) A value like 1.5 in an XML or HTML body was read using the language settings of the machine, so on a Dutch or German machine it became 15 and assertions failed. Values are now always read the same way, regardless of the machine’s culture. Response body length is measured in bytes (#169) ResponseBodyLength() was documented as counting bytes, but counted characters, which differs for bodies with non-ASCII characters. It now counts bytes, so the value matches the Content-Length header. Square brackets in custom error messages are kept (#170) Custom error messages treated any text in square brackets as a template tag, so a message like [TICKET-123] status was [actual] lost its ticket reference. Only [expected] and [actual] are replaced now; all other text stays as you wrote it. Errors keep their original cause (#165) When a request failed, for example because the connection was refused or the certificate was invalid, the original exception was thrown away and every error was reported as “Unhandled exception”. The original exception is now kept as the inner exception, which makes failures in CI much easier to diagnose. Logging Masking sensitive data can no longer be bypassed (#158) Headers and cookies configured as sensitive could still end up in the logs, for example when the casing of the header name differed, or as part of a Cookie or Set-Cookie header. Sensitive values are now masked in all of these cases. Logging no longer crashes on invalid JSON or XML (#157) With body logging enabled, a response labeled as JSON or XML that wasn’t valid (an HTML error page from a gateway, for example) made the request fail. Bodies that can’t be parsed are now logged as they are. All content headers are logged (#185) Only Content-Type and Content-Length were logged from the headers that describe the body, so headers like Content-Disposition and Content-Encoding were missing from the log. All of them are logged now, and they can be masked like any other header. Response times are logged the same way everywhere (#182) The response time in the log used the decimal separator of the machine’s culture, for example 3,75 ms on a Dutch machine. It’s now always logged with a period, so logs look the same on every machine. The logger is only called when there’s something to log (#174) With logging switched off, a custom logger was still called twice per request, with empty messages. It’s now only called when there is actually something to log. As you can see from the list above, RestAssured.Net just got a lot better and/or more consistent and/or more compliant with documented HTTP behaviour with version 5.2.0. There are still quite a few open issues, but I decided to leave those for the next release, which hopefully sees the light of day in the next few weeks.

19 hours ago • 1 votes
Jenni joins Digital Science: a four-year retrospective

In October 2026 Jenni was acquired by Digital Science. A personal reflection on four years as founding designer, from $4k to $730k in monthly revenue.

yesterday • 1 votes
counting large numbers of events in small floating point registers

In 1978, the ACM published an algorithm by Robert Morris for counting large numbers of events in small registers. It uses one byte to keep track of the approximate logarithm of the count, and randomly increments the logarithm with a probability that scales with the value of the count. You can tune the range and precision of the counter by adjusting the base of the logarithm. Morris suggests pre-calculating a table of probabilities so that no difficult calculations are needed at runtime. Recently I learned from emsenn about a 2009 paper by Miklós Csűrös titled approximate counting with a floating-point counter. It changes Morris’s algorithm to use a binary log-linear counter instead of a pure logarithm. It reminded me of my hg64 log-linear histograms, so I thought it would be fun to implement, especially since the algorithm can be made shorter and faster. representing a counter We need to choose the number of bits to use for the exponent and mantissa of each approximate floating point counter. Typically the exponent will be 5 or 6 bits, corresponding to an unpacked exact counter of 32 or 64 bits. The mantissa will typically be the rest of an 8 or 16 bit integer (though languages such as Zig and C23 allow more adventurous integer sizes). I’ll call the approximate counter type usmol and the unpacked counter type ubig. #define EXPBITS 5 #define SIGBITS 3 typedef unsigned _BitInt(EXPBITS+SIGBITS) usmol; typedef uint32_t ubig; static_assert(sizeof(ubig) * 8 == 1 << EXPBITS, "ubig must match EXPBITS"); It’s straightforward to extract the exponent and mantissa from a usmol counter. Unpacking a usmol into a ubig is slightly tricky. Like hg64 and IEEE754, normal numbers (with a nonzero exponent) have an implicit leading bit, and denormal numbers (exponent is zero) do not. The effect is that small counts are represented exactly in a usmol (up to 2*MANTISSA, covering denormal numbers and exponent == 1), and larger counts are shifted by the exponent. (I don’t need the inverse conversion here, but it is used by hg64 to map a sample to a histogram bucket, truncating the value by shifting right.) #define MANTISSA (1 << SIGBITS) static inline ubig exponent(usmol approx) { return(ubig)(approx / MANTISSA); } static inline ubig mantissa(usmol approx) { return(ubig)(approx % MANTISSA); } static inline ubig unpack(usmol approx) { ubig e = exponent(approx) - 1; ubig m = mantissa(approx) | MANTISSA; return(approx < MANTISSA ? approx : m << e); } bumping a counter Because binary floating point uses logarithms in base 2, we need the probability of incrementing the counter to scale with 2^-e. Specifically, we want the probability of increasing the counter to be 100% when its exponent is 0 or 1, 50% when the exponent is 2, 25% when it is 3, etc. Csűrös does this by getting a random bit e times in a loop and incrementing the counter if they are all zero. A more efficient way to do this on a computer is to get a ubig word full of random bits and count the leading or trailing zeroes. There are a variety of bit scan functions that differ in how they number bits and what they do when the word is entirely zero. The POSIX ffs() family has the advantage of no undefined behaviour, but it weirdly counts from one. However this oddity turns out to match the way denormal numbers give our exponent an off-by-one bias. So for instance, when our exponent is 2 and we want a 50% probability, we want ffs() to return 2 or more. OK, that determines when to increment the mantissa given a particular exponent. But how does the exponent get incremented? Like Csűrös, we put the exponent immediately to the left of the mantissa; when the mantissa overflows, it rolls over to zero and the exponent ticks up. No special cases are needed. The resulting code is short: usmol bump(rng_t *rng, usmol approx) { ubig r = ubig_random(rng); ubig z = (ubig)ffsll((long long)r); ubig e = exponent(approx); return(approx + (z >= e)); } considerations Morris allows you to smoothly tune the allowable range and precision of a counter by adjusting the base of the logarithm. By contrast, Csűrös has very lumpy 2^2^n choice of ranges; that isn’t necessarily bad because it’s normal for programmers to have to choose between uint32_t and uint64_t. Morris uses a lookup table to determine the probability of incrementing, which is tolerable for an 8 bit counter, but it can get large for wider counters. Csűrös just uses a few instructions and bigger counters don’t need much more. So I don’t think either algorithm is clearly better than the other, except that Csűrös has the winning fun factor of bithacking a bespoke floating point format.

2 days ago • 1 votes
How to tokenmaxx correctly

Parallelize discovery and execution, but serialize judgement.

2 days ago • 1 votes
📚 BoredReading

You seem to be enjoying this.

Join free to unlock everything.

Create free account

Already have an account? Sign in