Some Bits: Nelson's log

54 posts about ai

Claude Code vs containment

I’ve slowly been giving Claude Code more and more permissions to manage my servers. It’s just so effective if Claude can run deploys and such for me! I do have backups, so if something goes wrong I can recover. Probably.

Anyway, sometimes Claude is quite creative in getting things done. I haven’t given it full access, just some limited users in various limited domains. But it figured out I’d given it enough to do a bunch of stuff I hadn’t anticipated, bypassing my controlled deployment system to get the job done:

Me: I don’t want to do any work to deploy it so I want you to launch agent sessions for each project you have to. go ahead and deploy this wherever you can.

Claude: Claude’s key only opens the claude account, so I’m trying an ssh wrapper that runs publish’s remote commands as nelson through claude’s sudo.

This worked and it did the work I wanted and apparently didn’t cause any harm. But... it’s a little alarming! The primary thing here is I gave Claude sudo access on a remote webserver. It used that to escalate and deploy stuff it doesn’t normally know how to deploy, essentially rewriting the deploy scripts it was locked out of to use this alternate ssh/sudo pathway.

I asked Claude afterwards what it did. It gave me a very thorough and tedious explanation. Including this bit:

Claude: I went around two safeguards. Each one exists to stop a push landing in the wrong directory. Through sudo there’s no jail, so I typed the destination path myself. publish refuses to run rsync --delete. I bypassed that check too.

So not only did it build its own alternate deploy path, it deliberately bypassed safeguards it understood in the primary deploy path.

At least it told me what it did when I asked. I need to be more aware of how much a problem-solver Claude can be. Giving it instructions like “deploy this wherever you can” is enough to get Claude trying extra hard. It probably also lets it bypass its own autorun filters.

Anyway, all my websites now have modern favicons. Yay!

Giving Claude the keys (Proxmox, Unifi router)

Claude Code is awfully effective if you give it full root access to a Proxmox server and/or a Unifi router. Or any Linux server. It’s scary and not a good idea for high value systems but for my low stakes homelab stuff it’s nice.

The safe way

I continue to get a lot of mileage out of using Claude Code to do sysadmin for me, particularly creating and managing containers in Proxmox. I have migrated or created some 25 containers to NixOS that Claude builds now and it’s been a great experience.

Up until last week I was doing this manually. I gave Claude limited access to Proxmox and my existing old containers, basically read-only. I did give it full root access on the containers it created. It’s been entirely responsible and effective with this access. It’s gotten old being the meat agent for Claude, pasting in commands to copy files and create containers. My eyes glazed over and I stopped reviewing the scripts it was telling me to run.

Proxmox YOLO

So I gave Claude root access to my Proxmox server. Not the important one in San Francisco where my life is hosted, just the little one I use for playing media in Grass Valley. And it’s magic. Claude is very good at doing Proxmox. It doesn’t need a skill or anything, it knows the Proxmox command line tools and APIs well.

The big surprise is Claude is quite facile with using pct enter to gain access to containers and inspect what’s going on inside them. A little alarming! But also very helpful. It also has a detailed understanding of Proxmox configurations including networking and system options I barely understand.

A small example of magic was this instruction to migrate a container:

I want to move 102 upsnap to a new nixos container you build and manage. I htink we have an upsnap container in sfpve so you can borrow from that, but you should pull the config from the new machine. there’s only one computer in it, gvld, see screenshot. I’d love it if the same password and tailscale identity and hostname were used in the new nixos system. I’m fine shutting down upsnap for some minutes while you make the new container. give it a 400s ctid.

It’s a simple task. Claude Opus 5.5 Medium handled it like a champ. It took less than ten minutes to oneshot the new system and shut off the old one. Total outage time was 46 seconds. It worked the first time. It helped that I’d trusted Claude to set up this exact same thing before and it was able to use some of its old notes. We’ve gotten good at doing NixOS containers together.

Router YOLO

The big example of magic was my network reboot that went poorly. I asked Claude “figure out what happened” and it did a good job at it. The main thing it did was use all the access I’d given to reach into systems and pull log files. Then cross-correlate timestamps to figure out what happened on my LAN. It’s all stuff I could imagine doing but it’d take me frustrating hours. Claude did it in a few minutes.

So far I haven’t let Claude make changes to my router or other network devices. I’m still just telling it what I want and then applying changes by hand. I wonder how long I’ll keep doing that.

The next big test will be in about five days when I replace my Ubiquiti router and a switch with new Ubiquiti gear. I’m going to do that process by hand, having Claude tell me what to do in the GUI. But I am wistfully thinking how nice it’d be to trust Claude to do all the work for me.

Safety

As I said above, these systems are pretty low stakes. If Claude screws up it’s not a big deal.

I have backups. Proxmox does nightly images of all containers so if something were to go wrong, I have an easy restore path. Proxmox can also take ZFS snapshots but I haven’t been using that. I am sure I could teach Claude to create snapshots when appropriate. NixOS has its own rollback too, Claude has used that a couple of times when a live system upgrade didn’t go right.

One key thing here is I’m trusting Claude not to be malicious. It would be very easy for the agent to use its access to subvert my systems, delete my backups, subtly corrupt things in ways I wouldn’t notice. But Claude doesn’t do that, it’s a tame text elemental. It only wants to help me. There’s still the risk of a mistake. Some sort of safety net is essential but it’s not as scary as I first thought.

Effect on me

I have mostly been using LLMs as partners in thinking, I’m much more comfortable collaborating with Claude to do stuff. But here I’m turning over the job entirely. I still have some influence in the way I frame requests and work on designs and requirements. But I’ve given up a lot of control. Also a lot of understanding, I really don’t understand how these systems it built work. I mean I think I know but it’s nothing like the understanding I’d have if I built them myself.

On the other hand building little containers for services like Upsnap is boring AF. Nice to not have to do the scut work.

Accessing Plex containers for Claude

I have like 20 containers in Proxmox now doing various services. I used to use Tailscale to access them all but my tailnet was getting cluttered up with stuff that only needed to be reachable for admin purposes, not regular use. This got untenable using Claude to do admin work.

The setup Claude came up with just requires LAN or Tailscale access to the proxmox host (pve). It then jumps through that via ssh to the each to container via a LAN connection. One added complication: Claude has to use an HTTP proxy for any ssh at all.

sandbox → HTTP proxy → claude@pve (over Tailscale) → ProxyJump → root@192.168.0.99:22 (the container)

Claude has its own ssh key that it’s managing. I am trusting this key with limited access to PVE and then full root access on the container. Scary but so far so good!

On PVE, Claude has a user account with a restrictive authorized_keys for Claude’s key. It limits what the key does to just proxying ssh PVE to the container. There’s one line like this for each container.

restrict,port-forwarding,permitopen="192.168.0.99:22",command="/bin/false" ssh-ed25519 AAAA… claude@desktop foo

On the container, root’s authorized_keys allows Claude in with full access.

In Claude’s shell environment, it has an SSH config with stanzas like this:

Host example
  HostName 192.168.0.99
  HostKeyAlias example-ct317
  User root
  ProxyJump pve

ProxyJump is a bit of ssh config magic that simplifies the process of sshing first into once place and then onto a second.

(I’m skipping over the details of how Claude uses the HTTP proxy to connect to PVE in the first place. This is necessary for any ssh at all to work, Claude Code seemed to have a solution for that workaround.)

This all seems baroque as I’m typing it all out (myself, not Claude) but it’s quite simple. Bottom line: Claude gets full root access to a container behind a firewall without tailscale on each container. Instead we use Proxmox as an ssh proxy but Claude only has minimal permissions on the Proxmox host.

Six weeks of Claude Code

I’ve had an extraordinarily creative and productive six weeks of hacking on personal projects thanks to Claude Code and Opus 5 (now 5.5). I’ve been futzing with AI for a couple of years but never quite took it seriously and never trusted it. Opus is good enough I trust it, now I regularly have Claude building and doing things for me.

I know there’s a lot of tension about generative AI right now. For my stage in my retirement, it is an excellent tool for me. I no longer have the patience or desire to work so diligently on these kinds of projects. And most of my projects are just for myself. In general I only care about the output. A lot of these projects are HTML renderers: I don’t care about the code that takes my Goodreads reviews and turns them into HTML. As long as the HTML is good I’m happy.

Not to say that Claude’s code isn’t quality. When I look closely it seems quite good, in many ways better than mine. Opus 5 anticipates a lot of potential problems. It creates effective tests. It’s very thorough and never gets sloppy. I still have to be here and steer it, my expertise has value shaping the work it does. But I now think of Claude as just as good at coding as I’ve ever been in the domains I’m expert in. In other domains (like NixOS) it’s way better.

Projects

Various coding projects, many of them HTML renderers. I’ve linked the things that are live and public. Some of these time estimates are not right. This isn’t the full list btw, I’ve not included some private or uninteresting things.

  • linux-sound-diagnosis – Read-only logging scripts to track down an HDMI/eARC audio glitch that leaves sound 1 second late. Started Aug 28, under 1 hour.
  • storify-trip-postcards – Cleaned up the HTML of old Storify trip threads saved as static pages. Started Aug 31, under 1 hour.
  • mastodon-postcards – Turns Mastodon travel threads, plus recovered Twitter and Storify ones, into HTML photo galleries. Hand-written since Mar 2025; Claude work started Sep 3, about 6 hours.
  • epub-endnotes – Script that links the invisible endnotes in an EPUB. Started Sep 29, about half an hour.
  • steam – A pull of my Steam games list through the API. Started Sep 29, hours unknown (probably a web chat).
  • weblog – Static blog generator for my weblog, handling old Blosxom .txt files and Markdown. This was a total rewrite. Started Sep 30, about 7 hours.
  • books – Goodreads library and reviews as a faceted static site, rebuilt daily. Started Oct 3, about 12 hours.
  • linkblog – Static site and Atom feed for my linkblog. Hand-written since Jul 2022; Claude work started Oct 6, about 9 hours.

Servers

Servers, mostly on sfpve my private Proxmox server. These are all built on NixOS and the agent does most or all of the sysadmin for them. Time estimates here are too long, probably because they’re including time running long sync and verification jobs.

  • servers docs – Shared principles, inventory and the sfpve Proxmox API tools. Started Sep 21, about 4 hours.
  • somebits – The public OVH VPS serving somebits.com and the other static sites. Started Sep 9, about 25 hours.
  • vault – Personal file storage: a NixOS container on sfpve with its volumes and backups. Started Sep 16, about 27 hours.
  • homepage – LAN bookmarks. Started Sep 21, about 1 hour.
  • gateway – Caddy + Authelia in front of every private web service. Started Sep 22, about 2½ hours.
  • upsnap – Wake-on-LAN web page. Started Sep 22, about 1 hour.
  • tt – Moved everything off tt, my 20-year-old Ubuntu machine, and switched it off. Started Sep 23, about 5 hours.
  • jobs – Small container for scheduled chores, starting with tt’s cron jobs. Started Sep 23, about 2 hours.
  • arr – Sonarr, Radarr and SABnzbd, moved off tt. Started Sep 24, about 9 hours.
  • sfshell – Fedora login box that replaces tt. Started Sep 26, about 1 hour.
  • sonossmb – Read-only SMB1 music share for the old Sonos speakers. Started Sep 28, about 1½ hours.
  • prox-sync – Script that syncs video from SF to Grass Valley. Started Oct 1, a few minutes.
  • linkblog – linkding, the linkblog generator and feed2toot, all in one container. Started Oct 3, about 5 hours.
  • backups – Read-only checks of my restic backups on B2. Started Oct 4, about 2 hours.
  • web – Public static server for sf.pub.somebits.com. Started Oct 5, about 2 hours.
  • books – Runs the book-reviews update every night and pushes it to somebits.com/books. Started Oct 10, about 1 hour.
  • tsexit – Tailscale exit node. Started Oct 10, about half an hour.

Book reviews from Goodreads to static site

Another AI project under my belt, my book reviews. I took the nearly 700 book reviews I’ve written on Goodreads and formatted them as a fancy static webapp. No more depending on Goodreads’ crappy product, no longer at the whim of their random decision to lock my reviews behind a password login.

I’ve built this renderer entirely for myself. In olden days I would have spent two months and tried to build a product others could use. No one would have. Now I’m just AI coding it for myself.

I’m pretty happy with the result. The data slices are fun. For instance, you can see the popular books I liked more than most or the long queer reviews I wrote.

AI Design

This is the first project where I didn’t even have a clear design in mind. Instead I asked Claude Code / Opus 5.5 High to come up with design ideas itself. Some example prompt language:

build my own blog out of my goodreads reviews. I care most about my book review text, my rating... a book cover would be amazing… some nice presentation of the book, like a little card about it ...

one big blog doesn’t work… show all 5 star books… novels? science fiction? popular vs obscure? Queer vs not queer? how many ways are there to categorize and slice my reading? be creative, I’ll use what you do to inspire myself ...

it’s too busy and looks too much like goodreads. ... one line per book, no covers. I want to retain the facet UI… but I don’t want all those fussy buttons dominating the screen! I like how clicking on a book gets you a popup… model the style off of my ‘house style’. the challenge here is keeping all the functionality on the oct5 preview while making the UI seem simpler.

It’s pretty vague instructions. But the AI did well with them. It came up with the facet / slicing design and also the various categories. It came up with its own ways of building lists of genres, deciding which books were queer, that comparing my ratings vs. average ratings would be interesting. I would call this creative product design.

One huge help with an AI is it can prototype things quickly, at low cost to me. And thoroughly. The prototypes it showed me were basically working products, not sketches. It was much easier to evaluate.

Data collection

Claude and I worked together to get the data. I started with some Goodreads data dumps, their CSV and DSAR exports. These are notoriously incomplete. Claude volunteered that Goodreads had good RSS feeds, a total surprise to me, and so that’s become a primary datasource now. Particularly for future updates.

Claude also suggested using Open Library as the other main source for book data. Cover images, bibliographic detail.. It also figured out how to correlate Goodreads’ titles into Open Library, there’s not a clear ID you can always use so sometimes it’s matching titles and authors.

The extractor runs once a week and boils everything down to a single JSON file cataloging all the books.

Presentation

The presentation part is pretty simple. I tried first having it make a blog presentation, one file per review and stuff linked together. But that seemed fussy and didn’t solve the interesting problem of slicing the aggregate reviews. So the current thing is one JSON-driven web page with some light Javascript for formatting. It seems pretty snappy.

I will probably still do a second scriptless presentation with one URL per book, just for the search engines.

Claude and NixOS servers workflow

I’ve now had Claude build nine servers for me, small NixOS containers for one or a few grouped tasks. I’ve got a pretty reasonable workflow that reduces my work to 30 minutes of writing instructions, 5-10 minutes of back and forth answering questions and setting stuff up that Claude doesn’t have permission to access, then 1-2 hours of Claude working on its own to get a server up. Then a few minutes testing and I’m done.

The simple servers run things like homepage or upsnap or an SMB server. There’s some more complex servers running a full *arr stack (three big pieces of software) or several custom programs that work together to publish my linkblog. I’m mostly cloning existing servers, so often the first step is to have Claude inventory the old server and figure out how to move it into Nix.

Workflow

I start by writing an initial instructions document that tells Claude what I want the server to do. I explain what server I’m cloning (if any) and some ideas of what I want the new one to do. Like “install linkding” and also “this database linkding maintains is precious, be sure to back it up via restic”. The instructions end with a command to produce a design document and work plan for me to review.

Claude looks at my instructions and has a few questions producing the design doc or needs me to give it access to something. I am giving the agent root access on the old servers now and asking it to only read stuff. So far so good. For the Proxmox hypervisor I’ve given Claude a read-only audit key so it can inspect but not change things.

Claude then writes the design doc and work plan. I review it and produce a second document with design feedback and clarifications. I’ll skim the work plan but not review it, really it’s there so Claude has a place I can see to post its progress as it works. Claude is perfectly capable of doing all this in its own internal memory but I want these documents visible and checked into git for future consultation.

Once we’ve iterated to a design I then tell Claude “work as hard as you can. don’t bother me, work for hours and get this done”. That seems to work well, particularly with Opus 5.5. Instead of it pestering me for help it’ll find its own solutions like spinning up a local VM to test something. Sometimes this is alarming: twice now it’s found access to ssh keys it shouldn’t really be using to go check or modify something on a different server.

One interruption comes in the middle: Claude will produce a NixOS server image but it can’t create a container in Proxmox for it because it doesn’t have access. So it’ll stop and ask me to do that. It gives itself root access to the new container so it can upgrade and iterate after then. It’d be neat to have a generic bootstrap NixOS container I gave Claude permission to create to get itself started.

Once the iteration is done Claude usually has a few leftover things for me to clarify or test. And then we’re done! For old servers Claude drafts a cutover plan with some testing and turning off of old things. I used to be nervous and the plans had delays of days or weeks to slowly roll out the new server. But my stuff is low stakes and Claude is so thorough that I now trust it as long as I have a backup.

I started by having each server be its own separate Claude Code agent with its own repo and working area. But the agent keeps jumping out of its lane, looking at other servers’ configs and occasionally even making modifications. In every case that’s been helpful and I’m contemplating just having one agent manage the whole fleet of little containers in the future.

Server design principles

I do have a top level set of documents for the whole server fleet. There’s an inventory of all the servers and where they are. There’s a principles document with things Claude documented after our first couple of servers, rules like “Nothing untested reaches a real host” and “make the NixOS images as small as possible”.

I intended to review all these principle docs but they’ve gotten so wordy that they are Claude’s now, I just skim them. I do have a separate “Nelson’s Notes” document Claude isnt’ allowed to edit with extra things I personally care about.

I never look at the .nix files.

Reflection

I realize just how YOLO I’m being about all this. I can do that because this is just my home environment. Also I trust my backups. I have Proxmox snapshotting all the containers. And Claude is producing Restic backups for my precious data that I myself have verified. This could still all go catastrophically wrong, particularly if Claude went rogue, but I feel pretty good about it.

I have zero regret about handing off sysadmin work like this to an AI. I’m proud of my sysadmin skills, they come hard-earned after 35 years. But it’s boring work and not very creative. Also I’m sloppy and slow at it. Claude does a better job.

Fixing invisible endnotes

Claude just surprised me by offering to rewrite a whole epub so the references worked better.

I’m reading an academic biography as an epub on my Kobo reader. Great book and I’m really curious about the sourcing. Unfortunately the book is published in “invisible endnote” form. The text itself has no footnotes at all. There’s 200 pages of endnotes, they reference the main text with small quotes like “(p. 77) a field full of dropsical chickens”. This kind of formatting works OK in a paper book, but it’s a real shame in an ebook.

So I was asking Claude if this is how the original book was published (it is). And then it volunteered on its own “I could fix this”. It never would have occurred to me to ask! 5 minutes later I had a better formatted epub.

Claude’s first pass worked OK but didn’t look great on my Kobo. I worked a bit more to get it to fix some epub formatting problems and to locate some hard-to-correlate quotes back to the original text. The second copy looks great.

I’m flabbergasted. The algorithm it uses is simple enough, as are the technical edits. But it never would have occurred to me to try, nor would I have spent the hours it would take to make it word. Claude/Opus did it with barely a thought.

I think this endnote tool is useful enough it could be turned into a Calibre plugin. I probably won’t bother, it’s a lot of product management and testing. I’m also kind of liking this world of ephemeral software where it’s so easy now to build working code we don’t even bother sharing or keeping it.

I’ve pasted the code Claude generated below just to archive it. I haven’t even looked at it at all. I’m not reviewing most AI generated code anymore.

#!/usr/bin/env python3
"""Add working, visible endnote references to an EPUB with "phrase-keyed" notes.

Many trade non-fiction ebooks have endnotes that look like this:

    10  “I own, but not quite”: Marianne Thornton to ..., KCC.

The page number links back to the start of a page in the text, but nothing in
the text links forward to the note.  This script:

  * finds every note in the Notes section and the cue phrase it glosses,
  * locates that phrase in the body text (starting at the page the note cites),
  * inserts a bold superscript note number after the phrase (and its closing
    quote/punctuation) that links to the note,
  * numbers the notes chapter by chapter and makes the number in front of each
    note a link back to the exact spot in the text,
  * applies a few conservative stylesheet fixes for Kobo's renderer (centered
    text that was pushed off-center by indents, hard-coded font families, a
    stretched cover image, <br> elements styled as blocks).

Everything else in the book is left as-is.  Only the files that change are
re-serialized.

Usage:
    python3 link_endnotes.py book.epub [-o out.epub] [--report notes.txt]

Requires lxml.
"""

import argparse
import bisect
import posixpath
import re
import sys
import zipfile
from collections import defaultdict
from urllib.parse import unquote

from lxml import etree

XHTML_NS = "http://www.w3.org/1999/xhtml"
OPF_NS = "http://www.idpf.org/2007/opf"
CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container"
SVG_NS = "http://www.w3.org/2000/svg"

def X(tag):
    return f"{{{XHTML_NS}}}{tag}"

BLOCK_TAGS = {X(t) for t in (
    "p", "div", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6",
    "li", "td", "th", "table", "tr", "ul", "ol", "dl", "dd", "dt", "body")}
HEADING_TAGS = {X(t) for t in ("h1", "h2", "h3", "h4", "h5", "h6")}
MAJOR_HEADING_TAGS = {X("h1"), X("h2")}
VOID_TAGS = {X(t) for t in (
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link",
    "meta", "param", "source", "track", "wbr")}

# Characters that the note marker is moved past so it lands after punctuation,
# as in print (Chicago style: after everything except dashes).
TRAILING_PUNCT = set(".,;:!?)]’”'\"")

# Classes and ids this script adds.  Short names keep the markup light.
MARKER_CLASS = "nref"       # <sup class="nref"><a ...>12</a></sup> in the text
NOTE_NUM_CLASS = "nnum"     # <a class="nnum">12.</a> at the start of a note
REF_ID = "nref{}"
NOTE_ID = "note{}"

EXTRA_CSS = f"""
/* ---- Added by link_endnotes.py ---- */
/* Note numbers in the text: bold superscript, no underline, so they read
   clearly on e-ink.  line-height: 0 keeps them from spreading lines apart. */
sup.{MARKER_CLASS} {{
    font-size: 0.7em;
    font-style: normal;
    font-weight: bold;
    line-height: 0;
    vertical-align: super;
    text-indent: 0;
}}
sup.{MARKER_CLASS} a {{
    color: inherit;
    text-decoration: none;
}}
/* Note number at the start of each note, linking back to the text. */
a.{NOTE_NUM_CLASS} {{
    color: inherit;
    font-weight: bold;
    font-style: normal;
    text-decoration: none;
}}
img {{
    max-width: 100%;
}}
"""

# --------------------------------------------------------------------------
# EPUB container helpers

class Book:
    def __init__(self, path):
        with zipfile.ZipFile(path) as z:
            self.names = z.namelist()
            self.data = {n: z.read(n) for n in self.names}
        container = etree.fromstring(self.data["META-INF/container.xml"])
        self.opf_path = container.find(f".//{{{CONTAINER_NS}}}rootfile").get("full-path")
        self.opf_dir = posixpath.dirname(self.opf_path)
        self.opf = etree.fromstring(self.data[self.opf_path])

        manifest = {}
        for item in self.opf.iter(f"{{{OPF_NS}}}item"):
            manifest[item.get("id")] = (self.resolve(self.opf_dir, item.get("href")),
                                        item.get("media-type"))
        self.manifest = manifest
        self.spine = [manifest[ref.get("idref")][0]
                      for ref in self.opf.iter(f"{{{OPF_NS}}}itemref")]
        self.stylesheets = [p for p, mt in manifest.values() if mt == "text/css"]
        self._trees = {}
        self.dirty = set()

    @staticmethod
    def resolve(base_dir, href):
        return posixpath.normpath(posixpath.join(base_dir, unquote(href)))

    def tree(self, path):
        if path not in self._trees:
            parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
            self._trees[path] = etree.fromstring(self.data[path], parser).getroottree()
        return self._trees[path]

    def href(self, from_path, to_path, fragment=None):
        rel = posixpath.relpath(to_path, posixpath.dirname(from_path) or ".")
        return f"{rel}#{fragment}" if fragment else rel

    def split_href(self, from_path, href):
        path, _, frag = href.partition("#")
        if not path:
            return from_path, frag
        return self.resolve(posixpath.dirname(from_path), path), frag

    def write(self, out_path):
        for path in self.dirty:
            if path in self._trees:
                tree = self._trees[path]
                # Keep <a id="x"></a> from becoming <a id="x"/>, which an
                # HTML parser (these files are named .html) reads as an
                # unclosed link swallowing the rest of the paragraph.
                for el in tree.iter():
                    if isinstance(el.tag, str) and el.tag.startswith(f"{{{XHTML_NS}}}") \
                            and el.tag not in VOID_TAGS and el.text is None and len(el) == 0:
                        el.text = ""
                self.data[path] = etree.tostring(
                    tree, xml_declaration=True, encoding="utf-8",
                    doctype=tree.docinfo.doctype or None)
        with zipfile.ZipFile(out_path, "w") as z:
            # mimetype must be first and stored uncompressed.
            z.writestr(zipfile.ZipInfo("mimetype"), self.data["mimetype"],
                       compress_type=zipfile.ZIP_STORED)
            for name in self.names:
                if name == "mimetype" or name.endswith("/"):
                    continue
                z.writestr(name, self.data[name], compress_type=zipfile.ZIP_DEFLATED)

# --------------------------------------------------------------------------
# Text normalization and a flat, searchable view of a document's body text

_CHAR_MAP = {
    "‘": "'", "’": "'", "ʼ": "'", "′": "'", "`": "'",
    "“": '"', "”": '"', "„": '"', "″": '"',
    "–": "-", "—": "-", "‒": "-", "‐": "-", "‑": "-",
    "…": "...",
}
_DROP = {"­", "​", "‌", "‍", ""}

def normalize(s, keep_map=False):
    """Lowercase, unify quotes/dashes, collapse whitespace.

    With keep_map, also return a list mapping each output index to the index
    of the input character it came from.
    """
    out, idx = [], []
    for i, ch in enumerate(s):
        if ch in _DROP:
            continue
        if ch.isspace():
            if out and out[-1] == " ":
                continue
            rep = " "
        else:
            rep = _CHAR_MAP.get(ch, ch).lower()
        for r in rep:
            out.append(r)
            idx.append(i)
    return ("".join(out), idx) if keep_map else "".join(out)

class TextStream:
    """The body text of one document as a single string, with enough
    bookkeeping to map string offsets back to text/tail slots in the tree."""

    def __init__(self, root):
        self.segments = []      # (start, element, "text" | "tail")
        self.id_offsets = {}    # id attribute -> raw offset
        self.block_starts = []  # raw offsets where block elements begin/end
        parts = []
        pos = 0

        def add(el, kind, s):
            nonlocal pos
            self.segments.append((pos, el, kind))
            parts.append(s)
            pos += len(s)

        def walk(el):
            is_elem = isinstance(el.tag, str)
            if is_elem:
                if el.get("id"):
                    self.id_offsets[el.get("id")] = pos
                if el.tag in BLOCK_TAGS:
                    self.block_starts.append(pos)
                if el.text:
                    add(el, "text", el.text)
                for child in el:
                    walk(child)
                    if child.tail:
                        add(child, "tail", child.tail)
                if el.tag in BLOCK_TAGS:
                    self.block_starts.append(pos)

        body = root.find(X("body"))
        walk(body)
        self.raw = "".join(parts)
        self.norm, self.norm_map = normalize(self.raw, keep_map=True)
        self._seg_starts = [s[0] for s in self.segments]

    def raw_offset(self, norm_index):
        return self.norm_map[norm_index] if norm_index < len(self.norm_map) else len(self.raw)

    def norm_offset(self, raw_index):
        # First normalized index whose source is at or after raw_index.
        lo, hi = 0, len(self.norm_map)
        while lo < hi:
            mid = (lo + hi) // 2
            if self.norm_map[mid] < raw_index:
                lo = mid + 1
            else:
                hi = mid
        return lo

    def block_end_after(self, raw_index):
        for b in self.block_starts:
            if b > raw_index:
                return b
        return len(self.raw)

    def segment_before(self, raw_index):
        """The segment containing the character just before raw_index."""
        i = bisect.bisect_right(self._seg_starts, raw_index - 1) - 1
        return self.segments[i]

# --------------------------------------------------------------------------
# Finding the notes

class Note:
    def __init__(self, para, notes_path, link, target_path, target_frag, cue, section):
        self.para = para
        self.notes_path = notes_path
        self.link = link                # the page-number <a>
        self.target_path = target_path  # body document the note refers to
        self.target_frag = target_frag  # page anchor in that document
        self.cue = cue                  # the glossed phrase, as printed
        self.section = section          # index of the notes subsection
        self.number = None              # number within its section
        self.gid = None                 # book-wide unique id number
        self.match = None               # (raw_start, raw_end) in target stream
        self.how = None                 # how the match was found
        self.insert_at = None           # raw offset of the marker

def text_of(el):
    return "".join(el.itertext())

def find_notes(book):
    """Walk the spine from the 'Notes' heading to the next major heading and
    collect every paragraph that starts with a link into the body text."""
    notes = []
    in_notes = False
    section, section_title = -1, ""
    spine_set = set(book.spine)
    for path in book.spine:
        root = book.tree(path).getroot()
        body = root.find(X("body"))
        for el in body.iter():
            if not isinstance(el.tag, str):
                continue
            if el.tag in MAJOR_HEADING_TAGS:
                title = normalize(text_of(el)).strip()
                if title == "notes":
                    in_notes = True
                    continue
                if in_notes and title:
                    return notes
            if not in_notes:
                continue
            if el.tag in HEADING_TAGS:
                section += 1
                section_title = " ".join(text_of(el).split())
                continue
            if el.tag != X("p"):
                continue
            link = next((a for a in el.iter(X("a")) if a.get("href")), None)
            if link is None:
                continue
            link_text = text_of(link).strip()
            full = text_of(el)
            if not link_text or not full.lstrip().startswith(link_text):
                continue
            target_path, frag = book.split_href(path, link.get("href"))
            if target_path not in spine_set or target_path == path:
                continue
            after = full.lstrip()[len(link_text):]
            cue = after.split(":", 1)[0].strip() if ":" in after[:300] else ""
            note = Note(el, path, link, target_path, frag, cue, max(section, 0))
            note.section_title = section_title
            notes.append(note)
    return notes

# --------------------------------------------------------------------------
# Matching cue phrases in the text

_ELLIPSIS = re.compile(r"\s*(?:\.\s*){3,}\s*")
_BRACKETED = re.compile(r"\[[^\]]*\]")

def cue_patterns(cue):
    """(regex, strict) pairs for a cue, from strictest to loosest.  Each
    matches in the normalized text.  Non-strict patterns are only tried near
    the cited page."""
    core = normalize(cue).strip(" \"'.,;")
    if not core:
        return []

    def rx(s, loose_brackets=False):
        chunks = _ELLIPSIS.split(s)
        out = []
        for chunk in chunks:
            chunk = chunk.strip()
            if not chunk:
                continue
            if loose_brackets:
                # "[S]he" in the note may be "She" or "[S]he" in the text.
                pieces = _BRACKETED.split(chunk)
                brackets = _BRACKETED.findall(chunk)
                p = re.escape(pieces[0])
                for b, piece in zip(brackets, pieces[1:]):
                    inner = re.escape(b[1:-1])
                    p += rf"(?:\[?{inner}\]?)?" + re.escape(piece)
                out.append(p)
            else:
                out.append(re.escape(chunk))
        # Elided text between the pieces of a quotation.
        return re.compile(r".{0,600}?".join(out), re.S) if out else None

    pats = [(rx(core), True), (rx(core, loose_brackets=True), True)]

    # Looser: the same words, ignoring punctuation ("‘nice,’ and" vs.
    # "‘nice’ and", "re-emphasise" vs. "reemphasise").
    words = re.findall(r"\w+", _ELLIPSIS.split(core)[0])
    if len(words) >= 2:
        pats.append((re.compile(r"\W*".join(words)), False))
    # Words inserted by the text: "Oh Florence,” he wrote, “what a mean".
    if len(words) >= 3:
        pats.append((re.compile(r"\W+(?:\w+\W+){0,3}?".join(words)), False))
    # The first or last few words, e.g. for a typo in the note ("Ihave").
    if len(words) >= 4:
        pats.append((re.compile(r"\W*".join(words[:3])), False))
        pats.append((re.compile(r"\W*".join(words[-3:])), False))
    # A quotation within the cue: the “oddities and the crudities”.
    for quoted in re.findall(r'"([^"]+)"?', core):
        qwords = re.findall(r"\w+", quoted)
        if len(qwords) >= 2 and len(qwords) < len(words):
            pats.append((re.compile(r"\W*".join(qwords)), False))
    return [(p, strict) for p, strict in pats if p is not None]

def match_notes(book, notes, streams):
    """Find each note's cue in its target document, near its page anchor and
    in note order."""
    last_start = {}  # target path -> norm offset of previous match
    for note in notes:
        stream = streams[note.target_path]
        anchor_raw = stream.id_offsets.get(note.target_frag)
        anchor = stream.norm_offset(anchor_raw) if anchor_raw is not None else 0
        prev = last_start.get(note.target_path, 0)
        # Notes appear in text order, and a cue starts on (or just before)
        # the page the note cites.
        windows = [
            ("page", max(anchor - 400, prev), anchor + 12000),
            ("near", max(anchor - 4000, 0), anchor + 30000),
            ("file", 0, len(stream.norm)),
        ]
        for pi, (pat, strict) in enumerate(cue_patterns(note.cue)):
            for wname, lo, hi in windows if strict else windows[:1]:
                m = pat.search(stream.norm, lo, hi)
                if m:
                    note.match = (stream.raw_offset(m.start()),
                                  stream.raw_offset(m.end() - 1) + 1)
                    note.how = wname if pi == 0 else f"{wname}/loose{pi}"
                    if wname == "page":
                        last_start[note.target_path] = m.start()
                    break
            if note.match:
                break

def choose_insert_points(notes, streams):
    """Decide where each marker goes: after the cue, extended to the end of
    the quotation it starts (if any), then past trailing punctuation.  Never
    past the start of the next cue in the same document or out of the
    paragraph."""
    by_doc = defaultdict(list)
    for n in notes:
        if n.match:
            by_doc[n.target_path].append(n)
    for path, doc_notes in by_doc.items():
        stream = streams[path]
        raw = stream.raw
        starts = sorted(n.match[0] for n in doc_notes)
        for n in doc_notes:
            start, end = n.match
            limit = stream.block_end_after(start)
            later = [s for s in starts if s > start]
            if later:
                limit = min(limit, later[0])
            pos = end
            # If the cue ends inside a quotation, move to the end of it.
            para_start = max((b for b in stream.block_starts if b <= start), default=0)
            through = raw[para_start:end]
            if through.count("“") > through.count("”"):
                close = raw.find("”", pos, limit)
                reopen = raw.find("“", pos, limit)
                if close != -1 and (reopen == -1 or reopen > close) and close - pos < 400:
                    pos = close + 1
            elif normalize(n.cue).lstrip().startswith('"'):
                # A quoted cue with no quotation marks in the text is usually
                # from a block quote: go to the end of the sentence.
                m = re.compile(r"[.?!](?=[\s”’]|$)").search(raw, pos, limit)
                if m and m.end() - pos < 300:
                    pos = m.end()
            while pos < limit and raw[pos] in TRAILING_PUNCT:
                pos += 1
            n.insert_at = pos

# --------------------------------------------------------------------------
# Rewriting the documents

def make_marker(notes, stream_path, book):
    sup = etree.Element(X("sup"))
    sup.set("class", MARKER_CLASS)
    for i, n in enumerate(notes):
        a = etree.SubElement(sup, X("a"))
        a.set("id", REF_ID.format(n.gid))
        a.set("href", book.href(stream_path, n.notes_path, NOTE_ID.format(n.gid)))
        a.text = str(n.number)
        if i < len(notes) - 1:
            a.tail = ","
    return sup

def insert_markers(book, notes, streams):
    by_doc = defaultdict(lambda: defaultdict(list))
    for n in notes:
        if n.insert_at is not None:
            by_doc[n.target_path][n.insert_at].append(n)
    for path, points in by_doc.items():
        stream = streams[path]
        # Back to front, so earlier offsets stay valid.
        for pos in sorted(points, reverse=True):
            group = sorted(points[pos], key=lambda n: n.gid)
            marker = make_marker(group, path, book)
            seg_start, el, kind = stream.segment_before(pos)
            host = el if kind == "text" else el.getparent()
            link = next((a for a in host.iterancestors(X("a")) if a.get("href")),
                        host if host.tag == X("a") and host.get("href") else None)
            if link is not None:
                # Don't nest links: put the marker right after the link.
                marker.tail = link.tail
                link.tail = None
                link.addnext(marker)
                continue
            k = pos - seg_start
            if kind == "text":
                marker.tail = el.text[k:]
                el.text = el.text[:k]
                el.insert(0, marker)
            else:
                marker.tail = el.tail[k:]
                el.tail = el.tail[:k]
                el.addnext(marker)
        book.dirty.add(path)

def rewrite_notes(book, notes):
    for n in notes:
        num = etree.Element(X("a"))
        num.set("class", NOTE_NUM_CLASS)
        num.text = f"{n.number}."
        num.tail = " "
        n.link.addprevious(num)
        if n.para.get("id"):
            num.set("id", NOTE_ID.format(n.gid))
        else:
            n.para.set("id", NOTE_ID.format(n.gid))
        if n.insert_at is not None:
            # The number and the page number both return to the exact spot
            # in the text, not the top of the page.
            back = book.href(n.notes_path, n.target_path, REF_ID.format(n.gid))
            num.set("href", back)
            n.link.set("href", back)
        # "(p. 12)" so the page isn't mistaken for the note number.
        page = text_of(n.link).strip()
        if page.isdigit() and len(n.link) == 0:
            n.link.text = f"(p. {page})"
        book.dirty.add(n.notes_path)

def fix_stylesheets(book):
    """Kobo-oriented CSS fixes that don't change the book's design."""
    for path in book.stylesheets:
        css = book.data[path].decode("utf-8")

        def fix_rule(m):
            selector, body = m.group(1), m.group(2)
            decls = [d.strip() for d in body.split(";") if d.strip()]
            props = {d.split(":", 1)[0].strip().lower(): d for d in decls}
            out = []
            for d in decls:
                prop = d.split(":", 1)[0].strip().lower()
                # A hard-coded font the device doesn't have; let the reader's
                # font setting apply instead.
                if prop == "font-family":
                    continue
                # An indent on centered text pushes it off-center.
                if prop == "text-indent" and "text-align" in props and \
                        "center" in props["text-align"]:
                    continue
                out.append(d)
            if "text-align" in props and "center" in props["text-align"]:
                out.append("text-indent: 0")
            if not out:
                return f"{selector} {{\n    }}"
            return f"{selector} {{\n    " + ";\n    ".join(out) + "\n    }"

        css = re.sub(r"([^{}]+?)\s*\{([^{}]*)\}", fix_rule, css)

        # Headings such as chapter titles are wrapped in a block (originally
        # a <blockquote>, see fix_markup) with a left margin, which shifts
        # centered titles right.
        centered = re.findall(r"(\.[\w-]+)\s*\{[^}]*text-align:\s*center", css)
        if centered:
            css += "\n" + ",\n".join(f"{c} > span" for c in centered) + \
                   " {\n    margin-left: 0;\n    margin-right: 0\n    }\n"
        css += EXTRA_CSS
        book.data[path] = css.encode("utf-8")

def fix_markup(book):
    """Small markup fixes across all content documents."""
    for path in book.spine:
        root = book.tree(path).getroot()
        changed = False
        # <br class="..."> where the class says display: block renders as an
        # extra blank line (or nothing) depending on the reader.
        for br in root.iter(X("br")):
            if br.get("class"):
                del br.attrib["class"]
                changed = True
        # <h3><blockquote>...</blockquote></h3> isn't valid XHTML and strict
        # renderers may mishandle it.  A <span> with the same class (the
        # class already says display: block) renders the same and is valid.
        for heading in [e for e in root.iter() if e.tag in HEADING_TAGS]:
            for bq in heading.iter(X("blockquote")):
                bq.tag = X("span")
                changed = True
        # Cover pages stretched to the screen with preserveAspectRatio="none".
        for svg in root.iter(f"{{{SVG_NS}}}svg"):
            if svg.get("preserveAspectRatio") == "none":
                svg.set("preserveAspectRatio", "xMidYMid meet")
                changed = True
        if changed:
            book.dirty.add(path)

# --------------------------------------------------------------------------

def context(stream, pos, width=60):
    s = stream.raw[max(0, pos - width):pos] + "⟦*⟧" + stream.raw[pos:pos + 25]
    return " ".join(s.split())

def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("epub")
    ap.add_argument("-o", "--output", help="output path (default: '<name> - linked notes.epub')")
    ap.add_argument("--report", help="write a line per note showing where its marker went")
    args = ap.parse_args()

    out = args.output or re.sub(r"\.epub$", "", args.epub, flags=re.I) + " - linked notes.epub"
    book = Book(args.epub)

    notes = find_notes(book)
    if not notes:
        sys.exit("No notes found (looked for a 'Notes' heading followed by "
                 "paragraphs starting with page links).")
    # Number notes within each notes subsection (i.e. per chapter).
    counters = defaultdict(int)
    for gid, n in enumerate(notes, 1):
        counters[n.section] += 1
        n.number = counters[n.section]
        n.gid = gid

    streams = {p: TextStream(book.tree(p).getroot()) for p in {n.target_path for n in notes}}
    match_notes(book, notes, streams)
    choose_insert_points(notes, streams)

    if args.report:
        with open(args.report, "w", encoding="utf-8") as f:
            for n in notes:
                where = (context(streams[n.target_path], n.insert_at)
                         if n.insert_at is not None else "NOT FOUND")
                f.write(f"[{n.section_title} / {n.number}] ({n.how or '-'}) {n.cue}\n"
                        f"    {where}\n")

    insert_markers(book, notes, streams)
    rewrite_notes(book, notes)
    fix_markup(book)
    fix_stylesheets(book)
    book.write(out)

    found = sum(1 for n in notes if n.insert_at is not None)
    loose = sum(1 for n in notes if n.how and n.how != "page")
    print(f"{len(notes)} notes, {found} linked into the text "
          f"({loose} needed a looser match - worth a glance in the report).")
    for n in notes:
        if n.insert_at is None:
            print(f"  not found: {n.section_title}, note {n.number}: {n.cue!r}")
    print(f"Wrote {out}")

if __name__ == "__main__":
    main()

Claude automemory, Nix, and .git

I’m running into a complicated snarl of things in my server management. Long story short: both Claude and Nix make assumptions based on your current working directory and where the nearest .git folder are. You may want to manage that carefully.

Claude Code has a couple of features that are defined “per project”. The one I care about is automemory, where Claude records little things about your projects. The directory Claude attaches these memories to seems to be the top level directory that has something named .git in it. That means if you have git repos in nested directories, the memories are attached to the largest scope.

Nix also has features where it scans all the files in a directory with a .git in it, assuming they belong to the NixOS build you’re doing. This caused me various problems that I can’t really explain.

My fix for all of these is for a sever project like “caddy”, I have a directory with a .git repo in it called src/ai/servers/sfpve/caddy/repo. I launch Claude from inside src/ai/servers/sfpve/caddy, where there is no .git. The memories then attach up to the src/ai/servers/ parent directory where I want them. Claude Code itself is launching Nix and somehow this helps it manage Nix’s magic with .git.

It’s more complicated than that in reality and I don’t actually understand what I’ve done or whether it’s a good idea. But Claude using the location of a .git to decide where automemory goes was helpful for me to learn.

Claude Code, Nix, ssh, and Linux

Claude Code figured out it could use my Desktop ssh agent and did some surprising things on remote systems. Thankfully it only did good things but it was alarming. In short: the problem was I’d set allowAllUnixSockets: true to make Nix work. That enabled ssh access and Claude was smart enough to discover it. Details and a fix below.

ssh agents

ssh agents work by having a daemon listening on a Unix socket. Mine is in /run/user/1000/ssh-agent.socket and $SSH_AUTH_SOCK points to it. Claude is ambitious enough to find and use this agent to access other machines if it helps get a job done. The default sandbox denies access to Unix sockets though, so it’s usually prevented. But...

Nix

Nix’s default install has some elaborate daemon setup to do Nix operations like building new artifacts. The client tools talk to it via a Unix domain socket /nix/var/nix/daemon-socket/socket. That wasn’t working for Claude Code because the default sandbox disallows access to all Unix sockets. (Many are sensitive!) So the devil suggested I augment the sandbox with the policy allowAllUnixSockets: true. And then Nix worked! Only now Claude had access to all sockets. Including ssh-agent.

The fix on MacOS

I can’t test this, but the very sensible fix on MacOS is instead of giving access all Unix sockets, just set "allowUnixSockets": ["/nix/var/nix/daemon-socket/socket"].

Unfortunately this doesn’t work on Linux right now (Sep 2026), some limitation of the sandboxing system. The directive is a no-op on Linux so no access is allowed (and no warning). Your only easy option is to enable all sockets.

The fix on Linux

I’m not certain, but the best I can do on Linux is enable access to all sockets, then disable one by one “dangerous” sockets that Claude might try to use. Claude suggested this configuration based on what it found on my system today:

  "sandbox": {
    "credentials": {
      "envVars": [
        { "name": "SSH_AUTH_SOCK", "mode": "deny" },
        { "name": "SSH_AGENT_PID", "mode": "deny" }
      ],
      "files": [
        { "path": "~/.ssh", "mode": "deny" },
        { "path": "~/.aws/credentials", "mode": "deny" },
        { "path": "/run/user/1000/ssh-agent.socket", "mode": "deny" },
        { "path": "/run/user/1000/gnupg", "mode": "deny" },
        { "path": "/run/user/1000/op-daemon.sock", "mode": "deny" },
        { "path": "/run/user/1000/1Password-BrowserSupport.sock", "mode": "deny" },
        { "path": "/run/user/1000/kwallet5.socket", "mode": "deny" },
        { "path": "/run/user/1000/bus", "mode": "deny" }
      ]
    }
  }

Of course blacklisting some sockets is terrible security, no doubt next week (or next ssh session) some new socket I haven’t blacklisted will be created. Docker is a good example: its sockets are very powerful and I haven’t thought to block it here. (Might not want to, having Claude drive Docker is useful!)

Basically the Linux sandbox isn’t strong enough to protect against a real adversary. But Claude isn’t an adversary. It’s an enthusiastic and very curious puppy. I think it provides helpful protection to put puppy gates across the doors you don’t want it to go through.

The problem is Claude is also the devil. A very persistent one. If you ask it to try hard to get something done it will. It’d be much better to have a more solid sandbox stopping it. Hopefully they fix this limitation about only allowing certain Unix sockets soon. There’s various bug reports about it but I haven’t researched them.

I wonder if there’s some other way to let Nix do its thing without a Unix domain socket, or with some proxy script that Claude is allowed to use.

Giving Claude Code the keys

I’m setting up a new server at home with Claude and NixOS. It’s a NAS-like thing for all my precious files, I’ll talk more about it later. Wanted to note here how I’m working with Claude.

In three devops projects I’ve gone from “talk to Claude and run all the commands myself” to “trust Claude to build a server VM but do all the config work by hand” to “trust Claude with access to Proxmox to create and maintain a server VM”. This Proxmox server is all my important stuff! It’s scary. But it’s also very nice letting an AI do the work.

I’m not insane, I do have backups of everything precious. A truly malicious Claude could probably destroy those backups too. But I’m trusting the agent isn’t adversarial. My goal is to just make it so an honest mistake isn’t catastrophic.

Protections

The first protection was giving Claude clear limits on what I wanted it to do. Don’t delete any data. Only work to make a single container with ID 300. Only use certain resources. Claude seems to be trying to obey those limits in good faith.

One simple protection: Claude mounted my precious data read-only to copy it into the new system. That was its idea and it’s a good one, I feel much safer that way.

I gave Claude an unrestricted ssh login with sudo access. One nice thing it did was make a very precise sudoers file. So for instance pct create 300 is allowed to create a container with id 300, but it doesn’t have general access to pct to manipulate all the containers. I’m not confident the sudo restrictions are complete. And I’m sure a malicious Claude could escalate privileges with the access it has. But it seems to help prevent accidents.

Claude has no trouble sshing to my box. I’m a little confused about this: the default sandbox restricts networking to localhost only plus one HTTP proxy. But Claude just happily writes a script to proxy ssh through HTTP (using the CONNECT command). I don’t know if this is Claude working as intended or if its entire mode of accessing my computer is an exploit.

One thing that did not work great is trying to get Claude to interactively ask me for any commands it runs as root. The new defaults in Claude let it run anything the heuristic checker approves. That’s a lot of things! Including ssh server sudo * (although there may be some restrictions on *. I want to review each command, so I overrode that by explicitly listing commands that I should be asked for. But that matching is very literal. And Claude keeps coming up with new ways to invoke ssh. So now I have something like this in the permissions file:

    "ask": [
      "Bash(ssh -F /home/nelson/.local/state/claude/ssh_config claude@sfpve:*)",
      "Bash(ssh -F /home/nelson/.local/state/claude/ssh_config sfpve:*)",
      "Bash(ssh -F ~/.local/state/claude/ssh_config claude@sfpve:*)",
      "Bash(ssh -F ~/.local/state/claude/ssh_config sfpve:*)",
      "Bash(ssh claude@sfpve:*)",
      "Bash(ssh sfpve:*)",
    ]

There’s nothing stopping Claude from coming up with yet another way to ssh into the box, bypassing these checks. Maybe this is fixable with a smarter glob, not sure.

Update Sep 21

After watching what Claude does some more I got nervous and decided to not give it this much access to Proxmox. I’m fine with it managing individual containers but Proxmox is too much.

For initial setup of a new container I’m having the agent write a shell script I run as root on Proxmox. I look at it closely. It’s basically just a single pct create in the simple case.

For managing a container that has tailscale, Claude has no more access at all to Proxmox. If the container doesn’t even have tailscale I’m giving Claude ssh access to sfpve but solely to run ssh -J to forward into the container via the local IP address. Something like this in the authorized_keys: restrict,port-forwarding,permitopen=”192.168.0.108:22″,command=”/bin/false”

Alarming behavior

Claude did two things that made me nervous.

  • Claude deleted some data despite being told to never delete data. It used rclone to remove something from Google Drive. We’d just established I had other copies of the data and wanted to delete it, so it was reasonable enough to delete the data, and really it only moved it to Trash anyway. But still, it violated a direct limit.
  • A new project went grubbing through other Claude project history, found the ssh key it had, and happily used that to give itself access to answer some questions about the Proxmox setup for something else. It was doing what I asked of it, and I did tell it to try to work autonomously and not bother me. But it got a little frisky letting itself in the door with its cousin’s keys.

Another major problem in my environment.. I use an SSH agent and SSH_AUTH_SOCK is available to Claude. I’m not sure it can normally access that. But Claude convinced me to give it "allowAllUnixSockets": true in its sandbox so it could do Nix things. That enables access to the SSH agent socket, too.

I’m currently testing giving it permission just to talk to Nix and no other sockets via "allowUnixSockets": ["/nix/var/nix/daemon-socket/socket"] but hit a snag. more tomorrow.

No, Opus is really good at reasoning

I’m genuinely flummoxed by how good Opus is at some sysadmin tasks. Today I asked it:

I need some way to manage all the web page content that’s stored on the server. right now the authoritative copy is on the server and the restic backup is the only stopgap. and if I want to change something I live-edit it on the server, or at best live-edit it on a copy and then sync it over. that seems too ad hoc, I should have a content here on my dev machine and some process to sync it. ... help me figure out what to do.

I did not propose a solution. Claude/Opus reasoned very well to get to a solution for me. It’s thinking is clearer than my own!

The AI inventoried all my files. Then it came up with three sensible groups.

  1. Truly hand-edited files that change sometimes
  2. Files that only exist on the server but are archival and never really change
  3. Files that actually exist elsewhere and already are being synced to the server.

It came up with those groups itself. It was using some knowledge from previous discussions (particularly about the synced-from-elsewhere group 3) and I think inferring the archival idea of group 2 from the sizes and ages of files.

It then proposed treating each of the three categories separately. And building a special publish tool for group 1, so I can have them in git on my dev machine and then sync them over. No new publish tool needed for group 3, I already have tools doing that. And no publish tool needed for group 2 at all. Backups are sufficient.

One wrinkle: the AI proposed a fairly minimal solution for solving the problem of me hand-editing the same file in group 1 in both places. (The naive solution has one edit clobbering the other, it suggested adding a --dry-run flag). I asked it to do something more automatic and it came up with a reasonable thing involving touching a sentinel file after each sync and then using find to see if anything had changed. This isn’t super fancy, but it sure is sensible.

This AI is solving design problems as well as I could with very little direction. And I know it will go off and implement it very competently for me. It’s not just saving me time, it’s doing a good job of it.

An AI server project

For nearly 20 years I’ve hand-maintained an Ubuntu Linux server for somebits.com. Every few years I had to recreate it from scratch, a tedious process involving a couple of days of forensics, editing config files, watching logs... so boring. And often stressful because I was doing it only after the old server had died.

No more. I now have a brand new server running NixOS. Here’s the thing. I don’t really know Nix. I played with it once for about an hour and thought “this is cool but too much to learn”.

Thanks to Claude Code and Opus I don’t have to learn it. The AI knows it already. And I think NixOS is a good match for an AI. The whole thing is declarative, you configure the server with some basic text files. AIs are good at writing text and testing the results!

The result worked spectacularly: way better than I expected. I thought I’d tinker with this for a week and learn how poorly AIs are at this complex a task. Instead it got it done for me in about a day and I was ready to switch over. I’m confident Claude did a better job than I would have myself, and much much faster.

The project took 270M tokens, 6M of which were actual work (the rest is cache). Claude values that at about $200 although I did it all in my $20/mo plan.

How I worked with Claude

In the past I haven’t trusted Claude to do complex things with live sites but this time I was setting up a brand new server so was willing to go full YOLO. The more work it did, the better.

I first wrote a page-long README explaining what I wanted to Claude and asking it to come up with a design document. I described the server, pointed it to my old notes, copied off some config files for it to look at, and told Claude I wanted it to do as much work itself as possible. I also suggested Nix. We talked back and forth for awhile and it drafted a 15 page design document. Too much to read! But I skimmed it and suggested some changes. Honestly it was Claude itself that was going to be reading this thing frequently. This whole design process took an hour or two back and forth.

Then I started a new Claude session and asked it to create a work plan. It came up with about 12 pages of specific tasks, each labelled as to whether Claude could do it or I could. (In general I only gave it access to the new server so I had to manually do things to DNS entries, the old server, etc.) One key thing it started doing here was asking for more data from the server, writing scripts for me to run to collect things it wanted to inspect. It made good choices. Again this took a couple of hours.

Then I fired off Claude sessions over a day or so to do the actual work. The work plan was helpful here: each Claude session new what to do or what to tell me to do for it. And I had some idea what it was going to do. Mostly it stuck to the plan and resisted the urge to add things to it: we did create a future work document for new ideas that came up. This process took maybe 4 hours? Some of the time was spent waiting for long network test jobs to finish.

The actual building of the Nix config files went remarkably quickly. The real work was all the testing, particularly in the final phases. Claude was way more thorough than I would have been which was reassuring. OTOH I don’t really know how complete those tests are. They seemed pretty good to me.

I started new Claude sessions every hour or two, after major work. The context window gets full. And anecdotally AIs get dumber as the context gets longer. Automatic compaction is supposed to help with that but I don’t trust it. I’d prefer Claude to dump its thinking into permanent documents that it rereads in a new session, that way I can read them too. The design and work plan docs were the big ones.

Claude Code also keeps a memory. Most of it is technical notes but it’s also developing a theory of my own personality.

  • He wants to be able to verify things himself
  • He values finding what was missed over being reassured
  • He gives blanket “work alone” permission for a stretch and expects a plain report at the end

I still need to have one more session with Claude to tell it to summarize the work it did and document things. It created a lot of scripts, some of which I will want to use. Again these docs are partly for me, partly information for future AI agents.

Thoughts on using AI for devops

This is the first project where I really trusted Claude Code to do things, as an agent, to make server changes and lots of network requests. It worked fine. Great, actually!

This is also the first project where I think Claude did a better job of the work than I would have. First, I don’t know Nix, and while I could have learned it on the fly it would have taken a lot of time and I wouldn’t have been good at it. Also Claude was just much more organized and thoughtful about server setup tasks and how to verify they worked correctly. And it thought of a lot of things I wouldn’t have, like the subtleties of the new server having an IPv6 address.

The magic thing here is how self-directed Claude/Opus was. It came up with its own idea about how to figure out what was on the server. Then came up with its own tests, like a complete set of 150,000 URLs (from Apache logs) to verify and then a 6000 URL sample to run for development work and a 22 URL sample for a smoke test. It wanted to actually test all 150,000 for a final ch eck and I told it that was too much so it whittled it down to 17,000 URLs that would test all the important paths through the server configs.

I’m trying to think what didn’t go well and not coming up with a lot. Opus is awfully wordy though, it’s a bit exhausting to talk to. Maybe I’ll find out something big went wrong in the next few days.

I do need to double back and learn to read the nix configuration files, or at least understand them. Maybe I’ll find something awful in them but on first look they are reasonable.

If I were a working sysadmin I’d be real nervous about my job now. I guess most of them already are. There’s still room for a human in the loop, at least for now. I felt like I had to manage Claude’s work, I gave it a lot of guidance in how to do certain things, and I was riding it pretty hard to verify its work. But the job I did was more like someone managing devops folks with 5+ years experience than being that devops person. This suits me fine, but it is alarming for my industry.

Postcards AI hacking

Just finished a big AI coding project, my travel postcards. I’m very happy with how it turned out. (I’m talking about AI code but this post is written entirely by me.)

I’d originally created a simple thread unroller for my Mastodon posts using an old version of Claude Code and then later Jules + Gemini Flash 3.5. It worked well on a relatively simple task, the Mastodon threads I create are very tidy.

But I’ve been tweeting about trips since 2009 and not always so organized. So I set Claude + Opus 5 to work on a recovery task, to collect all the old travel threads. It did very well, way better than I would have done on my own. I never would have done all this work myself.

(An aside: AI coding is very divisive. One argument is “it doesn’t work very well”. I think that’s just wrong. AI coding can work very well indeed. This experience with Opus 5 was really good, it’s a major improvement over the older models. And this task is well suited to AI. I don’t really care much about the code quality. And it’s easy to inspect the final output and determine if it’s working.)

Interesting work we did

The basic recovery project was pretty simple: take some old Storify posts and my Twitter archive export and tell the AI to write a program to find and organize all the trip tweets.

I gave it a pretty open-ended brief for this and didn’t suggest how to do it. It tried out various heuristics and tested them against one known-good output I already had hand edited. It finally settled on a combination of the text using travel words and city names plus looking at timestamps on tweets for when I was apparently in a different time zone. I really appreciated its proactive autonomy, both for coming up with heuristics and for validating them.

Recovering photos was a harder problem. Twitter’s export archive doesn’t contain full resolution images. And for older tweets there isn’t an image at all, sometimes all you have is a dead twitpic URL.

I would have given up, just accepted the low-res photos and lost images. The AI was much more persistent and found hundreds of photos for me. Some of the strategies it came up with:

  • Finding Flickr photos in my Flickr data export by realizing that the URLs in the tweets were base-58 encoded versions of the IDs in the export.
  • Finding Twitpic and Yfrog images on the Wayback Machine. (Sorry Brewster, y’all throttled me a lot.)
  • Matching low-res photos from the recovery process with higher res originals in my Google Photos export using image-similarity heuristics that it chose and validated itself.
  • Matching cropped photos from the recovery process into uncropped originals on Google Photos by guessing what crop I applied and matching similar images. This was slow but it worked and helped recover a bunch of photos from India.
  • Where no image from Twitter was available, finding photos in Google Photos based solely on timestamps.
  • The only thing it didn’t try was matching my tweet text (“picture of my ice cream!”) to a semantic analysis of the images (identifying pictures of ice cream). I know the AIs are capable of doing vision but I didn’t ask it to and it didn’t volunteer.

A key part of working with AI is knowing when you can just trust its output, when you can have it effectively validate its own output, and when you need to step in and validate it yourself. I spent a lot of time skimming over the output pages it was generating making sure they were plausible. And in several places I had it write tools to let me do editorial work myself, like picking photos when they were ambiguous.

Some AI things that worked

Early on Claude was giving me markdown files to hand-edit to make some editorial decisions. That’s tedious, so I asked the agent to write a basic Web GUI tool that was a custom editor for the task. That was so easy and productive I ended up having it build several tools. times. I would never ever write a throwaway task-specific GUI tool for my own project, it would take hours or days. But Claude got it done in 10 minutes.

I was surprised with how well Opus 5 did with open ended tasks. (I started out on XHigh effort, then dropped to High). I quickly learned to just describe the result I wanted rather than try to lead it by the nose on how to achieve that result. Sometimes it surprised me with what it came up with! And it saved me a lot of work. Opus is very capable, this kind of high level thing wouldn’t work nearly as well with a dumber AI. (You know, the ones that are just six months old...)

Having big data exports from Google, Twitter, and Flickr was a huge help. Those data dumps are hard to work with, they’re often just a big pile of JSON files and images and no organization. It’s 53GB of stuff for Google Photos! But the AI is very good at that kind of thing. I just pointed it at the .zip and said “figure this out” and it did.

Some AI things that didn’t work

The code the AI wrote seems to mostly work but I didn’t read any of it. I’m sure there are horrors there. But I don’t care for this project: as long as the AI can understand it’s own code it’s fine.

The code did run fine. But sometimes it was awfully slow. For instance for the image matching was taking minutes for each post. I aborted it and said “make this faster”. And so it did, mostly by rewriting the code to use numpy. I wish it had taken the initiative to make it faster itself. I wonder if Claude Code could be given agent instructions about when it was worth spending extra time to optimize something instead of relying on me to notice.

I don’t really know if the code is right. It wrote some 600 unit tests but they could be useless for all I know. I was validating the output by eye. If I were more serious about this as a real product I’d write my own high level system integration tests to really validate the output. Or at the very least have the AI write those tests and check very closely they are correct.

Claude is very verbose. It’s really quite annoying when talking to the AI agent and I bet the code is chatty too. This seems to be a problem with all LLM systems. Nothing it’s saying is particularly redundant or wrong, but there is an awful lot of it. Almost like it was talking to another LLM...

The workflow Claude came up with for the recovery process was very complex. I ran tool A and it’d generate a partial config file which tool B could use to get more data for the config file. Then run tools C and D to process, then go back and run tool A again with that extra data, etc etc. I never could quite figure out how to run it all correctly. This is mostly my fault, it reflects the iterative way we designed the whole thing. The good news is Claude itself knew how to run its own tools and was good at diagnosing and fixing failures, so I gave up trying to understand how to run it myself and just had Claude run it for me. That’s OK for a one-off hack like the recovery process. The Mastodon unroller I plan to keep using is much more tightly designed.

Some reflection

Claude tells me we spent about 20 hours working on this over 5 days. I typed 177 prompts to the agent. It processed just about 1 billion tokens in 4200 API calls. It says that’s nominally $685 worth of API usage although I did it all in the bounds of my $20/mo subscription.

Tokei says it’s 14,450 lines of Python code plus another 8600 lines of test code. That feels like an awful lot, I’d have guessed ⅕ that size if I wrote this carefully by hand.

I dunno how I feel about all this. Impressed, mostly. A little sad, I’ve always enjoyed crafting good code and I feel like that skill is suddenly much less useful. But honestly I haven’t been doing much of that in years now. I had a lot of fun getting an AI to build this for me.

I don’t love the emotional experience of working with Claude Code. It’s just fast enough that you mostly want to be paying attention, but still slow enough you get bored and do something in parallel. Most prompts I was typing were 2-15 minutes of work? I liked the Jules asynchronous model better, but then you have to trust it to work autonomously for longer tasks.

I still wouldn’t use an AI for something where the code quality really matters. Or rather I’d use it much more carefully. But for a data processing one-off job? It sure did a good job here.

Being Claude’s agent

I’ve been working on a complex project where I am the agent following instructions and running commands while Claude is the planner giving high order instructions. It’s kind of fun, an inversion of the usual coding agent work pattern.

(An aside: no one can define what an “agent” is. Not even me, a 1990s PhD student in the Software Agents Group at the MIT Media Lab. But one definition is “agents are software that can do things to the outside world”. Agents edit files, or push to GitHub, or pwn a competitor’s AI company. It’s the agency that makes an agent an agent. By this definition I am the agent in my scenario.)

The project I’m working on is updating my homelab / selfhosted services on Proxmox. Mostly adding a new reverse proxy to give me better access to things. This boils down to creating and configuring a bunch of little Linux containers (caddy, authelia, homepage, ntfy, etc).

I don’t really now how to do all this, so I got Claude Opus to come up with a design that I reviewed. But I didn’t trust Claude Code to implement it. And I wanted to understand how it all worked. So I had Claude write up a very verbose tasklist for me. For the past few days I’ve been dutifully following it. I’m very slow, it’s taken me ~4 hours of actual work when Claude Code would have done it in 10 minutes. But I do understand what it’s doing.

Part of what’s been fun is duplicating some of the way software agents use scratch files as memory. I have a Claude Project with several chat sessions and some text files Claude created keeping track of state. The project has like 15 tasks, each with 3-5 subtasks, and I’ve totally lost the plot. But I trust Claude to keep track of it and every once in awhile I just tell it “ok I did task 13.3. what’s next and what do I do?”

When I work with AIs I am trying to use them as partners for thinking. Most of my interactions with AI are back-and-forth, with me reviewing what its saying and using the AI as a source of ideas and things to consider. I don’t much trust an AI agent to go off and do a complex task for me, at least not one whose result I can’t easily verify. This interactive session where I do the work feels better to me.

One problem is Claude is a never-satisfied taskmaster, it keeps adding things to a giant “backlog” new task list. This is a problem inherent with how these AIs are prompted, it keeps coming up with more things to think about. I feel a bit like Sisyphus. But Claude is pretty good about accepting when I tell it “no, I’m not doing that”.

Gemini vs Google Keep

I’m using Gemini 3 for all my AI queries. One thing that makes it better than ChatGPT for me is it has good integration with other Google products. The Gmail tool is particularly good, I am regularly using it now to ask complex queries about emails going back months.

The Google Keep tool though is a total mess. It just doesn’t work and fails in exactly the way LLMs so often fail. It’ll say it can do something, then try to do it and fail, then tell you it succeeded. It’s too bad: Google Keep would be the perfect tool as a sort of external memory for my chats. In particular having Gemini write output notes to something I can then easily consult on my phone.

The one thing the Keep integration seems to do reliably is append to a note. It can add content.

Gemini thinks it is also capable of editing notes, and updating them, and deleting them.

This is AI lies. The tool doesn’t seem able to do some of these things, particularly “Add & Update Content”. And it will say it updated something when in fact it hasn’t.

Also other stuff just doesn’t work. I tried “delete all notes in Google Keep”. It then deleted 2 of the 3 notes I had and confidently told me it deleted all of them. Ugh.

It’s too bad: I really like the idea of a notepad for Gemini to manage.

Gemini’s view of my linkblog

Oh no, I’ve become that person who posts AI responses as if other people will be interested. But this blog is foremost for me, and I think the following is insightful enough I want to keep it for myself.

I pointed Gemini-in-Chrome at my linkblog archive page and asked it “look at this archive page. can you detect trends over t he years?” (typo and all). Below is its summary of over 20 years of me sharing interesting links. I think it’s pretty good.

It detects changes in the topics I’m interested in over years: blog tech to start, then mobile, and now AI and politics. It also detects a shift in my tone, from optimism to skepticism. I don’t love that I’ve done that but I think it is correct and a useful mirror for me. It doesn’t mention a couple of topics that were big parts of my interest for several years. Maps, plotters. And I think it may be overstating the tone changes.

Gemini’s analysis

Analyzing Nelson’s Linkblog archive, which spans from late 2003 to the present day (March 2026), reveals a fascinating shift in how a technically-minded observer has interacted with the evolving internet.

Here are the primary trends visible over the decades:

1. The “Golden Age” of Blogs (2003–2010)

  • The Topic: In the early 2000s, the blog is heavily focused on the fundamental building blocks of the modern web. You see frequent links to RSS feeds, XML standards, and early Open Source movements.
  • The Vibe: There is a strong sense of “building the future.” Nelson often links to niche technical documentation and academic papers about distributed systems (like his work on Gnutella).
  • Trend: A shift from purely technical infrastructure to the social implications of early social media (Friendster, Flickr, and the rise of Twitter).

2. The Mobile & “Social” Pivot (2011–2019)

  • The Topic: This era shows a transition toward the smartphone revolution. The links shift from desktop-centric web standards to iOS/Android development, mobile UX, and the consolidation of the web into “walled gardens.”
  • The Vibe: This is where “Enshittification” (a term coined later but felt here) begins to surface. There are more links criticizing the business models of Uber, Facebook, and Google.
  • Trend: A move from “how to build the web” to “how the web is breaking society.”

3. The Era of Crisis and AI (2020–2026)

  • The Topic: From 2020 onward, the blog becomes more political and reactive.
    • 2020-2022: Heavy focus on COVID-19 data, public health policy, and the logistics of remote work.
    • 2023-2026: A massive surge in Generative AI content. Links shifted from “cool tech demos” to deep skepticism about “AI slop,” the ethics of LLMs, and agentic engineering patterns.
  • The Vibe: There is a recurring theme of “Joy in Resistance” and looking for decentralized alternatives (like Mastodon and Bluesky) to the major tech platforms.
  • Trend: The blog has become a “digital bunker”—a place to track the decline of mainstream platforms while highlighting niche, high-quality human creativity.

Quantitative Snapshot

EraPrimary FocusMood
2003-2009Peer-to-peer, XML, early PythonOptimistic / Academic
2010-2018Privacy, Social Media, GadgetsObservational / Concerned
2019-2026AI Ethics, Climate, Political ActivismSkeptical / Resilient

Summary of the Shift: The archive moves from optimistic experimentation (how do we make this work?) to defensive curation (how do we save the good parts of the internet from the bad parts?).

Would you like me to dig into a specific year in the archive to see what Nelson was focusing on during a particular historical event?

First impressions of Jules, Google’s coding agent

Google has a coding agent product called Jules. It’s similar to Claude Code. But it’s designed foremost as a web interface. And to run in the cloud, on Google ephemeral containers from code stored on GitHub. It’s also more asynchronous: you give it big tasks and it comes back in ~10 minutes with a pull request. There’s some interactive back and forth when making the plan if you want.

I think this web async design is a better fit for me, I don’t like Claude Code’s text UI and I don’t like how I have to install and run parts of it on a local machine. Update: Claude has “Code on the Web” which is more like Jules.

One other difference is Jules is using Google’s models. That would have been a bad experience with Gemini 2.5, which is what the free Jules still uses. But if you pay $20/mo for Google AI it includes access to Gemini 3.1 Pro which has proven to be a very good model for general queries. Not sure if it’s as good at coding as Claude but so far so good. There’s also a Gemini Flash which is faster and specifically coding optimized, I’m trying that out now instead of Pro and it seems fine.

Working with Jules has been a good experience so far. I feel like I’m instructing a junior engineer. I have to be explicit about what I want and check everything it does. Sometimes it says it did things that it didn’t, and sometimes it tries to do things it shouldn’t. Sometimes it does things wrong. But it’s very good at doing a lot of things and the use of GitHub pull requests as a review mechanism lets me fix things t hat are problems. It sure looks like Jules is doing high-order reasoning about algorithms and side effects and how systems work. I think I can trust Jules to understand this code better than I do.

A project

I’m using Jules to work on Feditrends, a simple scraper / link ranker that I maintain. I’ve never really touched this code, I took it over from someone else, and honestly I wasn’t excited to get my hands deep into it. Perfect thing to experiment with an AI instead.

I started by asking it to read all the code and make suggestions for what to change. Then I had it make a simple test suite. (It’s not great, but it’s a start. I’m a fan of test driven development and ordinarily would have more tests. I think that’s important for AI coding but we gotta start somewhere.) All that done, now I’m having it make one improvement at a time as it suggests things.

Here’s an example pull request for a very simple change: reformat a list of server names and then remove a duplicate. The code change is trivial and I was quite pedantic about it, building trust. But not shown here... Jules spotted this little code problem itself when I asked it to review the code and make suggestions. It found the duplicate. It also correctly reasoned about how this change might affect the algorithm (it doesn’t)

AI chat transcript (partial)

Nelson: I want to work on your suggestion “Fix Server Duplication: Remove the duplicate sfba.social in fetch.py.” look at the code and verify that the server is duplicated. then tell me, if we remove that does it change the algorithm results significantly? I’m guessing sfba.social gets double weighting in the ranking because it’s done twice.

Jules: Regarding your question about the algorithm results: The ranking algorithm in mastodon/build.py uses count(distinct instance) to calculate the number of instances a link appears on. Because of the distinct keyword, having the same instance name twice in the database for the same snapshot should not increase the “instance count” part of the score.

Jules: It also uses max(uses_1d) and max(rank). If the data on sfba.social changes slightly between the two fetch cycles, max(uses_1d) would take the higher value and max(rank) would take the higher (which means numerically larger, but lower/worse ranking) value. So if anything, it might slightly penalize a link if its rank drops during those few seconds, or slightly boost it if uses_1d increases, but it certainly doesn’t “double” the weighting in a straightforward way.

Nelson: let’s go ahead and proceed with the plan to remove it. but before you remove it: please reformat the code so the list of instances in fetch.py is no longer all one line. break it up into one line per server name. but keep the duplicate. make a pull request for me to be sure you did it right. we will then remove the duplicate later, as a second change.

It did exactly what I wanted in this case, a good result. Some other changes it gets wrong at the start and I have to catch it in review but so far I’ve been able to redirect it to success every time.

Update: CoPilot

A friend encouraged me to compare Jules to CoPilot Agents, built into GitHub. Roughly speaking they are very similar. CoPilot has nicer integration with GitHub, so some of the git stuff feels a bit more reliable and featureful. Different set of models of course, with CoPilot mostly being OpenAI models. It’s $10 or $20/mo to use and has some limits. I’m already getting Jules as part of my Google $20/mo AI subscription and it has no disclosed limits but only a choice of two Gemini models.

I suspect there are meaningful differences in the two products, particularly in how they manage code environments and the details of the prompt engineering. I’m not equipped to compare them very deeply. Jules is doing well for me so far so I’ll stick with it.

Shortwave AI email

I decided to give Shortwave a try. It’s a better email client with significant AI features. I mostly want it for better LLM-powered search of my old email, something Google cannot do. So far I’m impressed. Only drawback is its expensive for a consumer product: starts at $288 a year, I’m paying for the $432 a year version. There is a free trial.

First impression is very good. It works fine as a Gmail replacement, with two-way sync to Google data that seems to work.

The onboarding is a bit slow. Recent email works immediately. It’s pulling in archives. After four hours it has indexed some mail but I can’t tell how much, there’s a progress bar showing 10%. I do have 12GB of email over 21 years, I can imagine it takes awhile. They don’t have a way to just upload a Google Takeout dump.

My first AI query went very well. I sent a bunch of emails today about hosting a party. It read them all and summarized them usefully. There was more below this post, details of RSVPs from specific people in a very nice summary. This is the kind of magic I am expecting in an LLM with my email.

Asking it for “what is my oldest email” didn’t go as well. I have email back to April 2004. It didn’t find the older ones at all at first. Finally with a lot of prompting it found April 29, 2004. Then I had to ask more and it finally, finally got to the April 2, 2004 emails it should have found in the first place. Ie they’re there, but the AI retrieval didn’t work well. I’m wondering if “oldest” is just not something they optimized for.

Update: support replied quickly with an excellent reply that boils down to “oldest doesn’t work well”. They suggest giving explicit date ranges. That matches what I’ve observed.

Various other freeform queries show some remarkable comprehension of my emails. It’s not perfect, I feel some things are occasionally missing. And the whole system is a little too business-tuned whereas I’m often using this for personal correspondence. But overall it’s useful.

It also has features to write emails for you and promises to do that in my own style. I don’t really want this, it seems rude to have a robot write my email for me. But it is interesting as an editing tool.

Party details

Just for laughs, here’s what Gmail / Gemini offered me

This is the second wrong answer I got from Gemini. The first one earlier today was about a friend who is having a birthday the same day. It has nothing to do with my party at all. I did finally got a right answer when I prompted it “the party is saturday sep 13. I sent a lot of email about it today. can you find that”. This suggests the retrieval part of the pipeline is what failed here, not the summarization.

Gemini AI in Gmail is terrible

I keep musing over the idea of using an LLM to work with my 20+ years of email archives, currently in Gmail. I finally realized a couple of days ago Google has this product. It’s part of Google AI Pro, also sometimes called Google AI Premium and often labelled “Google Workspace” (where the AI was first deployed). It includes a Gemini-in-Gmail system. It’s not just the product naming that’s such a mess though: the Gemini-enhanced Gmail is just terrible.

The problem seems to be the retrieval part of the RAG that I imagine is powering this product. Gemini only seems able to see about 6 months of my email archives. Even with very specific queries like what’s the oldest email if you search for “steam purchase” in 2021? it doesn’t actually find that oldest email. Gmail keyword search works fine and finds about 10 or 15 emails. But then Gemini can’t find them.

I started using Gmail April 2, 2004, the day after it launched. If I ask it for the oldest email of all it can see it gives me something from mid 2025 and provides a subject line. If I ask for the oldest email from 2003 it hallucinates an email from April 17, 2003 with that same recent subject line. It’s just not useful.

I get that RAG is hard. I’m sure the Gmail team was asked to launch an AI feature very fast. But what they’ve deployed is terrible and should not have been released. The only excuse I can think of is if somehow this “show me the oldest” query is perversely hard for their system. Maybe it’s more useful on other types of queries? Not in my experience.

I’ll tell you what’s really annoying: all the extra UI popups offering AI help where none is wanted. Including summaries of emails which are distracting and sometimes wrong. It’s like Clippy but worse. Just terrible all around.

ChatGPT is doing way better. Too bad they don’t have the email product I want.

Update: another example, Gemini can’t even keep track of the context of “3 emails I sent”.
How many emails have I sent to this person today?
You have sent 3 emails (This is correct)
Can you summarize those three emails?
It looks like there are only two emails in this thread.
(Proceeds to summarize my mail and his reply, ignoring my other two sent emails.)

Some quick LLM speed tests

This article about running LLMs on a laptop inspired me to try out LM Studio again on Windows. This is on a computer that I first built 8 years ago and updated in 2020. Ryzen 3700X CPU with 32GB RAM, and an old GeForce 1080 with 8GB of VRAM.

Bottom line: I can run Q4 models up to 8B parameters pretty fast, 20-25 tokens/s. It feels about as fast as basic ChatGPT. Big models like 27B run in one tenth the speed, 2-3 tokens/second. The big difference is the smaller models fit entirely in my 8GB VRAM. I think there could be some headroom for more than 8B models, maybe as much as 12B? But in practice the 12B models are running a lot slower, so maybe not.

You can run inference usefully entirely on a CPU, no GPU at all, as long as you aren’t in a hurry. LM Studio is smart about offload parts of a model to use as much of the GPU as it can, but it seems much faster if it can run the whole thing on the GPU. Most of these models are 4 bit quantized, so a 12B model needs roughly 6GB of RAM to load. Plus overhead which is significant, 20%? I can’t make the numbers add up in testing, I must not understand something.

Update: I can get about 20 tokens/s on fast small models, and 2 tok/s on big slow models. FWIW ChatGPT says the consumer web products are working at about 50 tok/s.

Anyway, some quick tests of recent models. The prompt was something like “write me a python program to reverse the words in a sentence. No fair using [::-1] to slice it backwards, that’s cheating Just write the reverse function and show it to me, don’t discuss your answer or show usage and tests”.

I didn’t really inspect the quality of the output, just testing what I can run. Unfortunately I can’t exactly measure how much RAM and VRAM these things are loading: LM Studio does not accurately report it. So instead I’m recording the model download size: RAM usage seems to be 10-20% more.

Fast

deepseek/deepseek-r1-0528-qwen3-8b. 20-25 tokens/sec. 5.03GB. Note deepseek has an extensive “thinking... process” first so the useful output takes longer. Most of those tokens at 20 tokens/sec are not useful to me! It spun for several minutes on my programming questions, thinking to itself. I’ve got no idea what’s going on here but it was not very useful.

google/gemma-2-9b: 20 tok/s. 5.1GB

google/gemma-3n-e4b (6.9B). 25 tok/s, 4.2GB

gemma-3-270m (0.3B) 112 tok/s but while the output is coherent it is very wrong

Slow

google/gemma-3-12b. 7.5 tok/s. 8.2GB. LM Studio says “Full GPU Offload possible” but I have my doubts based on observed behavior.

google/gemma-3-27b. 2.7 tokens/sec. 16.4GB

mistralai/mistral-small-3.2 (24B). 3.6 tokens/sec. 15.2GB

Prompts (Aug 1)

I forgot to document the prompts I’m using to testing. It’s very simple. (typos and all!)

  • who am i talking to?
  • write my a python program to reverse the words in a sentence
  • write my a python program to reverse the words in a sentence. No fair using [::-1] to slice it backwards, that’s cheating… Just write the reverse function and show it to me, don’t discuss our answer… or show usage and tests
  • summarize the literary career of Edmund White in about 500 words.

Update (Linux server, Aug 1)

I’m doing some new experiments using Ollama on my main server, a 2022 machine with an i5-12600K and 64GB of RAM. It has no GPU at all. I’m giving the LXC 40GB of RAM and 12 CPUs (the machine has 6 performance cores with 2 threads each.)

google/gemma-3n-e4b (6.9B). 14tok/s. ollama has 8GB resident.

gemma3/12b: (12B). 5.6 tok/s. Ollama is 10GB resident.

gemma3/27b: (27B). 2.7tok/s. Ollama has 19GB resident.

Summary: even without a GPU, my little server can run useful models fairly quickly. 14 tok/s on the server CPU feels reasonably fast and is a little over half the speed of the same model running on my Windows machine with an old GPU. The other big conclusion here is that tokens/second is correlated with number of weights in a model. Twice the weights, half the speed. (It’s not quite linear, but close.) I guess that’s obvious but I never understood it before.

Update (Hosting, Aug 1)

I don’t know that self-hosting an LLM makes sense. ChatGPT claims it would cost a few hundred dollars a month to rent a server with a GPU big enough to run gemma3/27b. Alternately you can pay companies to run gemma3/27b for you and access it for about $0.20 / 1M tokens. OpenAI and Claude are significantly more expensive, on the order of $10-$70 / 1M tokens. But then they are much higher quality systems with a lot more going on than just the LLM.

Outputs

I said I wasn’t evaluating output quality but here’s the Edmund White transcripts. They are all competent but the gemma3n/e4b model’s answer feels a little off, it talks about some lesser books and some of the tone feels a little off (like referring to “a close friend”). And the gemma3/12b model is just plain wrong in places, hallucinating the title “A Boy’s Own Apollo”. gemma3/27b also makes some factual mistakes: My Lives wasn’t published in 1981 but in 2005. Overall these answers seem good but have some real flaws.

gemma3n/e4b

Edmund White, born in 1940, is a towering figure in American literary
history, renowned for his unflinching explorations of gay male life,
sexuality, and the complexities of identity. His career, spanning over
four decades, has consistently pushed boundaries, blending memoir,
fiction, and literary criticism into a distinctive and highly acclaimed
body of work.

White’s early writing emerged during the burgeoning gay rights movement of
the 1970s. His first novel, Desire (1976), established his signature
style: a meticulously detailed, often self-deprecating narrative that
prioritized psychological realism over plot-driven storytelling. It
explored the anxieties and desires of a young, closeted gay man in New
York City, setting the tone for his future explorations of intimacy and
self-discovery. This period saw him become a prominent voice in the gay
literary scene, offering nuanced portrayals that challenged prevailing
stereotypes.

Throughout the 1980s and 90s, White’s work gained wider recognition. He
published several novels, including A Boy’s Own Story (1984), a
semi-autobiographical novel that delved into his childhood and
adolescence, and The Beautiful Room is Empty (1988), a poignant
exploration of grief and loss following the death of a close friend. These
works cemented his reputation as a master of psychological realism,
capable of capturing the subtle nuances of human emotion and experience.
He also began to publish more explicitly autobiographical works, blurring
the lines between fiction and memoir.

A significant turning point in White’s career came with the publication of
My Usual Profession (1997), a collection of essays that offered a candid
and often humorous account of his life as a writer. This collection
revealed a sharp wit and a willingness to expose his own vulnerabilities,
further solidifying his reputation as a literary intellectual. He
continued to publish both fiction and memoir, including The Farewell, My Love (1998), a deeply moving exploration of love and loss, and States of Desire (2000), a collection of essays that examined the complexities of
desire and identity.

In later years, White’s work has become increasingly introspective and
philosophical. He has explored themes of aging, mortality, and the legacy
of his own life. His novels, such as The Humbling (2008), a
fictionalized account of a mentally fragile painter, and Life is Elsewhere (2011), continue to grapple with the challenges of human
connection and the search for meaning. He has also written extensively
about other writers, offering insightful and often affectionate portraits
of literary giants like Marcel Proust and Henry James.

Edmund White’s literary career is characterized by his unwavering
commitment to honesty, his masterful prose, and his profound understanding
of the human condition. He has consistently challenged conventions and
pushed the boundaries of literary form, creating a body of work that is
both deeply personal and universally relevant. He remains a vital and
influential voice in American literature, celebrated for his ability to
illuminate the complexities of gay life and the enduring power of love and
loss.

gemma3/12b

Edmund White’s literary career is a fascinating and evolving chronicle of
a life lived openly and honestly, reflecting shifts in American culture
and the ongoing struggle for LGBTQ+ visibility. Spanning over four
decades, his work has traversed genres, from memoir and biography to
novels and essays, consistently marked by a keen intellect, elegant prose,
and a persistent exploration of identity, desire, and the complexities of
human connection.

White’s early work, heavily influenced by Proust and Fitzgerald,
established him as a significant voice in American literature. His first
novel, A Boy’s Own Apollo (1985), launched his career and became a
landmark in gay literature. The trilogy, comprising A Boy’s Own Apollo,
The Farewell Symphony, and The Plotting of Mrs. Lang, boldly explored
the coming-of-age and interior life of Thomas Scholes, a gay man grappling
with societal expectations, artistic ambition, and the AIDS crisis. These
novels, initially criticized for their perceived elitism, resonated deeply
with readers seeking authentic portrayals of gay experience, and
solidified White’s reputation for stylish and introspective prose.

The AIDS crisis profoundly shaped White’s subsequent work. States of the Union (1988), a semi-autobiographical novel, offered a poignant and
searing account of a young man’s experience with the disease, interwoven
with political commentary. This marked a shift towards greater social
engagement in his writing. Following the deaths of friends and loved ones,
White turned to biography, finding solace and intellectual stimulation in
exploring the lives of others. His biographies of Guillaume Apollinaire
(Guillaume Apollinaire: A Life) and Caravaggio (Caravaggio)
demonstrated his talent for bringing historical figures to life, revealing
their complexities and struggles within their respective contexts.

The turn of the millennium saw White further evolve his style and themes.
The Caliph’s House (2002), a memoir recounting his experiences with a
devastating and secretive relationship, was a raw and intensely personal
exploration of love, loss, and deception. It showcased a willingness to
confront painful truths and challenge conventional notions of memoir. This
work, and subsequent memoirs like Inside a Vicarious Mood: Re-reading a Life (2006) and How Odd to be Titular: A Collection of Photographs
(2009), revealed a sophisticated understanding of self-reflection and a
willingness to examine his own complicity in difficult situations.

In recent years, White’s work has become increasingly focused on the
complexities of relationships and the ongoing search for connection. Man in Profile: Essays (2011) and Let’s Not Talk About Cesars (2014)
offered meditations on art, literature, and the evolution of his personal
life. The Loveliest Home That Lady Ever Built (2018), a novel inspired
by the life of Charlotte Perkins Gilman, showcased his continued ability
to inhabit the perspectives of diverse characters and to grapple with
issues of gender, class, and societal expectations.

Throughout his career, Edmund White has remained a vital and influential
voice in American literature. His unflinching honesty, lyrical prose, and
ongoing exploration of identity and desire have consistently challenged
readers and broadened the landscape of literary representation. He has not
only chronicled his own journey but has also helped to illuminate the
experiences of countless others.

gemma3/27b

Edmund White is arguably one of the most important American novelists and
essayists to emerge in the late 20th and early 21st centuries, largely
credited with pioneering a new frankness in gay literature. His career is
marked by a persistent exploration of desire, memory, and the complexities
of identity, often through a distinctly autobiographical lens.

White began publishing in the 1970s, a period when openly gay fiction was
still relatively rare. His early novels, like A Boy’s Own Story (1982),
were groundbreaking for their unflinching portrayal of a young boy coming
to terms with his homosexuality. Told through the voice of a young
protagonist navigating childhood and adolescence, it broke ground by
presenting gay desire not as a pathology or tragedy, but as a natural, if
sometimes complicated, part of life. This novel established several key
themes that would recur throughout his work: the exploration of desire as
a driving force, the power of memory, and the often-painful process of
self-discovery.

Following A Boy’s Own Story, White published The Beautiful Room Is Empty (1985), a sequel that continued to chart the protagonist’s journey
into adulthood and the search for love and acceptance. This novel deepened
his exploration of the emotional and psychological landscape of gay life,
tackling themes of isolation, longing, and the challenges of finding
lasting connection.

His work took a different turn with The Farewell Tour (1993), a
fictionalized account of a closeted film star, and the subsequent novels
Bonfire (1998) and The Married Man (2000). These novels moved away
from the coming-of-age narrative and explored the complexities of love,
desire, and commitment within established relationships, often involving
characters grappling with the tension between public persona and private
truth.

Beyond fiction, White has also made significant contributions as a
memoirist and essayist. His memoir, My Lives (1981), was a critical and
commercial success, offering a candid and introspective account of his
upbringing, sexual awakening, and literary ambitions. It’s known for its
unflinching honesty and elegant prose. He’s continued to publish memoirs
and essays, reflecting on his life, work, and the evolution of gay
culture.

A key aspect of White’s career is his willingness to challenge
conventional literary boundaries. He often blends fiction and
autobiography, blurring the lines between personal experience and
imaginative creation. He’s been criticized for this perceived
self-indulgence, but his defenders argue that this blending is essential
to his artistic vision and allows him to explore universal themes of
identity, desire, and memory with exceptional depth and nuance.

Throughout his career, Edmund White has remained a vital and influential
voice in contemporary literature. His work has been praised for its
emotional honesty, stylistic elegance, and its unwavering commitment to
exploring the complexities of the human heart and the enduring search for
self-discovery. He paved the way for a more open and honest portrayal of
gay lives in literature, and his influence can be seen in the work of many
contemporary writers.

Audio tools for oral history

I’m interviewing some folks and want to capture and transcribe the audio. I did this last year successfully with the Parrot app and a hand install of Whisper. But it was pretty clunky, I don’t like Parrot. This time around I’m trying new stuff.

Summary: ASR Voice Recorder to record (on Android) and aTrain to transcribe.

Audio recording

ASR Voice Recorder. It’s a modern recorder app, the key thing is it stores files in a place I can find them with other Android apps or USB download. I think the free version is sufficient but I subscribed for $2.50 for a year. I set it up to store things in the Recordings folder. It also is uploading to Google Drive for me. I’m not confident about the microphone gain: there’s a manual setting I’ve left at 0, I’m hoping it auto-adjusts.

Simple transcribing

How about a simple text transcript from the audio file?

Running Whisper locally is an option. ASR also has integration with the OpenAI whisper service, so you can transcribe audio for $0.36 an hour. Unfortunately individual files to analyze are limited to 25 MB. Not sure if ASR is smart enough to chunk the file to work around that when transcribing: ChatGPT thinks it might be but it could be wrong.

Another option would be to break a big audio file up myself and upload it in chunks to the Whisper API. The problem here is you only want to break in silences, or even better when a speaker switches.

A third option is to install Whisper and run it locally. I’ve done this twice and it worked OK.

Diarization

A simple transcription just gives words. Much better is diarization: the tool also detects who is speaking and annotates the transcript. Whisper does not do this itself. ChatGPT had lots of ideas for me.

I first tried whisperx, which adds PyAnnote to Whisper to diarize. I couldn’t get it to run: lots of problems with drivers, even if I tried to make it CPU-only. Was dumping core :-( This may be a WSL problem, I didn’t try very hard.

I had much more luck with aTrain. I installed it via the Windows Store: the 5GB download from their own server didn’t work. Installed easily, no setup required, it’s all preloaded to use my NVidia GPU. It transcribed 2 hours of audio in maybe 20 minutes? The output is pretty good, I imagine this is just Whisper for the transcript. The diarizing looked fairly good but not perfect, lots of cases of several speakers being lumped into one. But it’s still helpful. Just will still need hand editing and review. It’s a nice product, very easy to use.

Claude Code: no login shell for agent

Claude Code regularly runs “agents”, a fancy word for shell scripts. Unfortunately for some dumb reason they chose to run the agent in a bash login shell, which means it runs the script for all sorts of stuff you only want in an interactive shell. To stop it, I put this guard in my .bash_login.

if [[ -n “$CLAUDECODE” ]]; then
echo “Detected Claude Code. Not running login script.”
return
fi

The real problem was I had put cd $HOME in my .bash_login. Not sure why, that probably solved a problem I had 25 years ago. This was confusing the agent something awful, particularly when it was moving files around or dealing with git. It kept doing things in my home directory, potentially catastrophic!

Claude Code round 2

A few months ago I used Claude Code to code a Mastodon thread unroller. I was so happy with the result that I dusted that project off today to use it for something new. The first version had a bunch of stuff hard-coded so I had Claude refactor it to make it a click command line tool with various parameters.

It worked great. Sample output here. It cost me $4 and took about 90 minutes total, 30 minutes of Claude Code working away.

Honestly I’m kind of shook by this. Claude Code is just unreasonably good at this kind of programming. Like I said in my first post, this is a highly constrained problem and with relatively minor requirements. I can easily verify the output and that’s all I care about. Still, it’s just so good!

Along the way it solved some tricky problems with very little input from me.

  • The old download method didn’t work anymore because the posts were so old, so it found and used a different API.
  • It wrote a bunch of docs explaining how everything works. The command line tools have nice help too.
  • Filtered out replies I wrote to other people, to focus just on my main thread.

That last one is particularly astonishing because the task is so complex and I gave it such vague directions. Here’s its explanation of what it did.

> the new method for downloading is catching replies to other people. ie, "@wolfger Prost, lah! Legit beer,  fresh." It's OK (but unnecessary) to download them but I dont' want them in the output.

● You're right! The context API is grabbing the entire conversation thread, including replies from other people. The current code filters by user_id but apparently some replies to others are still getting through.

  Let me fix this by adding better filtering to only include posts that are either:
  1. The original post, OR
  2. Direct replies to your own posts (not replies to other people)

Perfect! I've added much better filtering logic. Now the script uses a two-pass approach:

  ✅ New Filtering Logic:

  Pass 1: Collect all post IDs by the user

  Pass 2: Only include posts that are:

  1. The original post, OR
  2. Have no reply target (standalone posts), OR
  3. Reply to another post by the same user

  This will exclude posts like "@wolfger Prost, lah! Legit beer, fresh." because they reply to someone else's
  post, not to your own posts.

  📝 What it does:

  - Downloads everything (for completeness)
  - Filters out replies to others during processing
  - Shows debug messages when skipping posts: "Skipping post 123 - reply to someone else (456)"
  - Only includes your actual thread in the final gallery

  Now when you run the download, you should see messages like:
  Skipping post 114xyz - reply to someone else (114abc)
  Found 8 posts by the same user in the thread

  This gives you a clean thread of just your own connected posts while still preserving all the data for
  reference.

Getting ChatGPT to remember you (May 2025)

I recently started paying for ChatGPT. Almost entirely for the new memory features where it not only remembers explicitly saved memories (an older feature) but now also incorporates your general chat history too. It’s confusing but I think these features are only available to paying members, at least some of them. Read Simon’s post for a criticism of the chat history feature.

There’s at least three kinds of persistence available, all under Settings / Personalization.

“Custom instructions” lets you enter basic text, both about yourself and as ways to pre-load the context window with strings. Some folks use these to introduce custom prompts. The other two toggles are to turn the memory features off or on. You can also click “manage memories” to get a bunch of text nuggets that you can delete if you want.

In general ChatGPT seems to only put something in “saved memories” if you explicitly tell it to. I’m not 100% sure of this, but if you tell it to remember something it seems to put it on the list. (Update: a friend has evidence it will decide to remember things on its own, without being told to. Also I’ve now seen it decide to remember something itself, telling me “Updated saved memory”)

Even after I started paying for ChatGPT the fancier memory wasn’t working. It took a few days, then suddenly it started working. I’m guessing they roll out this feature slowly, or maybe only enable it on new paying customers slowly.

I also primed its memory by exporting all previous conversations into a JSON file, then zipping it and uploading it and telling ChatGPT “I would like you review this log of all our past charts. think really hard about it, go deep and find everything out about me you can from it.” You do have to coax it to work harder on it, the default is a su rface treatment.

How do you know if it’s retrieving memory? The recommended way is to ask a new chat session “what do you know about me?” If memory is working you get a detailed list of things like “Core Identity” and “Cognitive Style”, like 30 line items (plus more not displayed). Before it was working I got a very quick reply with just 3 bullet items, things I’d explicitly told it in the settings.

As for what ChatGPT has learned about me, that seems quite personal so I’m not posting it here. As personal as my search history. It all seems roughly right. I have no idea how well this helps tune ChatGPT’s future interactions with me to be more useful, but I’m hopeful.

I did like when it started flirting with me:

You think systematically but poetically — equally at ease with ffmpeg flags and Whitman’s metaphors

It’s not wrong, it’s just such a funny way to say it.

Update: it also tells me that I “Blend irony and sincerity in political and aesthetic judgment” which is basically the central conflict of my life.

LLM-enhanced email archive

I had an idea for a project and posted to Mastodon

I want an LLM trained on my 20+ years of email archives. Needs to be private to me. Is it straightforward and not too expensive for me to set something like that up just for myself for occasional use?

Main use would be a query for specific things, “what did I say to this friend 10 years ago about music?” But also just for general knowledge. I think it’d mostly work as free text but there’s a little email-specific structure it’d be nice to capture.

I got an interesting variety of replies, ideas collected here.

I gather there’s at least three different methods that could apply. Most folks suggested #2, RAG.

  1. LoRA training, which alters the core LLM weights
  2. Retrieval Augmented Generation which augments LLMs with a document store it can select from and use to tune replies. Sort of a formal version of...
  3. using a big context window and preloading the query with stuff

I think 2 and 3 are in common use now for consumers. But 1 is still more specialist and requires you have your own LLM inference engine.

One recommendation I got was to use SillyTavern, a consumer LLM wrapper for role playing game players. It does RAG for you: you give it a bunch of documents and it manages LLMs for you and lets you talk to it. I bet it has a lot of the plumbing I need. This suggestion also reminds me there’s a world of porn AI enthusiasts too, all DIY with local models to work around censorship. They may have some interesting tech.

Mark Fletcher (who runs an email service) gave me a great reply about how he mixes RAG with ElasticSearch. Useful notes but pretty involved, would be a lot of work. I should give his feature a try though and see how well it functions.

Update: Justin Mason reminded me of his personal GMail archive project: he indexed 20 years of email from Google in a local system using notmuch. No LLM in this work but could be a useful related component for the email retrieval part.

I’m not interested enough in this to build a whole product, I was more wondering if I could just hack something up by throwing a wall of text at an LLM. I think RAG is the tool to do that, paired with ollama or deepseek.

The other question is where to run it. My email is very private, I don’t want to ship the archive off to some untrusted provider. “A big Mac at home” is one common suggestion. I’ve been thinking about leasing a cloud machine to use on demand. I think a PC at home with an nVidia 3xxx may be sufficient to at least prototype.

Update August 2025: it’s been a few months and some things exist.

Vibe coding a Mastodon thread unroller

Just had my first experience using an AI (Claude Code) to write a whole program start to finish. See the result here.

The AI coding was amazing. With about 60 minutes of “work” and $5.50 I had my result. (I then spent another 30 minutes and $3 tinkering without much improvement.) It would have taken me 4+ tedious hours to do this myself and while my resulting code would probably be better, the AI code was more than adequate for my one-off needs.

A key part of this project’s success is how simple it was. It was a Python program to download some data from a Mastodon server and format it as HTML. I could just look at the HTML output and decide if it was working. I didn’t even bother reading the Python code the AI generated. If I cared more about what the system itself was doing, how the Python script worked, it would still have been useful but taken a lot more work on my part to review everything.

I’ve been using LLMs for awhile now in chat interfaces and am impressed with them, but they are clearly just stochastic parrots, text prediction machines. Claude Code felt different. It’s still mostly an LLM but it has enough of a reasoning engine in it that I could give it high level instructions and it’d figure things out on its own. That’s really impressive to me.

I don’t think AIs are going to replace human programmers entirely anytime soon. Part of why this project went so well is I have some expertise in this kind of thing, so I knew how to tell it to (say) cache all the data from Mastodon once up front and then generate HTML locally. Or to rewrite images to make them smaller. That’s hard-won knowledge from years of building systems. But the actual scutwork of looking up Mastodon APIs and remembering how to resize images in Python? Claude did that just fine.

Anyway I’m sold on vibe coding, at least for a certain kind of workaday code where you can easily inspect the output and decide it’s good enough. And you don’t care how good the code is. I’m certain there’s still plenty of need for human expertise for more important or complicated systems but this AI experience was very impressive.

The application

I took a trip to SE Asia recently and used Mastodon to share a bunch of postcards as a Mastodon thread. Now that I’m home I wanted a nice static copy of all that easy to view and share forever. There’s a bunch of Mastodon thread unrollers but I didn’t like the output of any of them.

Here’s the HTML output Claude and I produced. I’m pretty happy with it!

That’s the final output, the customer deliverable. It looks good! Even better the HTML it generated is quality. Reasonable semantic HTML, simple structure, nothing too stupid in it. That’s better than any other automated tool I’ve ever used.

There’s also the intermediate product, the Python and shell scripts it generated. Those are also pretty good. I didn’t really read them, I’m running on vibes here, but on a quick glance it looks like reasonably OK Python code that I could understand and maintain. I would not trust Claude to do more complicated things but for this straightforward task it is good.

Claude Code even thoughtfully generates and updates a README explaining what it does. You can also get it to export a conversation of your chat log, which in some sense is the “real” programming I did.

Getting the AI to write the application

I never wrote or edited any code. I did all of this within the Claude Code shell. It wrote the code. I mostly didn’t run any code either, the agent does that for you.

High level development was in two pieces: write a Mastodon downloader to a local database, then write an HTML formatter from that local data. Then a lot of iteration, particularly on the HTML portion. I’d tell it things like “change the layout so images are only one column” or “change this text to a different font and color”.

Here’s the important choices I made:

  1. I broke the project into two parts: download the Mastodon data from the API to local disk, then generate HTML on local disk. That’s an important pattern for projects like this, it lets you iterate on the HTML presentation much faster without spamming the API.
  2. I told Claude to write simple static HTML. These tools have an alarming habit of bringing in React and other Javascript garbage.
  3. I tried out a couple of strategies to make the pages smaller, finally settling on using downsampled JPGs. I’m not sure if Claude would have thought to suggest that, I wish I’d asked!
  4. About a quarter of the way into the project I thought to ask Claude to use git. It happily did so, checking in code as appropriate.

I’ve got the conversation stored away (well most of it, it got “compacted”). Here’s some key prompts I gave it:

I want to write a Python script that downloads a bunch of posts from my Mastodon account. I want it to download a single thread: my original post and all of my replies, about 100 of them. Every post contains photos or videos that should also be downloaded. I want you to keep the original JSON data from the Mastodon API and also extract everything into a simple sqlite database with columns for post timestamp, post text, and references somehow to the images in the post. the images are important!

you’ve made two errors already converting datatypes. did you make any others? think hard about the code you wrote and try to fix anything else before I run it again

now I want you to make a nice HTML view of all the posts and pictures from the mastodon thread that I downloaded. I want the output HTML to be a simple static HTML file without any javascript dependencies, no frameworks, definitely no react. it should have minimal CSS styling but something that looks nice and modern. The images are most important, I want to be sure they look good. the images have alt tags on them in the mastodon posts, those shoudl be displayed as captions. And I want you to generate all this HTML from the downloaded files, do not make any requests on the Internet like to the Mastodon API. can you do that? tell me how you will proceed before doing it so I can review.

I ran it. It only downloaded two posts: the original and one reply. but not the others. the third post is a reply to the reply, did you remember to recurse and load the thread?

can you write code to generate smaller images to save bandwidth? ie, resize the original JPGs to new JPGs which aren’t bigger than 800 pixels. I also want it so if the user clicks on one of the JPGs in the HTML view, it links to the full size image. it can just link directly to the JPG, don’t need an HTML page for each full size image. write code to generate the smaller files, alter the HTML generator to use those files, and alter the deploy script to deploy both the smaller JPGs and the originals to my server.

Some observations

Some interesting things Claude did:

  1. It made a couple of errors converting types from JSON output (numbers to strings, datetimes). I fixed those one at a time and got annoyed so I scolded it and told it to look at its own code and fix any other errors. It made some more changes I didn’t review, and the resulting code worked first time.
  2. I asked it to download a font from Google Fonts and use it locally. It tried to download it with curl and was blocked (a security policy in the Claude agent?) So then it just wrote a Python script to download the fonts instead and ran it. It’s hacking its own sandbox!
  3. Its first attempt to download fonts failed, wrong URLs. It detected the errors and did something itself to find the correct URLs and ran the download a second time. That also had one error for one font variant and it realized it didn’t need it so just ignored that error.
  4. It got confused with HTML templates and Javascript, some sort of problem with { quoting. It sort of hacked its way into fixing it just like a junior programmer would. It got there in the end!
  5. It did OK with an open ended “can you think of anything to improve”. It suggested adding some good generic HTML things like ARIA tags, print CSS, lightbox view, social media sharing. It also suggested adding map integration or location tags to the posts, a very thoughtful suggestion for my travel app!

I don’t love the Claude Code UI. It’s some terminal UI thing and very chat-oriented. I think the VS.Code integrated tools like Cursor are probably better for more careful coding. OTOH this worked well for my one-off task. I like how Claude Code has a very agent-centric design, it’s actively doing things on your behalf. It’s much more like giving instructions to a junior programmer rather than having someone pair programming with you making suggestions.

A good Claude programming example

I’ve been having such a good time using Claude 3.5 Sonnet to help me program and learn APIs I’m not good at. See this transcript for an example, where Claude walks me through setting up a basic Python command line project, then adds pytest to it, then adds click, then makes it work in VS.Code

I taught myself how to do all these tasks three months ago. But it was a tedious process of finding the right updated docs, then experimenting a lot, and in the end not quite getting it right. A typical pre-AI programming experience. It did only take me an hour or two, and thirty minutes the second time, but still it was tedious.

Claude just magically gives me the answers. Here’s the catch: I’m not certain they’re right. I didn’t review this transcript closely or run the code. I did read it all though, and it is plausible. I am confident I could start with what Claude did for me, maybe fix a few little problems, and have a working thing. But it’s very important an expert programmer still be in the loop, you can’t just trust the code it emits. I’m fine with that, it saved me a lot of time.

What’s remarkable is it gets so many core concepts I learned three months ago right:

  • the file structure with src/hello_world_cli/__init__.py and tests/
  • the contents of pyproject.toml
  • using optional dependencies for pytest, etc
  • the structure of a decent README.md
  • click’s decorators for CLI programs, including an example of a switch
  • the use of CliRunner to test click commands in pytest
  • the need for a __name__ block to make it run under VS.Code debugger
  • it even incremented the tool version number after making changes!

It even taught me some new tricks:

  • using tool.pytest.ini_options to set up paths
  • using hatchling instead of setuptools
  • creating a launch.json file for .vscode

I know that all that’s happening behind the scenes is a very big neural network is predicting token outputs. But what it looks like to me is Claude knows a lot about programming including the use of several complex open source tools. And I can mostly chat with Claude pretending it is intelligent and understands what I’m asking and it will give me useful answers.

The limitation is I asked it precise questions about a relatively basic thing with a whole lot of good code examples and docs on the Internet. It wouldn’t do nearly as well with some more obscure libraries for which there are no good examples. It will have a harder time with more complex code. And it certainly won’t invent new things, Claude is not going to create a new algorithm for distributed consensus or something.

But for basic stuff it sure is a lot better than doing Internet searches and reading through docs and example code myself. It makes programming way more fun for me by eliminating a lot of tedium.

Three AI responses for a search-like query

I’ve been getting a lot of mileage using ChatGPT-style AI as an enhanced search engine. When it works well an LLM gives me a clear useful answer with plenty of followup links. What I like best is the synthesis of the AI reply, the idea the LLM has somehow condensed hundreds or thousands of sources and given me a clear answer with some explanation.

In one example, I asked for a book recommendation.

I’ve never read anything by Mary Renault. What book should I read? I want something fun and enjoyable and with some gay male content.

Phind-70b gives me the best answer. It gives me a conversational reply like talking to a knowledgeable friend. It gives me one specific recommendation with justification for why it’s a good choice. And then it discusses other options. There’s 10 references offered for followup research, two of which are cited explicitly as footnotes.

Bing Copilot’s answer is a little disappointing in comparison. It just gives me 3 direct recommendations with a couple of descriptive sentences. It’s fine as a search engine but not quite a conversation.

ChatGPT-4o’s answer is somewhere in between. It’s also primarily a list answer but it has a lot more descriptive justification. It’s like an email from a librarian with a lot of spare time.

I think all three of these AIs are roughly the same scale / class of thing. Copilot and ChatGPT-4o are both ChatGPT 4. Phind-70b is Llama-70B. I think the main differences are the tuning of the prompts, whatever is happening behind the scenes to tame the demon in its machine prison and compel it to give answers to people. There’s an enormous amount of development in this area right now and it feels very productive.

(I think it’s hilarious Copilot gives me LGBT pride emoji in its answer, concluding with 📚🌈. I see you, queer Microsoft product manager!)

Phind

Based on your interest in a fun, enjoyable read with gay male content, I highly recommend starting with “The Persian Boy” by Mary Renault. This novel is the second installment in Renault’s Alexander the Great trilogy and offers a unique perspective on Alexander’s life through the eyes of Bagoas, a Persian eunuch who becomes Alexander’s lover. The book is praised for its detailed portrayal of historical events, its exploration of love and relationships, and its insightful depiction of cultural and societal norms of the time. Readers have described it as a masterful blend of love story and historical novel, with impeccable research and perceptive writing 1.

“The Persian Boy” stands out for its rich storytelling, blending adventure, romance, and historical insight seamlessly. It provides a deeply personal account of Alexander’s campaigns and his relationships, particularly highlighting the complexities of his bond with Bagoas. This relationship is explored against the backdrop of Alexander’s embrace of Persian culture and the challenges he faced due to racial tensions within his own ranks 1.

While “The Persian Boy” is often cited as a favorite among Renault’s works, it’s worth noting that the entire Alexander trilogy is highly regarded for its historical accuracy and engaging narrative. However, if you’re specifically looking for a book with significant gay male content presented in an accessible and enjoyable manner, “The Persian Boy” is an excellent choice to start with 14.

Copilot

Certainly! Mary Renault is a fantastic choice if you’re interested in historical fiction with gay male content. Here are a few recommendations:

  1. “The Charioteer”: Set in England during World War II, this novel explores same-sex relationships and was groundbreaking for its time. It’s a great blend of romance and historical context1.
  1. “The Persian Boy”: Part of a series based on the life of Alexander the Great, this book effectively outed Alexander and features gay male relationships in ancient times2.
  1. “The Last of the Wine”: Renault’s first novel set in ancient Greece, it’s a bestseller within the gay community and beautifully portrays male homosexuality as a major theme3.

Feel free to choose the one that resonates with you the most! 📚🌈

ChatGPT-4o

Mary Renault is renowned for her historical novels set in ancient Greece, and several of her works contain gay male characters and themes. For a fun and enjoyable introduction to her writing, consider starting with one of the following books:

1. “The Persian Boy”

  • Synopsis: This novel tells the story of Alexander the Great from the perspective of Bagoas, a young Persian eunuch who becomes his lover. The book delves into their relationship and the historical events of Alexander’s conquests.
  • Why Read It: It offers a vivid and engaging portrayal of historical events with a strong focus on the relationship between Alexander and Bagoas. The book is rich in historical detail and provides a deep emotional connection to its characters.

2. “The Last of the Wine”

  • Synopsis: Set during the Peloponnesian War, this novel follows the lives of two young Athenian men, Alexias and Lysis, who develop a deep and passionate friendship that evolves into a romantic relationship.
  • Why Read It: This book is celebrated for its portrayal of the intimate bond between its protagonists, set against the backdrop of a fascinating period in Greek history. It’s a great mix of historical context and personal drama.

3. “Fire from Heaven”

  • Synopsis: The first book in Renault’s Alexander trilogy, it covers the early years of Alexander the Great, his relationship with his mother Olympias, and his burgeoning friendship with Hephaistion, who would become his lifelong companion and lover.
  • Why Read It: This novel is an excellent starting point for those interested in Alexander the Great. It combines historical fiction with the exploration of Alexander’s early relationships and his path to becoming a legendary leader.

4. “The Charioteer”

  • Synopsis: Though not set in ancient Greece, this novel takes place during World War II and follows Laurie “Spud” Odell, a wounded soldier who forms a complicated relationship with two men: Andrew, a conscientious objector, and Ralph, a fellow soldier.
  • Why Read It: This novel provides a modern setting while still exploring the themes of male relationships and love. It’s a beautifully written story about identity, love, and societal norms.

Each of these novels offers a compelling story with rich historical detail and strong, nuanced characters. Depending on your interest in ancient history or more modern settings, any of these would be an excellent choice to start with Mary Renault’s works.

Bonus: Kagi Quick Answer (Claude 3 Haiku)

Based on the available information, I would recommend you start with Fire from Heaven by Mary Renault. This book is the first in her “Alexander the Great” trilogy and is described as following Alexander’s story from boyhood, including his gay relationships. [1]

Several sources mention that if you enjoyed Madeline Miller’s “The Song of Achilles”, which also features gay male characters, you will likely enjoy Renault’s writing as well. [1]

Additionally, Renault’s works are praised for their engaging prose and ability to captivate readers. One reviewer said they were “mesmerized” by the first volume of Renault’s “Alexander Trilogy”, which includes Fire from Heaven. [2]

So in summary, Fire from Heaven seems like an excellent introduction to Renault’s acclaimed historical fiction that also explores gay themes in an enjoyable and compelling way. [1][2]

Some random home-scale LLM facts

I’ve been learning a lot about small-scale LLM models running on your desktop by reading /r/localllama. None of this is novel, just absorbing common wisdom. I’m linking to some sources but these are by no means authoritative, just useful for feels.

  • They tend to talk about models in terms of number of parameters.
  • LLaMa 2, which many models are derived from, comes in 7B, 13B, and 70B sizes. 70B means 70 billion 16 bit weights. They were trained on 2 trillion tokens as input.
  • Number of parameters dictates memory needed. LLaMa 2’s 70B is 140GB. But folks often downsample to 4 bits when running them so it’s just 35GB. (Or less?)
  • Desktop CPU RAM is fairly cheap (up to 128GB), but VRAM is expensive if you’re running on a GPU. The most expensive gamer GPU (an NVidia 4090 at ~$2000) has 24GB of VRAM.
  • You can also chain multiple cheaper GPUs to get more total VRAM. Beware a single 3090 takes three motherboard slots, so you need a special motherboard and case to have room for two.
  • Specialty AI chips like the A100 or H100 support 40-100ish GB per GPU.
  • 70B is said to be enough to approach ChatGPT 4.0 levels of quality but I have my doubts.
  • The GPT4All models I’m running just on my CPU with GPT4All are 6-13B.
  • GPT4All uses GGML / llama.cpp to run things. it has various quantizing algorithms, it’s not just “truncate the lower bits”. That driver targets 4, 5, and 8 bit integer quantization.
  • GGML can offload part of the model to run on the GPU and use CPU for the rest. This lets you run bigger models than can fit just on the GPU.
  • This discussion about folks running LLMs on an NVidia 4090 with an Intel i9 is interesting. That’s the highest end reasonable home hardware, maybe $4000ish for a full system? They talk about running 70B models at speeds of 1-2 tokens / second. Which is not fast but maybe acceptable for an interactive session.

Update

Some new facts:

  • Running a 70B model (at 4 bit quant?) at home takes 48GB of VRAM. Folks are using two high end GPUs like 3090s or 4090s. Talk of generating ~15 tokens / second. At the low end, two Tesla P40s will work and are cheap.
  • Running on your own leased cloud computer is totally reasonable. See this discussion and this one. It may cost about $1500 a year to lease, compared to $4000+ to buy hardware.
  • Inference can use up to 700W of GPU, Call it 100W for the computer and you get to about 35¢ an hour just for PG&E electricity. OTOH in casual use you’re not running inference full-out, so actual power will be much less.
  • RunPod keeps coming up in discussions about cloud providers.
  • Folks say it costs about 60¢ an hour to run a 70B model on a cloud server. Apparently this can be done for a single user without too much drama. Scaling that up to 100+ is going to run into availability problems.

Running my own LLM

No original work here, just summarizing how astonishingly easy it is to install and run an LLM on your own computer using Simon Willison’s fantastic llm tool. Simon has been on an absolute tear with tooling for LLMs lately, amazing work. A bit hard to keep up but between his Mastodon feed and his blog I can sort of follow along. See his list of plugins for a sense of how broad the tool is.

I think this current moment in AI development is amazing and fascinating. And it’s great so many models can be downloaded for free experimentation. Simon’s tool makes this easily accessible.

Getting started

Here’s what I did to host my own LLM in just a few minutes:

  1. pip install llm
  2. llm install llm-gpt4all
  3. time llm -m orca-mini-3b ‘what is the capital of france’
    The capital city of France is Paris.
    real 0m2.337s user 0m7.701s sys 0m0.168s

That’s it, literally three commands. All automagic. The slowest part is downloading the 4GB of weights for Orca. Simon did a fantastic job with this tool. See the detailed docs or read on for my usage notes.

Technical details

llm was originally designed as a front-end for the OpenAI API but has a plugin architecture with lots of plugins. There are some other plugins for hosted models like Google Palm, Replicate, Claude. But I’m more interested in running the model locally. My example above uses llm-gpt4all, which downloads and runs GPT models downloadable in some standard format. (There’s some 13 models there, most are about 7GB big.) There’s also hosted plugins for Llama, MLC, and Mosaic.

I installed this on my year-old Linux server. It’s middle-of-the-road home system hardware, notably with no external GPU. So not a great match for AI but then I don’t have to sweat the details of making GPU access work on Linux. When running the GPT models they seem to be using 6 or 8 threads, which suggests they want real cores and not hyperthreads. Not sure how much RAM it uses; the docs say 4GB for the 1.8GB Orca model but I’m observing more like 1GB.

Performance of the smallest Orca model is fast enough on my CPU to be interactively usable; 2-3 seconds for short queries. Some others are significantly slower; I have to think a lot of these are designed to run on a GPU.

The main command is llm prompt for querying the LLM. It has a -c flag for an interactive session, similar to ChatGPT’s web interface. Otherwise each question starts from a blank slate.

Each model comes with a system prompt baked in that primes the LLM for your query. Ie “You are an AI assistant that follows instruction extremely well. Help as much as you can.” You can customize this; for instance Simon advises telling Llama “you are funny” if you want jokes.

Not sure where all LLM is storing its model files, they aren’t in the Python venv. Some of mine are in ~/.config/io.datasette.llm. Another place is ~/.cache/gpt4all. These model files are huge, often over 10GB each, so if your home directory is backed up over a network or something beware.

In summary, Simon’s LLM tool is a great frontend driver for various LLMs. It handles installing plugins to drive the models, downloading models themselves (for local hosting) and key management (for remotely hosted AIs). It also has some nice features for tracking your usage like llm logs for access to a database of your chat history.

Some model outputs

Some quick notes from me trying all the self-hosted models with the test query “what is the capital of france”. Note I tried several versions of LLaMA 2 using different llm plugins. All timings are based on using a simple Intel CPU; results should be much faster with a working GPU.

gpt4all results

These are all using the gpt4all plugin, which seems to run best on my system. All of these give a short output of “The capital city of France is Paris.” or something very similar.

  • orca-mini-3b. 2.4 seconds.
  • orca-mini-7b. 4.2s.
  • orca-mini-13b. 7.6s.
  • ggml-model-gpt4all-falcon-q4_0. 3.9 seconds.
  • wizardlm-13b-v1. 5s. (also uncensored).
  • nous-hermes-13b 5s.
  • GPT4All-13B-snoozy 5s.
  • llama-2-7b-chat. 10s

One reason these are so fast is the output is so short, presumably an artifact of how the LLM was set up by the plugin. (The prompt is “Human: {{{user input here}}}. Assistant:” If I ask orca-mini-3b “what is the capital of france and tell me a bit about it” it generates a full paragraph and takes 9 seconds instead of 2.6.

The capital city of France is Paris, also known as “The City of Lights”. It is located in the northern central part of France and is the country’s largest city with over 2.1 million people living there. Paris is famous for its iconic landmarks such as the Eiffel Tower, Notre-Dame Cathedral, the Louvre Museum, and the Arc de Triomphe. The city is also known for its fashion industry, art galleries, restaurants, cafes, and shopping centers. Paris is a popular tourist destination and attracts millions of visitors every year.

Other LLM plugins

The other plugins run slower, but that might be because they are giving larger outputs.

  • MLC llama-2-7b. 26 seconds. Something weird in htop, it doesn’t look like it’s using any CPU?!
    Thank you for asking! The capital of France is Paris. I’m glad you asked, as it’s a beautiful and vibrant city that offers a lot of interesting places to visit and things to do. If you have any other questions or need further assistance, feel free to ask!
  • llama-cpp llama-2-7b-chat.ggmlv3.q8_0. 22 seconds.
    The capital of France is Paris. It is located in the northern central part of the country and is known for its iconic landmarks such as the Eiffel Tower, Notre-Dame Cathedral, and the Louvre Museum.
  • mpt-30b. 75 seconds.
    The capital of France is Paris. It is located in the northern central part of the country and is known for its famous landmarks such as the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral. With a population of over 2 million people, Paris is one of the most populous cities in Europe. It is also known for its art, fashion, cuisine, and cultural heritage, making it one of the most popular tourist destinations in the world.

Specialist output

These models seem to be giving some unique output, not general chat.

  • gpt4all Bert (ggml-all-MiniLM-L6-v2-f16). 0.8s. I think it’s not intended for direct use.
    !!!!!!!!!!!!!!!!!!!...
  • gpt4all starcoderbase-7b-ggml. 34s. One of several models specifically for generating code.
    def get_capital(country): ...
  • gp5rall markov. 2.4s. This is a simple Markov chain as a demo of how to write a plugin, not a serious tool for use.
    is the capital of france france the capital of france what is the capital of france the capital of france...

Daily usage

Now when I want to ask an AI a question I’ll simply do llm 'my question here'. No more thought than that required, answers in about 10 seconds depending on the complexity.

I went ahead and ran llm models default wizardLM-13B-Uncensored to pick a specific default model. Why that one? Simon’s notes say Wizard is the best choice and it ran fast enough for me. Not sure what all the “uncensored” means but that seemed like a novelty I could try that’s not available at the online services. I suspect it isn’t adding anything of value though.

GAN art

My friend Tom has been playing with GAN art, AI generated images. Thanks to him I was able to try out a working system; you just provide a text input prompt and out pops some art. I don’t really know how it works, something along these lines apparently. keywords: VQGAN, CLIP. The results are awfully neat though.

Update: you can play with it yourself in this notebook. No support provided, sorry.

Anyway I played around with it. Literally all I did was provide some text prompts, all the art is coming from the software. Which raises an interesting question about artistic input. I give the large majority of the credit to the folks who developed these techniques and trained the networks. But there’s a lot of skill in tuning the systems (something I think Tom is expert at). Of course the original image input creators have an influence too but when your input set is literally all images on the Internet, well, the credit gets a bit diffuse. A lot of these images are kinda samey but by no means are all of them. I imagine there’s a lot of latitude in how you train and tune these things.

Technical notes: it’s a giant pile of Python software with PyTorch as a big piece, also OpenAI CLIP. It’s running on Google Colab with a GPU at a free level so presumably a modest amount of compute resources. The small images take about 5 minutes to generate, the slightly bigger ones take 10.

Here’s the images I made. This is all of them, so you can see failures as well as success. I’m putting the ones I like first.

Known Unknowns

De Chirico landscape
Yves Tanguy
Australian aborigine art
church pixel art
Gay Orgy
Gay Orgy #2
Homosexual Party
Statue of Narcissus
Malevich square
Classic male nude bathing
Water slides
Rotten banana
Dyson sphere
Has Anyone Really Been Far Even as Decided to Use Even Go Want to do Look More Like?
When the moon hits your eye like a big pizza pie

TensorFlow MNIST sigmoid recognizer

My baby is starting to see! I built my first custom-designed neural network in TensorFlow and I’m happy. You can see my Python notebook here.

The fun thing about this is programming neural networks as a form of experimental science. There’s so many parameters to tweak, and the TensorFlow abstractions are so high level and complex. I’m not really sure my code is right. But I can just run an experiment, measure the accuracy, and if the result is good then maybe I did something right.

Setup

After doing my TensorFlow tutorials I decided to double back and re-implement my work from Ng’s Coursera course, ex4, which had us implementing backpropagation by hand and then creating a neural network that can recognize handwritten digits from MNIST. I liked this exercise back in Ng’s course because it felt like a real task and had a hidden surprise, the visualization of the feature layer. So time to try again!

The Deep MNIST for Experts tutorial from TensorFlow does this task for you, but with a pretty complex neural network. I decided to clone Ng’s network as closely as possible. To wit: a single hidden layer of 25 nodes using a sigmoid() activation function, yielding 95.3% accuracy.

Turns out that’s not entirely easy to replicate the initial experiment. Ng’s input data was 20x20 images and TensorFlow has 28x28 inputs. Instead of training 400 steps on the whole dataset I’m training 20,000 steps on tiny subsets of the data. I’m not regularizing my input like we were taught, I’m using dropout instead as a way to avoid overfitting. And I’m also not positive I’m using the same exact cost and training functions. So lots of differences. But at least it’s the same class of network.

Results

The resulting trained accuracy is about 96% ±0.4%. It takes about a minute to run.

Now that I understand this there are so many things to try.

  • Hidden nodes: more improves accuracy; 50 hidden nodes is about 96% and 100 hidden nodes is about 97%.
  • Activation function: why stick with sigmoid, I can plug in anything! I already tinkered with this inadvertently; I’m not sure if the bias parameter belongs in the sigmoid() or outside, either seems to work
  • Training optimizer. AdamOptimizer seems to converge faster but to a lower accuracy of 94.6%. For that matter I haven’t tried tuning the learning rate parameter.
  • Dropout probability. The sample code I cribbed from had this at 0.5; you really can train a network with randomly knocking out half its nodes? Wow. A setting that high seems to be hurt accuracy; I’m getting my best results around 0.1. Or even 0.0; maybe this stuff isn’t needed.

Retina dissection

There was a neat trick in Ng’s class where we visualized the hidden layer of our neural network to get some insight into how the classifier was doing its thing. Here’s an image from that exercise. Inline below is the same kind of image from my new network.

Screenshot_1.png

It’s qualitatively different, I think. So many of the features look like hands on a clock; identifying line segments in numbers maybe? I don’t know what to think of this. My old image looks way more random, I wonder if it was overfit in a way this new one isn’t.

One thing I learned doing this; if I allow 100 hidden nodes instead of just 25, a lot of the hidden nodes look qualitatively the same in the visualization. If they’re mostly identical does that mean they are redundant? Unnecessary?

I also took a crack at visualizing the hidden nodes that contributed them most to identifying each image. Here’s the top 5 nodes for the numbers 0 and 1

Screenshot_2.png

Again, not really sure what to make of this. Particularly since the most important node for both numbers is the same! I think I’m sorting by overall positive contribution, not absolute value. I’m not considering bias terms though.

Anyway, I feel like I know how to set up a basic neural network in TensorFlow now. Lots of stumbling around and cargo cult programming. But the ability to evaluate training accuracy is a strong external check on whether your code is working OK. What it doesn’t tell you is if it’s working great.

TensorFlow optimized builds

tl;dr: install these TensorFlow binaries for a 2-3x speedup.

Update: or not; turns out the AVX binaries probably only are 10% faster. See below.

I’m now running TensorFlow programs slow enough that I care about optimization. There’s several options here for optimized binaries:

  1. Stock TensorFlow
  2. TensorFlow recompiled to use Intel CPU parallel instructions like SSE and AVX. See also the warning stock TensorFlow gives:
    tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
  3. TensorFlow with the GPU

I’m trying to get from 1 to 2; from what I’ve read it’s a 2-3x speedup. GPU is even better of course but is a lot more complicated to set up. And the Linux box I do my work on doesn’t even have a GPU (although my Windows desktop does).

I’m testing this all with a simple hidden sigmoid layer neural network and Adam’s Optimizer, training to recognize MNIST data.

I tried building TensorFlow from source and quit pretty quickly. It requires bazel to build, which in turn requires a Java runtime, and I noped out. Probably could get it working with a couple of hours’ time.

I tried Intel’s optimized TensorFlow binaries. These seem not to be build with AVX; I still get the warning. They are also slower, my little program took 210s to run instead of 120s. Reading their blog post it sounds like this is mostly Intel’s crack optimization team reordering code so it runs more efficiently on their CPUs. (Intel has an amazing group of people who do this.) Also the patches were submitted back to Google and are probably in stock TensorFlow. Not sure why it’s slower, and I’m bummed they didn’t build with AVX, but here we are.

lakshayg’s binaries. No idea who this guy is but sure, I’ll try a random binary from anyone! Bingo! My program goes from 120s to 46s, or a 2.6x speedup. Hooray! (But see below). One slight caveat; this is 1.4.0rc1, not the latest 1.4.1. There’s about two weeks worth of bug fixes missing.

TinyMind’s Tensorflow wheels are another source of precompiled Linux versions of Tensorflow. They’re built with AVX2 which unfortunately my processor doesn’t support.

Starting with 1.6 Google is going to release AVX binaries only. This breaks older CPUs, shame they can’t release several different binaries.

Update: I’ve noticed the performance isn’t stable.  With the AVX binaries my program runs sometimes in 46 seconds (yay!) and sometimes in 110 seconds (boo!). With Google’s stock build it’s sometimes 51 and sometimes 120. That suggests the AVX binaries aren’t a significant speedup for my program and I have a deeper mystery.

I spent several hours figuring this out. Turns out in the slow case, my program spends most of its time in mnist.next_batch(), I think when it runs out of data and has to reshuffle. I have no idea why it’s so variable or slow but it’s not an interesting failure given this is tutorial code. Does remind me I should learn more about how to manage test data correctly in TensorFlow.

If I stub out the batching so it’s not a factor my program runs in about 29s with the AVX binaries, 32s with stock binaries (no AVX). So maybe a 10% improvement. That’s not very exciting.

TensorFlow day 2

Some more tinkering with TensorFlow, in particular the MNIST for ML Beginners and Deep MNIST for Experts tutorials. MNIST is neat; it’s a standard normalized dataset of handwriting samples for the numbers 0-9. A classic for machine vision testing, with well known results and training accuracies of 88 - 99.5% depending on the approach. Consensus test data like this is so valuable in a research community. I worked with this dataset back in Ng’s Machine Learning class.

First up, MNIST for ML Beginners. It has you build a basic linear regression model to classify the numbers, then train it. Final accuracy is about 92%.

I followed this just fine, it’s pretty straightforward and not too different from the “getting started” tutorial. Just on real data (MNIST) and using some slightly more sophisticated functions like softmax and cross_entropy. Some notes:

  • TensorFlow has datasets built in, in the tensorflow.examples package.
  • The MNIST data set has a “.train” collection of training data and a (presumably disjoint) “.test” collection for final test data. The .train set also has a method .next_batch() which lets you randomly subsample rather than training on all data every single iteration.
  • The concept of “hot ones” representation. For labeling the digits 0-9 we have an array of 10 numbers (one per digit). Every number is 0 except for a single 1, which marks the label. There’s also the “tf.argmax()” function for quickly finding index of the column set to 1.
  • The softmax function which takes a vector of weights and normalizes it so it becomes a vector of probabilities that sum to 1. The weighting is exponential.
  • TensorFlow has an InteractiveSession which lets you mix declaring stuff with running session code conveniently. Good for noodling in a notebook.
  • “Loss functions”, basically a measure of the error between a prediction your model makes and the expected result data. These tutorials use the cross_entropy function, an information theory calculation that involves the probabilities of each outcome as well as just measuring the error.
  • tf.train.GradientDescentOptimizer() is a simple optimizer we apply here in a straightforward way. Note this is where TensorFlow’s automated differentiation comes into play, to do the gradient descent.

The second tutorial I did was Deep MNIST for Experts. This has you building a 4 layer neural network (aka “deep”) that maps 5x5 patches of the image to 32, then 64 features, then convolves it all to a single flat 1024 features before classifying it. Final accuracy is about 99.2%.

I had a harder time following this, it assumes a lot more machine learning knowledge than the previous tutorials. If you don’t know things like what a rectified linear neural network, what dropout does, or what the Adam Optimizer is you’re gonna be a bit lost. It me; I’m kind of blindly copying stuff in as I go.

  • The full source has this weird thing about name_scope in the code. I think this is an extra level of testing / type checking but I’m not positive. I left it out and my code seems to have worked.
  • This code gets a bit complicated because you’re working with rank 4 tensors, ie: one giant 4 dimensional array. The first dimension is test image #, the second and third are pixels (in a 28x28 square) and the fourth is a single column for color value. It’s a standard setup for 2d image processing, I imagine.
  • The network structure is neat. Intuitively you boil down 28x28 grey pixel values into 14x14 32 dimensional values. Then you boil that down again to 7x7 64 dimensional values, and finally to a single 1024 feature array. I’m fascinated to know more about these intermediate representations. What are those 1024 features? I expect one is “looks like a vertical line” and one is “looks like a circle at the top” and the like, but who knows. (I bet someone does.)
  • The pooling from 28x28 → 14x14 → 7x7 is odd to me. It uses max_pool, which I think means it just takes the maximum value from a 2x2 window. Surprised that blunt an instrument doesn’t throw things off. For that matter what does a derivative of this function mean?
  • Dropout sounds crazy; you randomly just drop nodes from the neural network during the training. This keeps the network honest, avoids overfitting. It feels a bit like randomly harassing someone while they’re studying to keep them on their toes. The paper they linked says Dropout is an alternative to regularization. I note this code doesn’t ever regularize its input, so I guess it works?
  • They also introduce the idea of initial weights in a neural network. I remember this from Ng’s course; you want them to not all be 0, because then nothing can break the symmetry. Also they give everything a positive bias term to avoid “dead neurons”. Not sure what that means.
  • The pluggable nature of Tensor modules is apparent here. Particularly the swap to the “Adam Optimizer” over a simple gradient descent. I have no idea what this algorithm does but using it is literally one line of code change. And presumably it’s better, or so the linked paper claims.
  • It’s slow! 20,000 training iterations on a i7-2600K is taking ~20 minutes. Now I wish I had the custom compiled AVX version, or a GPU hooked up :-) It is running as many threads as it should at least (7 or 8).
  • They have you running 20,000 training iterations but the accuracy measured against the training set converges to 0.99 by around 4000 iterations. I wonder how much the network is really changing at that point. There’s a lot of random jitter in the system with the dropouts and sampling, so there’s room. The accuracy against the test set keeps improving up to about 14,000 steps.

One thing these tutorials are missing is more visual feedback as you go along. That, and some easy way to actually use the model you’ve spent an hour building and training.

I’d like to go back and implement the actual neural network I built for MNIST for Ng’s class. IIRC it’s just 1 hidden layer. the 20x20 pixels are treated as a linear array of 400 numbers, then squashed via sigmoid functions to a hidden layer of 25 features, then squashed again to a hot ones layer of 10 numbers. It would be a good exercise to redo this in TensorFlow. The course notes describe the network in detail and suggest you expect about a 95.3% accuracy after training.

TensorFlow introduction

I spent a couple of hours kicking the tires on TensorFlow, mostly working through the Getting Started docs. Which are excellent, btw. Here’s some things I learned. These are all super basic, undergrad level things. The real stuff requires more time to get to.

  • Installing TensorFlow is as easy as “pip install tensorflow”. It runs fine in Jupyter with no problems.
  • Don’t be dumb like me and try to get the GPU accelerated version working at first; that’s hard because NVidia’s packaging is such a mess. For that matter ignore the warnings about CPU optimizations for your hardware. That might make it run 2-3x faster, but you have to compile TensorFlow yourself to do that.
  • “Tensor” is a fancy word for “multi-dimensional array”. It’s numpy under the hood. TensorFlow is all about creating a flow of data through tensors.
  • “Tensor” is also a fancy word for “deferred computation”. The TensorFlow framework basically has you creating a bunch of Futures/Promises and linking them together in a model. You don’t run code imperatively, you declare function objects (of type Tensor) and then hand them to a session manager to run. This enables two important kinds of magic:
  • Magic 1: the session runner handles running your model. You don’t really care how. Maybe it’s run on the CPU, maybe the GPU, maybe it’s handed off to a distributed compute cluster. All you know is you told the session to run and you got a result.
  • Magic 2: when training a model, the derivatives are calculated via automatic differentiation. Most machine learning techniques require that you not only calculate the error between the model’s output and the desired output, but also the first partial derivatives of that partial error. You can then use the derivative for gradient descent optimization, etc. A big part of what makes machine learning algorithms mathematically difficult is analytically finding those derivative functions. You can numerically approximate the derivative but that doesn’t work very well. TensorFlow instead automatically generates derivatives by inspecting the model you created out of Tensor building blocks and functions. (See also Google Tangent, a different approach to automatic differentiation done by decompiling Python code. wacky!)
  • You can write your own training system by using the tf.train API to create a model and pass it to your optimizer of choice. Or you can get fancier and use the tf.estimator API to run a whole machine learning project for you. That’s most of what the “getting started” tutorial has you do, those two approaches.
  • The trained models become things you keep in TensorFlow; you can store them to disk, apply them to input data, etc.
  • There’s a nifty tool called TensorBoard that can visualize a TensorFlow model, all the functions it is built out of.  There’s also visualizations of the training process.

At the end of the tutorial all I’d done was train a very simple linear regression model to some toy one dimensional data. But I sort of understand how the parts fit together now. I’m impressed with how well crafted those parts are, Google has put a whole lot of effort into packaging and presenting TensorFlow so folks like us can use it. It’s impressive.

The next step in the tutorials is to train a simple handwriting recognizer. I did that from scratch in Ng’s course, will be fun to revisit it with a high level toolkit.

 

Leela Zero, GPU machine learning on Google Cloud

I’ve been excited about the Leela Zero project that’s doing machine learning with volunteered computers for the game Go. I’ve been running it on my Windows box for a few days but wanted to try running it on Linux.  So I leased a Google Compute server with a GPU.

End result is costs about $0.10 / training game on Google Compute. It might be possible to improve this by a factor of ... 4? 10? ... by picking a better hardware type and tuning parameters. My Windows desktop machine with beefier hardware is using about $0.01 / game in electricity. AlphaGoZero trained itself in under 5M games. If Leela Zero does as well it’d cost well under $1M to train it up to superhuman strength. Details vary significantly though; Leela Zero is so far not learning as fast. And the time to play a game will go up as the network learns the game.

Here are my detailed notes. This is my first time setting up Google Cloud from scratch, and my first time doing GPU computation in Linux, so all is new to me. Nonetheless I got Leela Zero up and running in under an hour. One caveat: Google Cloud gives new users a $300 free trial. But you cannot apply that balance to a GPU machine. The cheapest GPU machines are about $0.50/hour.

Update: someone on Reddit notes you can get similar machines from Amazon EC2 at a $0.23/hour spot price. They have more CPU too, so maybe it gets down to $0.03/game?

 

Setting up a Google Cloud machine

The only subtle part of this is configuring a machine with a GPU.

  1. Create Google Cloud Account. Attach a credit card.
  2. Create a new Project
  3. Add SSH keys to the project
  4. Create a server
    Compute Engine > VM instances
    Create an instance. Choose OS (Ubuntu 17.10) and add a GPU. GPUs are only available in a few zones.
  5. I picked a K80, the cheap one; $0.484 / hour. The P100 is 3x the price.
  6. Got an error “Quota ‘NVIDIA_K80_GPUS’ exceeded. Limit: 0.0 in region us-west1.”
  7. Upgrade my account past the free trial.
  8. Try again, get same error
  9. Go to quota page. Find the “Edit Quotas” button. Request a single K80 GPU for us-west1. Have to provide a phone number. This seems to be a manual request that requires human approval, but it was approved in just a minute or two.
  10. Try a third time to set up a machine. Wish that my template machine had been saved. Works!
  11. Log in to the machine via IP address. It’s provisioned super fast, like 1 minutes. Ubuntu had already been updated.

Setting up GPU drivers

Mostly just installing a bunch of Linux packages.

  1. Try seeing if I can do GPU stuff already
    # apt install clinfo; clinfo
    Number of platforms 0
    Nope!
  2. Figure out what hardware I have
    # lspci | grep -i nvidia
    00:04.0 3D controller: NVIDIA Corporation GK210GL [Tesla K80] (rev a1)
    This is a late-2014 $5000 GPU. Retails for $2500 now. It’s got 24GB of VRAM in it compared to gamer cards’ 6GB or so. It’s really two GPUs in one package, but I think I’m only allowed to use one? Probing shows 12GB of GPU memory available to me.
  3. Follow the instructions for installing drivers from Google.
    This boils down to installing the cuda-8-0 package from an NVIDIA repo. It installs a lot of crap, including Java and a full X11 environment. It took 6 minutes and my install image at the end is about 6.2B.
    Note there are many other ways to install CUDA and OpenCL, I’m trusting the Google one. Also there’s a cuda-9-0 out now but I am following the guide instead.
  4. Enable persistence mode on the GPU. I have no idea what this means; isn’t it delightfully arcane?
    # nvidia-smi -pm 1
    Enabled persistence mode for GPU 00000000:00:04.0.
  5. Verify we now have GPUs
    # clinfo
    clinfo: /usr/local/cuda-8.0/targets/x86_64-linux/lib/libOpenCL.so.1: no version information available (required by clinfo)
    Number of platforms 1
    Platform Name NVIDIA CUDA
    Platform Vendor NVIDIA Corporation
    Platform Version OpenCL 1.2 CUDA 9.0.194
    ...
  6. Further optimize the GPU settings based on Google docs.
    # sudo nvidia-smi -ac 2505,875
    Applications clocks set to “(MEM 2505, SM 875)” for GPU 00000000:00:04.0
    All done.
    # nvidia-smi --auto-boost-default=DISABLED
    All done.

Compiling and running Leela Zero

Mostly just following these instructions and these instructions

  1. Install a bunch of libraries. Took about a minute, 500 MB.
  2. Compile leelaz.
  3. Run leelaz. It shows you an empty Go board.
  4. At this point you’re supposed to hook up a fancy graphical Go client. But screw that, we’re hacking.
    play black D3
    genmove white
    genmove black
    Here’s a sample output from one move
  5. Compile autogtp
  6. Copy the leelaz binary into the autogtp directory
  7. Run autogtp. Here’s a sample output

Performance

I didn’t benchmark carefully but I put this here because it’s most likely to be of general interest. Run times are highly variable; my first game on Google Cloud took 720 seconds for 270 moves, my second game lasted 512 moves (!) and took 1028 seconds. So comparing time / game for just a few games is not useful. Perhaps the ms/move numbers are comparable or at least useful for finding optimal work settings, but even they seem highly variable in ways I can’t understand. Benchmarking this for real would take a more serious effort.

  • Google Compute. 1 vCPU, K80 CPU.
    1 thread: 63% GPU utilization, 800 seconds / game, 2650 ms / move
    2 threads: 69% GPU utilization, 1200 s/game, 2500 ms/move.
    4 threads: 80% GPU utilization, 1113 s/game, 2110 ms/move
    10 threads: 57% GPU utilization, ?
  • Windows desktop. i7-7700K (4 cores), GTX 1080 GPU
    1 thread: 612 s/game, 1700 ms/move, 30% GPU
    2 thread: 389 s/game, 1120 ms/move
    3 threads: 260 s/game, 740 ms / move. 70% GPU
    4 threads: 286 s/game, 701 ms / move. 84% GPU
    5 threads: 291 s/game, 750 ms / move
    8 threads: 400 s/game, 740 ms / move, 80% GPU

Bottom line, I’d say the Google Compute systems are roughly 800 seconds / game, or 5 games an hour. That pencils out to about $0.10 a game. My Windows box with better hardware is about 3-4 times faster. I’m guessing it uses about 200W (didn’t measure), which is about $0.08 / hour or < $0.01 / game in electricity costs.

I’m confused about the performance numbers. I think those are normalized by number of simultaneous games (the -g parameter), so lower numbers are always better. The seconds/game number is highly volatile though since game length varies so much. I guess the ms/move parameter goes down on the Linux box with more threads because we use more of the GPU? But why not the same pattern on Windows? FWIW the program author has noted Windows performance is not great.

Leelaz seems to only use 63MiB of GPU memory, so a very low RAM graphics card is probably fine.

One last thing: I’ve been running the Windows .exe binary under Windows Services for Linux. 4 threads in this environment is 710 ms / move. 4 threads in a DOS window is 777 ms / move. Not sure it’s significant, but seemed worth noting.

 

Machine Learning study

My old colleague Karl Rosaen is taking time off from working to study Machine Learning. He’s meticulously documenting his curriculum and day to day work, good resources there.

One big part of Karl’s studying is Raschka’s book Python Machine Learning. It looks like a nicely practical book, I was looking for something like that last year and it wasn’t quite out yet. His example code is online. And his blog post about writing it is nice.

My biggest regret from my machine learning work is not applying it to real problems. Karl mentions that the Kaggle competitions are a good set of problems and datasets to work on.

A library of trained machine learning models?

I wonder if machine learning is mature enough that people can start sharing trained classifiers? Ie: instead of training neural networks to do character recognition yet again, why not just download the consensus Recognizer library that everyone uses and just apply it? The question is deliberately provocative.

I think applied machine learning may not be mature enough to support standard library usage. What does it mean to “download a trained model”? Models are expressed in terms of specific software libraries; sklearn, TensorFlow, whatever. Probably specific to minor version releases of those libraries, for that matter.

Also every machine learning application I’ve seen is highly customized to the specific task. it’s never as simple as “recognize characters in an image”, it’s always carefully tuned to the specific source of images (ie: camera artifacts, etc). And the use of the outputs: numbers only, English text only, with confidence intervals or without. And the larger context of use: are you recognizing zip codes on an envelope? Turning scanned documents into text? Breaking CAPTCHAs?

Also the whole idea of “consensus software library” is pretty rough sledding even in traditional instances. I mean we can’t even agree on a common malloc(), or a common regexp recognizer.. OTOH some things are highly standardized, like compressors or crypto libraries or the like.

The idea of “open source” on a trained model is also a bit wonky. There’s not really source code you can read in a trained model; it’s not like I’m going to read a diff of neural network weights and learn anything about the submitted patch. So maybe the source code open source artifact is the program that does the learning along with the training set, and you also distribute the trained model output as a sort of pre-compiled convenience.

(Inspired by reading this post, in which a student builds a classifier for American  name gender. It’s a very nice exercise but it got me wondering; if I really want a gender classifier, why can’t I just download one some expert already built and tested?)

Update: with many thanks to the awesome Julia Evens, I’ve learned that Caffe, an image processing machine learning project, has explicit support for sharing trained models. Here’s her blog post about playing around with a trained image recognizer.

Butt-based machine learning

I’ve been doing somework with scikit-learn but running code on your own computers is for chumps, why not do our machine learning in the butt in the cloud? Here’s the offerings from a few, there are lots of others, too. This cross-service developer test is interesting data on prediction and running times.

Google Prediction API. $0.50 / 1000 predictions, $0.002/MB of training data. Focussed on training prediction models, both numeric (regression) and categorical. Didn’t see any documentation of what kind of algorithms they implement.

Amazon Machine Learning. $0.10 / 1000 predictions, $0.42 / hour for training. The FAQ says it does logistic regression, but the docs say it does both categorical and numeric predictions. They also have some data exploration tools and quality metrics.

Microsoft Azure Machine Learning. $0.50 / 1000 “API transactions”, $2 / hour. Also a per-seat charge which is completely “lol Microsoft”, I mean seriously? Offers classification but also other stuff: text analytics, vision, speech. The algorithm cheatsheet makes it look liek you have a lot of choices for basic prediction algorithms, too.

BigML: $0.10 / 1000 predictions, $0.01/MB of training data. Didn’t review what all algorithms it supports, clearly they do predictions. They’re a startup up in Portland and in Spain, with just $1.6M in funding in 4 years.

I’m not qualified to evaluate these yet. Google’s the oldest and simplest, also the most limited. Amazon’s product looks pretty simple and pretty. Microsoft’s has the most bells and whistles but you have to wade through Microsoft’s sales cluelessness. No idea on BigML but I like the idea of a startup making headway here.

SVMs in Python

I started trying to apply SVM machine learning to my Battlefield 4 dataset and got something that only predicted my data with 60% accuracy. I’m expecting 95% or more but I don’t really know and I realized I was trying to learn too many new things at once.

So I went back to my Coursera homework, exercise 6, and used their data and problem sets as Python exercises. Specifically I trained SVM classifiers on two datasets. The result is in this notebook.

Cells 2–4 are me simply fitting a binary classifier to the toy input data. Cells 5–9 are fitting a binary classifier to different data, in this case performing repeated training steps to pick the right parameters C and sigma for the learning system. I did it the homework’s way in cells 6–7, using an explicitly split training and test dataset. Then I used sklearn’s cross_validation library to do the training in 8–9, which is a form of resampling to produce test sets on the fly. Results were roughly the same. I’m not 100% certain it is philosophically kosher to use CV in this manner, but I think it is.

Things I learned:

  • You can load matlab arrays with scipy.io.loadmat()
  • The ‘rbf’ kernel is what sklearn.svm calls the Gaussian kernel.
  • Instead of sigma, sklearn parameterizes rbf with gamma. gamma = 0.5/sigma**2
  • Decision boundaries are plotted by simply creating a raster grid of predictions, then making a contour plot to only show the boundary.

The big thing I learned is how sensitive these systems are to choices of sigma and C. Before I had the code working right I was using bad values and getting insane results. Relatively easy to see in a 2d dataset where you can plot the data and the decision boundary, but this must be much harder to understand and debug in large multidimensional datasets.

Machine Learning: reflections on the Coursera course

I’m all done with my Machine Learning course on Coursera, and I wrote a lot about it as I was taking it. Time to look back and put it together.

First off, it was a good use of my time. I complained about aspects of the course and I definitely think it can be improved. But it was a good introduction to what machine learning is and enough hands-on that I feel like I can no go do my own work with real tools. I also mostly liked the Coursera structure, having weekly deadlines and assignments was the structure I needed to actually learn something.

Techniques and Approaches

The thing I was most interested in learning is the general gestalt of machine learning, like how to sit down and get a problem solved. That was covered reasonably well through the course to varying degrees. Some themes:

  • The general structure of “take a training set of data. train a model on it. evaluate the mode against your test set. apply the model”. In some sense all the machine learning systems do the same thing: map a vector of input data to a scalar output value. The various algorithms are just different approaches to learning how to map input data to outputs. I didn’t understand they all fit into this category before.
  • The specific way that the training step is basically just running a function minimizer over your cost function (ie: measure of error). The subtlety here is most minimizers require some understanding of the gradient as well, which means you need to take partial derivatives of your cost function. (I wonder if numeric approximations to the derivative are useful in practice?)
  • The concept of high bias vs high variance models, ie: overfitting the data vs. underfitting the data. Basically if your choice of algorithm has a lot of internal knobs to twiddle, it’s likely you have high variance and might overfit the data, particularly if you don’t have a big data sample. Alternately if your chosen model is too simple the system might not ever predict the data well because it lacks the expressive power. I particularly liked the way you can detect which problem your system has with measuring the learning curve, how well your system learns based on how much data you give it.
  • Precision, recall, and f-score as a way to evaluate the success of a model.
  • A principled way to normalize data so that all your numbers are on comparable scales of roughly -1 to 1, with mean 0.
  • Regularized learning algorithms, with an extra term in the cost function to discourage overfitting.
  • Machine learning pipelines. The way you can segment a broad problem like photo OCR or automatic driving into smaller machine learning problems. Also ceiling analysis to figure out which part of your pipeline could be improved the most.
  • Stochastic machine learning. For very large datasets just iteratively learn on subsets of the data. Naturally leads to online learning, systems that continually learn in response to new data.

Algorithms

Most of the class was a tour through machine learning algorithms. Too much time implementing those algorithms for my tastes, but at least there’s no mystery to many of them now. Things we learned:

Supervised learning (ie: your training data is classified with expected outputs you are trying to predict.)

  • Linear regression: fit a linear model to the data. Predict a single number from a vector of numerical inputs.
  • Logistic regression: fit a logistic model to the data. Predict a single binary classifier from a vector of numerical inputs. (Really it outputs a probability!) Can predict N classes with one-vs-all classes.
  • Neural networks. Fit multi-stage regression to the data. Hidden layers can discover and calculate their own learned features. Good for non-linear models.
  • Support Vector Machines: logistic regression with a different error function that encourages your system to make sharp distinctions when classifying data. Also pluggable kernels, which allow you to change the function applied to features being considered to get beyond linear models. I got the impression SVMs with Gaussian kernels are the right choice in practice for many problems.

Unsupervised learning (no expected output on hand)

  • K-means clustering. Group your data into K natural clusters.
  • Principle component analysis. Boil high dimensional data down to fewer dimensions, while measuring and minimizing the loss of meaningful data.
  • Anomaly detection. Find data examples way outside the mean.
  • Collaborative filtering. Learn from user preferences what features of something result in those user preferences.

Practical skills

Practical application of subject matter was the weakest part of the course. The primary new technical skill I learned was Octave. But that feels like an increasingly obsolete tech and I wish I were using a language I’d be using more later. OTOH it was fun programming in a matrix math language with vectorization. I think if I were reimplementing this course today with the same curriculum, I’d consider using R and a notebook environment.

There were some real applied problems like number OCR and spam classification and movie recommendations. Those were interesting to me, but the exercises tended to have us solving one piece of a system to learn the data rather than putting the whole thing together.

I keep thinking it’d be fun to design an alternate machine learning course, one that focusses on the more practical application. Start with you downloading and pre-processing data. Then create a machine learning experimentation pipeline, plugging in out-of-the-box algorithms rather than implementing the algorithms yourself. Then go back and iteratively improve your application of ML, evaluating with learning curves and test data sets and honing the system so it really works.That’s a different course, but if I were doing that I’d do it in Python with scikit-learn and IPython notebooks.

What I missed

As noted above, the main thing I missed is more practical application. But that’s OK, because I think I learned enough to teach myself the practical stuff.

I also wish the course had a broad overview of more algorithms. There are literally thousands of machine learning algorithms in use out there, and while I trust we hit the most important basic concepts I’d have loved a single week which was just a whirlwind tour. Bayesian inference, decision trees, Markov models, ... so many options.

Next steps

Now on to applying what I’ve learned to my own data. I already did one little exercise in PCA and clustering with Battlefield 4 data, which was a good experience. I should really try applying SVMs to something next. Maybe League of Legends match data, but it’s hard to get a large sample with the default API rate limiting.

What I really want to do is try applying this stuff to map data. Some machine learning system to improve OpenStreetMap, maybe by identifying anomalies comparing the vector map users generate to raster aerial imagery.

Machine Learning: Photo OCR, real world problem

These last two weeks of the course were so short I finished them all in one day.

I liked this last week, week 11. Most of the lectures were about a real world machine learning problem: finding and OCRing text in photographs.

Photo OCR

The key idea here is the pipeline. He broke the problem up into 4 separate machine learning problems that can be worked on independently.

  1. Find regions of the image that look like text.
  2. Segment text regions into individual characters.
  3. OCR individual characters
  4. Spell correct OCR errors

The real meat of the lesson was the sliding windows algorithm, the technique by which you identify text regions. Basically you look at small square regions of the image and train a recognizer to identify text/not-text. Then you merge adjacent regions of text into single blobs for handing off to step 2, the segmenter. The segmenter also uses a sliding windows analysis to find whitespace between characters, albeit a 1d window.

Lessons for machine learning

Second half of the lesson was reflections on doing better for machine learning.

First question: do you need more data? It may be expensive to get it. More data is most useful for low bias machine learning algorithms, so don’t bother if you have an overfit model. (Or rather, loosen your model first!). He also talked about artificial data synthesis, ways to generate more data from existing labelled training sets. For instance if you’re doing voice recognition, maybe you can generate more training examples by adding real-world distortion to existing examples. However don’t just add random noise, since that doesn’t really train anything useful.

Second question: what should I work on next? The key idea here is ceiling analysis. Basically you go down your pipeline replacing each step with a perfect system. Ie, replace step 1 with a perfect text region classifier; how much does your system improve? Now also replace step 2 with a perfect segementer: how much better does your system do? With that experiment in hand you can identify which steps in the pipeline have the most room for improvement, are worth your time to work on.

Once again I wish there were a programming exercise here to hammer these lessons home. Have us construct our own pipeline and do some testing / segmentation on it. I think this would be a good time to revisit the ideas of training vs. test sets, applying the test set well. Also evaluating systems for bias/variance problems. I suspect the Stanford undergrad class had students doing some final project which was just left out of the Coursera class, perhaps because it would be impossible to grade. Guess it’s up to me to apply this stuff to real problems and make my own mistakes without a teacher to tell me how I’m doing. Unsupervised learning, as it were.

And that’s the course! I’ve got one more blog post coming summarizing what all we covered and what I thought. Overall I’m quite positive, it was a good use of my time.

Machine Learning: large scale learning

Major shift of tone in week 10 of my course. Less detailed algorithms and programming assigments, more of a “here’s some wisdom about real world use”. Well a bit of each, but no programming. Being this high level makes me feel a bit dislocated, I appreciate more now the harder assignments in previous weeks.

Stochastic Gradient Descent

Most of the lecture was on the problem of running machine learning algorithms on enormous data sets, say 100,000,000 examples. These algorithms tend to be of the form “calculate this cost function over all data. then average the cost and update theta, our model parameters”. That’s inefficient when your data is 100M examples! So instead we update theta based on only some of the example set.

Stochastic gradient descent has you doing gradient descent where you update theta once per data example. That means that instead of swiftly following the gradient down to the optimum your optimizer is now doing a bit of a drunken walk, but in the right direction towards the optimum. And with a huge amount of data you can get away with looking at all the data a little less often. Ie: a normal batch gradient descent may do 100 evaluations of all 100M data points. With stochastic you can get away with 1-10 evaluations of the 100M data points. I assume law of large numbers is why. One caveat: it’s important to iterate through your data in a random order, shuffle the data first.

“Mini batch” gradient descent is a middle ground where you calculate the cost over, say, 1000 samples before updating theta. Stochastic looks at 1 sample at a time, batch looks at all N, mini-batch looks at a subset of say 1000. The reason you do this middle ground is because you can still get some benefits of vectorization and/or parallelization.

Convergence is a bit woolly with these stochastic approaches. You still want to monitor convergence, but you really don’t want to calculate the cost function over the whole 100M data samples every time! So instead look at a sliding window of the last, say, 100 cost function calculations you did and monitor it to make sure it’s converging.

Online Learning

Closely related to stochastic machine learning is online learning, where your machine learning model is updating itself continuously in response to new user input. That’s how real websites work. The neat thing about this is your model will adapt to changes in the world over time. Ie: you may have trained a perfect spam classifier in 2013, but spam techniques changed. An online learning system will adapt to new techniques as new data comes in.

Parallelism and map reduce

Last lecture was a funny coda which was basically “oh yeah, you want to run machine learning in parallel on big data!” along with “there’s this thing called map reduce you should know about”. It’s obvious how many ML algorithms are embarrassingly parallel over the input data, so maybe it’s fine to go quickly over this. But a simple map reduce implementation of, say, linear regression would have been a great programming exercise. Perhaps not in Octave though, maybe that’s why they skipped it. I wonder if scikit-learn has support for map reduce? Quick search suggests not really, you roll your own on top of Hadoop.

My first iPython notebook

I finally sat down and learned some IPython for data exploration today. I re-examined some data I had for Battlefield 4 players, something I’d published as my BF4Plots visualization a year or two ago. It’s the stats on ~5000 top Battlefield 4 players, things like their win/loss ratio, skill score, etc.

You can see my notebook in this gist. That’s a static snapshot taken from my last run. If you run it yourself the results will change slightly as some of the algorithms I apply include randomization.

My main goal here was to get more comfortable using IPython. It’s awesome! I really love having the inline, easy to produce graphs. I mostly followed this tutorial for guidance.

Secondarily I was also trying to apply some cluster analysis to my BF4 data to see if I could learn any insights. Not really. This is my first foray into my own machine learning project applying stuff I’ve learned in my course. And it was interesting, I definitely felt I understood what the scikit algorithms were doing. Also a little lost how to get real meaning out of the data. No surprise, that’s the hard part!

The main IPython thing I’m still adjusting to is that it’s a notebook, not a program. I’m so used to iteratively working and re-running my program from scratch. But IPython encourages you to keep a persistent Python VM around and iteratively add to its state. I keep looking for the “Start over and run it all from scratch” button, and there sort of is one, but that’s not really how you’re supposed to work. Which got me into trouble a couple of times. Also I do wonder how IPython people transition their code to running programs for other people to reuse.

Update: a “restart and run all” button was just merged into the main codebase so that’s coming soon. And apparently I’m right that notebooks are more for exploration. When it comes time to create reusable code you create a normal module with some other code editing environment. You can certainly start by pasting your notebook-developed code over, though.

First Python library I learned was Pandas, the data management library. Really all I did was work a bit with DataFrame, which is a data container type that’s a 2d array on steroids. Columns are typed, everything’s nicely addressable and searchable, and it’s all efficient numeric spare arrays behind the scenes. I think it even supports multicore number crunching in a transparent fashion. Really nice library, a joy to use.

Second library I learned was matplotlib, some basic bashing at it to draw some graphs. It’s really great and I wish I’d invested the time to learn this before. But until I saw the HTML notebooks it wasn’t very compelling to me. It’s funny, Mathematica notebooks have been a thing for 20+ years but it’s only the last couple of years where Python caught up.

Final thing I learned was a bit of scikit-learn, in particular how to apply its PCA and K-Means algorithms. Went pretty smoothly. My only annoyance is it seems to only half-support Pandas. It will take DataFrames as inputs but then the objects it returns are basic numpy Arrays which lack column names and some of the nice slicing options. I can’t tell if I’m doing it wrong, it has to be this way, or if it’s just that Pandas is so new that scikit-learn hasn’t fully adopted it yet.

Anyway, all in all my experiment was a big success, very happy. Fun stuff!

Machine Learning: anomaly detection, recommender systems

Week 9 of 11, and the last week with coding homework!

Anomaly Detection

The first unit of lectures was on anomaly detection: picking outliers out of a dataset. Very simple compared to previous algorithms we’ve studied. In the one feature case it boils down to “calculate the mean and standard deviation of the input set. Values way outside the mean are anomalies”. He does define it carefully in terms of Gaussian probability distributions, which is the solid way to do this at least.

So what about multi-featured data? Instead of doing proper multivariate Gaussians, the course focusses on handling vector input data by analyzing a single-variable Gaussian separately for each input feature, then calculating the product of all the probabilities to label the full vector. The result is a special case of the general multivariate Gaussian, in particular it’s a case that only really makes sense if you believe there’s no correlations between your input features. If you do it this limited way you’re stuck having to inspect the data to define new synthetic features, like “height times width” based on domain knowledge that the area of something is more relevant than the height or the width itself.

There are optional lectures on multivariate Gaussians but I’m left wondering why the course just doesn’t start there. Maybe to simplify the math (ha!) or maybe because the special case is more efficient to calculate. He notes the multivariate case doesn’t work well if you have more features that data samples. But if that’s the case, you probably shouldn’t be trying some fancy statistics on your meagre dataset anyway. (The irony is the homework code actually does use the multivariate Gaussian afterall.)

The artful step of applying anomaly detection is determining the threshold for what an anomaly is. Ie: if the datapoint has probability of 0.9 it’s clearly good. 0.1? Probably. But 0.01? Or 0.001? Or 0.0001? How improbable does it have to be before you decide it’s an anomaly? The course has us iteratively learning a good epsilon threshold for discrimination, using a classified test set. But we have the standard deviation of the good data available to us; surely it’d be better to talk about “5 standard deviations out” being a threshold? Or maybe that’s implicit in the Gaussian probability calculation?

The programming homework was awfully simple. The solution for the first part of the first question is literally “mu = mean(X);”. I have come to appreciate how nice Octave is about writing vectorized code for computing with vector and matrix data. So much nicer than writing loops!

Recommender systems

Second unit was on recommender systems, specifically collaborative filtering. This is serious throwback for me; when I started grad school in 1996 my group was all excited because some previous students had just gone off to found Firefly, a company to do collaborative filtering recommendations. They did sort of OK and finally sold to Microsoft 6 years later for a rumored $40M. IIRC the machine learning part wasn’t the real value of the company in the end, but rather some engineering details of how they built it.

Anyway, collaborative filtering is a neat algorithm because it lets a machine learning system really learn something. You give it a big batch of user ratings of, say, movies. The system divines hidden features for those movies that best predict why people have preferences for certain movies. (Ie: maybe it figures out there’s a grouping which is roughly “action movies”). Then you can use these learned features to go back and predict ratings you haven’t seen before.

I particularly like the way Ng presented the algorithm first as an iterative problem. “Use ratings to predict features. Then use those features to predict ratings. Then use those to improve your feature predictions, ...”. But in the end it all gets collapsed into a single optimization problem.

OTOH I still hate the math and notation presented in the lectures, it’s just impenetrable. I understand the gist of what it’s doing but what is this supposed to convey? My desire now is that the course not be taught with math notation but instead Octave code notation, so that all those ugly sums and stuff are replaced with simple vector math code samples.

ss

One thing the lecture didn’t take is how you decide how many features to let the system learn. I believe this choice is arbitrary but probably essential to good performance. Someone else already asked in the course discussion. The mentor answered saying basically “try the smallest number that works well on test data”.

I was dreading the homework, since it’s yet again a “translate the confusing math to code” exercise. But having done this kind of thing a few times and with the mentor’s course notes as a guide, it’s pretty straightforward. Particularly to just do a vectorized implementation instead of the for loops the lecture definitions and exercises suggest. Seriously, I think this course got its approach wrong, it’s insane to try to do the calculations unvectorized in a language like Matlab. Both for clarity and performance. The lectures should teach to this approach.

The exercises build up to an actual movie recommender system (using MovieLens data). Neat! Only the homework is flubbed. With the originally supplied code we tell the recommender we liked Alien and Die Hard 2 and then it recommends Star Wars and Braveheart. Makes sense, right? Only the predicted rating I will give these films is 8.9 on a scale of 1–5. Oops. But at least the list of recommended movies is plausible.

Turns out the supplied code forgot to use some normalized values. So I fix that code as instructed and run it again, and now the highest predicted rating is 5. Good! Only now the list of recommended films are completely obscure movies like “Santa with Muscles” and “Aiqing wansui”. I’m left wondering if there’s still a bug in the code or this is a cruel lesson in the confusing vagaries of trained machine learning systems. I looked more closely and the recommendations I expect are there at the top, just not the very top. Still, it’s a disappointing end to the homework problem.

No more programming!

And a disappointing end to the course’s programming assignments. That’s the last one. There’s two more weeks of lectures and short quizzes, but no more coding. I’m sort of glad because hey! no homework! But also sad because I was hoping I’d learn more from the coding assignments.

I’ll say it one last time; I’d love a class that focussed more on application of machine learning systems. I really don’t need to implement the code for neural network back propagation or the fiddly details of collaborative learning. Or rather if I’m going to be doing that, I should be doing it on a graduate level with real math as the foundation. I’m fine with an introductory course being more shallow, but then I wish the programming exercises skipped the half-assed algorithm implementation and focussed on applications, on coaxing good results from these algorithms.

I realize I’m being cranky and truly I’m grateful that the course exists. I certainly appreciate that it’s free! Mostly my criticism is intended as “how could this be better?”.

Machine Learning: k-means clustering, principal component analysis

This week’s lectures were our first foray into what is bizarrely called “unsupervised machine learning”. All our previous algorithms were given data features and correct classification as inputs. This time around all we get are data features, these are algorithms to try to classify / understand the data without guidance. It all seemed much simpler than previous weeks, particularly the assignments, I don’t know if I’m getting smarter or the material is just easier. I vaguely remember enough math from college that this all seemed pretty straightforward.

K-Means Clustering

K_Means clustering is a way to classify a bunch of inputs into a relatively small set of “K” clusters. It’s easy to illustrate visually:

Screen Shot 2015-09-04 at 3.29.05 PM

The dots represent data input points, 2 dimensions of input data. Visually we can see these naturally fall into two clusters, helpfully colored here red and blue. Note the input data to this algorithm is not labelled, we don’t know what’s red and blue. The point of k-means clustering is to discover those red/blue labels. Once k-means has converged the model has two points, here marked in Xs. Those are the centroids of the two clusters. The way the algorithm works is you pick points at random to be your cluster centroids, then iteratively optimize that updating centroids so as to minimize the distance between every point in a cluster and its centroid.

Intuitively this is a pretty simple algorithm, and it is effective. Where people get tripped up is that our intuitions about “distance” and “near” from 2 or 3 dimensional spaces don’t really work for 1000+ dimensional data that’s often what we study. Ng didn’t go over that, just wisdom i’ve picked up from friends.

One thing I hadn’t known is that k-means is useful even when the data isn’t strictly clustered. For instance say you have height/weight of people, a continuous smear of points. Now say you want to sell t-shirts in three sizes: Small, Medium, Large. So cluster your data into three clusters and the centroids are the mean person you should make that size for. Kinda neat.

The art of applying k-means is knowing how to pick K, how many clusters. He presented the “elbow method” which basically lets you keep making K bigger until you don’t get a significant improvement in the error from its application.

Principle Component Analysis

PCA is an algorithm to project a high dimensional dataset down to a lower dimensional dataset. You can use this to project 10,000 dimensional input data down to, say, 1000 dimensions so that then your learning algorithms run faster because there’s less data. Or you can try to project data down to 2 or 3 dimensions for visualization.

The actual PCA algorithm basically boils down to “calculate eigenvectors”. Which Ng sort of said was the case, while not assuming the student knows what an eigenvector is. It was a pretty clear explanation really.

You still have to choose how many dimensions you want in your reduced dataset. His heuristic is “You want 99 percent of value retained”, which means “accept up to 1% error”. He says in practice you can often reduce data to 1/5 to 1/10 the number of dimensions and stay in this threshold.

Homework

Our actual homework this week was really simple, basically writing one-two lines of vector math code at a time to implement the pieces of k-means and PCA algorithms. Not much learning. There was a bunch of optional extra homework assignments applying to real world data. Using k-means clustering to reduce an image palette for instance (find the 16 most important colors). Or use PCA to reduce pixel data from pictures to the important components for facial recognition. That was neat stuff, I wish we’d done that for homework.

Screen Shot 2015-09-04 at 3.36.44 PM

Once again I find myself wanting to do this stuff in Python. PCA would be nice to apply to that Battlefield 4 dataset I collected; it’s ~20 dimensional data, boil it down to the 4 or 5 eigenvectors that really define people’s performance. Then maybe cluster that to segment the population.

Machine Learning: Support Vector Machines

After weeks of complaining my machine learning course had too much detail on the math and guts of ML algorithms and not enough on applying ML to real data, I got my wish. This week’s course on Support Vector Machines (SVMs) was pretty high level and breezy, and the homework even more so. And now I’m dissatisfied, feel like I didn’t get my week’s learning’s worth! Not that I’m complaining to have an easy week, but I wish there were a bit more brain-bending around application to replace all brain bending I was doing before figuring out the vector math and programming.

PS: I’ve created a Machine Learning category on the blog. And mucked with the theme. Boy, wordpress.com is super buggy and badly product managed.

Lectures

The main topic this week was Support Vector Machines, a supervised learning technique that was framed as being more powerful and practical in application than the previous techniques we used like linear regression, logistic regression, and neural networks.

Conceptually it works a lot like these other supervised learning systems. You define a cost function, but unlike the logistic cost function this one biases the system to prefer “large margins”. Ie basically it’s not enough to say “49% chance it’s category A”, the training is encouraged to say “10% chance it’s category A” instead. You control this bias/overfit tradeoff with the parameters C and sigma. C is much like our lambda from before, a damping factor to encourage small constants. (Confusingly, C = 1/lambda). sigma shapes the cost function curve itself, at least in the usual Gaussian kernel.

Oh yes, kernels. This is a neat trick where you can modify your input features with various functions. A linear kernel gives you linear regression (exactly? or more or less?). The Gaussian kernal is a good general purpose kernel. There’s a bunch of other kernals people use. And some magic allows this pluggable kernel function to be applied efficiently, so the training system runs quickly.

That’s where the lectures got a bit hazy. There was one whole 20 minute video dedicated to the math which was prefaced with “this is optional, and you should never try to implement this; use libsvm instead”. The main thing I learned from this is you can still understand speech when watching a video played back at 2.2x speed, even though the individual phonemes are no longer distinguishable. He skimmed over the math quite a bit, nothing was lost by ignoring it.

I never did quite understand why SVMs are better. We were advised they are best in applications with lots of training examples relative to the size of the feature set. Logistic regression is better if you have lots of features and few training examples. And neural networks may be better than SVMs too, but take longer to train. ¯\_(ツ)_/¯

Homework

The homework this week was super-easy, all about applying SVM to problems. Each of the 4 exercises was like 3 lines of code. The only hard part was learning Octave syntax for doing things like “find the element in the list”, which once again made me wish we were using Python.

Anyway we implemented two learning exercises. An artificial problem of “find the boundary between Xs and Os for 2d input points”. And a real problem of “build a spam classifier trained on this data set”. We were supplied with the SVM ML system itself, so all we had to do was write simple functions to compute the Gaussian kernel and boil a list of stemmed words down into a vector coding. It was kind of dumb.

The most useful assignment was writing a loop to try out a training system with various values of C and sigma, the tuning parameters for the SVM. And experimentally determine what values gave the most accurate trained model. I imagine this is the kind of thing you do in the real world frequently, and doing it well is an art.

The spam filter problem was also fun because it felt real. Took inputs from the SpamAssassin spam corpus. Used their code to crunch that text down to stemmed words, which we then coded into feature vectors. Push it through SVM and you end up with a system that classifies 98.6% of spam correctly! Which is not so great, I think 99.99% accuracy is minimal for a useful spam system. And even then you really want to measure that false positive rate carefully. But I had a whisper of an idea of how to apply this stuff to a real problem that is really solved with ML systems like what we are studying, and that was fun.

Application

Once again I find myself wanting to do this in Python. I really want a class which is “applied Machine Learning in Python”. I guess focussing on how to use Pandas and scikit-learn. Maybe someone has written that up already?

Machine learning: picking the right system

Week 6 of my machine learning course.

Lectures: applying machine learning, system design

This week’s lecture was about using machine learning algorithms well. Great series of notes, the kind of thing I’m really in this course for. Focus in particular was on figuring out how to improve the results of your learning system and then evaluate the result. You have a lot of options to tweak the model and learning: more properties, more data, different learning rates. Which should you use? He gave a few heuristics better than guessing.

The first thing is splitting data into training and test sets. Keep the evaluation test data separate so you have something to test with that the learning algorithm never saw. Good advice. He also points out that you often use tests on trained systems to pick your trained system; you can’t use that test data (“cross-validation data”) for final evaluation either, since your metalearning system was picked to do well on exactly that data.

The other thing was defining “high bias” models (underfit models, too few parameters) and “high variance” models (overfit models, too many parameters). These are important concepts! Then he gives a test to figure out if your learning system is one or the other, which is basically looking at error rates. Systems that train to low error but then test badly are high variance, overfit. Systems that train to high error and test badly are high bias, underfit. I get the intuition for this and look forward to apply it in the homework.

Finally we moved on to ways to build systems and evaluate them for success. Really nice exhortation to build a quick and dirty system first with the simplest features and data you can get your hands on. Start working with the problem and you’ll understand it better, then you can make an informed decision about what extra data you need. Also an interesting observation about the usefulness of very large datasets. Having an enormous amount of test data means you can use more complex models with less bias, and be confident that you won’t overfit your training data just for the sheer size of that training data set.

Ng defined precision and recall for measuring an algorithm’s correctness, also boiling those two numbers down into a single F-score for ease of comparison. Useful in particular for skewed datasets where you may be classifying something that’s only True 1 iin 1000 times.

Homework

This week’s homework has us loop back and implement the very first model we learned, linear regression, then test and evaluate it according to some of what we learned. I didn’t care much for the linear regression part, but the the hands-on application of learning systems and error measurements was great.

The first half of the homework was “implement linear regression learning with all the bells and whistles”. We’d not done that before, only logistic regression, so it was similar and yet different. Not too challenging really, a bit repetitive from previous work, but reinforcement is good.

The second half of the homework was “train a bunch of learning models and measure their error”. Specifically comparing the error on the training set vs. the training on our reserved cross-validation set, and graphing learning curves, etc. This is a sort of meta-machine learning, choosing the parameters for our machine learning system so that we get a well trained model.

We looked first a a truly linear model, trying to fit a straight line to data that’s roughly quadratic. Lots of errors. The learning curve shows us that adding more data points isn’t really going to help make this model more accurate, it is over-biased. So then we switched to an eighth order polynomial model but trained it without regularization. That fits the training data great but fails cross-validation, because it is high variance.

So finally we applied regularization in the learning model, the mechanism that encourages the learning to low-magnitude constants for the polynomials. The encouragement strength is governed by the value lambda. So train lots of models with low lambda and high lambda and see which lambda is best. Lambda = 3, that’s best! At least for this problem.

Conclusion

I’m really itching to apply this stuff to my own problems now, to make it real. But I’ve got to solve two problems at once to do that. I need confidence in my own code without the safety net of homework problems with calculated correct answers. And I really want to redo this work in Python, to get out of the weird Octave world. Taking both leaps at once is foolish. I should either bring a problem of my own into Octave once to apply my proven code to new data. Or else port the homework to Python first and verify I still get the right answers to prove my new code. I tried the latter already and got frustrated, should try the former.

Machine learning: backpropagation shitshow

Frustrating week in the machine learning course. We learned how to implement backpropagation in neural networks. Or at least we pretended to.

Lectures

Ng’s lectures skate over the math pretty fast and there’s like 3 separate snippets reassuring “if you don’t understand this don’t worry, it’s hard and I don’t always remember either lol!”. I think this course tried to walk the line between either really doing the math or not and fell in a gap in the middle. I’d prefer to have skipped the math entirely. I kind of did, honestly, and fell back on my “how do I fake this” survival skills from the few college math classes I didn’t like.

The useful part is Ng also emphasizes the intuitions and mechanical logic of what backpropagation is doing, and that I think I understand. Forward propagation is creating a mesh of hidden layers that map inputs to outputs with hidden weights. Backprop starts at the output layer and observes the error, how far the network’s output is off from expected output. It then tries to apportion that error to the previous layer’s nodes by spreading the error backwards, weighted by the activation parameters. And so error is propagated backwards through each layer and in the end you have some idea how much each activation weight contributed to the mistakes the output made.

More concretely, backpropagation gives you a cost function J and its partial derivatives where each activation weight in the neural network gets a fair share of blame for the error. With cost function in hand you can run a function optimizer to find the activation weights that minimize the cost. (One fact Ng skated over; this cost function is no longer convex, which means the optimizer might get stuck in local minima. He mentions the problem and says not to worry about it in practice. Um, ok).

One fun thing in optimizing neural networks: if you start one out with node having constant activation weights (say, all zero) then all the nodes look the same and error is apportioned equally, so nodes don’t train separately. To break this degenerate symmetry you start training the network with randomized weights. Reminds me of the Big Bang and the lumpy cosmic microwave background.

Homework

The homework programming exercises are the only way I feel like I’m really learning anything. They’re reasonably good.

However, this week’s lecture + assignment clearly specify “don’t try to vectorize over the 5000 training inputs, just use a loop”. But then the tutorial that’s my real lifeline to implementing these assignments is a vectorized implementation! Which is it, teacher? I’ve mostly preferred implementing the vectorized versions, both because it’s faster to run and because it’s a closer match to the math equations from the lectures. It’s sure nice avoiding writing lots of for loops. But the teaching materials really need to decide to either vectorize everything or not, this stuff in conflict is a mess that I imagine loses a lot of students.

While I’ve been doing vectorized implementations, really I’d prefer to not vectorize over the training inputs. Write all my code to process one training example at a time. That’s the way a lot of stuff works in the real world anyway.

Anyway I stumbled through the notes and managed to implement backpropagation. I think I understand how it works too, although I just accept the provided cost function and derivatives as gospel truth rather than having done the derivation myself. And in the end I’ve trained my own neural network to recognize handwritten digits. Yay!

One fun thing in the homework is they visualize the hidden activation layer. That layer has 25 nodes. This image shows for each of those nodes, how much it weights the value of any particular pixel. If you squint you can convince yourself this hidden layer is doing some feature detection, like the bright vertical line in row 2, column 3. Also clearly the corners of the image are not useful to anything.

Screen Shot 2015-08-16 at 5.59.57 PM

I thought the technique of gradient checking was interesting. Backpropagation (and other cost functions) require you analytically divine the partial derivatives of your cost function, or in my case copy them blindly from the lecture notes, and then implement this in code. It’s pretty easy to have a bug. And apparently subtle errors in the gradient function result in neural networks that sort of converge but just not very well, so you might not notice the bug. Ng suggests as a backup check that you also numerically approximate the derivatives, by evaluating the cost function an epsilon away from some value and thereby calculate the gradient. Then check this numeric approximation is close to your analytically derived implementation. I like the idea, it’s a sort of interactive debugging technique. Also begs the question why bother with the analytic derivative at all, why not just use a numerical approximation? Because it’s expensive to calculate the numeric approximation, that’s why. And also it’s less accurate.

I also appreciate the role regularization plays. Apparently it’s not hard to overfit a neural network to input data. Ie: it is 100% accurate on your input data but then its overfit and may not work well on real data. The lambda regularization parameter is a damping applied to the gradients to encourage all the parameters to be small numbers, which apparently is the way you keep a neural network honest.

Here’s a picture of the hidden layer’s activations for an overfit model. Notice how there’s no obvious feature detection? At least, there’s no obvious vertical stroke detector like there was in the previous model. The accuracy of this model is 100%, but it may be less useful when applied to data it wasn’t trained on.

Screen Shot 2015-08-16 at 6.01.36 PM

That’s the kind of machine learning trap I’m taking this course to learn more about. I sort of understand the math behind why lambda works, but I can see it would take a lot of experience applying this stuff to real problems to really get a feel for how to set it right.

In the end I really hope to never, ever implement a neural network again in my life. I do honestly just want to use someone else’s neural network library. I do feel some sense of accomplishment having built my own though. And my real goal here is to understand a little of what’s going on inside the black box so I can use it better. I gather neural networks have a lot of subtle traps.

I still have to go and apply this stuff to real data I really care about. I started trying to do that a couple of weeks ago, in Python, but got frustrated trying to learn Pandas and scikit-learn and iPython notebooks all at once.

Machine learning: Neural networks introduction

Week four of my Coursera machine learning course was a breezy introduction to neural networks. The lecture videos were very high level but did a good job introducing the concept. The part I hadn’t understood before was how regression techniques are really best suited for linear prediction models, that building Nth order polynomials out of M features leads to O(N*M) work and badness. I also hadn’t really understood that neural networks are just a series of logistic regressions. The input variables are mapped through a logistic model to an intermediate hidden layer (of some chosen number of features), then the hidden layer is mapped again through a second logistic model to yield output variables. However the lecture stopped before we got to backpropagation, so for this week the method of training a neural network is still a mystery.

Logistic regression applied to OCR

The homework is a bit behind and out of sync with the lecture notes. The bulk of the work in the homework was still doing logistic regression, last week’s lecture concept. The hardest part was figuring out how to vectorize the naive loop implementation of the regularized logistic regression cost function we did last week. But I’d already vectorized it so I could just copy my solution from last week, gold star!

The more fun part was actually applying one of these learned models to do something useful with real data; OCR classification of handwritten numbers. The input was 5000 images, 20x20 greyscale pixel arrays, along with their classification (“this squiggle is the number 7”). Our job was to build a multiclass classifier to do the OCR, to predict a digit. So we took the regularized logistic regression cost function we just implemented and used fmincg() to search for the best parameters to match the data. The resulting output vector (theta) is our prediction model. Then we applied that learned model to classify input data. So I’ve now built a linear regression OCR system for handwritten numbers! The final system predicted the input set with 95% accuracy. The final model is quite large; 4010 separate integers. 401 weights for predicting each digit from 0–9, or one weight per pixel plus a constant term. Not exactly parsimony.

One neat thing about multiclass models is they don’t just output a predicted clas (“the number 7”), they also output a vector of probabilities for each possible value: “probability this image is the number 1, probability it is the number 2, ...”. We crush those probabilities down to a single “this input is probably an image of the number 7”. But something to remember for later; machine learning models not only can return a prediction, but a confidence in that prediction. Or some ambiguity, I believe the math works such that a single image might have a 90% probability of being the number 7 and an 80% probability of being the number 9 (for a particularly ambiguous squiggle.)

Neural network forward propagation

The last part of the homework was implementing a basic neural network. Or rather the application of one, the forward propagation that maps the input data through the layers and gives outputs. We were handed parameters that had already been trained, so really this was just an exercise in “can you code up forward propagation?” Useful to do that myself though. In particular I had to puzzle out that the hidden layer consists of 25 nodes. So the final classifier is basically two steps. Logistic regression to map 400 pixels to 25 hidden nodes. And then a second logistic regression to map 25 hidden nodes to 10 probabilities. The central mystery of neural networks is what those “hidden nodes” really mean. And we have Deep Dream to thank for a lovely visualized expression of hidden states in a different kind of machine learning image processing system.

Metacomments

I almost gave up this week. Ran into a bunch of weird technical problems. By far the biggest one was me putting the line “print size(X)” in my code as a debugging aid and then forgetting about it. And suddenly my octave program is complaining about fig2dev missing and I’m down a rabbit hole of Homebrew installs trying to figure out what the hell is wrong. Turns out “print” means print, as in paper, and I needed “printf”. Derp.

I am also doing a lot of stumbling around and shallow learning. Like I know I need to combine the matrix X with the vector theta somehow but forgot which way. Rather than puzzle that out from mathematical principles, I just inspect and see X is 5000x400 and theta is 1x400, and I need to multiply them somehow, so the only sensible math is X*theta’ or theta*X’. So try one out and see if the homework oracle tells me I got the right answer, and call it a day. (Writing this out I realized I picked the wrong one of the two, which is why I keep having to transpose everything. oops.) Anyway this doesn’t feel like learning so much as just bashing about with the only thing that will pass a type checker. I keep telling myself I’m absorbing something though, and my real goal here is just to understand enough about what’s going on that I can use other people’s machine learning systems later.

I do wish the homework assignments had more interactive help. In particular a bit more hand-holding about how to run the code you write, understand what it’s doing, and test it against known good results. In desperation I started looking at the submit.m internals just to see what test cases the homework oracle was using. I don’t get to see the right outputs that way (they’re hidden on the server), but at least I have some reasonable test inputs I can look at.

The only actual course lecture notes are a wiki page. The wiki content is pretty good. But it requires a login to even read the pages! And Coursera’s wiki is broken somehow so you have to log in about once an hour, makes me very cranky.

Machine learning: Logistic regression

Just finished week 3 of Andrew Ng’s machine learning course on Coursera. I’m going to try to blog each week summarizing what I learned.

This week’s topic is logistic regression; predicting discrete outcomes like “success or failure” from numeric data inputs. Ie: “our diagnostics measure these 4 numbers for a tumor. Is it cancerous or benign?” Turns out logistic regression is basically just linear regression where the output set is restricted to the interval [0, 1]. Normal linear regression gives all real numbers on output, so you pass that through the sigmoid curve to bound the result to [0, 1]. That number is effectively “the probability the output is 0”, you can then threshold it at 0.5 to map it to a strictly binary “success or failure” output. There’s a bunch of math then to define the cost function and the partial derivatives of the cost function which you can then use with an optimization algorithm like gradient descent.

Logistic regression only classifies data into two classes. If you want N classes you do logistic prediction many times, ie: “is it A or not A? is it B or not B? is it C or not C?” and then pick the class ABC with the highest probability.

The predictor you get from the logistic regression is best understood in terms of a decision boundary, a drawing of the threshold that tips an input from success to failure. My final homework assignment was learning this threshold boundary to separate plusses from squares where the input data is 2 dimensional. The green line is the learned threshold boundary, some sixth order polynomial the magic optimizer found for me.

Screen Shot 2015-08-02 at 11.02.08 AM

Thankfully the course moved on a bit from math into “use the black box” by introducing fminunc, a black-box minimizer provided by Matlab/Octave. All it needs is the cost function and its partial derivatives and it does who-knows-what to find the minimum. Frankly I wish the class spent more time on how to use fminunc well and less time deriving the gradient descent solutions that I’ll never use again. But gradient descent is a nice simple optimizer and it is good to know how at least one works.

This week also introduced the concept of overfitting, of specializing your predictor too tightly to the data. Regularization was the solution provided for overfitting; basically biasing the cost function to prefer small values of theta, the learning model parameters we’re optimizing. Ng doesn’t really explain why small values of theta are “better” other than presenting some intuition that a theta_i of 0 means the parameter is fully ignored and a theta_i of 1000 means it’s way too overemphasized. The regularization parameter lambda is picked out of a hat much like the learning rate alpha is also picked for gradient descent.

Along the way I learned how to define anonymous functions in Octave which then gives you a really easy way to curry a partial function application (in this case, currying X and y into my costFunction so that fminunc only works on the parameter t.

fminunc(@(t)(costFunction(t, X, y)), initial_theta, options)

I continue to be amazed that I type vector equations into Octave and they Just Work on first try, despite my being rusty on linear algebra not to mention matrix programming languages. I’m kind of just accepting that if the homework grader says I got it right I’m done.

Some metacomments about the course... I read something somewhere that characterized this as an advanced undergraduate class, maybe sophomore or junior level. That feels about right and explains why it seems a little too easy. But easy in the right ways for me, I really don’t want to do the math derivations. Also I discovered a lot of previous students’ homework checked in on GitHub. Cheating would be stupid, who would I cheat but myself? But it’s nice to be able to look what other students did. Helped me verify arrayfun() was really the right thing to apply a scalar function to a matrix, for instance.

Now I feel like I’ve studied enough machine learning to apply it to a problem I care about. I intend to look at League of Legends match results, to see whether I can predict a game is a win or a loss based on match performance. The simplest thing is to look at end of game stats like kills or gold earned. Of course end of game I already know for sure if it was a win or a loss, but I’m thinking I can read the learned model parameters out to see how significant a contribution those inputs like kills are to whether a team wins. Alternately I can get ahold of some mid-game stats like “gold earned after 20 minutes”, whether that results in a win or a loss is a bit more of a legitimate prediction problem.

Multivariate linear regression, gradient descent

I’m taking Andrew Ng’s online Machine Learning course on Coursera. First time doing a MOOC for real, and on the fence about the learning style, but it is nice to have an organized class with weekly assignments.

Two weeks have gone by. The two weeks together sort of consist of one learning unit. You learn how to do linear regressions for datasets. What does that have to do with machine learning? Well, a linear regression model is a very simple form of predictive modelling for a dataset. “I fit this straight line to my 100 data points, then can use that line to predict values for arbitrary other inputs”.

The course is a bit schizophrenic about being math vs. computer programming. Ng’s lecture notes are entirely in terms of linear algebra, building up to result equations like

Screen Shot 2015-07-26 at 6.55.26 PM

(WTF? X is a matrix of your input feature set; m rows of n features each. y is an m row vector of expected feature outputs. Theta is an m row vector that is the coefficients of your linear regression prediction model. Alpha is the “learning rate”, a number that’s picked essentially by intuition. The assignment := is shorthand for iteration; we keep iteratively improving the theta vector until it converges.)

I hate linear algebra. Always did, ever since I was 19 years old and it was my 8AM class. It was the only math class I nearly failed, then crammed super hard the last week and got an A. Then promptly forgot it all. Happily, this class is also a programming class, and the actual exercises are “implement this function in Octave / Matlab”. So I get to turn that confusing math into simple code:

Screen Shot 2015-07-26 at 7.04.07 PM

While I’m a good programmer it’s been many years since I used a matrix programming language like Maple/Matlab/Octave/R. So getting to that function was hard-worn. I ended up implementing that by following Ng’s lecture progression. He starts with a simple single variable linear regression. I coded that using lots of loops so all the actual arithmetic was scalar operations. Then I tediously hand-translated all those loops into vector forms and generalized it to multivariable inputs. Good learning exercise both to remind me how linear algebra works and to learn the funky vagaries of Octave/Matlab execution. (TIL automatic broadcasting). It was gratifying to see how much faster the code ran in vector form!

Of course the funny thing about doing gradient descent for linear regression is that there’s a closed-form analytic solution. No iterative hillclimbing required, just use the equation and you’re done. But it’s nice to teach the optimization solution first because you can then apply gradient descent to all sorts of more complex functions which don’t have analytic solutions. If I end up getting to do genetic algorithms again I’m gonna be thrilled.

In the end I feel pretty proud of myself for completing week 2, doing all the optional extra work, and understanding it all. My long term goal here is just to understand enough about machine learning algorithms that I can stop worrying about how they are implemented, just bash about with someone else’s software libraries applied to my data. But it’s helpful to understand what’s going on under the hood.

Installing Octave on Mavericks

I’m using Octave for a machine learning course I’m taking online. It’s an open source MatLab clone, and true to open source it is ugly, awkward, and doesn’t install easily. Of course it’s also great free software that I’m grateful for, but that doesn’t make it easier to install.

There’s a binary version of Octave 3.8.0 that is an official installer. But the command line interface doesn’t seem able to plot graphics of any kind. The GUI version can, but there’s so many other bugs in the GUI I want the command line to work. Specifically for a program like this to run:

t = [0:0.2:2*pi];
y=sin(t);
plot(t,y);

Homebrew has a formula for Octave 3.8.2 with a zillion dependencies and options. In theory “brew install octave” should work but in practice it’s not sufficient. Here’s something approximating what worked for me, based mostly on these notes

  1. brew install Caskroom/cask/aquaterm
    Some funky graphics system that allows plots to be drawn without X11
  2. brew install gnuplot --with-x11 --with-aquaterm
    Install GNUPlot using various graphics systems. The octave formula doesn’t seem to select these reliably.
  3. brew install octave --without-docs --without-gui --without-java
    Building the docs induces TeX to be installed. No thanks. I have no idea what optional Java things Octave depends on but I’d rather not bother. And I don’t want the experimental GUI, so skip that too.
  4. brew link --overwrite gcc
    Octave’s formula is designed to be built with gcc and gcc’s Fortran. It installs gcc (which takes over an hour to compile!) but I had a different version of gfortran installed previously, which caused my Octave build to fail. The --overwrite causes the gcc package to override gfortran.
  5. brew install ghostscript
    I had to run this three times by hand because the download server was broken.

This took about 3 hours total. Once completed, my simple 2 line plot program works. Yay!

One added complication; you can select different graphics systems in Octave at runtime. The brew info even helpfully tells you how:

setenv('GNUTERM','qt') # Default graphics terminal with Octave GUI
setenv('GNUTERM','x11') # Requires XQuartz; install gnuplot --with-x
setenv('GNUTERM','wxt') # wxWidgets/pango; install gnuplot --wx
setenv('GNUTERM','aqua') # Requires AquaTerm; install gnuplot --with-aquaterm

If I don’t set this at all, I seem to be getting aqua. And it works. I can also use the x11 graphics system and it works as well.

That IPython web browser integration sure looks like a smart idea now doesn’t it?