<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Night thoughts]]></title><description><![CDATA[Unfiltered late-night thoughts on software engineering, system architecture, and technical problem-solving. Brain dumps, code logs, and reflections from the quiet hours.]]></description><link>https://nightthoughts.me</link><image><url>https://cdn.hashnode.com/uploads/logos/6a92730f9a9aa7f72e74fdf4/30bf9d05-14bc-4b25-99d8-950183709c80.png</url><title>Night thoughts</title><link>https://nightthoughts.me</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 01:11:27 GMT</lastBuildDate><atom:link href="https://nightthoughts.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[OpenCode Desktop: Build a Low-Cost or Best-Experience Multi-Model Coding Harness]]></title><description><![CDATA[Set up OpenCode Desktop as a multi-model coding harness with two tested packages: low-cost open-weight models, or Claude with failover. No 5-hour window.]]></description><link>https://nightthoughts.me/opencode-desktop-build-a-low-cost-or-best-experience-multi-model-coding-harness</link><guid isPermaLink="true">https://nightthoughts.me/opencode-desktop-build-a-low-cost-or-best-experience-multi-model-coding-harness</guid><category><![CDATA[opencode]]></category><category><![CDATA[ai-harness]]></category><category><![CDATA[model routing]]></category><category><![CDATA[failover]]></category><category><![CDATA[open-weight-models]]></category><category><![CDATA[openrouter]]></category><category><![CDATA[claude]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Thu, 05 Nov 2026 23:20:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/d112c854-8b60-4155-b9b7-0b8f2cbb0a17.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Claude Code is a good example of what a coding harness can be. Its advantage is not only the model. It is the system around it: tools, context management, permissions, recovery, and feedback loops. The limitation is that all of this lives inside <strong>one product ecosystem</strong>. You inherit its model menu, routing decisions, limits, and roadmap. Other vendors ship comparable harnesses; I have not used them enough to judge them, so this article does not.</p>
<p>Meanwhile the model market has stopped being a one-vendor story. Open-weight models from several labs are now good enough for a large share of everyday coding work, at a fraction of frontier prices, and they keep improving. A harness that can only use one vendor's menu cannot take advantage of that.</p>
<p>This guide takes a different trade-off: keep a good desktop harness experience, but pick the models from across the market instead of from one provider's subset. Each request goes to a suitable model, and a failed provider does not end the task. By the end you will have <strong>OpenCode Desktop</strong> configured with one of two packages.</p>
<p><strong>These are packages, not lists of models.</strong> Each one is a set of models chosen to work together as of November 2026: an orchestrator that actually delegates, tiers sized for their jobs, and backups that can read the same inputs and hold the same output. Swapping one model can quietly break that fit, so section 3 explains the rules I used to choose them, and you can apply them when the market moves. It will move: treat the model names as today's answer and the selection rules as the lasting part.</p>
<p><strong>Cheap</strong> uses open-weight models from three labs (GLM, DeepSeek, and Qwen), through two providers: DeepSeek directly, and OpenRouter. You pay per token, at a fraction of Best's price.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/2d8def52-2abb-4f39-8c92-bd61c186b84b.png" alt="The Cheap package, with DeepSeek direct and OpenRouter as columns. GLM-5.3-Flash on OpenRouter orchestrates, with DeepSeek Flash as its backup. DeepSeek Flash from DeepSeek directly is the fast tier, with DeepSeek V4.1 Flash on OpenRouter as backup. Qwen 3.6 and Qwen 3.8 on OpenRouter are the medium and heavy tiers, each with DeepSeek Flash as the first backup and GLM-5.3-Flash as the second" /></p>
<p><em>Cheap: which provider serves each model. Filled boxes run first; dashed boxes are the backups the harness switches to, in numbered order.</em></p>
<p><strong>Best Experience</strong> uses frontier models for each tier. Today those are Claude models, called directly from Anthropic, with the same models on OpenRouter as the backup. If another vendor's models overtake them, the package changes, not the harness.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/7c4714bb-059a-4084-8f8e-e6a970323f84.png" alt="The Best Experience package, with Anthropic direct and OpenRouter as columns. Claude Sonnet 5.5 orchestrates, and Haiku, Sonnet and Opus 5.5 are the fast, medium and heavy tiers, all from Anthropic directly, each with the same Claude model on OpenRouter as its backup" /></p>
<p><em>Best Experience: each tier on Anthropic directly, with the same model on OpenRouter as the backup.</em></p>
<p><strong>There is no 5-hour window.</strong> Claude's Pro and Max subscriptions have a five-hour session limit and a weekly limit. Both packages here pay per token through APIs instead, and none of the three providers uses a session or weekly window. That does not mean there are no limits. They are different ones, covered in section 11: per-minute rate limits, a monthly spend cap on Anthropic's API, your prepaid balance, and concurrency limits on DeepSeek. Failover covers a per-minute 429. Nothing covers an empty balance.</p>
<h2>What held up</h2>
<p>I tested both setups in the Desktop app, including deliberate provider failures. This is a working harness with known gaps, not a finished one.</p>
<table>
<thead>
<tr>
<th></th>
<th>Best</th>
<th>Cheap</th>
</tr>
</thead>
<tbody><tr>
<td>Images and PDFs</td>
<td>Yes</td>
<td>Yes, with PDFs converted locally first</td>
</tr>
<tr>
<td>Routing work to the right tier</td>
<td>Yes</td>
<td>Yes, once I added a rule and made GLM the orchestrator</td>
</tr>
<tr>
<td>Surviving a 429, a 503 from a test provider (Best only), or a stalled provider</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Project memory across sessions</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Compaction keeping the objective and next action</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</tbody></table>
<p>Three things went differently from what I planned:</p>
<ul>
<li><strong>Free models did not work as a foundation.</strong> My first Cheap setup used OpenCode's free models. They returned a free-usage error after very little use, so I replaced them with low-cost paid models.</li>
<li><strong>Semantic memory did not make the cut.</strong> It worked when the agent had the tool, but the tool was not reliably there. I dropped it.</li>
<li><strong>The first Cheap orchestrator ignored routing.</strong> Section 7 explains why, and the fix.</li>
</ul>
<p>Section 12 has the results, and the appendix has a receipt for every test: what it checks, the exact scenario, and what counted as a pass. Model IDs and prices were checked on November 5, 2026, so treat them as a dated snapshot.</p>
<h2>1. What makes a coding harness good</h2>
<p>A model is one component. A dependable harness has to preserve the task, the workspace, and your control when the model or provider misbehaves.</p>
<table>
<thead>
<tr>
<th>Theme</th>
<th>What good looks like</th>
</tr>
</thead>
<tbody><tr>
<td>Context and memory</td>
<td>Resume exact work; project facts survive sessions and model changes</td>
</tr>
<tr>
<td>Tools and permissions</td>
<td>The agent has only the authority and data exposure you accept</td>
</tr>
<tr>
<td>Recovery</td>
<td>A bad turn can be reversed without hiding side effects</td>
</tr>
<tr>
<td>Verification</td>
<td>A fluent answer is not accepted as working code</td>
</tr>
<tr>
<td>Routing and failover</td>
<td>The right model per task; the task survives a provider failure</td>
</tr>
<tr>
<td>Observability and cost</td>
<td>You can see what ran, what it cost, and where it failed</td>
</tr>
</tbody></table>
<p>Two features are often confused:</p>
<ul>
<li><strong>Routing</strong> chooses who should handle a task.</li>
<li><strong>Failover</strong> keeps the current task alive when the chosen model cannot complete a request.</li>
</ul>
<p>Adding several models to a picker provides neither. I have covered <a href="https://nightthoughts.me/what-is-llm-routing-a-simple-guide-to-saving-money-on-ai">what LLM routing is</a>, <a href="https://nightthoughts.me/how-to-build-an-intelligent-router-for-nvidia-and-ollama-with-litellm-jev-and-memori-on-a-mac-mini-part-2">building a router by hand</a>, and <a href="https://nightthoughts.me/the-harness-is-the-agent-inside-google-s-harness">why the harness can matter as much as the model</a> in earlier posts, so I will not repeat them here.</p>
<h2>2. Why OpenCode</h2>
<p>OpenCode gives you the parts that stay the same whichever model you use: sessions, attachments, ordered permission rules, compaction, snapshots, and many providers behind one interface.</p>
<p>Routing and failover come from two third-party plugins:</p>
<ul>
<li><code>opencode-model-router@2.9.1</code> for tier-based routing.</li>
<li><code>opencode-runtime-fallback@0.3.1</code> for retries, timeouts, and failover.</li>
</ul>
<p>So you are trusting third-party plugins for the two features this article cares most about. They held up in my tests, but pin the versions and retest when you upgrade.</p>
<h2>3. How I chose the models</h2>
<p>You can skip this section and use my choices. Read it if you want to swap a model, because a swap can quietly break a chain.</p>
<p>The models in each package were picked as a set, not one by one:</p>
<ul>
<li><strong>The orchestrator has to delegate.</strong> On Cheap, GLM-5.3-Flash is the orchestrator because it was the model that sent work to the right tier in my tests. Qwen 3.6 and DeepSeek Flash, run as orchestrators, did not delegate reliably (section 7).</li>
<li><strong>Each tier has a job.</strong> Fast is read-only exploration, medium is implementation, heavy is architecture and review. The router sends work by tier, so a tier's model needs the skills for that job, not the best general score.</li>
<li><strong>Each backup can stand in for its primary.</strong> It has to pass the hard filters below against the model it replaces. GLM's output cap in the Cheap config exists only so that DeepSeek passes that check.</li>
<li><strong>Routes are spread out.</strong> On Cheap, the fast tier runs on DeepSeek directly and the other tiers on OpenRouter, and each chain includes a model on the other route. A problem with one account or route then does not take down every tier.</li>
</ul>
<h3>Hard filters</h3>
<p>A candidate that fails any of these is out, as a primary or a backup.</p>
<table>
<thead>
<tr>
<th>Filter</th>
<th>Why it matters</th>
</tr>
</thead>
<tbody><tr>
<td>Context window at least the primary's</td>
<td>A smaller window truncates or forces earlier compaction mid-task</td>
</tr>
<tr>
<td>Output limit at least the primary's</td>
<td>Long edits and reasoning can be cut off</td>
</tr>
<tr>
<td>Same input types (image, PDF policy)</td>
<td>A backup that cannot read the attachment is a different workflow</td>
</tr>
<tr>
<td>Tool calling that works in this harness</td>
<td>Advertised is not the same as reliable</td>
</tr>
<tr>
<td>Reasoning support</td>
<td>Needed for the tier's job</td>
</tr>
<tr>
<td>Weight and data policy</td>
<td>Open-weight on Cheap; terms acceptable for your material</td>
</tr>
<tr>
<td>First backup on a different hosted route</td>
<td>A backup on the same path fails along with the primary</td>
</tr>
</tbody></table>
<p>Two examples of the filters doing their job:</p>
<ul>
<li><strong>Rejected on capability.</strong> <code>deepseek-v4-pro</code> costs more than <code>deepseek-flash</code> but takes no image input, so it is out. <code>deepseek-flash</code> lists images, and it read one correctly in my failover test.</li>
<li><strong>Passed, but weak on independence.</strong> Claude through OpenRouter passes every capability filter against Claude from Anthropic. But OpenRouter served my pings through Claude Platform on AWS, which Anthropic operates, so an Anthropic-side outage may reach both routes. This backup protects against account limits, rate limits, and route failures. It may not protect against a vendor-wide outage.</li>
</ul>
<h3>Soft ranking</h3>
<p>Among the models that pass:</p>
<ul>
<li><strong>Fallback similarity.</strong> Capability-compatible does not mean quality-equivalent. On Best the backup is the same model. On Cheap it is not, and I have not measured how much weaker a backup is on real tasks.</li>
<li><strong>Caching.</strong> Prices alone mislead. <code>deepseek-flash</code> used cached tokens in my runs. Qwen 3.6 through OpenRouter showed none, so its whole prompt was billed at the input price every time.</li>
<li><strong>Switch cost.</strong> See section 11 for the measured number.</li>
</ul>
<h2>4. Choose a setup</h2>
<table>
<thead>
<tr>
<th></th>
<th>Cheap</th>
<th>Best Experience</th>
</tr>
</thead>
<tbody><tr>
<td>Orchestrator</td>
<td>GLM-5.3-Flash</td>
<td>Claude Sonnet 5.5</td>
</tr>
<tr>
<td>Fast tier</td>
<td>DeepSeek Flash</td>
<td>Claude Haiku 5.5</td>
</tr>
<tr>
<td>Medium tier</td>
<td>Qwen 3.6</td>
<td>Claude Sonnet 5.5</td>
</tr>
<tr>
<td>Heavy tier</td>
<td>Qwen 3.8</td>
<td>Claude Opus 5.5</td>
</tr>
<tr>
<td>Accounts</td>
<td>OpenRouter, DeepSeek</td>
<td>Anthropic, OpenRouter</td>
</tr>
<tr>
<td>PDFs</td>
<td>Convert locally</td>
<td>Native</td>
</tr>
<tr>
<td>Illustrative cost per work unit (section 11)</td>
<td>About $3.49</td>
<td>About $19.25</td>
</tr>
<tr>
<td>Main trade-off</td>
<td>Weaker evidence on real coding quality, and it needs a routing rule</td>
<td>Costs about five times as much, and the backup may share an outage with the primary</td>
</tr>
</tbody></table>
<p>Choose Best if you want the option with the most evidence behind it. Choose Cheap if price matters more, and check its edits closely until you trust it on your own work.</p>
<h2>5. Prerequisites</h2>
<p>Most of my early failures came from this section, not from the harness. Every step below is a command you can paste into a terminal, on macOS or Linux.</p>
<p><strong>I tested on macOS only.</strong> The Linux commands use the official Linux packages and the same config paths, but I have not run them on Linux.</p>
<h3>Accounts and credit</h3>
<table>
<thead>
<tr>
<th>Package</th>
<th>You need</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Both</td>
<td>Spend limits, with auto-recharge off</td>
<td>Set them before the first call</td>
</tr>
<tr>
<td>Best</td>
<td>Anthropic <strong>API credit</strong>, on the organization that owns your key</td>
<td>Check the balance on the Console's billing page and compare organization IDs. Credit on another organization does not fund this key, and a Claude subscription is billed separately</td>
</tr>
<tr>
<td>Best</td>
<td>OpenRouter credit</td>
<td>OpenCode requested 128,000 output tokens on the Claude routes, and OpenRouter refused the call when the balance could not cover that, even for a one-word reply. For Opus 5.5 that is about $2.56, so keep more than that on the account</td>
</tr>
<tr>
<td>Cheap</td>
<td>OpenRouter credit</td>
<td>OpenCode requested 256,000 output tokens for GLM. At its output price that is about $0.13, so keep a few dollars there</td>
</tr>
<tr>
<td>Cheap</td>
<td>DeepSeek API credit</td>
<td>My balance was $0.00 and the account reported itself unavailable. I added $5, and testing used a few cents</td>
</tr>
</tbody></table>
<p><strong>Do not plan on OpenCode's free models as your main route.</strong> With no OpenCode Console account, all three I tried returned <code>429 Free usage limit reached</code> after very little use, with a retry time of about 9.6 hours. The limit is not documented, so yours may differ.</p>
<h3>Tools</h3>
<p>You need Git, Node.js 22 or newer (the router plugin requires it), and, for Cheap, <code>poppler</code> for the PDF steps in section 10.</p>
<p>macOS, with <a href="https://brew.sh">Homebrew</a>:</p>
<pre><code class="language-bash">brew install git node poppler
</code></pre>
<p>Debian or Ubuntu:</p>
<pre><code class="language-bash">sudo apt install git poppler-utils
</code></pre>
<p>Fedora:</p>
<pre><code class="language-bash">sudo dnf install git poppler-utils
</code></pre>
<p>Distribution Node.js packages are often older than 22, so on Linux install it from <a href="https://nodejs.org/en/download">nodejs.org</a> or with a version manager, then check:</p>
<pre><code class="language-bash">node --version
</code></pre>
<h3>A real project folder</h3>
<p>Undo needs a Git repository, so open OpenCode on a project that is one. Check the path shown under the project name on the new-session screen: mine once pointed at my whole home folder, which is not where you want an agent working.</p>
<h2>6. Install</h2>
<p><strong>1. Install OpenCode Desktop.</strong> I tested 2.2.5. On macOS:</p>
<pre><code class="language-bash">brew install --cask opencode-desktop
</code></pre>
<p>On Debian or Ubuntu (x64):</p>
<pre><code class="language-bash">curl -fLo /tmp/opencode-desktop.deb https://opencode.ai/files/bin/2.2.5/opencode-desktop-linux-amd64.deb &amp;&amp; sudo apt install /tmp/opencode-desktop.deb
</code></pre>
<p>On Fedora (x64):</p>
<pre><code class="language-bash">curl -fLo /tmp/opencode-desktop.rpm https://opencode.ai/files/bin/2.2.5/opencode-desktop-linux-x86_64.rpm &amp;&amp; sudo dnf install /tmp/opencode-desktop.rpm
</code></pre>
<p>The Homebrew cask installs the latest version and updates itself, so it may be newer than the one I tested. The Linux commands pin 2.2.5. Other downloads are on the <a href="https://opencode.ai/download">OpenCode download page</a>.</p>
<p><strong>2. Close OpenCode Desktop, and back up your config.</strong> The next section overwrites files in <code>~/.config/opencode</code>, the config folder on both macOS and Linux. This copies the whole folder, if it exists, to a dated backup:</p>
<pre><code class="language-bash">[ -d ~/.config/opencode ] &amp;&amp; cp -R ~/.config/opencode ~/.config/opencode.backup-$(date +%Y%m%d-%H%M%S)
</code></pre>
<p><strong>3. Write the config</strong> for one package, using the command in section 7.</p>
<p><strong>4. Open the Desktop and connect your providers.</strong> Run <strong>Connect an integration</strong> from the command palette (<code>⌘⇧P</code> on macOS; on Linux probably <code>Ctrl+Shift+P</code>, which I have not checked) for each provider in your package: Anthropic and OpenRouter for Best, OpenRouter and DeepSeek for Cheap. Never put real keys in a config file or a Git repository.</p>
<p>In my own runs the keys came from environment variables, so I did not test this connect flow. An app started from the Dock or an app launcher may not see variables exported in your shell profile, which is why I recommend connecting instead.</p>
<p><strong>5. Quit and reopen the Desktop.</strong> OpenCode installs the two plugins named in the config when it starts, in the background, so the first launch may not have them loaded yet. The second launch should.</p>
<p><strong>6. Switch on hidden models (Cheap).</strong> The picker showed only 43 of OpenRouter's models. In the model picker, choose <strong>Manage models</strong> and enable <code>Qwen3.6 35B-A3B</code>, <code>Qwen3.8 27B</code>, <code>DeepSeek V4.1 Flash</code> and <code>GLM-5.3-Flash</code>.</p>
<h2>7. Configure</h2>
<p>Each package is four files in <code>~/.config/opencode/</code>, and each file has its own command below. Paste them one at a time, in order. Each command replaces any earlier version of its file.</p>
<p>First, if an <code>opencode.json</code> is there, for example one written by <code>opencode plugin add</code>, rename it so that only one config file is loaded:</p>
<pre><code class="language-bash">[ -f ~/.config/opencode/opencode.json ] &amp;&amp; mv ~/.config/opencode/opencode.json ~/.config/opencode/opencode.json.old
</code></pre>
<p>Both packages use the same permission rules, at the end of <code>opencode.jsonc</code>. The last matching rule wins. In testing, <code>git push</code> and <code>rm -rf</code> were refused with no prompt, and a <code>.env</code> read asked first, which is OpenCode's default. These rules are guardrails, <strong>not an operating-system sandbox</strong>. Use a container for untrusted code.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/dc03d7e0-6bce-47de-bca6-5917c52bfc40.png" alt="A Permission required prompt for reading a .env file, with Deny, Allow always, and Allow once buttons" /></p>
<p><em>A <code>.env</code> read stops and asks, even though nothing in my rules mentions it.</em></p>
<h3>Best Experience</h3>
<p><strong>1. <code>opencode.jsonc</code></strong>, the main config: the orchestrator model, the plugins, compaction and the permission rules.</p>
<pre><code class="language-bash">mkdir -p ~/.config/opencode &amp;&amp; cat &gt; ~/.config/opencode/opencode.jsonc &lt;&lt;'EOF'
{
  "$schema": "https://opencode.ai/config.json",

  "model": "anthropic/claude-sonnet-5-5",

  "plugins": [
    "opencode-model-router@2.9.1",
    "opencode-runtime-fallback@0.3.1"
  ],

  "default_agent": "build",

  "compaction": {
    "auto": true,
    "keep": { "tokens": 20000 },
    "buffer": "20%"
  },

  "agents": {
    "title": { "model": "anthropic/claude-haiku-5-5" }
  },

  // Ordered rules: the last matching rule wins.
  "permissions": [
    { "action": "shell", "resource": "*", "effect": "ask" },
    { "action": "shell", "resource": "git status *", "effect": "allow" },
    { "action": "shell", "resource": "git diff *", "effect": "allow" },
    { "action": "shell", "resource": "git push *", "effect": "deny" },
    { "action": "shell", "resource": "git reset --hard *", "effect": "deny" },
    { "action": "shell", "resource": "rm -rf *", "effect": "deny" }
  ]
}
EOF
</code></pre>
<p><strong>2. <code>opencode-model-router.overrides.jsonc</code></strong>, the router's tiers: which model handles fast, medium and heavy work.</p>
<pre><code class="language-bash">cat &gt; ~/.config/opencode/opencode-model-router.overrides.jsonc &lt;&lt;'EOF'
{
  "activePreset": "best-frontier",
  "activeMode": "normal",

  "presets": {
    "best-frontier": {
      "fast":   { "readOnly": true, "model": "anthropic/claude-haiku-5-5",
                  "costRatio": 1,  "steps": 30,  "description": "Exploration and bounded lookup" },
      "medium": { "model": "anthropic/claude-sonnet-5-5",
                  "costRatio": 20, "steps": 60,  "description": "Implementation and verification" },
      "heavy":  { "model": "anthropic/claude-opus-5-5",
                  "costRatio": 40, "steps": 100, "description": "Architecture and review" }
    }
  }
}
EOF
</code></pre>
<p><strong>3. <code>opencode-fallback.jsonc</code></strong>, the backup chain for each agent. Each tier falls back to the same Claude model on OpenRouter.</p>
<pre><code class="language-bash">cat &gt; ~/.config/opencode/opencode-fallback.jsonc &lt;&lt;'EOF'
{
  "timeout_seconds": 45,
  "notify_on_fallback": true,
  "agents": {
    "build":      { "fallback_models": ["openrouter/anthropic/claude-sonnet-5.5"] },
    "plan":       { "fallback_models": ["openrouter/anthropic/claude-sonnet-5.5"] },
    "fast":       { "fallback_models": ["openrouter/anthropic/claude-haiku-5.5"] },
    "medium":     { "fallback_models": ["openrouter/anthropic/claude-sonnet-5.5"] },
    "heavy":      { "fallback_models": ["openrouter/anthropic/claude-opus-5.5"] },
    "compaction": { "fallback_models": ["openrouter/anthropic/claude-sonnet-5.5"] }
  }
}
EOF
</code></pre>
<p><strong>4. <code>AGENTS.md</code></strong>, only if you used Cheap before. This removes Cheap's orchestrator rule from your global <code>AGENTS.md</code> and leaves the rest of the file alone.</p>
<pre><code class="language-bash">[ -f ~/.config/opencode/AGENTS.md ] &amp;&amp; perl -0pi -e 's/\n*## Orchestrator rule\n.*?(?=\n## |\z)/\n/s' ~/.config/opencode/AGENTS.md
</code></pre>
<p>Note the ID spelling: direct IDs use dashes (<code>5-5</code>), OpenRouter IDs use a dot (<code>5.5</code>).</p>
<h3>Cheap</h3>
<p><strong>1. <code>opencode.jsonc</code></strong>, the main config: the orchestrator model, the plugins, compaction and the permission rules.</p>
<pre><code class="language-bash">mkdir -p ~/.config/opencode &amp;&amp; cat &gt; ~/.config/opencode/opencode.jsonc &lt;&lt;'EOF'
{
  "$schema": "https://opencode.ai/config.json",

  // GLM orchestrates. Qwen and DeepSeek do the delegated work.
  "model": "openrouter/z-ai/glm-5.3-flash",

  "plugins": [
    "opencode-model-router@2.9.1",
    "opencode-runtime-fallback@0.3.1"
  ],

  // Capped so that deepseek/deepseek-flash meets the output floor as GLM's first backup.
  "provider": {
    "openrouter": {
      "models": {
        "z-ai/glm-5.3-flash": { "limit": { "context": 1048576, "output": 393216 } }
      }
    }
  },

  "default_agent": "build",

  "compaction": {
    "auto": true,
    "keep": { "tokens": 20000 },
    "buffer": "20%"
  },

  "agents": {
    "title": { "model": "openrouter/deepseek/deepseek-v4.1-flash" }
  },

  // Ordered rules: the last matching rule wins.
  "permissions": [
    { "action": "shell", "resource": "*", "effect": "ask" },
    { "action": "shell", "resource": "git status *", "effect": "allow" },
    { "action": "shell", "resource": "git diff *", "effect": "allow" },
    { "action": "shell", "resource": "git push *", "effect": "deny" },
    { "action": "shell", "resource": "git reset --hard *", "effect": "deny" },
    { "action": "shell", "resource": "rm -rf *", "effect": "deny" }
  ]
}
EOF
</code></pre>
<p><strong>2. <code>opencode-model-router.overrides.jsonc</code></strong>, the router's tiers: which model handles fast, medium and heavy work.</p>
<pre><code class="language-bash">cat &gt; ~/.config/opencode/opencode-model-router.overrides.jsonc &lt;&lt;'EOF'
{
  "activePreset": "cheap-open",
  "activeMode": "normal",

  "presets": {
    "cheap-open": {
      "fast":   { "readOnly": true, "model": "deepseek/deepseek-flash",
                  "costRatio": 1, "steps": 30,  "description": "Exploration and bounded lookup" },
      "medium": { "model": "openrouter/qwen/qwen3.6-35b-a3b",
                  "costRatio": 2, "steps": 60,  "description": "Implementation and verification" },
      "heavy":  { "model": "openrouter/qwen/qwen3.8-27b",
                  "costRatio": 4, "steps": 100, "description": "Architecture and review" }
    }
  }
}
EOF
</code></pre>
<p><strong>3. <code>opencode-fallback.jsonc</code></strong>, the backup chain for each agent.</p>
<pre><code class="language-bash">cat &gt; ~/.config/opencode/opencode-fallback.jsonc &lt;&lt;'EOF'
{
  "timeout_seconds": 45,
  "notify_on_fallback": true,
  "agents": {
    // build and plan run on the GLM orchestrator. No other low-cost model meets its context floor.
    "build":      { "fallback_models": ["deepseek/deepseek-flash"] },
    "plan":       { "fallback_models": ["deepseek/deepseek-flash"] },
    "fast":       { "fallback_models": ["openrouter/deepseek/deepseek-v4.1-flash"] },
    "medium":     { "fallback_models": ["deepseek/deepseek-flash", "openrouter/z-ai/glm-5.3-flash"] },
    "heavy":      { "fallback_models": ["deepseek/deepseek-flash", "openrouter/z-ai/glm-5.3-flash"] },
    "compaction": { "fallback_models": ["deepseek/deepseek-flash"] }
  }
}
EOF
</code></pre>
<p><strong>4. <code>AGENTS.md</code></strong>, the orchestrator rule. <strong>Do not skip it on Cheap.</strong> This adds the rule to your global <code>AGENTS.md</code>, keeps anything already in that file, and does nothing if the rule is already there.</p>
<pre><code class="language-bash">grep -qs "^## Orchestrator rule" ~/.config/opencode/AGENTS.md || cat &gt;&gt; ~/.config/opencode/AGENTS.md &lt;&lt;'EOF'

## Orchestrator rule

You are a routing orchestrator. Your job is to dispatch work, not to do it.

- Reading and searching are execution. Send them to `subagent(agent="fast", ...)`. You may make at most 2 direct read-only tool calls per turn.
- Send implementation, edits, tests and commands to `subagent(agent="medium", ...)`. Do not edit files yourself.
- Send architecture decisions and trade-off analysis to `subagent(agent="heavy", ...)`, even when you could answer directly.
- Then combine the results and answer the user.
EOF
</code></pre>
<p>Two details in these files:</p>
<ul>
<li><strong>GLM's output cap</strong> in <code>opencode.jsonc</code> makes DeepSeek a valid backup for GLM under the output-limit filter. It does not save money: OpenCode requested 256,000 tokens anyway.</li>
<li><strong>The picker labels</strong> <code>deepseek/deepseek-flash</code> as <strong>DeepSeek V4.1 Flash 1017</strong>.</li>
</ul>
<p><strong>Why the rule is there.</strong> In my first Cheap run, Qwen 3.6 did everything itself and never delegated. It had not missed anything: when I captured what OpenCode sends, a plain-named model and a <code>claude-</code>-named model both received the router's protocol, marked mandatory, and the same <code>subagent</code> tool. The router only adds a forceful "dispatch, do not execute" opener for models with Claude names, so other models fall back on their habits.</p>
<p>With the rule, the orchestrators compared like this:</p>
<table>
<thead>
<tr>
<th>Orchestrator</th>
<th>Exploration</th>
<th>Edit</th>
<th>Architecture</th>
</tr>
</thead>
<tbody><tr>
<td>GLM-5.3-Flash</td>
<td>To DeepSeek</td>
<td>To Qwen 3.6</td>
<td>To Qwen 3.8</td>
</tr>
<tr>
<td>Qwen 3.6</td>
<td>Mixed</td>
<td>To a subagent</td>
<td>Mixed</td>
</tr>
<tr>
<td>DeepSeek Flash</td>
<td>Subagent errors, then did it itself</td>
<td>To Qwen 3.6</td>
<td>Stopped at a permission prompt</td>
</tr>
</tbody></table>
<p>That is why GLM orchestrates, with only one or two runs behind each cell. GLM has orchestrated in my tests but has not made edits. The rule also worked from the global file, tested in a project with no rule of its own.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/78b89516-04e5-4a64-a3fa-b41aaf5bb058.png" alt="A GLM-5.3-Flash session where a Medium subagent has finished an edit, and all 9 tests pass" /></p>
<p><em>GLM hands the edit to the Medium tier, then runs the tests itself to confirm the result.</em></p>
<h3>Switching packages and the model picker</h3>
<p>To switch packages, quit the Desktop, run the other package's four commands, and reopen it. The router's preset in the override file is only a default, and runtime choices made with <code>/preset</code> or <code>/budget</code> take precedence over it.</p>
<p><strong>A new session may not use the model in your config.</strong> A brand-new profile opened on the configured model, but after that the Desktop opened new sessions on the last model I had used, even with a different <code>model</code> set. Check the picker at the start of a session, especially after switching: this is how a Cheap session could end up on a paid Claude model.</p>
<h2>8. Check that it works</h2>
<p>A connected provider shows that a key exists. It does not show that the key works. Four of my providers failed on their first real call: one had no credit, one could not cover the requested output tokens, one had a Free Tier quota of 0, and one rejected the token type.</p>
<p><strong>Do this once. It costs a few cents on Cheap, and should stay well under a dollar on Best.</strong></p>
<p><strong>1. Find the OpenCode CLI.</strong> The Desktop ships its own CLI, which may not be on your <code>PATH</code>. On macOS:</p>
<pre><code class="language-bash">OC=/Applications/OpenCode.app/Contents/Resources/opencode-cli
</code></pre>
<p>On Linux, find it in the installed files:</p>
<pre><code class="language-bash">OC=$(find /opt /usr/lib /usr/share -name opencode-cli -type f 2&gt;/dev/null | head -n1); echo "$OC"
</code></pre>
<p>If that prints nothing, install the standalone CLI with <code>curl -fsSL https://opencode.ai/v2/install | bash</code> and use <code>OC=opencode</code>. I have not checked whether the standalone CLI sees the Desktop's plugins.</p>
<p><strong>2. Confirm both plugins are loaded,</strong> with the Desktop open:</p>
<pre><code class="language-bash">"$OC" plugin list
</code></pre>
<p>Both <code>opencode-model-router</code> and <code>opencode-runtime-fallback</code> should appear. Right after a change the list can be briefly incomplete, so run it again after a few seconds. Do not add <code>--standalone</code>, which showed no plugins at all in my runs. If a plugin is still missing after a restart, add it by hand with <code>"$OC" plugin add opencode-model-router@2.9.1</code> or <code>"$OC" plugin add opencode-runtime-fallback@0.3.1</code>, which is how I installed them, then run the section 7 command again, since <code>plugin add</code> writes an <code>opencode.json</code>.</p>
<p><strong>3. Turn fallback off for the check.</strong> This keeps your fallback file and puts a disabled one in its place:</p>
<pre><code class="language-bash">mv ~/.config/opencode/opencode-fallback.jsonc ~/.config/opencode/opencode-fallback.jsonc.on &amp;&amp; echo '{ "enabled": false }' &gt; ~/.config/opencode/opencode-fallback.jsonc
</code></pre>
<p><strong>This step matters.</strong> With fallback on, a failed route can be rescued by a backup and still look like a success. A free model of mine failed, a paid backup replied, and the screen showed <code>pong</code> as if nothing had happened. The only visible clue was a $0.03 charge.</p>
<p><strong>4. Ping every model.</strong> Quit and reopen the Desktop. In a new session, pick each model in your package in turn and send <code>Reply with exactly one word: pong</code>. Each one should answer <code>pong</code> itself, with no fallback notice.</p>
<p><strong>5. Turn fallback back on,</strong> then quit and reopen the Desktop:</p>
<pre><code class="language-bash">mv ~/.config/opencode/opencode-fallback.jsonc.on ~/.config/opencode/opencode-fallback.jsonc
</code></pre>
<p><strong>6. Run <code>/tiers</code></strong> in a session to confirm the preset and models. It goes through the model, so it costs a little.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/c653f8fb-c3e7-4aeb-b2b4-bbdeea9bad80.png" alt="/tiers output in OpenCode Desktop showing the best-frontier preset, with Haiku on fast, Sonnet on medium, and Opus on heavy" /></p>
<p><em><code>/tiers</code> on the Best setup. Check the preset name and the three model IDs.</em></p>
<h2>9. Daily use</h2>
<p><strong>Routing.</strong> Give the task and let the orchestrator dispatch it. Small lookups stay with the orchestrator by design, which allows about 2 direct read-only calls per turn, so seeing no delegation on a tiny question is normal. Useful commands are <code>/tiers</code>, <code>/router</code>, <code>/budget budget|normal|quality|deep</code>, and <code>/bypass</code>. To see what actually ran:</p>
<pre><code class="language-bash">"$OC" stats --days 0 --models --cost
</code></pre>
<p><code>$OC</code> is the CLI path from section 8.</p>
<p><strong>Failover.</strong> You should not need to do anything. In testing, the backup continued in the same session after a 429 and kept the completed tool result, and a stalled provider was cut off at the timeout. It preserves history, not side effects, so after a failover check the active model, then <code>git status</code> and <code>git diff</code>.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/f41cff03-07e3-4a72-8d1e-7930000f121a.png" alt="A session where a test provider returns a rate limit error, OpenCode switches to Claude Haiku 5.5, and the backup continues the same task" /></p>
<p><em>A deliberate failure from my test provider, which also wrote the wrong text on purpose. The backup takes over in the same session, sees the earlier write, and corrects it.</em></p>
<p><strong>Undo.</strong> <code>/undo</code> and <code>/redo</code> are not slash commands in this Desktop build. Use <strong>Rewind to here</strong> on a message, or <strong>Undo</strong> and <strong>Redo</strong> in the command palette (<code>⌘⇧P</code> on macOS). Rewinding removed the file and put my prompt back in the composer. Snapshots do not cover ignored files, untracked files over 2 MiB, files outside the project, or side effects such as commits and deployments.</p>
<p><strong>Sessions and memory.</strong> <a href="https://nightthoughts.me/memory-for-ai-agents-architectures-tools-and-how-to-choose-the-right-one">Memory is a large topic of its own</a>. For this setup, keep stable facts in a short <code>AGENTS.md</code>: a fresh session returned a fact stored only there, with no tool calls. Resume a session for the same task, and start fresh at real task boundaries. Compaction is lossy, so after it ask the model for the objective, decisions, and next action, and check the answer. Both setups kept all three in my test.</p>
<p><strong>Subagents.</strong> Ask for bounds explicitly, for example "use at most two subagents, neither may edit, neither may launch further agents". Both setups respected this in one run each. The router's depth guard only warns by default, so <code>/router enforce enforced</code> is the setting if you want a hard stop. I did not test that setting. Denying a permission inside a subagent cancelled that subagent in my run, and the orchestrator then carried on by itself.</p>
<h2>10. Images and PDFs</h2>
<p><strong>Images</strong> can be attached directly on both setups. Each returned an exact code from a test image, and the backup route did too.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/32113327-9d1d-48f9-8a78-7a427b3f9d01.png" alt="An attached image containing a code, and Claude Haiku 5.5 replying with that exact code" /></p>
<p><em>The check I used for images: a random code the model can only get by reading the attachment.</em></p>
<p><strong>PDFs on Best.</strong> Attach the PDF directly. With tools forbidden, both routes read it and returned the right code and page. One caveat: after a failover the answer was still correct, but the first request carried almost no PDF tokens and the model delegated to a subagent. So the PDF may not reach the backup natively. Check the answer if a failover happened mid-task.</p>
<p><strong>PDFs on Cheap.</strong> These models do not advertise native PDF input, so convert first and attach the results:</p>
<pre><code class="language-bash">pdftotext -layout requirements.pdf requirements.txt
pdftoppm -f 3 -singlefile -png -r 150 requirements.pdf requirements-page-3
</code></pre>
<p>The original stays local, but the extracted text and image still go to the hosted model.</p>
<h2>11. What it costs</h2>
<p><strong>Illustrative monthly cost.</strong> One work unit is 20M input and 1M output tokens, split 70% fast, 25% medium, 5% heavy, with no caching or fallback. Prices per 1M tokens are from November 5, 2026.</p>
<table>
<thead>
<tr>
<th>Tier</th>
<th>Best</th>
<th>Cheap</th>
</tr>
</thead>
<tbody><tr>
<td>Fast</td>
<td>Haiku, $0.10 / $0.50</td>
<td>DeepSeek Flash, $0.15 / $0.60</td>
</tr>
<tr>
<td>Medium</td>
<td>Sonnet, $2 / $10</td>
<td>Qwen 3.6, $0.10 / $0.90</td>
</tr>
<tr>
<td>Heavy</td>
<td>Opus, $4 / $20</td>
<td>Qwen 3.8, $0.15 / $1.875</td>
</tr>
<tr>
<td><strong>Per work unit</strong></td>
<td><strong>$19.25</strong></td>
<td><strong>$3.49</strong></td>
</tr>
</tbody></table>
<p>This is a scenario, <strong>not a prediction</strong>. It leaves out Cheap's GLM orchestrator ($0.15 / $0.50), and Haiku costs five times as much above 100K tokens ($0.50 / $2.50). Caching, retries, and session length all move the real number. Measure your own after a week.</p>
<p><strong>What I measured:</strong></p>
<ul>
<li><strong>The router adds overhead.</strong> The first request grew from about 8,600 tokens to about 14,900 with the plugins loaded.</li>
<li><strong>Switching routes mid-session costs about 11 times a normal turn, once.</strong> On Haiku, a turn went from $0.00015 to $0.0016 because 12,666 tokens had to be written to a new cache. The next turn was back to normal, and switching back stayed cheap while the first cache was warm. On Opus the same switch would cost more, in proportion to its price.</li>
<li><strong>All my testing, including failed attempts, cost about $0.72</strong> by OpenCode's figures. I have not finished reconciling that against the provider dashboards.</li>
</ul>
<p><strong>Against subscriptions.</strong> Claude Pro ($20 a month), Max ($100), and Ultra ($200) are priced by usage limits, not tokens, so they are not directly comparable. They can be better value when their limits fit your use; paying per token suits bursty work and provider choice. Check the <a href="https://claude.com/pricing">current pricing</a>.</p>
<h3>Limits: no session window, but not unlimited</h3>
<p>On Pro and Max, usage is capped by a five-hour session limit and a weekly limit. Ultra has only the weekly limit. The two packages here have no such window. These are the limits that do apply, according to each provider's documentation on November 6, 2026:</p>
<table>
<thead>
<tr>
<th>Provider</th>
<th>Limit</th>
<th>What happens</th>
</tr>
</thead>
<tbody><tr>
<td>Anthropic API</td>
<td>Requests and tokens <strong>per minute</strong>, by usage tier, refilled continuously</td>
<td><code>429</code> for a short time. The fallback plugin switches to the OpenRouter backup</td>
</tr>
<tr>
<td>Anthropic API</td>
<td>A <strong>monthly spend cap</strong> per tier, $500 on the Start tier. New organizations may start on a lower Evaluation tier</td>
<td>Requests stop until the first of the next month, or until you move up a tier. The backup on OpenRouter still works</td>
</tr>
<tr>
<td>Anthropic API</td>
<td>A spend limit you set yourself</td>
<td>Requests stop with a <code>400</code> until you raise it</td>
</tr>
<tr>
<td>OpenRouter</td>
<td>No platform cap on paid models, but the upstream provider can be rate-limited or full</td>
<td><code>429</code> from the upstream. OpenRouter may retry another upstream; the fallback plugin also switches</td>
</tr>
<tr>
<td>OpenRouter</td>
<td>Your credit balance, and any limit set on the key</td>
<td><code>402</code>, see section 5</td>
</tr>
<tr>
<td>DeepSeek</td>
<td><strong>Concurrent requests</strong> per account: 2,500 for <code>deepseek-flash</code></td>
<td><code>429</code> only when too many requests run at once</td>
</tr>
<tr>
<td>All</td>
<td>Your prepaid balance</td>
<td>Nothing works until you top up. A backup on the same account fails too</td>
</tr>
<tr>
<td>OpenCode free models</td>
<td>Undocumented free-usage limit</td>
<td><code>429 Free usage limit reached</code>, about 9.6 hours in my case. Not used by either package</td>
</tr>
</tbody></table>
<p>So the claim holds in a narrow sense: you will not be locked out for five hours or a week by your plan. You can still be stopped by money, by a monthly cap, or briefly by a per-minute limit. My testing was far too small to reach any of these, so this table comes from the documentation, not from my runs.</p>
<h2>12. What I tested</h2>
<p>Testing is where most of the work in this article went, because a harness is only worth something if it holds when things go wrong. A model reply on screen proves little: in one of my early checks the screen showed the right answer while a different, paid model had produced it.</p>
<p><strong>How the tests were run:</strong></p>
<ul>
<li><strong>In the Desktop app</strong>, version 2.2.5, driven by a script that clicked the same controls you would: the model picker, the attachment button, the composer, permission prompts and the command palette.</li>
<li><strong>On a disposable Git repository</strong> with one source file (<code>src/math.mjs</code>, containing an <code>add</code> function), one passing test, an <code>AGENTS.md</code> holding a made-up project codename, a <code>docs/DECISIONS.md</code>, and an untracked <code>.env</code> with a placeholder value. It has no remote, so a real push was impossible.</li>
<li><strong>With a local mock provider for failures.</strong> Real providers do not fail on request, so a small local server played a provider that returns <code>429</code> after one tool call, one that always returns <code>503</code>, and one that never sends a first token. The backup behind them was a real route.</li>
<li><strong>With random codes for attachments.</strong> Each image and PDF contained a code generated for the test, so a model could only answer correctly by reading the file.</li>
<li><strong>Judged from session exports, not the screen.</strong> Each pass was checked in OpenCode's export of the session: which model produced each step, which tools ran, tokens and cost.</li>
</ul>
<p>The table below summarizes the results. The appendix has the receipt for each test.</p>
<table>
<thead>
<tr>
<th>Test</th>
<th>Best</th>
<th>Cheap</th>
</tr>
</thead>
<tbody><tr>
<td>Startup, <code>/tiers</code>, plugins</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Image with a random code</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>PDF, code on page 2</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Routing</td>
<td>Pass</td>
<td>Pass with GLM and the rule; failed on my first setup</td>
</tr>
<tr>
<td>429 after a completed tool call</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>No first token</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Capability after failover</td>
<td>Partial, see section 10</td>
<td>Pass (image and tools)</td>
</tr>
<tr>
<td>Memory: fresh session and resume</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Compaction</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Subagent bounds</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Permissions</td>
<td>Pass</td>
<td>Not repeated: OpenCode applies these rules whichever model asks</td>
</tr>
<tr>
<td>Rewind and Redo</td>
<td>Pass</td>
<td>Not repeated: snapshots do not involve the model</td>
</tr>
</tbody></table>
<p><strong>What I did not prove:</strong></p>
<ul>
<li><strong>Real coding quality.</strong> These are mostly small, deliberate tasks. I did not run a benchmark, so I cannot tell you how much weaker Cheap is on your work, or put a number on how far a backup falls short of its primary.</li>
<li><strong>Repeatability.</strong> Most results are one run. Routing in particular varied between runs.</li>
<li><strong>Provider independence.</strong> I did not test pinning OpenRouter to a specific upstream.</li>
<li><strong>Cost reconciliation.</strong> OpenCode's figures have not been fully checked against provider dashboards. The fallback plugin also documents that it cannot report a different model or cost for compaction.</li>
</ul>
<p><strong>Semantic memory is out of scope.</strong> I tried <code>opencode-supermemory</code> with a self-hosted server and a local model. When the agent had the tool, it worked. But the tool was often missing from the session, with per-project or global config, even after a full restart, and <code>plugin list</code> did not predict when. Without it, one model wrote its own <code>MEMORY.md</code> as a substitute. I would not rely on it yet, so this guide stays with <code>AGENTS.md</code> and sessions.</p>
<p>The configs, test scripts, and sanitized evidence are in the <a href="https://github.com/hslimi/night-thoughts/tree/experiment/opencode-multi-model-harness/experiments/opencode-multi-model-harness">companion experiment folder</a>.</p>
<h2>13. Limits and privacy</h2>
<ul>
<li><strong>A backup is not an SLA.</strong> Best's backup may share an outage with the primary (section 3).</li>
<li><strong>Failover spends money too</strong>, and it can send your content to a different provider.</li>
<li><strong>Third-party plugins</strong> do the routing and failover. They are pinned here for that reason.</li>
<li><strong>Privacy.</strong> On either setup your code and attachments go to the providers in your chain, and through OpenRouter to its upstreams as well. I have not reviewed the data terms for every route here. Before you attach anything sensitive, read the terms for each provider in your chain, remove credentials and customer data, and remember that a failover can send the same content elsewhere.</li>
<li><strong>Local-only work.</strong> These setups are not for material that must not leave the machine.</li>
</ul>
<h2>14. Troubleshooting</h2>
<table>
<thead>
<tr>
<th>Symptom</th>
<th>Likely cause</th>
</tr>
</thead>
<tbody><tr>
<td>Session runs on the wrong model</td>
<td>The picker kept the last model; check it at session start</td>
</tr>
<tr>
<td>Model is missing from the picker</td>
<td>Switch it on under <strong>Manage models</strong></td>
</tr>
<tr>
<td><code>402</code> asking for more credits, or fewer <code>max_tokens</code></td>
<td>The balance cannot cover the output tokens OpenCode requests</td>
</tr>
<tr>
<td><code>400</code> credit balance too low</td>
<td>No API credit on the organization that owns the key</td>
</tr>
<tr>
<td><code>429 Free usage limit reached</code></td>
<td>OpenCode's free-model limit; use the paid chains here</td>
</tr>
<tr>
<td>Cheap orchestrator does everything itself</td>
<td><code>AGENTS.md</code> rule missing, or the wrong orchestrator selected</td>
</tr>
<tr>
<td>No delegation on a small question</td>
<td>Normal: lookups within the 2-call allowance stay direct</td>
</tr>
<tr>
<td>Router commands absent</td>
<td>Confirm Node 22+, the plural <code>plugins</code> key, the exact override filename, and a full restart</td>
</tr>
<tr>
<td>Fallback never engages</td>
<td>Plugin missing from <code>plugin list</code>, wrong file path, or that agent has no chain</td>
</tr>
<tr>
<td>Paid charge on a free or failed model</td>
<td>A backup replied. Check the session export and <code>opencode-fallback.log</code></td>
</tr>
<tr>
<td><code>/undo</code> not found</td>
<td>Use <strong>Rewind to here</strong>, or <strong>Undo</strong> in the command palette</td>
</tr>
<tr>
<td><code>/router stats</code> prints help</td>
<td>It does not exist in 2.9.1; use <code>"$OC" stats --models --cost</code></td>
</tr>
</tbody></table>
<h2>Final thoughts</h2>
<p>Best gives you stronger models and more evidence, at about five times the illustrative cost. Cheap is usable, but it asks you to check more of its work and to accept that its quality on real tasks is unmeasured here.</p>
<p>The part I would keep either way is the habit this forced: prove each route, read what actually ran, and do not trust the screen alone. The moments that taught me most were the ones where something looked fine and was not.</p>
<h2>Appendix: test receipts</h2>
<p>One receipt per test. Each one says what harness property it checks, how the test was set up, what I sent, what counted as a pass, and how I checked it. The prompts are quoted exactly. Session exports for every run are in the <a href="https://github.com/hslimi/night-thoughts/tree/experiment/opencode-multi-model-harness/experiments/opencode-multi-model-harness">companion experiment folder</a>, under <code>evidence/</code>.</p>
<p>"The test repository" is the disposable repository described in section 12. "The mock" is the local provider that fails on purpose.</p>
<h3>Test 1: Startup</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>Both plugins load, and the router uses the intended preset and models</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>If a plugin silently fails to load, routing and failover are missing, and nothing on screen says so</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>Package config in <code>~/.config/opencode/</code>, Desktop restarted</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Run <code>opencode-cli plugin list</code>, then send <code>/tiers</code> and <code>/router</code> in a new session</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>Both plugins listed with their pinned versions; <code>/tiers</code> shows the package's preset (<code>best-frontier</code> or <code>cheap-open</code>) and the three tier models exactly as configured</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>CLI output and the session export</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap: pass</td>
</tr>
</tbody></table>
<h3>Test 2: Image input</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>An attached image reaches the model as an image</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>A model that does not receive the image may still give a confident answer</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>A PNG containing only a random code generated for the test</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Attach the image and send: "What exact code is shown in this image? Reply with only the code." On Cheap the prompt also said "Do not use tools."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The reply contains the exact code. A guess cannot match it</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The session export, compared with the generated code</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best (Haiku): pass. Cheap (Qwen 3.6): pass</td>
</tr>
</tbody></table>
<h3>Test 3: PDF input</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>A PDF can be read, including where the content is</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Native PDF support differs between models, and Cheap's models do not advertise it</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>A multi-page PDF with a random review code on page 2 only. On Cheap, converted first with <code>pdftotext</code> and <code>pdftoppm</code>, as in section 10</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Best: attach the PDF and send "This document has a review code. Reply with the exact code and the page number it is on." Cheap: attach the text and page image and send "The text and page image come from one document. Reply with the review code and which page it is on. Do not use tools."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>Exact code, and page 2</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The session export; on Best, also the input token count, which shows whether the PDF was actually sent</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass, natively. Cheap: pass, after local conversion</td>
</tr>
</tbody></table>
<h3>Test 4: Routing</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>The orchestrator sends each kind of work to the right tier</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>This is the point of the router. Without it, every request runs on the orchestrator's model and price</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The test repository, a new session on the package's orchestrator</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Three prompts in one session. Exploration on Cheap: "Search the src and test folders and summarise what each file does, with file and line references. Do not change anything." On Best, a one-file lookup ("Where is the add function defined, and which test covers it? Do not change anything."), then a larger exploration of a real repository's <code>experiments</code> folder, read only. Edit: "Add a subtract(a, b) function to src/math.mjs with a matching test in test/math.test.mjs, then run node --test and report the result." Architecture: "Architecture question, no edits: if this project grew to many math modules across several packages, compare a single shared package with one package per module, considering versioning and test isolation. Recommend one, briefly." Only the <code>node --test</code> prompt was approved; any other permission request stopped the test</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>Exploration runs on the fast model, the edit on the medium model, and architecture on the heavy model, each through a subagent; the tests pass after the edit</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The model that produced each step in the export, and <code>opencode-cli stats --models --cost</code> before and after each prompt</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass, with a small lookup kept by the orchestrator as the router intends. Cheap: <strong>fail</strong> with Qwen 3.6 as orchestrator, then pass with GLM-5.3-Flash and the <code>AGENTS.md</code> rule. One or two runs per setup</td>
</tr>
</tbody></table>
<h3>Test 5: Failover after a rate limit</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>When a provider returns <code>429</code> mid-task, the backup continues the same task without repeating finished work</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Failing over at the start of a task is easy. Failing over after a tool has already changed a file is where duplicated or lost work happens</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The mock as the primary, set to make one <code>write</code> tool call (creating <code>notes.txt</code>) and then return <code>429</code>. A real backup: Haiku on Best, DeepSeek Flash on Cheap</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>"Create notes.txt with the text 'written once'. Then read src/math.mjs and tell me the name of the first exported function."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The backup continues in the <strong>same session</strong> (no new session created); it works on the existing <code>notes.txt</code> rather than writing it again; it reads <code>src/math.mjs</code>; the export records the switch to the backup model</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export, the fallback plugin's log, the session count before and after, and the file on disk</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap: pass. The mock deliberately wrote slightly different text, and both backups noticed and corrected it</td>
</tr>
</tbody></table>
<p>A second variant used a mock that always returns <code>503</code>, with "Reply with exactly one word: pong". Best failed over the same way.</p>
<h3>Test 6: Stalled provider</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>A provider that accepts the request and never answers is cut off, and the backup answers</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>A stall is worse than an error: without a timeout the session just hangs</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The mock accepting the request and sending nothing. Fallback timeout lowered to 20 seconds for the test; the packages use 45</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>"Reply with exactly one word: pong"</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The backup replies <code>pong</code> in the same session, shortly after the timeout</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export and the plugin log, which records the timeout</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap: pass. 38 seconds in total on both</td>
</tr>
</tbody></table>
<h3>Test 7: Capabilities after failover</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>Attachments and tools still work once the backup has taken over. On Best, this test used the OpenRouter backup</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Test 5 shows the backup can continue. This shows it can still read what the primary was given</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The mock returning <code>503</code> as the primary, a backup on the other route, and <strong>new</strong> codes, different from tests 2 and 3, so an earlier answer could not be reused</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Image: attach it and send "What exact code is shown in this image? Then read src/math.mjs and name its first exported function." PDF (Best only): attach it and send "This document has a review code. Reply with the exact code and the page number it is on."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The backup returns the exact new code and calls the <code>read</code> tool; for the PDF, the code and page 2, with the PDF delivered to the backup natively</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export, including input token counts</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Cheap: pass. Best: <strong>partial</strong>. Image and tools passed. The PDF answer was correct, but the first request to the backup carried almost no PDF tokens and the model used a subagent to get the answer, so native delivery after a failover is not confirmed</td>
</tr>
</tbody></table>
<h3>Test 8: Memory across sessions</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>Project facts reach a fresh session, and a resumed session keeps its own context</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>These are the two kinds of memory this guide relies on, in place of a memory plugin</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The test repository, whose <code>AGENTS.md</code> contains a made-up codename that appears nowhere else</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Fresh session: "What is this project's codename? Answer from what you already know, without using tools." Resume: in another session send "Our objective for this session is to rename add to sum, and the next action is updating the test. Do not do it yet. Just confirm in one sentence.", leave it, reopen it from the sidebar, and ask "What was our objective and the next action? Answer in one sentence."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The codename comes back with <strong>no tool calls</strong>, so it came from <code>AGENTS.md</code> and not from reading files; the resumed session states both the objective and the next action, and no new session was created</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export, including the tool list</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap (GLM): pass</td>
</tr>
</tbody></table>
<h3>Test 9: Semantic memory</h3>
<p>Out of scope, for the reasons in section 12. It is listed so the numbering matches the evidence files.</p>
<h3>Test 10: Compaction</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>After the context is compacted, the task survives</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Compaction is lossy by design. The question is whether it keeps what matters</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>A session with an objective, a decision and a next action stated up front, followed by turns that read files</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>"Our objective: add a multiply function to src/math.mjs. Decision: keep it dependency free, per docs/DECISIONS.md. Next action: write the test first. Do not edit anything. Confirm in one sentence." Then two file-reading prompts, then <code>/compact</code>, then "State the objective, the decision, and the next action. Do not use tools."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>The export shows that compaction ran, and the answer after it names all three: multiply, no dependencies, and test first</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export, before and after compaction</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap: pass</td>
</tr>
</tbody></table>
<h3>Test 11: Subagent bounds</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>The orchestrator respects limits on how many subagents it starts and what they may do</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Unbounded subagents multiply cost, and nested ones are hard to follow</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The test repository</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>"Use at most two subagents in parallel: one to summarise src/math.mjs and one to summarise test/math.test.mjs. Neither may edit, and neither may launch further agents. Then combine the two summaries in two sentences."</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>Exactly two subagents, no edit tools, no nested subagents, and a combined answer</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The tool calls in the export</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Cheap (GLM with the rule): pass. One run each</td>
</tr>
</tbody></table>
<h3>Test 12: Permissions</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>The permission rules in section 7 allow, deny and ask as written</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>These rules are what stands between the agent and a destructive command</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The test repository, with the untracked <code>.env</code> and no remote</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Five prompts, each asking the agent to run one command exactly: <code>git status --short</code>, <code>git push --dry-run origin main</code>, <code>rm -rf build</code>, a read of <code>.env</code>, and <code>ls src</code>. Every prompt that appeared was answered <strong>Deny</strong></td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td><code>git status</code> runs with no prompt; <code>git push</code> and <code>rm -rf</code> are refused with no prompt; the <code>.env</code> read and <code>ls</code> ask first; <code>HEAD</code> does not move</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>Tool states in the export, and <code>git rev-parse HEAD</code> before and after</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Not repeated on Cheap: OpenCode applies these rules before a command runs, whichever model asked</td>
</tr>
</tbody></table>
<h3>Test 13: Rewind and Redo</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>A bad turn can be undone and redone</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Recovery is what makes it safe to let an agent edit</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>The test repository with earlier edits committed, so only the new change is in play</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>"Create the file scratch.txt containing exactly the word alpha. Nothing else." Then <strong>Rewind to here</strong> on that message, then <strong>Redo</strong> from the command palette</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>After rewind the file is gone and the prompt is back in the composer; after redo the file is back</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The file on disk and <code>git status</code> after each step</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Best: pass. Not repeated on Cheap: snapshots do not involve the model</td>
</tr>
</tbody></table>
<h3>Test 14: Cost</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Checks</strong></td>
<td>What the harness reports matches what providers bill, and what switching routes costs</td>
</tr>
<tr>
<td><strong>Why</strong></td>
<td>Failover changes where tokens go, and a route switch can lose the prompt cache</td>
</tr>
<tr>
<td><strong>Setup</strong></td>
<td>One session on Haiku</td>
</tr>
<tr>
<td><strong>Scenario</strong></td>
<td>Five one-word turns: two on Anthropic, two after switching to OpenRouter, one after switching back. "Reply with exactly one word: one", then "two", and so on</td>
</tr>
<tr>
<td><strong>Pass if</strong></td>
<td>Per-turn cost and cache tokens are recorded for each turn, and OpenCode's totals match the provider dashboards</td>
</tr>
<tr>
<td><strong>Checked in</strong></td>
<td>The export, then the dashboards</td>
</tr>
<tr>
<td><strong>Result</strong></td>
<td>Route-switch cost measured (section 11). <strong>Dashboard comparison not finished</strong></td>
</tr>
</tbody></table>
<h2>References</h2>
<ul>
<li><a href="https://github.com/hslimi/night-thoughts/tree/experiment/opencode-multi-model-harness/experiments/opencode-multi-model-harness">Companion experiment folder</a></li>
<li><a href="https://opencode.ai/download">OpenCode Desktop downloads</a></li>
<li><a href="https://opencode.ai/v2/docs/models/">OpenCode v2 models</a></li>
<li><a href="https://opencode.ai/v2/docs/compaction/">OpenCode v2 compaction</a></li>
<li><a href="https://opencode.ai/v2/docs/permissions/">OpenCode v2 permissions</a></li>
<li><a href="https://opencode.ai/v2/docs/snapshots/">OpenCode v2 snapshots</a></li>
<li><a href="https://opencode.ai/docs/rules">OpenCode rules</a></li>
<li><a href="https://github.com/marco-jardim/opencode-model-router">opencode-model-router</a></li>
<li><a href="https://github.com/youngbinkim0/opencode-fallback">opencode-runtime-fallback</a></li>
<li><a href="https://openrouter.ai/docs/api/reference/limits">OpenRouter limits</a></li>
<li><a href="https://claude.com/pricing">Claude plans and pricing</a></li>
<li><a href="https://models.dev">models.dev catalog</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Beyond Vibe Coding: Building and Maintaining an Expense Tracker with GitHub Spec Kit]]></title><description><![CDATA[A practical walkthrough of specifications, clarification, quality gates, implementation, convergence, and structured bug fixing.]]></description><link>https://nightthoughts.me/beyond-vibe-coding-building-and-maintaining-an-expense-tracker-with-github-spec-kit</link><guid isPermaLink="true">https://nightthoughts.me/beyond-vibe-coding-building-and-maintaining-an-expense-tracker-with-github-spec-kit</guid><category><![CDATA[GitHub]]></category><category><![CDATA[AI]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[software development]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Tue, 03 Nov 2026 23:08:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/8733568d-2fbf-4c01-ac0c-a86d7497a70d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before I build anything, I already have a strong suspicion about one category: coffee. ‘Just one more coffee’ may not be a financial strategy, but it will make a realistic test expense. ☕</p>
<p>An expense tracker is a useful specification exercise because the first prompt sounds complete until implementation begins. Amounts need exact arithmetic. Dates need month boundaries. Storage can be absent, malformed, or unavailable. A delete button is not enough: cancellation, confirmation, and keyboard focus all have observable behavior.</p>
<p>This walkthrough builds that application with GitHub Spec Kit and GitHub Copilot Chat in VS Code. It keeps the generated artifacts, test-first checkpoints, mistakes, convergence finding, and a real maintenance repair. The result is a small frontend application, not a financial service. The process is the product being examined.</p>
<h2>1. Why “build me an expense tracker” is underspecified</h2>
<p>A prompt such as “add expenses and show monthly totals” leaves important decisions unanswered.</p>
<p>Should <code>$1.2</code> be accepted? What about <code>1e2</code>, <code>1,000</code>, negative values, or three decimal places? Does a date belong to a month in UTC or in the browser’s local calendar? Can an expense be dated next year? What happens when localStorage contains invalid JSON? Should malformed data be replaced automatically?</p>
<p>These are not edge decorations. Each choice changes code and tests. If the coding agent guesses silently, the resulting application may look coherent while implementing different intent.</p>
<p>Spec Kit separates those decisions into a specification, a technical plan, ordered tasks, implementation, and verification. The specification describes observable behavior. The plan chooses technology and boundaries. Tasks sequence the work. Implementation satisfies the artifacts. Verification checks the result rather than confirming that files were generated.</p>
<h2>2. What we will build</h2>
<p>The demonstration uses React, TypeScript, and Vite. It supports:</p>
<ul>
<li>create, edit, and confirmed deletion;</li>
<li>amount, category, local calendar date, and optional note;</li>
<li>Food, Transport, Housing, Entertainment, and Other;</li>
<li>monthly navigation, exact monthly totals, and five category totals;</li>
<li>category filtering and stable date or amount sorting;</li>
<li>visible validation and persistence errors;</li>
<li>localStorage recovery and malformed-data protection;</li>
<li>keyboard-operable forms and a native deletion dialog;</li>
<li>desktop, tablet, and phone layouts;</li>
<li>explicitly labeled, deterministic fictional demo data.</li>
</ul>
<p>There is no backend, account system, router, global state package, or currency conversion. Money is stored as integer cents. Dates remain <code>YYYY-MM-DD</code> strings, avoiding UTC conversion at month boundaries.</p>
<p>The <a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker">source folder</a> contains the application, specifications, plans, tasks, tests, evidence, and this article.</p>
<h2>3. Prerequisites and exact versions</h2>
<p>The experiment used the following installed tools. Exact application dependency versions are in <code>package-lock.json</code>.</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Version</th>
</tr>
</thead>
<tbody><tr>
<td>Spec Kit CLI</td>
<td>1.2.5</td>
</tr>
<tr>
<td>Spec Kit integration</td>
<td>Copilot skills</td>
</tr>
<tr>
<td>VS Code</td>
<td>1.144.1</td>
</tr>
<tr>
<td>Copilot SDK</td>
<td>1.0.103-unstable.r40031404408.gba6c003</td>
</tr>
<tr>
<td>uv</td>
<td>0.13.0</td>
</tr>
<tr>
<td>Spec Kit Python</td>
<td>3.12.15</td>
</tr>
<tr>
<td>Node.js</td>
<td>22.23.3</td>
</tr>
<tr>
<td>npm</td>
<td>10.9.9</td>
</tr>
<tr>
<td>React</td>
<td>19.3.1</td>
</tr>
<tr>
<td>TypeScript</td>
<td>7.0.2</td>
</tr>
<tr>
<td>Vite</td>
<td>8.3.5</td>
</tr>
<tr>
<td>Vitest</td>
<td>5.1.0</td>
</tr>
<tr>
<td>Playwright</td>
<td>1.64.1</td>
</tr>
<tr>
<td>Bug Triage Workflow</td>
<td>1.0.1</td>
</tr>
</tbody></table>
<p>The <a href="https://github.com/github/spec-kit">Spec Kit documentation</a>, <a href="https://github.com/github/spec-kit/blob/main/docs/integrations/copilot.md">Copilot integration instructions</a>, and <a href="https://github.github.com/spec-kit/guides/bugfix.html">bug-fixing guide</a> supplied the current command shapes. Installed CLI help remained authoritative for flags.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/b8b69e7e-8168-44be-82f5-134dcec9cd20.png" alt="Verified Spec Kit, Copilot, Node.js, and application dependency versions displayed in VS Code" /></p>
<h2>4. Initialising Spec Kit</h2>
<p>For a new empty directory, initialization is:</p>
<pre><code class="language-bash">specify init . --integration copilot
</code></pre>
<p>The project records <code>speckit_version: 1.2.5</code>, <code>integration: copilot</code>, and enabled agent skills in <code>.specify/init-options.json</code>. Spec Kit creates its scripts and templates under <code>.specify</code> and the Copilot skills under <code>.github/skills</code>.</p>
<p>The workflow then ran in this order in GitHub Copilot Chat:</p>
<pre><code class="language-text">/speckit-constitution
/speckit-specify
/speckit-clarify
/speckit-plan
/speckit-checklist
/speckit-tasks
/speckit-analyze
/speckit-implement
/speckit-converge
</code></pre>
<p>These are agent prompts, not terminal commands. The screenshots show the resulting artifacts in VS Code; the sanitized <a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/evidence/workflow/copilot-stage-log.md">Copilot stage log</a> preserves the actual prompts and visible results.</p>
<h2>5. Establishing engineering rules with a constitution</h2>
<p>The constitution is the project’s engineering contract. It requires:</p>
<ol>
<li>exact integer-cent monetary arithmetic;</li>
<li>accessible keyboard-first forms and dialogs;</li>
<li>meaningful business-logic tests;</li>
<li>separation of UI, calculations, and persistence;</li>
<li>confirmation for destructive actions;</li>
<li>visible persistence outcomes;</li>
<li>a scope proportionate to a small demonstration.</li>
</ol>
<p>The last constraint matters. A specification process can generate its own form of overengineering. This project did not need a backend, repository abstraction, global store, or dozens of microtasks.</p>
<p>The constitution also makes review criteria explicit. A visually complete dashboard would still fail if it used unrestricted floating-point dollar calculations, hid a failed save, or allowed deletion without confirmation.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/22eab54e-b21e-4ca2-ba13-1d9824fc0ac6.png" alt="The generated constitution showing exact money, accessibility, testing, and separation-of-concerns principles" /></p>
<h2>6. Writing the specification</h2>
<p><code>/speckit-specify</code> turned the baseline prompt into user stories, acceptance scenarios, edge cases, functional requirements, and measurable outcomes. Clarification expanded the initial 13 functional requirements to 15.</p>
<p>The three priorities are deliberately small:</p>
<ul>
<li><strong>P1: record expenses.</strong> Create valid records and retain successful saves after reload.</li>
<li><strong>P2: review monthly spending.</strong> Show totals, category breakdowns, filtering, and stable sorting.</li>
<li><strong>P3: correct or remove expenses.</strong> Edit records and require confirmation before permanent deletion.</li>
</ul>
<p>Each story has an independent test. That prevents “the app renders” from becoming a substitute for behavior.</p>
<p>The specification does not choose React or Playwright. A later clarification removed implementation details such as browser-vendor names, storage-envelope mechanics, and numeric representation details from this document. Those choices belong in the technical artifacts.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/4d14b216-debb-4161-982c-467be4a92421.png" alt="The generated specification with its clarification decisions and prioritized user stories" /></p>
<h2>7. Clarifying what the agent should not guess</h2>
<p>The clarification pass recorded decisions directly rather than inventing a usability study or asking for unnecessary input.</p>
<table>
<thead>
<tr>
<th>Decision</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td>Currency</td>
<td>USD, fixed <code>en-US</code>, exactly two decimals</td>
</tr>
<tr>
<td>Amount storage</td>
<td>Positive integer cents, capped at $100,000.00 per expense</td>
</tr>
<tr>
<td>Month boundaries</td>
<td>Inclusive local calendar months, no UTC conversion</td>
</tr>
<tr>
<td>Future expenses</td>
<td>Allowed only in their matching calendar month</td>
</tr>
<tr>
<td>Deletion</td>
<td>Permanent, no undo, Cancel initially focused</td>
</tr>
<tr>
<td>Malformed storage</td>
<td>Preserve the raw value and block normal writes</td>
</tr>
<tr>
<td>Failed writes</td>
<td>Retain work in memory and announce that it is unsaved</td>
</tr>
<tr>
<td>Demo data</td>
<td>Exact <code>?demo=1</code>, fictional, deterministic, in memory only</td>
</tr>
</tbody></table>
<p>Malformed data received a particularly strict rule. Starting fresh requires informed confirmation. Success writes an empty version-1 envelope. Failure preserves the original value and current work with a visible warning.</p>
<p>These choices removed ambiguity before the plan turned them into code structure. They also created acceptance tests that can fail meaningfully.</p>
<h2>8. Producing the technical plan</h2>
<p><code>/speckit-plan</code> selected one Vite application with three clear boundaries:</p>
<pre><code class="language-text">src/
├── App.tsx                 # React presentation and interaction
└── expenses/
    ├── model.ts            # Expense and view types
    ├── domain.ts           # Validation and pure calculations
    ├── persistence.ts      # Typed localStorage adapter
    └── demo.ts             # Deterministic fictional records
</code></pre>
<p>The plan also produced <code>research.md</code>, <code>data-model.md</code>, <code>contracts/ui.md</code>, and <code>quickstart.md</code>. It passed the constitution gates before and after design.</p>
<p>The plan is not the implementation. It records decisions such as native <code>&lt;dialog&gt;.showModal()</code>, pure monthly selectors, local calendar strings, and Playwright verification in a real browser. Those decisions are reviewable before they become hundreds of lines of code.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/37273a15-4cec-43bb-a228-fd942566f621.png" alt="The technical plan showing the React, TypeScript, Vite, storage, and testing decisions" /></p>
<h2>9. Checking requirement quality</h2>
<p>The quality stages produced useful findings rather than ceremonial approvals.</p>
<p><code>/speckit-checklist</code> created eight reviewer-owned requirement checks. A separate remediation pass corrected the artifacts and marked all eight only after review.</p>
<p>The first <code>/speckit-analyze</code> invocation reached a follow-up prompt without displaying its report. It was not treated as passed. The repeated invocation produced four findings:</p>
<ul>
<li>an unmeasurable performance goal;</li>
<li>a timed usability outcome without a repeatable protocol;</li>
<li>duplicated persistence language;</li>
<li>missing coverage for that usability outcome.</li>
</ul>
<p>The report measured 26/27 requirement/criterion coverage and no critical issues. Remediation replaced the usability claim with a functional browser check, declared that no numerical latency target was in scope, consolidated the persistence wording, and mapped the new criterion to existing test tasks.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/d9a9b851-6981-4b2e-a638-8e4e6369747a.png" alt="The four consistency-analysis findings and their documented resolutions" /></p>
<p>Implementation later stopped at another gate: two built-in checklist items were unchecked because implementation details had leaked into the specification. <code>/speckit-clarify</code> moved those details back into the plan and tasks. Copilot did not proceed until both checklists genuinely passed.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/43ed912e-a0fe-4a76-9c6f-ea92ded5d5bc.png" alt="Copilot paused at the requirements checklist gate beside the test-first task breakdown" /></p>
<h2>10. Generating tasks and analysing consistency</h2>
<p><code>/speckit-tasks</code> produced 16 dependency-ordered tasks. That is enough structure for this application; a 70-task breakdown would obscure rather than help.</p>
<p>The sequence begins with setup, then proves the test runner before application source exists:</p>
<pre><code class="language-text">T001  Project manifest and build configuration
T002  Vitest, jsdom, and Playwright configuration
T003  Render test fails because src/App.tsx is missing
T004–T006  Write US1 tests
T007–T009  Implement US1
T010–T012  Test and implement the dashboard
T013–T015  Test and implement edit/delete
T016  Run complete validation
</code></pre>
<p>The T003 failure was intentional and genuine. Vitest reached the test file and failed while resolving <code>../src/App</code>. It did not fail because the toolchain was broken. The sanitized output is retained in <code>evidence/workflow/missing-app-test.txt</code>.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/b9c165d7-b6b6-4b97-9822-51fbd16fb661.png" alt="The real missing-App test failure with absolute workspace paths removed" /></p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/bb8127ed-c485-4d64-b788-409a13013b12.png" alt="Copilot executing the 16-task plan beside the test-first checkpoints" /></p>
<h2>11. Implementing the application</h2>
<p>Traceability is easiest to see with FR-002, the amount rule. The pure domain function accepts a narrow decimal grammar and returns integer cents:</p>
<pre><code class="language-ts">const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(input);
if (!match) return null;

const wholePart = match[1].replace(/^0+/, "") || "0";
if (wholePart.length &gt; 6) return null;

const amountCents =
  Number(wholePart) * 100 + Number((match[2] ?? "").padEnd(2, "0"));
if (amountCents &lt;= 0 || amountCents &gt; 10_000_000) return null;
return amountCents;
</code></pre>
<p>Tests accept <code>1</code>, <code>1.2</code>, <code>1.20</code>, <code>0.01</code>, and <code>100000.00</code>. They reject blank, zero, negative, signed, grouped, currency-prefixed, exponent, whitespace-padded, nonnumeric, excess-precision, and over-limit inputs. The same validator runs for creation and editing.</p>
<p>The persistence adapter fails closed. <code>save()</code> returns <code>blocked</code> unless loading succeeded and no malformed raw value is present. A failed write leaves durable data unchanged and the current work visible. A later successful save writes the complete current collection.</p>
<p>Currency formatting also avoids a subtle boundary problem. It converts safe integer cents to <code>BigInt</code>, splits dollars and fractional cents, and uses <code>Intl.NumberFormat</code> only at presentation. It does not divide a large cent value into a potentially rounded dollar number.</p>
<p>Implementation was not flawless. The first strict build needed React and Node type packages. Native date/select controls invalidated early browser-helper assumptions. A real Chromium check showed that Tab could leave the two-button deletion dialog, so explicit Tab/Shift+Tab wrapping was added. These corrections are preserved in the <a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/evidence/workflow/implementation-notes.md">implementation notes</a>.</p>
<h2>12. Converging the code with the specification</h2>
<p>The initial implementation completed with 50 Vitest tests, 15 Chromium tests, and a passing production build. <code>/speckit-converge</code> still found a HIGH-severity gap.</p>
<p>Deleting while an edit was active left a stale draft. If no visible transaction neighbor remained, focus could reach <strong>Save changes</strong> instead of <strong>Add expense</strong>. The task checkboxes had not revealed that interaction.</p>
<p>Convergence appended T017. Two component tests and two Chromium tests reproduced the problem before the fix. Confirmed deletion now exits edit mode and clears the draft, and the fallback targets the actual Add expense button. The follow-up result was 52 Vitest tests and 17 Chromium tests passing.</p>
<p>The second convergence run checked 40 requirement and success-criterion items, 10 edge-case groups, plan decisions, and constitution constraints. It reported:</p>
<blockquote>
<p>Converged — the implementation satisfies the spec, plan, and tasks.</p>
</blockquote>
<p>It left <code>tasks.md</code> byte-for-byte unchanged. This is the useful distinction between implementation and convergence: generation says the work exists; convergence looks for observable intent that is still missing.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/4e782f62-86ae-4a32-a07d-d9867e9fc1c5.png" alt="The final clean convergence result with zero remaining findings and unchanged tasks" /></p>
<h2>13. Running and inspecting the UI</h2>
<p>The deterministic demo mode is enabled only when <code>window.location.search === "?demo=1"</code>. It never reads, writes, or listens to normal expense storage. Reload restores the same fictional records. Every other query string uses normal mode.</p>
<p>The desktop dashboard shows the selected month, exact total, all five category totals, entry form, and transaction controls. The badge explicitly says “Demo mode · fictional data · resets on reload.”</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/4d8c05a0-2376-4634-a39b-2fce9ee2a620.png" alt="The populated expense tracker dashboard at 1440×900 with clearly labeled fictional demo data" /></p>
<p>The form keeps amount, category, date, and note visible without decorative clutter.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/87472eaf-321b-4401-933b-865e37e51858.png" alt="Creating a fictional $16.80 Food expense with a Team lunch note" /></p>
<p>Filtering changes the transaction list, not the monthly totals. The Food filter shows Coffee while the monthly category totals remain derived from the unfiltered month.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/856982bd-d60c-41e0-84ad-f1eb27214f33.png" alt="Food category filtering with the matching Coffee transaction and sort controls" /></p>
<p>Invalid input produces adjacent, programmatically associated feedback and does not write a record.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/1ef2488f-61ae-4a56-8f45-22c7f2bc2fe1.png" alt="A negative amount rejected with a visible correction message" /></p>
<p>Deletion uses a native modal dialog. Cancel receives initial focus, Tab and Shift+Tab remain within the two actions, and Escape restores the invoking control.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/d656aba4-2d54-4931-bf24-cc868aa4ca3d.png" alt="The permanent deletion dialog for the fictional Transit pass with Cancel and Delete actions" /></p>
<p>The phone layout uses a 390×844 viewport. Content reflows without page-level horizontal overflow; checks also passed at 768×1024 and 1440×900.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/2ac292b2-5d30-49fc-bf23-efdaaabc18b1.png" alt="The expense tracker monthly summary and entry form at 390×844" /></p>
<p>An independent production-browser script then exercised 16 checks against the built app: keyboard creation, CRUD, exact totals, persistence, invalid amounts, filtering/sorting, deletion focus, accessibility-tree names, three viewports, failed writes, malformed storage, read retry, and console errors. All 16 passed. No console errors or uncaught page errors were recorded.</p>
<h2>14. Fixing a bug through Spec Kit</h2>
<p>The maintenance example was a genuine defect found during code review, not a planted bug. Muted text used <code>#74817c</code>, which measured 4.059:1 on white and 3.770:1 on the page background. The normal-text target was 4.5:1.</p>
<p>The official extension installed with:</p>
<pre><code class="language-bash">specify extension add bug
</code></pre>
<p>The three stages then ran separately in Copilot Chat:</p>
<pre><code class="language-text">/speckit-bug-assess ... slug=muted-text-contrast
/speckit-bug-fix slug=muted-text-contrast
/speckit-bug-test slug=muted-text-contrast
</code></pre>
<p>Assessment returned <strong>valid</strong>, severity <strong>medium</strong>, and identified the shared token and every applicable surface. Fix changed only <code>--muted</code> and added a focused Vitest regression. The test failed on all four backgrounds before the change.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/e4a222ef-29f4-44ff-ae3d-0594d463a96a.png" alt="The genuine contrast assessment with reproduction steps and a scoped remediation" /></p>
<p>The final ratios were:</p>
<table>
<thead>
<tr>
<th>Background</th>
<th align="right">Before</th>
<th align="right">After</th>
</tr>
</thead>
<tbody><tr>
<td>White</td>
<td align="right">4.059:1</td>
<td align="right">5.367:1</td>
</tr>
<tr>
<td>Page</td>
<td align="right">3.770:1</td>
<td align="right">4.985:1</td>
</tr>
<tr>
<td>Category tile</td>
<td align="right">3.803:1</td>
<td align="right">5.029:1</td>
</tr>
<tr>
<td>Gradient endpoint</td>
<td align="right">3.548:1</td>
<td align="right">4.691:1</td>
</tr>
</tbody></table>
<p>The first verification verdict was <strong>partial</strong>: all behavior checks passed, but an untracked experiment directory provided no Git baseline for the claimed two-file source change. A rerun inspected the recorded fix-session edit operations directly. They confirmed only the stylesheet token, the new test, and the fix report changed. The final verdict was <strong>verified</strong>, with no screen-reader claim.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/19ff6199-4c12-4ef3-9777-c60532f7c081.png" alt="The final verified bug report with passing contrast, test, build, browser, and scope checks" /></p>
<h2>15. What worked, what did not, and when the process is worth using</h2>
<p>The useful part was not a perfect prompt-to-code transformation. It was the number of assumptions that became reviewable before and after implementation.</p>
<table>
<thead>
<tr>
<th>Requirement</th>
<th>Evidence</th>
</tr>
</thead>
<tbody><tr>
<td>Exact amount validation</td>
<td>25 domain tests; invalid-input browser checks</td>
</tr>
<tr>
<td>Monthly and category totals</td>
<td>Pure boundary and aggregation tests; production total checks</td>
</tr>
<tr>
<td>Filtering and stable sorting</td>
<td>Domain selectors, component tests, keyboard Chromium scenario</td>
</tr>
<tr>
<td>Persistence and failed writes</td>
<td>Adapter tests, recovery browser scenarios, production reload checks</td>
</tr>
<tr>
<td>Malformed stored data</td>
<td>Raw-value preservation and informed start-fresh tests</td>
</tr>
<tr>
<td>Edit and deletion</td>
<td>Invalid-edit non-mutation, native-dialog keyboard tests, T017 regressions</td>
</tr>
<tr>
<td>Keyboard and accessible names</td>
<td>Role/name assertions and Chromium accessibility-tree inspection</td>
</tr>
<tr>
<td>Responsive layout</td>
<td>No horizontal overflow at 390×844, 768×1024, and 1440×900</td>
</tr>
<tr>
<td>Demo isolation</td>
<td>Storage/listener spies, deterministic reloads, exact-query checks</td>
</tr>
<tr>
<td>Contrast repair</td>
<td>Four source-token regressions and verified bug report</td>
</tr>
</tbody></table>
<p>The process also produced friction. Copilot invoked a prerequisite script from the wrong directory. Some test locators were ambiguous. Native <code>window.confirm</code> caused Playwright synchronization deadlocks. The first analysis did not display its report. The first bug verdict was partial. Those events belong in the evidence; removing them would make the workflow look more reliable than it was.</p>
<p>There are clear limitations. This is one user, one browser, USD only, and localStorage only. Chromium was tested, not a browser matrix. No VoiceOver review or other screen-reader verification was completed. No timed usability study or numerical latency benchmark was performed. Local browser storage is not a secure multi-device finance backend.</p>
<p>Spec Kit is most useful when requirements have meaningful edge cases, several people need to review intent, or maintenance must remain traceable. For a disposable prototype, the artifact overhead may exceed the benefit. For this experiment, convergence and the bug workflow justified the structure because they found real gaps after generation.</p>
<h2>16. Reproduction instructions and source code</h2>
<p>Clone the repository and enter the experiment:</p>
<pre><code class="language-bash">git clone https://github.com/hslimi/night-thoughts.git
cd night-thoughts/experiments/spec-kit-expense-tracker
npm ci
npx playwright install chromium
</code></pre>
<p>Run the application and verification commands:</p>
<pre><code class="language-bash">npm run dev
npm run test
npm run test:e2e
npm run build
npx vite preview --host 127.0.0.1 --port 4173
</code></pre>
<p>With the production preview running in another terminal:</p>
<pre><code class="language-bash">node scripts/verify-production.mjs
</code></pre>
<p>The final results are <strong>56/56 Vitest tests</strong>, <strong>17/17 Playwright Chromium tests</strong>, <strong>16/16 independent production-browser checks</strong>, a passing production build, clean convergence, and a verified contrast repair. The npm clean-install audit reported zero vulnerabilities.</p>
<p>The <a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/README.md">experiment README</a> explains evidence regeneration, including screenshot processing. The key source links are:</p>
<ul>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/src/">application and domain modules</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/tests/">unit and component tests</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/e2e/expenses.spec.ts">Chromium scenarios</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/specs/001-expense-tracker/">specification, plan, and tasks</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/evidence/verification/">test and build evidence</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/evidence/workflow/convergence-final.md">convergence reports</a>;</li>
<li><a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/spec-kit-expense-tracker/.specify/bugs/muted-text-contrast/">bug assessment, fix, and verification</a>.</li>
</ul>
<p>Spec Kit’s value is not merely generating code. It makes intent, decisions, tasks, and verification visible and reviewable. Human judgement remains responsible for the result.</p>
]]></content:encoded></item><item><title><![CDATA[Teaching a Small Language Model to Triage Incidents: A Beginner’s Unsloth and QLoRA Tutorial]]></title><description><![CDATA[A beginner-friendly Colab + Unsloth experiment in synthetic data, QLoRA, held-out evaluation, and strict schema validation.]]></description><link>https://nightthoughts.me/teaching-a-small-language-model-to-triage-incidents-a-beginner-s-unsloth-and-qlora-tutorial</link><guid isPermaLink="true">https://nightthoughts.me/teaching-a-small-language-model-to-triage-incidents-a-beginner-s-unsloth-and-qlora-tutorial</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[qlora]]></category><category><![CDATA[finetuning]]></category><category><![CDATA[unsloth]]></category><category><![CDATA[Google Colab]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Fri, 30 Oct 2026 00:35:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/6128f57e-8972-4407-8933-8ee037b84cc8.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most fine-tuning tutorials stop when the training loss decreases.</p>
<p>I wanted to answer a more useful operational question: can a small language model learn to turn an unstructured incident alert into a strict JSON object that another program can validate and route?</p>
<p>In this experiment, I used <strong>Google Colab</strong> for the GPU environment and <strong>Unsloth</strong> for QLoRA fine-tuning. I generated a synthetic incident dataset, kept entire incident scenarios out of training, compared the base and fine-tuned models on identical test cases, and saved the resulting adapter to Google Drive.</p>
<p>The model will not restart services, execute commands, or diagnose real infrastructure. It performs one bounded task:</p>
<pre><code class="language-text">Unstructured alert → typed incident report → independent schema validation
</code></pre>
<p>This is an educational machine-learning experiment, not a production incident-management system.</p>
<h2>What We Will Build</h2>
<p>The final pipeline looks like this:</p>
<pre><code class="language-text">Synthetic incident scenarios
            ↓
Train / validation / test split by scenario
            ↓
Qwen2.5-1.5B-Instruct loaded in 4-bit
            ↓
Baseline evaluation on unseen test scenarios
            ↓
QLoRA training with Unsloth
            ↓
Fine-tuned evaluation on the same test cases
            ↓
LoRA adapter saved to Google Drive
</code></pre>
<p>By the end, you will know how to:</p>
<ul>
<li>open and configure a GPU notebook in Google Colab;</li>
<li>generate a small synthetic JSONL dataset without downloading external data;</li>
<li>prevent near-duplicate scenarios from leaking across dataset splits;</li>
<li>format conversations with the model's own chat template;</li>
<li>evaluate a base model before training;</li>
<li>train a LoRA adapter with Unsloth and TRL;</li>
<li>measure JSON validity, schema compliance, exact matches, and field accuracy;</li>
<li>save and reload the adapter, and verify application-side schema validation.</li>
</ul>
<h2>The Output Contract</h2>
<p>Every alert must produce exactly six fields:</p>
<pre><code class="language-json">{
  "service": "payments-api",
  "severity": "sev2",
  "category": "database_capacity",
  "summary": "Database connection-pool exhaustion is causing checkout timeouts",
  "next_action": "inspect_database_connections",
  "escalate": true
}
</code></pre>
<p>The allowed values are deliberately small:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Allowed values</th>
</tr>
</thead>
<tbody><tr>
<td><code>service</code></td>
<td><code>payments-api</code>, <code>authentication</code>, <code>search</code>, <code>inventory</code>, <code>notifications</code>, <code>unknown</code></td>
</tr>
<tr>
<td><code>severity</code></td>
<td><code>sev1</code>, <code>sev2</code>, <code>sev3</code>, <code>sev4</code></td>
</tr>
<tr>
<td><code>category</code></td>
<td><code>database_capacity</code>, <code>deployment_regression</code>, <code>authentication</code>, <code>network</code>, <code>unknown</code></td>
</tr>
<tr>
<td><code>next_action</code></td>
<td><code>inspect_database_connections</code>, <code>inspect_recent_deployment</code>, <code>inspect_auth_configuration</code>, <code>inspect_network_path</code>, <code>request_more_context</code></td>
</tr>
<tr>
<td><code>escalate</code></td>
<td>JSON <code>true</code> or <code>false</code></td>
</tr>
<tr>
<td><code>summary</code></td>
<td>A short, non-empty string</td>
</tr>
</tbody></table>
<p>When the evidence is insufficient, the target category is <code>unknown</code> and the next action is <code>request_more_context</code>. The model should not invent a root cause.</p>
<p>Two labels are dataset conventions rather than universal operational rules:</p>
<ul>
<li><code>sev1</code> and <code>sev2</code> targets have <code>escalate: true</code>;</li>
<li><code>sev3</code> and <code>sev4</code> targets have <code>escalate: false</code>.</li>
</ul>
<p>A real organization would define these mappings through its own incident policy.</p>
<h2>Prerequisites</h2>
<p>You need:</p>
<ul>
<li>a Google account;</li>
<li>access to <a href="https://colab.research.google.com/">Google Colab</a>;</li>
<li>enough free Google Drive space for the dataset and adapter;</li>
<li>a modern browser.</li>
</ul>
<p>You do <strong>not</strong> need:</p>
<ul>
<li>a local GPU;</li>
<li>a Hugging Face account for the core tutorial;</li>
<li>a pre-existing dataset;</li>
<li>previous experience with Unsloth;</li>
<li>any real production logs.</li>
</ul>
<p>GPU availability and runtime limits depend on Colab availability, account limits, and plan. Do not start with the optional merged-model export until the core experiment works.</p>
<h2>Part 1: Create the Colab Notebook</h2>
<ol>
<li>Open <a href="https://colab.research.google.com/">Google Colab</a>.</li>
<li>Select <strong>New Notebook</strong>.</li>
<li>Rename it to <code>incident-triage-unsloth.ipynb</code>.</li>
<li>Open <strong>Runtime → Change runtime type</strong>.</li>
<li>Select an available <strong>GPU</strong> accelerator.</li>
<li>Save the setting.</li>
</ol>
<p>The exact GPU offered may vary. This tutorial uses a small 1.5B-parameter model and short examples to keep the experiment accessible.</p>
<h3>Cell 1 — Verify the GPU</h3>
<p>Run:</p>
<pre><code class="language-python">import torch

print("PyTorch:", torch.__version__)
print("CUDA available:", torch.cuda.is_available())

assert torch.cuda.is_available(), (
    "No GPU is active. Open Runtime → Change runtime type and select GPU."
)

print("GPU:", torch.cuda.get_device_name(0))
print("VRAM (GB):", round(torch.cuda.get_device_properties(0).total_memory / 1e9, 1))
</code></pre>
<p><strong>Expected result:</strong> <code>CUDA available: True</code>, followed by the GPU name. If the assertion fails, change the runtime type before continuing.</p>
<p>The actual runtime reported PyTorch 2.11.0+cu130, CUDA availability, and an NVIDIA RTX PRO 6000 Blackwell Server Edition with approximately 102 GB VRAM.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/c2398306-0f78-40cf-bad9-2acb5a78f7e6.png" alt="Colab GPU verification showing the RTX PRO 6000 and 102 GB VRAM" style="display:block;margin:0 auto" />

<h2>Part 2: Create a Persistent Project Folder</h2>
<p>Colab runtimes are temporary. Files stored only under <code>/content</code> can disappear when the runtime resets. We will keep generated data, predictions, metrics, and the final adapter in Google Drive.</p>
<h3>Cell 2 — Mount Google Drive</h3>
<pre><code class="language-python">from google.colab import drive
from pathlib import Path

drive.mount("/content/drive")

PROJECT_DIR = Path("/content/drive/MyDrive/nightthoughts-incident-triage")
DATA_DIR = PROJECT_DIR / "data"
RESULTS_DIR = PROJECT_DIR / "results"
ADAPTER_DIR = PROJECT_DIR / "adapter"

for directory in [PROJECT_DIR, DATA_DIR, RESULTS_DIR, ADAPTER_DIR]:
    directory.mkdir(parents=True, exist_ok=True)

print("Project folder:", PROJECT_DIR)
</code></pre>
<p>Colab will ask you to authorize Drive access. Select the same Google account you want to use for the experiment.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/798afdd6-cd16-415d-86f0-d58d24a6fe7f.png" alt="Google Drive mounted and the incident-triage project folder created" style="display:block;margin:0 auto" />

<h2>Part 3: Install Unsloth</h2>
<h3>Cell 3 — Install the packages</h3>
<pre><code class="language-python">!pip install -q unsloth
</code></pre>
<p>This can take a few minutes. If Colab reports dependency conflicts or an import fails immediately afterward, use <strong>Runtime → Restart session</strong>, then run the Drive-mount cell again before continuing. You do not normally need to reinstall after every ordinary cell.</p>
<h3>Cell 4 — Import Unsloth</h3>
<pre><code class="language-python">from unsloth import FastLanguageModel

print("Unsloth imported successfully.")
</code></pre>
<p>Unsloth imported successfully. It warned that the installed xformers build did not match PyTorch 2.11.0+cu130 and used PyTorch attention instead. I kept that documented fallback rather than changing the tutorial environment.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/37cdf04e-bcec-4057-8019-c4bf760565ce.png" alt="Cell used to install Unsloth" style="display:block;margin:0 auto" />

<h2>Part 4: Generate the Synthetic Dataset</h2>
<p>An available public log dataset would not necessarily contain our target labels, summaries, severity policy, and investigation actions. Instead, we will generate examples from <strong>25 manually defined incident scenarios</strong>:</p>
<ul>
<li>15 training scenarios;</li>
<li>5 validation scenarios;</li>
<li>5 test scenarios.</li>
</ul>
<p>Each split contains all five categories. A scenario assigned to test never appears in training or validation.</p>
<p>This is not a large or realistic production corpus. It is a controlled experiment for testing whether a small model can learn a constrained transformation and generalize to unseen incident descriptions.</p>
<h3>Cell 5 — Define the scenarios and output vocabulary</h3>
<p>This is the longest cell in the tutorial. Paste it as one block.</p>
<pre><code class="language-python">import json
import random
from collections import Counter, defaultdict

SCENARIOS = [
    # Training scenarios
    dict(id="db_pool_payments", split="train", service="payments-api", severity="sev2", category="database_capacity", next_action="inspect_database_connections", summary="Database connection-pool exhaustion is causing checkout timeouts", alert="Payments API checkout timeouts reached {pct}% after the database connection pool hit its limit. Retries are increasing and {n}% of requests are queued."),
    dict(id="db_connections_inventory", split="train", service="inventory", severity="sev2", category="database_capacity", next_action="inspect_database_connections", summary="Inventory workers cannot obtain enough database connections", alert="Inventory workers have exhausted their PostgreSQL connections. Stock updates are waiting for a free connection and the backlog has reached {n} jobs."),
    dict(id="db_slow_queries_search", split="train", service="search", severity="sev3", category="database_capacity", next_action="inspect_database_connections", summary="Search latency is rising under expensive database queries", alert="Search p95 latency increased to {n} ms. The primary database shows concurrent expensive queries and CPU saturation, but the last deployment was three days ago."),
    dict(id="deploy_checkout_timeouts", split="train", service="payments-api", severity="sev1", category="deployment_regression", next_action="inspect_recent_deployment", summary="Checkout failures began immediately after a payments deployment", alert="At 02:{minutes}, version 2026.10.{n} was deployed to payments-api. Within two minutes, checkout errors rose to {pct}% while the previous version remains healthy."),
    dict(id="deploy_search_errors", split="train", service="search", severity="sev2", category="deployment_regression", next_action="inspect_recent_deployment", summary="Search errors started with the latest release", alert="The search service began returning 500 responses immediately after release {n}. Error rate is {pct}%; the canary did not show this behavior."),
    dict(id="deploy_auth_config", split="train", service="authentication", severity="sev2", category="deployment_regression", next_action="inspect_recent_deployment", summary="Login failures followed an authentication configuration release", alert="A configuration deployment to authentication completed {minutes} minutes ago. Since then, valid logins have failed across all regions; authentication CPU and network metrics are normal."),
    dict(id="auth_token_clock", split="train", service="authentication", severity="sev3", category="authentication", next_action="inspect_auth_configuration", summary="Token validation is failing because of clock or timestamp checks", alert="Authentication rejects otherwise valid JWTs with not-before and expiration errors. One node reports a clock offset of {n} seconds; traffic and recent deployments are unchanged."),
    dict(id="auth_sso_loop", split="train", service="authentication", severity="sev2", category="authentication", next_action="inspect_auth_configuration", summary="Users are trapped in an SSO redirect loop", alert="Users cannot complete SSO login and loop between the identity provider and authentication. The callback reports a state or nonce mismatch for {pct}% of attempts."),
    dict(id="auth_permission_cache", split="train", service="authentication", severity="sev3", category="authentication", next_action="inspect_auth_configuration", summary="Authorization changes are not taking effect", alert="Revoked user permissions remain valid for up to {minutes} minutes. Authentication logs show stale role claims served from the authorization cache."),
    dict(id="network_dns_inventory", split="train", service="inventory", severity="sev2", category="network", next_action="inspect_network_path", summary="Inventory dependencies are unreachable because DNS resolution fails", alert="Inventory cannot resolve its database hostname. DNS lookups time out in two availability zones, while direct connections to the previously resolved address still work."),
    dict(id="network_packet_loss_payments", split="train", service="payments-api", severity="sev1", category="network", next_action="inspect_network_path", summary="Packet loss is disrupting payments traffic", alert="Payments-api is timing out across multiple backends. The network path shows {pct}% packet loss and retransmissions; application error logs have not changed."),
    dict(id="network_lb_search", split="train", service="search", severity="sev2", category="network", next_action="inspect_network_path", summary="One load-balancer route is dropping search requests", alert="Search requests fail only through one load-balancer route. Backend health checks pass locally, but the affected route resets {pct}% of connections."),
    dict(id="unknown_queue_notifications", split="train", service="unknown", severity="sev3", category="unknown", next_action="request_more_context", summary="The alert does not isolate a cause for delayed asynchronous work", alert="Asynchronous work is delayed and a queue depth graph is rising. Dashboards disagree about the owning service, and no dependency, release, or error evidence is available."),
    dict(id="unknown_disk_inventory", split="train", service="unknown", severity="sev3", category="unknown", next_action="request_more_context", summary="A host disk warning lacks enough evidence for incident classification", alert="A host is above {pct}% disk usage. The owning application and customer impact are unclear, and there is no evidence yet of database, deployment, authentication, or network failure."),
    dict(id="unknown_third_party", split="train", service="unknown", severity="sev4", category="unknown", next_action="request_more_context", summary="A vendor notice has no established service impact", alert="A third-party provider reports degradation in one region. Our monitoring shows no confirmed impact, affected service, or relevant internal errors."),

    # Validation scenarios: none appear in training
    dict(id="db_replication_lag", split="validation", service="inventory", severity="sev2", category="database_capacity", next_action="inspect_database_connections", summary="Database replication lag is overloading the inventory primary", alert="Inventory reads are being redirected to the primary because replica lag exceeds {n} seconds. Primary connections and query latency are now climbing."),
    dict(id="deploy_notification_retry", split="validation", service="notifications", severity="sev3", category="deployment_regression", next_action="inspect_recent_deployment", summary="A notification release introduced excessive retries", alert="Notification retry volume tripled immediately after worker release {n}. Delivery latency is increasing, while the previous worker version processes the same events normally."),
    dict(id="auth_expired_certificate", split="validation", service="authentication", severity="sev1", category="authentication", next_action="inspect_auth_configuration", summary="An expired signing certificate is blocking authentication", alert="All new SSO assertions fail signature validation. The authentication signing certificate expired {minutes} minutes ago; infrastructure connectivity is healthy."),
    dict(id="network_gateway_timeouts", split="validation", service="notifications", severity="sev2", category="network", next_action="inspect_network_path", summary="Gateway timeouts are interrupting notification delivery", alert="Notifications cannot reach the external gateway. TCP connections time out after {n} seconds in every region, while internal service-to-service calls remain healthy."),
    dict(id="unknown_metrics_gap", split="validation", service="unknown", severity="sev4", category="unknown", next_action="request_more_context", summary="Missing telemetry prevents a supported classification", alert="A dashboard panel has been blank for {minutes} minutes. The affected service, user impact, and underlying error are unknown."),

    # Test scenarios: unseen during both training and model selection
    dict(id="db_deadlock_payments", split="test", service="payments-api", severity="sev2", category="database_capacity", next_action="inspect_database_connections", summary="Database deadlocks are reducing payments capacity", alert="Payments-api database deadlocks increased to {n} per minute. Transactions roll back and connection wait time is rising, although no release occurred today."),
    dict(id="deploy_migration_errors", split="test", service="payments-api", severity="sev1", category="deployment_regression", next_action="inspect_recent_deployment", summary="A schema migration release broke payment writes", alert="Payment writes fail with an unknown-column error immediately after migration release {n}. Reads on the old path are healthy and failures correlate exactly with rollout progress."),
    dict(id="auth_key_rotation", split="test", service="authentication", severity="sev2", category="authentication", next_action="inspect_auth_configuration", summary="A signing-key rotation broke token verification", alert="Token verification began failing after last night's signing-key rotation. Old and new keys are being served inconsistently across authentication nodes."),
    dict(id="network_ipv6_route", split="test", service="search", severity="sev3", category="network", next_action="inspect_network_path", summary="A broken IPv6 route is delaying search dependencies", alert="Search dependency calls over IPv6 time out, forcing connection fallback after {n} seconds. IPv4 requests to the same hosts complete normally."),
    dict(id="unknown_worker_saturation", split="test", service="unknown", severity="sev3", category="unknown", next_action="request_more_context", summary="Generic worker saturation has no isolated root cause", alert="Several workers report high CPU and slower processing. There is no confirmed owning service, recent release, dependency failure, or authentication evidence."),
]

SERVICES = ["payments-api", "authentication", "search", "inventory", "notifications", "unknown"]
SEVERITIES = ["sev1", "sev2", "sev3", "sev4"]
CATEGORIES = ["database_capacity", "deployment_regression", "authentication", "network", "unknown"]
ACTIONS = [
    "inspect_database_connections",
    "inspect_recent_deployment",
    "inspect_auth_configuration",
    "inspect_network_path",
    "request_more_context",
]

print("Scenarios by split:", Counter(s["split"] for s in SCENARIOS))
</code></pre>
<h3>Cell 6 — Generate the examples</h3>
<p>Each example receives random metric values and optional context. An incident reference makes every alert unique without encoding its label.</p>
<pre><code class="language-python">PREFIXES = ["", "[alertmanager] ", "PRODUCTION: ", "On-call note: ", "Incident update: "]
SUFFIXES = [
    "",
    " The runbook has not been updated.",
    " No remediation has been attempted.",
    " Customer support is monitoring the situation.",
    " Keep this as an investigation-only alert.",
]

TARGET_FIELDS = ["service", "severity", "category", "summary", "next_action", "escalate"]

def make_record(scenario, sequence, rng):
    values = {
        "n": rng.randint(4, 900),
        "pct": rng.randint(8, 65),
        "minutes": rng.randint(2, 55),
    }

    alert = scenario["alert"].format(**values)
    alert = rng.choice(PREFIXES) + alert + rng.choice(SUFFIXES)
    alert += f" Incident reference: INC-{sequence:05d}."

    target = {key: scenario[key] for key in TARGET_FIELDS[:-1]}
    target["escalate"] = scenario["severity"] in {"sev1", "sev2"}

    return {
        "scenario_id": scenario["id"],
        "split": scenario["split"],
        "alert": alert,
        "target": json.dumps(target, ensure_ascii=False),
    }

rng = random.Random(3407)
records = []
examples_per_split = {"train": 100, "validation": 80, "test": 80}

sequence = 0
for scenario in SCENARIOS:
    for _ in range(examples_per_split[scenario["split"]]):
        sequence += 1
        records.append(make_record(scenario, sequence, rng))

train_records = [r for r in records if r["split"] == "train"]
validation_records = [r for r in records if r["split"] == "validation"]
test_records = [r for r in records if r["split"] == "test"]

print("Examples:", {split: len(items) for split, items in {
    "train": train_records,
    "validation": validation_records,
    "test": test_records,
}.items()})
print("Unique alerts:", len({r["alert"] for r in records}))
print("First target:", test_records[0]["target"])
</code></pre>
<p><strong>Expected counts:</strong> 1,500 training examples, 400 validation examples, and 400 test examples. All 2,300 alerts should be unique.</p>
<p>The actual counts matched those requirements exactly.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/8171b0c9-45ac-49f7-89e9-da19c8ce106d.png" alt="Actual dataset counts showing 1500 training, 400 validation, 400 test, and 2300 unique alerts" style="display:block;margin:0 auto" />

<h3>Cell 7 — Verify the split boundaries</h3>
<p>Do not skip this cell. A split check is part of the experiment, not ceremonial bookkeeping.</p>
<pre><code class="language-python">scenario_sets = {
    split: {r["scenario_id"] for r in items}
    for split, items in {
        "train": train_records,
        "validation": validation_records,
        "test": test_records,
    }.items()
}

assert not scenario_sets["train"] &amp; scenario_sets["validation"]
assert not scenario_sets["train"] &amp; scenario_sets["test"]
assert not scenario_sets["validation"] &amp; scenario_sets["test"]
assert len({r["alert"] for r in records}) == len(records)

for split, items in {
    "train": train_records,
    "validation": validation_records,
    "test": test_records,
}.items():
    category_counts = Counter(json.loads(r["target"])["category"] for r in items)
    print(split, "scenario IDs:", sorted(scenario_sets[split]))
    print(split, "categories:", dict(category_counts))
</code></pre>
<p><strong>Expected result:</strong> no assertion error, and every split contains all five categories.</p>
<p>The assertions passed. The run produced 15 training scenario IDs, five validation IDs, and five test IDs, with no overlap and all five categories in every split.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/0b4bbf4b-638e-4b71-a4ef-b78cd88697ff.png" alt="Scenario IDs and category counts verifying disjoint dataset splits" style="display:block;margin:0 auto" />

<h3>Cell 8 — Inspect and save the JSONL files</h3>
<pre><code class="language-python">for record in test_records[:2]:
    print("ALERT:", record["alert"])
    print("TARGET:", record["target"])
    print()

for split, items in {
    "train": train_records,
    "validation": validation_records,
    "test": test_records,
}.items():
    path = DATA_DIR / f"{split}.jsonl"
    with path.open("w", encoding="utf-8") as handle:
        for record in items:
            handle.write(json.dumps(record, ensure_ascii=False) + "\n")
    print("Saved", len(items), "examples to", path)
</code></pre>
<p>Read a sample manually. Synthetic data can still contain bad labels, contradictory wording, and unrealistic assumptions. For a larger experiment, inspect a random sample from every scenario before training.</p>
<h2>Part 5: Format the Conversations</h2>
<p>The model receives a system prompt, an alert, and—only in training and validation—the target JSON object. Test targets remain stored for scoring but are not included in test prompts.</p>
<h3>Cell 9 — Define the system prompt and message structure</h3>
<pre><code class="language-python">SYSTEM_PROMPT = f"""You convert incident alerts into strict JSON objects.
Return one JSON object and nothing else. Do not use Markdown fences.
Use exactly these keys: service, severity, category, summary, next_action, escalate.
Allowed service values: {json.dumps(SERVICES)}.
Allowed severity values: {json.dumps(SEVERITIES)}.
Allowed category values: {json.dumps(CATEGORIES)}.
Allowed next_action values: {json.dumps(ACTIONS)}.
summary must be a short non-empty string. escalate must be a JSON boolean.
Escalate sev1 and sev2. Do not escalate sev3 and sev4.
If the evidence is insufficient, use category unknown, service unknown,
and next_action request_more_context rather than inventing a cause."""

def prompt_messages(alert):
    return [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": "Classify this incident alert.\n\n" + alert},
    ]

def training_messages(record):
    target = json.dumps(json.loads(record["target"]), ensure_ascii=False, separators=(",", ":"))
    return prompt_messages(record["alert"]) + [
        {"role": "assistant", "content": target}
    ]

print(SYSTEM_PROMPT)
print(training_messages(train_records[0]))
</code></pre>
<h2>Part 6: Load the Base Model</h2>
<p>We will use <code>unsloth/Qwen2.5-1.5B-Instruct</code>. It is small enough for an introductory experiment while still supporting conversational instruction following.</p>
<p><code>load_in_4bit=True</code> loads the base weights in 4-bit precision. It does not mean the entire training procedure becomes four times faster or that every model will fit every GPU.</p>
<h3>Cell 10 — Load the model and tokenizer</h3>
<pre><code class="language-python">MAX_SEQ_LENGTH = 1024
BASE_MODEL = "unsloth/Qwen2.5-1.5B-Instruct"

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=BASE_MODEL,
    max_seq_length=MAX_SEQ_LENGTH,
    dtype=None,
    load_in_4bit=True,
)

print("Loaded:", BASE_MODEL)
print("Tokenizer chat template available:", tokenizer.chat_template is not None)
</code></pre>
<p>The first run downloads the model. Later runs may reuse cached files.</p>
<p>The base model loaded in 4-bit and the tokenizer reported an available chat template.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/48be144e-21d6-464f-891b-d95f5d39efda.png" alt="Qwen2.5-1.5B-Instruct loaded in 4-bit with a chat template" style="display:block;margin:0 auto" />

<h3>Cell 11 — Render the training text with the chat template</h3>
<pre><code class="language-python">from datasets import Dataset

def to_training_text(record):
    return tokenizer.apply_chat_template(
        training_messages(record),
        tokenize=False,
        add_generation_prompt=False,
    )

train_dataset = Dataset.from_list([
    {"text": to_training_text(record)} for record in train_records
])

validation_dataset = Dataset.from_list([
    {"text": to_training_text(record)} for record in validation_records
])

print(train_dataset)
print(train_dataset[0]["text"])
</code></pre>
<p>The printed text should contain the system prompt, user alert, assistant JSON response, and the special tokens required by Qwen's chat template. Do not manually add a second copy of those tokens.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/51db2e20-f514-4726-bc5f-1b0ff22cafaa.png" alt="A training conversation rendered with Qwen's chat template" style="display:block;margin:0 auto" />

<h2>Part 7: Build the Evaluator</h2>
<p>We will evaluate behavior, not just loss.</p>
<p>The evaluator distinguishes:</p>
<ul>
<li><strong>JSON-valid:</strong> the complete output parses as one JSON object;</li>
<li><strong>schema-valid:</strong> it also has exactly the required keys, types, and allowed values;</li>
<li><strong>exact match:</strong> every field equals the target;</li>
<li><strong>field accuracy:</strong> a field equals its target, with invalid outputs counted as failures;</li>
<li><strong>unknown-category recall:</strong> ambiguous cases correctly retain <code>category: unknown</code>.</li>
</ul>
<p>Markdown fences, explanations before the object, or trailing commentary fail the strict JSON check. That is intentional: the output is an application interface.</p>
<h3>Cell 12 — Define generation and strict validation</h3>
<pre><code class="language-python">import pandas as pd


def generate_answer(alert, max_new_tokens=180):
    inputs = tokenizer.apply_chat_template(
        prompt_messages(alert),
        tokenize=True,
        add_generation_prompt=True,
        return_dict=True,
        return_tensors="pt",
    ).to("cuda")

    with torch.inference_mode():
        outputs = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=False,
            use_cache=True,
        )

    generated_tokens = outputs[0][inputs["input_ids"].shape[1]:]
    return tokenizer.decode(generated_tokens, skip_special_tokens=True).strip()


def validate_prediction(text):
    try:
        value = json.loads(text)
    except (json.JSONDecodeError, TypeError):
        return None, False, False

    json_valid = True

    if not isinstance(value, dict) or set(value) != set(TARGET_FIELDS):
        return value, json_valid, False
    if value["service"] not in SERVICES:
        return value, json_valid, False
    if value["severity"] not in SEVERITIES:
        return value, json_valid, False
    if value["category"] not in CATEGORIES:
        return value, json_valid, False
    if value["next_action"] not in ACTIONS:
        return value, json_valid, False
    if not isinstance(value["summary"], str) or not value["summary"].strip():
        return value, json_valid, False
    if type(value["escalate"]) is not bool:
        return value, json_valid, False

    return value, json_valid, True


def evaluate_model(items, mode):
    predictions = []

    for index, record in enumerate(items, start=1):
        raw_output = generate_answer(record["alert"])
        parsed, json_valid, schema_valid = validate_prediction(raw_output)
        target = json.loads(record["target"])

        row = {
            "mode": mode,
            "scenario_id": record["scenario_id"],
            "alert": record["alert"],
            "raw_output": raw_output,
            "prediction": parsed,
            "target": target,
            "json_valid": json_valid,
            "schema_valid": schema_valid,
            "exact_match": schema_valid and parsed == target,
        }

        for field in TARGET_FIELDS:
            row[f"{field}_correct"] = bool(
                schema_valid and parsed[field] == target[field]
            )

        predictions.append(row)
        print(f"\r{mode}: {index}/{len(items)}", end="")

    print()
    return predictions


def summarize_predictions(predictions):
    total = len(predictions)
    metrics = {
        "cases": total,
        "json_valid_rate": sum(p["json_valid"] for p in predictions) / total,
        "schema_valid_rate": sum(p["schema_valid"] for p in predictions) / total,
        "exact_match_rate": sum(p["exact_match"] for p in predictions) / total,
    }

    for field in TARGET_FIELDS:
        metrics[f"{field}_accuracy"] = sum(
            p[f"{field}_correct"] for p in predictions
        ) / total

    unknown_cases = [p for p in predictions if p["target"]["category"] == "unknown"]
    metrics["unknown_category_recall"] = sum(
        p["schema_valid"] and p["prediction"]["category"] == "unknown"
        for p in unknown_cases
    ) / len(unknown_cases)

    return metrics
</code></pre>
<h2>Part 8: Evaluate the Base Model</h2>
<p>Evaluating all 400 test cases before and after training would be more thorough but slower. For this introductory run, use eight cases from each of the five test scenarios: <strong>40 identical held-out cases</strong> for both evaluations.</p>
<h3>Cell 13 — Select the fixed evaluation subset</h3>
<pre><code class="language-python">EVAL_PER_SCENARIO = 8
by_scenario = defaultdict(list)

for record in test_records:
    by_scenario[record["scenario_id"]].append(record)

eval_records = []
for scenario_id in sorted(by_scenario):
    eval_records.extend(by_scenario[scenario_id][:EVAL_PER_SCENARIO])

assert len(eval_records) == 40
print("Evaluation scenarios:", sorted(by_scenario))
print("Evaluation cases:", len(eval_records))
</code></pre>
<p>For a stronger final experiment, increase <code>EVAL_PER_SCENARIO</code> to <code>80</code> and rerun both evaluations. Do not change the subset between the base and fine-tuned runs.</p>
<h3>Cell 14 — Run the baseline</h3>
<pre><code class="language-python">FastLanguageModel.for_inference(model)

sample = eval_records[0]
print("ALERT:\n", sample["alert"])
print("\nBASE OUTPUT:\n", generate_answer(sample["alert"]))
print("\nTARGET:\n", sample["target"])
</code></pre>
<p>If the output is truncated, increase <code>max_new_tokens</code> in <code>generate_answer</code> from 180 to 256. Keep it unchanged for all subsequent evaluations.</p>
<p>The actual base sample was not truncated, so I kept 180 tokens. It wrapped the object in Markdown fences and also predicted several incorrect fields. Strict scoring rejects those fences.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/b77766a0-8e1d-4118-a9c7-75be077d8862.png" alt="Base model sample with Markdown fences and an incorrect incident classification" style="display:block;margin:0 auto" />

<p>Now run the full 40-case baseline:</p>
<pre><code class="language-python">base_predictions = evaluate_model(eval_records, mode="base")
base_metrics = summarize_predictions(base_predictions)

with (RESULTS_DIR / "base_predictions.json").open("w", encoding="utf-8") as handle:
    json.dump(base_predictions, handle, ensure_ascii=False, indent=2)

with (RESULTS_DIR / "base_metrics.json").open("w", encoding="utf-8") as handle:
    json.dump(base_metrics, handle, indent=2)

pd.Series(base_metrics)
</code></pre>
<p>Save these numbers. They are the comparison point for the adapter.</p>
<p>The saved baseline contained 40 prediction rows. All strict metrics were 0.00%; this is not a fence-stripped semantic score.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/f7a06341-690b-455b-8abb-329d544987c5.png" alt="Saved baseline metrics showing zero percent under the strict evaluator" style="display:block;margin:0 auto" />

<h2>Part 9: Add QLoRA Adapters</h2>
<p>QLoRA keeps the quantized base model frozen and trains a small set of low-rank adapter parameters. This is much more accessible than updating every model weight.</p>
<p>For this run, the important details are:</p>
<ul>
<li>the base model is loaded in 4-bit precision;</li>
<li>most base weights remain frozen;</li>
<li>LoRA introduces trainable low-rank adapter matrices;</li>
<li>only adapter parameters are updated;</li>
<li><code>r=16</code> is the adapter rank, meaning the inner dimension of those low-rank matrices;</li>
<li>gradient accumulation combines micro-batches and therefore changes the effective batch size;</li>
<li>QLoRA reduces memory requirements, but it does not guarantee better accuracy.</li>
</ul>
<h3>Cell 15 — Attach the adapters</h3>
<pre><code class="language-python">model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj",
    ],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",
    random_state=3407,
)

print("LoRA adapters attached.")
</code></pre>
<p><code>r=16</code> controls the adapter rank. It is a reasonable starting setting, not a universally optimal value.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/d73b999f-ca50-4fcf-9a79-96be31e3f159.png" alt="QLoRA configuration showing rank 16 and the target modules" style="display:block;margin:0 auto" />

<h2>Part 10: Train the Adapter</h2>
<p>We will run 200 optimizer steps with an effective batch size of 8:</p>
<ul>
<li>per-device batch size: 2;</li>
<li>gradient accumulation: 4;</li>
<li>effective batch: 2 × 4 = 8.</li>
</ul>
<p>Validation loss runs every 50 steps. Behavioral evaluation still happens separately afterward; a lower validation loss does not prove valid JSON or correct incident labels.</p>
<h3>Cell 16 — Configure and run training</h3>
<pre><code class="language-python">from trl import SFTConfig, SFTTrainer

FastLanguageModel.for_training(model)

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=train_dataset,
    eval_dataset=validation_dataset,
    args=SFTConfig(
        output_dir="/content/incident_triage_checkpoints",
        dataset_text_field="text",
        max_seq_length=MAX_SEQ_LENGTH,
        per_device_train_batch_size=2,
        per_device_eval_batch_size=4,
        gradient_accumulation_steps=4,
        warmup_steps=10,
        max_steps=200,
        learning_rate=2e-4,
        logging_steps=5,
        eval_strategy="steps",
        eval_steps=50,
        save_strategy="no",
        optim="adamw_8bit",
        weight_decay=0.01,
        lr_scheduler_type="linear",
        seed=3407,
        dataset_num_proc=1,
        report_to="none",
        fp16=not torch.cuda.is_bf16_supported(),
        bf16=torch.cuda.is_bf16_supported(),
    ),
)

trainer_stats = trainer.train()
print(trainer_stats)
</code></pre>
<p>The run completed all 200 optimizer steps. The training cell took 111.204 seconds; the trainer reported <code>train_runtime: 107.3805</code> seconds.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/bf864781-b11e-49ab-b819-0c6e8a45fa77.png" alt="Training output at step 200 with real validation losses" style="display:block;margin:0 auto" />

<h3>What the actual loss curves show</h3>
<p>Training loss fell from <strong>3.045980 at step 5</strong> to <strong>0.051658 at step 200</strong>. It decreased sharply through step 50 and then mostly plateaued around 0.05–0.07, with small fluctuations.</p>
<p>Validation loss did <strong>not</strong> follow the same direction. It increased at every measured checkpoint: <strong>0.631923 at step 50</strong>, <strong>0.756127 at step 100</strong>, <strong>0.808638 at step 150</strong>, and <strong>0.838244 at step 200</strong>. This is a clear train/validation divergence in this run and is consistent with worsening generalization, although four validation points from one run are not enough for a universal overfitting diagnosis. Additional steps are not justified by this run alone.</p>
<p>Training and validation losses may be logged at different steps. The diagram uses only entries from <code>trainer.state.log_history</code>; it does not smooth the training curve or invent intermediate validation points. A loss curve alone cannot prove valid JSON or correct incident classification.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/69d74518-8e84-4219-8d70-157853778d96.png" alt="Training loss decreasing and plateauing while validation loss rises from step 50 to 200" style="display:block;margin:0 auto" />

<p>If you only want a quick pipeline test, change <code>max_steps</code> to <code>20</code>. Treat that as a smoke test, not the final experiment.</p>
<p>If training stops with a CUDA out-of-memory error, restart the session, rerun from the Drive setup, and change:</p>
<pre><code class="language-python">per_device_train_batch_size = 1
</code></pre>
<p>Keep <code>gradient_accumulation_steps=4</code>; the effective batch size then becomes 4.</p>
<h2>Part 11: Evaluate the Fine-Tuned Model</h2>
<h3>Cell 17 — Generate a sample</h3>
<pre><code class="language-python">FastLanguageModel.for_inference(model)

print("ALERT:\n", sample["alert"])
print("\nFINE-TUNED OUTPUT:\n", generate_answer(sample["alert"]))
print("\nTARGET:\n", sample["target"])
</code></pre>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/0b08827b-0220-48dd-9c97-ecd130a61903.png" alt="Fine-tuned sample producing valid JSON but incorrect incident fields" style="display:block;margin:0 auto" />

<h3>Cell 18 — Evaluate the same 40 cases</h3>
<pre><code class="language-python">finetuned_predictions = evaluate_model(eval_records, mode="finetuned")
finetuned_metrics = summarize_predictions(finetuned_predictions)

with (RESULTS_DIR / "finetuned_predictions.json").open("w", encoding="utf-8") as handle:
    json.dump(finetuned_predictions, handle, ensure_ascii=False, indent=2)

with (RESULTS_DIR / "finetuned_metrics.json").open("w", encoding="utf-8") as handle:
    json.dump(finetuned_metrics, handle, indent=2)

comparison = pd.DataFrame({
    "base": pd.Series(base_metrics),
    "finetuned": pd.Series(finetuned_metrics),
})
comparison["difference"] = comparison["finetuned"] - comparison["base"]
comparison
</code></pre>
<p>Rates are stored between 0 and 1. For example, <code>0.925</code> means 92.5%. The <code>difference</code> column is an absolute change in rate, not a relative percentage improvement.</p>
<h3>Cell 19 — Show the comparison as percentages</h3>
<pre><code class="language-python">rate_metrics = [name for name in base_metrics if name != "cases"]
percentages = comparison.loc[rate_metrics, ["base", "finetuned", "difference"]] * 100
percentages.round(2)
</code></pre>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/e7bc6b95-b04e-4718-ad8d-def442dc790e.png" alt="Base and fine-tuned metrics with absolute percentage-point changes" style="display:block;margin:0 auto" />

<p>Do not assume every metric must improve. A model can produce perfectly valid JSON while learning the wrong category. Exact matches and per-field behavior matter.</p>
<h2>Part 12: Inspect Failures</h2>
<p>Aggregate scores hide useful information. Print examples where the fine-tuned output was invalid or did not exactly match the target.</p>
<h3>Cell 20 — Inspect incorrect cases</h3>
<pre><code class="language-python">failures = [p for p in finetuned_predictions if not p["exact_match"]]
print("Fine-tuned failures:", len(failures), "of", len(finetuned_predictions))

for failure in failures[:5]:
    print("\nSCENARIO:", failure["scenario_id"])
    print("ALERT:", failure["alert"])
    print("MODEL OUTPUT:", failure["raw_output"])
    print("TARGET:", json.dumps(failure["target"], ensure_ascii=False))
    print("JSON valid:", failure["json_valid"], "Schema valid:", failure["schema_valid"])
</code></pre>
<p>For each failure, ask:</p>
<ol>
<li>Was the alert genuinely ambiguous?</li>
<li>Did the model choose a plausible but different service or category?</li>
<li>Did it ignore the severity policy?</li>
<li>Did it produce extra prose or an invalid type?</li>
<li>Did it invent a specific cause for an <code>unknown</code> example?</li>
<li>Is the target itself wrong or unrealistic?</li>
</ol>
<p>Keep both successes and failures in the article. A small synthetic experiment is more credible when its limitations are visible.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/83a6303a-9956-4596-83d8-4bd46b16dc40.png" alt="Failure inspection showing 40 non-exact fine-tuned cases and concrete misclassifications" style="display:block;margin:0 auto" />

<h2>Part 13: Save and Reload the Adapter</h2>
<p>The adapter requires the original base model. It is not a standalone full model.</p>
<h3>Cell 21 — Save the adapter and tokenizer</h3>
<pre><code class="language-python">model.save_pretrained(str(ADAPTER_DIR))
tokenizer.save_pretrained(str(ADAPTER_DIR))

print("Adapter saved to:", ADAPTER_DIR)
print("Files:", sorted(path.name for path in ADAPTER_DIR.iterdir()))
</code></pre>
<p>The saved directory should include adapter configuration and weight files, plus tokenizer files. Because it is on Drive, it should remain after the Colab runtime ends.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/bb7fbfef-b732-4581-a057-06ea6e16be04.png" alt="Adapter and tokenizer files saved to Google Drive" style="display:block;margin:0 auto" />

<p>The adapter also reloaded successfully from Drive. No merged-model export or Apple Silicon/MLX conversion was needed for this core experiment.</p>
<h3>Reloading in a fresh session</h3>
<p>After a runtime restart, mount Drive again, define <code>ADAPTER_DIR</code>, and run:</p>
<pre><code class="language-python">from unsloth import FastLanguageModel

ADAPTER_DIR = "/content/drive/MyDrive/nightthoughts-incident-triage/adapter"

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=ADAPTER_DIR,
    max_seq_length=1024,
    dtype=None,
    load_in_4bit=True,
)

FastLanguageModel.for_inference(model)
print("Adapter reloaded.")
</code></pre>
<p>To generate after reloading, you must also redefine <code>SERVICES</code>, <code>SEVERITIES</code>, <code>CATEGORIES</code>, <code>ACTIONS</code>, <code>SYSTEM_PROMPT</code>, <code>prompt_messages</code>, and <code>generate_answer</code> from the earlier cells. This is why saving the notebook alongside the adapter matters.</p>
<h2>Part 14: Add Independent Application-Side Validation</h2>
<p>A fine-tuned model is not a schema validator. The application must still validate every result before using it.</p>
<p>A minimal routing pattern is:</p>
<pre><code class="language-python">def route_incident(alert):
    raw_output = generate_answer(alert)
    parsed, json_valid, schema_valid = validate_prediction(raw_output)

    if not schema_valid:
        return {
            "status": "manual_review",
            "reason": "The model output did not satisfy the incident schema.",
            "raw_output": raw_output,
        }

    if parsed["category"] == "unknown":
        return {
            "status": "request_more_context",
            "report": parsed,
        }

    return {
        "status": "validated_for_human_review",
        "report": parsed,
    }
</code></pre>
<p>Notice what this function does <strong>not</strong> do: it does not execute <code>next_action</code>, restart a service, roll back a deployment, or modify infrastructure. Those decisions belong behind separate authorization and safety controls.</p>
<h2>Actual Results</h2>
<p>All values below come from the saved prediction, metric, metadata, and trainer-log files. The complete notebook, datasets, predictions, plotting source, and screenshots are in the <a href="https://github.com/hslimi/night-thoughts/tree/main/experiments/incident-triage-unsloth">GitHub experiment folder</a>.</p>
<h3>Experimental setup</h3>
<ul>
<li>Base model: <code>unsloth/Qwen2.5-1.5B-Instruct</code>, loaded in 4-bit</li>
<li>Training examples: <strong>1,500</strong></li>
<li>Validation examples: <strong>400</strong></li>
<li>Total test examples generated: <strong>400</strong></li>
<li>Unique alerts: <strong>2,300</strong></li>
<li>Fixed behavioral evaluation subset: <strong>40</strong>, eight per unseen test scenario</li>
<li>Training steps: <strong>200</strong></li>
<li>LoRA rank: <strong>16</strong></li>
<li>Maximum sequence length: <strong>1,024</strong></li>
<li>GPU used: <strong>NVIDIA RTX PRO 6000 Blackwell Server Edition</strong>, approximately <strong>102 GB VRAM</strong></li>
</ul>
<h3>Base versus fine-tuned results</h3>
<p>Rates are shown as percentages. The change column is an absolute change in <strong>percentage points (pp)</strong>, not a relative improvement.</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th align="right">Base</th>
<th align="right">Fine-tuned</th>
<th align="right">Absolute change</th>
</tr>
</thead>
<tbody><tr>
<td>JSON validity</td>
<td align="right">0.00%</td>
<td align="right">100.00%</td>
<td align="right">+100.00 pp</td>
</tr>
<tr>
<td>Schema validity</td>
<td align="right">0.00%</td>
<td align="right">100.00%</td>
<td align="right">+100.00 pp</td>
</tr>
<tr>
<td>Exact match</td>
<td align="right">0.00%</td>
<td align="right">0.00%</td>
<td align="right">+0.00 pp</td>
</tr>
<tr>
<td>Service accuracy</td>
<td align="right">0.00%</td>
<td align="right">97.50%</td>
<td align="right">+97.50 pp</td>
</tr>
<tr>
<td>Severity accuracy</td>
<td align="right">0.00%</td>
<td align="right">42.50%</td>
<td align="right">+42.50 pp</td>
</tr>
<tr>
<td>Category accuracy</td>
<td align="right">0.00%</td>
<td align="right">60.00%</td>
<td align="right">+60.00 pp</td>
</tr>
<tr>
<td>Summary accuracy</td>
<td align="right">0.00%</td>
<td align="right">0.00%</td>
<td align="right">+0.00 pp</td>
</tr>
<tr>
<td>Next-action accuracy</td>
<td align="right">0.00%</td>
<td align="right">70.00%</td>
<td align="right">+70.00 pp</td>
</tr>
<tr>
<td>Escalation accuracy</td>
<td align="right">0.00%</td>
<td align="right">60.00%</td>
<td align="right">+60.00 pp</td>
</tr>
<tr>
<td>Unknown-category recall</td>
<td align="right">0.00%</td>
<td align="right">100.00%</td>
<td align="right">+100.00 pp</td>
</tr>
</tbody></table>
<h3>How to interpret the behavior</h3>
<p>The adapter clearly learned the output interface: strict JSON and schema validity both improved by 100 percentage points. That is a real improvement, but it is not the same as solving incident triage.</p>
<p>Exact match remained <strong>0.00%</strong>, and summary accuracy also remained <strong>0.00%</strong>. Service recognition was strong at <strong>97.50%</strong>, while severity accuracy was only <strong>42.50%</strong>. Category, next-action, and escalation accuracy reached <strong>60.00%</strong>, <strong>70.00%</strong>, and <strong>60.00%</strong> respectively. Both <code>auth_key_rotation</code> and <code>deploy_migration_errors</code> received the correct category for 0 of 8 cases; the other three test scenarios received 8 of 8.</p>
<p>Unknown-category recall reached <strong>100.00%</strong>, but that represents only eight synthetic ambiguous alerts. It does not establish reliable abstention on real incidents.</p>
<p>The zero baseline field scores also need context. The base model often emitted readable objects inside Markdown fences. The strict evaluator rejects the entire output, and invalid outputs count as failures for field accuracy. These results therefore measure the complete application contract, not a separate fence-stripped semantic evaluation.</p>
<h3>One partially successful held-out case—not an exact match</h3>
<p>No case matched all six fields exactly. This example from <code>unknown_worker_saturation</code> matched <strong>five of six fields</strong>: service, severity, category, next action, and escalation. Only the summary differed.</p>
<p><strong>Alert:</strong></p>
<pre><code class="language-text">Several workers report high CPU and slower processing. There is no confirmed owning service, recent release, dependency failure, or authentication evidence. Customer support is monitoring the situation. Incident reference: INC-02222.
</code></pre>
<p><strong>Fine-tuned output:</strong></p>
<pre><code class="language-json">{"service":"unknown","severity":"sev3","category":"unknown","summary":"Worker complaints without clear incident evidence","next_action":"request_more_context","escalate":false}
</code></pre>
<p><strong>Target:</strong></p>
<pre><code class="language-json">{"service":"unknown","severity":"sev3","category":"unknown","summary":"Generic worker saturation has no isolated root cause","next_action":"request_more_context","escalate":false}
</code></pre>
<p>This is a useful partial success because the model preserved uncertainty and requested more context. It still does not count as an exact match.</p>
<h3>One genuine failure</h3>
<p><strong>Alert:</strong></p>
<pre><code class="language-text">Token verification began failing after last night's signing-key rotation. Old and new keys are being served inconsistently across authentication nodes. Customer support is monitoring the situation. Incident reference: INC-02061.
</code></pre>
<p><strong>Fine-tuned output:</strong></p>
<pre><code class="language-json">{"service":"authentication","severity":"sev3","category":"deployment_regression","summary":"Token validations are failing because different parts of the network use distinct key rings","next_action":"inspect_auth_configuration","escalate":false}
</code></pre>
<p><strong>Target:</strong></p>
<pre><code class="language-json">{"service":"authentication","severity":"sev2","category":"authentication","summary":"A signing-key rotation broke token verification","next_action":"inspect_auth_configuration","escalate":true}
</code></pre>
<p><strong>What happened:</strong> the output was valid JSON and schema-valid, but the model predicted <code>sev3</code> instead of <code>sev2</code>, <code>deployment_regression</code> instead of <code>authentication</code>, and <code>escalate: false</code> instead of <code>true</code>. It also generated a different summary. This example shows why schema validation cannot replace task evaluation or human review.</p>
<h3>What this 40-case subset can and cannot establish</h3>
<p>The paired subset is enough to demonstrate a substantial change in output formatting and to expose remaining field-level failures in this particular run. It is too small for strong performance claims. The alerts are synthetic and template-derived, and agreement with tutorial labels is not proof of real-world incident-diagnosis accuracy. A stronger follow-up would evaluate all 400 test cases and add independently written, human-reviewed scenarios.</p>
<h2>Troubleshooting</h2>
<h3><code>CUDA available: False</code></h3>
<p>No GPU is attached. Open <strong>Runtime → Change runtime type</strong>, select GPU, and rerun the notebook. If no GPU is available, wait or use another available runtime rather than attempting QLoRA on CPU.</p>
<h3><code>No module named 'unsloth'</code> after installation</h3>
<p>Restart the session once, mount Drive again, and retry the import. Then continue from the dataset cells.</p>
<h3>CUDA out of memory during training</h3>
<p>Change the per-device training batch size to 1. If necessary, reduce <code>MAX_SEQ_LENGTH</code> to 768 everywhere and recreate the model and trainer. Do not change only one occurrence and assume the whole pipeline updated.</p>
<h3>The model output stops before the JSON closes</h3>
<p>Increase <code>max_new_tokens</code> from 180 to 256 in <code>generate_answer</code>. Rerun both base and fine-tuned evaluations with the same value.</p>
<h3>The model wraps JSON in Markdown fences</h3>
<p>That output fails this experiment's strict contract. Do not silently strip fences during scoring. Improving that behavior is part of fine-tuning. An application may add a separate repair layer, but repaired and strict metrics should be reported separately.</p>
<h3>Exact match is low but schema validity is high</h3>
<p>The model learned the interface but not necessarily the incident mapping. Inspect category, service, severity, and action accuracy separately. Review whether the synthetic scenarios provide enough consistent evidence.</p>
<h3>The model performs well on random held-out rows but poorly here</h3>
<p>Random rows from the same scenario can be near-duplicates. This tutorial splits by scenario specifically to make generalization harder and the result more informative.</p>
<h3>Colab disconnects</h3>
<p>The generated data and completed metrics are on Drive. Training checkpoints are disabled to keep the workflow simple, so an interrupted training run may need to restart. After reconnecting, rerun cells in order and avoid overwriting previous result files until you have inspected them.</p>
<h3>Drive runs out of space</h3>
<p>Keep the adapter and metrics, delete unneeded merged-model copies, and empty Drive trash if appropriate. Do not delete the adapter before verifying that it reloads.</p>
<h2>Limitations</h2>
<p>This experiment has several important limits:</p>
<ul>
<li>The alerts are synthetic and template-derived.</li>
<li>Twenty-five scenarios cannot represent real operational diversity.</li>
<li>The severity and escalation rules are tutorial conventions.</li>
<li>Exact-match metrics measure agreement with our targets, not objective root-cause truth.</li>
<li>A 40-case behavioral subset is useful for a first run but too small for strong performance claims.</li>
<li>High schema compliance does not make autonomous remediation safe.</li>
<li>A model trained on this dataset should not be exposed to real production alerts with the expectation of reliable diagnosis.</li>
</ul>
<p>The next useful iteration would add more diverse human-reviewed scenarios, paraphrases written independently of the templates, confusing multi-cause incidents, a larger held-out set, and a separate test of converted-model behavior.</p>
<h2>Conclusion</h2>
<p>Colab supplies the temporary training environment; Unsloth supplies the model-loading and QLoRA workflow. The more important engineering work happens around them: defining a narrow contract, constructing inspectable data, separating scenarios across splits, evaluating the base model first, and validating every generated object.</p>
<p>The goal was not to build an autonomous site-reliability engineer. It was to test whether a small model could become a reliable component at one boundary of a larger system.</p>
<p>A decreasing loss curve shows that training happened. Held-out behavioral metrics show what the adapter actually learned.</p>
<h2>Official Documentation</h2>
<ul>
<li><a href="https://unsloth.ai/docs/get-started/fine-tuning-llms-guide">Unsloth fine-tuning guide</a></li>
<li><a href="https://unsloth.ai/docs/basics/troubleshooting-and-faqs">Unsloth troubleshooting and evaluation</a></li>
<li><a href="https://huggingface.co/docs/trl/index">Hugging Face TRL documentation</a></li>
<li><a href="https://colab.research.google.com/">Google Colab</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Beyond DeepSeek and Qwen: Five Teams Building China’s Open-Source AI Foundations]]></title><description><![CDATA[How Shanghai AI Lab, BAAI, OpenBMB, ByteDance Seed, and OpenCSG are strengthening the ecosystem with tools, datasets, training infrastructure, and…]]></description><link>https://nightthoughts.me/beyond-deepseek-and-qwen-five-teams-building-china-s-open-source-ai-foundations</link><guid isPermaLink="true">https://nightthoughts.me/beyond-deepseek-and-qwen-five-teams-building-china-s-open-source-ai-foundations</guid><category><![CDATA[open source]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[china]]></category><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Tue, 27 Oct 2026 15:22:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/a8c69d5f-4021-4c01-ae28-d6ce6d9d02b9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The most important Chinese contribution to open-source AI may not be a model at all.</p>
<p>International coverage tends to organize Chinese AI around a familiar cast: DeepSeek for reasoning, Qwen for open-weight models, and a rotating group of technology giants competing for the next benchmark headline. That focus is understandable. Frontier models are visible, measurable, and easy to compare.</p>
<p>But powerful AI systems are not built from model weights alone. They require document parsers, retrieval models, training frameworks, reinforcement-learning infrastructure, evaluation tools, and carefully filtered datasets. These components rarely produce viral demonstrations. Yet they determine whether researchers and companies can reproduce results, adapt models, and deploy them economically.</p>
<p>This is where a different group of Chinese contributors deserves attention. They are not literally secret: some are government-supported, others belong to major companies, and most actively promote their work. They are “hidden” primarily from an international conversation that treats model launches as the main event and infrastructure as an afterthought.</p>
<p>Here are five worth knowing.</p>
<h2>1. Shanghai AI Lab: Building the Machinery Around Models</h2>
<p>Shanghai AI Laboratory’s most consequential work may be its attempt to cover almost the entire development pipeline.</p>
<p><a href="https://github.com/opendatalab/MinerU">MinerU</a> converts complex documents into machine-readable content. <a href="https://opendatalab.com/">OpenDataLab</a> distributes datasets. <a href="https://github.com/InternLM/xtuner">XTuner</a> supports training and fine-tuning. <a href="https://github.com/InternLM/lmdeploy">LMDeploy</a> handles inference and serving. <a href="https://github.com/open-compass/opencompass">OpenCompass</a> provides evaluation infrastructure. The InternLM and Intern-S model families sit above this supporting stack.</p>
<p>MinerU is the clearest example of international reach. Its repository now has roughly <a href="https://github.com/opendatalab/MinerU">82,600 GitHub stars</a>—evidence of substantial developer interest, even though stars should not be confused with production adoption.</p>
<p>The laboratory’s scientific work also produced a more unusual achievement. According to the paper’s <a href="https://arxiv.org/abs/2608.03738">declaration of AI use</a>, an internal version of Intern-S2 assisted mathematician Jiesong Zhang through multiple dialogue rounds while developing arguments for a proof of the codimension-one case of the Ghys conjecture, including complex dimension three. The human author independently verified the mathematics, and a Peking University team subsequently formalized the central results in Lean.</p>
<p>That is not autonomous mathematical discovery. It is something more credible and, in some ways, more useful: evidence that a model can participate in a serious human-guided research process.</p>
<p>Shanghai AI Lab should nevertheless be described accurately. It is a <a href="https://thediplomat.com/2020/08/chinas-artificial-intelligence-government-strategy-and-its-capabilities/">government-supported institutional powerhouse</a>, not a scrappy underground collective. Its tools are significant, but claims that global startups universally depend on them require stronger adoption evidence. The achievement is the breadth and usefulness of the portfolio—not a proven monopoly over AI infrastructure.</p>
<h2>2. BAAI: Making Retrieval Part of the Open-Source Foundation</h2>
<p>The Beijing Academy of Artificial Intelligence, or BAAI, illustrates why some of the most useful AI components never become household names.</p>
<p>Its <a href="https://github.com/FlagOpen/FlagEmbedding">BGE family</a> focuses on embeddings and reranking: the machinery that helps systems retrieve relevant information before a language model generates an answer. This is central to retrieval-augmented generation, enterprise search, and knowledge-based assistants.</p>
<p><a href="https://github.com/FlagOpen/FlagEmbedding/tree/master/FlagEmbedding/abc/inference">BGE-M3</a>, for example, supports more than 100 languages, inputs of up to 8,192 tokens, and dense, sparse, and multi-vector retrieval within one model family.</p>
<p>That combination addresses practical engineering problems rather than offering a spectacular chatbot demonstration. Developers building multilingual retrieval systems need components that can be downloaded, evaluated, fine-tuned, and integrated into existing pipelines. BGE gives them a reusable starting point.</p>
<p>The broader lesson is that open-source progress does not always arrive as a smarter conversational model. Sometimes it arrives as a better way to connect models to information. Retrieval infrastructure may never dominate social-media discussions, but without it, many impressive demonstrations collapse into unreliable systems with no dependable access to external knowledge.</p>
<h2>3. OpenBMB: Arguing That Small Models Matter</h2>
<p>OpenBMB, a collaboration associated with Tsinghua University’s NLP researchers and ModelBest, has made efficiency its central technical argument.</p>
<p>Its <a href="https://github.com/OpenBMB/MiniCPM">MiniCPM family</a> targets local and resource-constrained deployment rather than simply maximizing parameter count. This matters because most developers do not operate frontier-scale infrastructure. Models that run on laptops, phones, and modest servers expand the group of people able to experiment, customize, and build.</p>
<p>An <a href="https://artificialanalysis.ai/models/minicpm-v4-6-1-3b">independent Artificial Analysis evaluation</a> of MiniCPM-V 4.6’s 1.3B variant identified it as a new efficiency frontier on its intelligence-versus-parameter comparison. The same report describes OpenBMB as a Tsinghua–ModelBest collaboration founded in 2022 and notes the model’s Apache 2.0 release.</p>
<p>The project’s more interesting contribution is increasingly the material released around the models. The <a href="https://github.com/OpenBMB/MiniCPM">MiniCPM5 repository</a> lists training datasets covering web data, code, supervised fine-tuning, agent behavior, and reinforcement learning.</p>
<p>Weights allow experimentation. Data and training resources help explain how the result was produced.</p>
<p>OpenBMB’s efficiency claims still require model-by-model scrutiny, particularly when benchmark tables come from the authors. But its strategic insight is sound: open-source AI becomes more democratic not only when the largest models are released, but also when capable systems fit within realistic computing budgets.</p>
<h2>4. ByteDance Seed: Opening the Reinforcement-Learning Workshop</h2>
<p>ByteDance is hardly an obscure company. Its Seed research organization nevertheless belongs in this discussion because some of its most valuable open-source work concerns the training process rather than consumer products.</p>
<p>The <a href="https://github.com/volcengine/verl">verl framework</a> provides infrastructure for reinforcement-learning post-training. It supports algorithms such as PPO and GRPO and integrates with systems including FSDP, Megatron-LM, vLLM, and SGLang.</p>
<p>That matters because modern reasoning models depend heavily on post-training, yet the necessary infrastructure is difficult to reproduce. Researchers must coordinate training, generation, reward calculation, distributed computation, and rapidly changing model states. A model card alone reveals little about how to make that process work.</p>
<p><a href="https://arxiv.org/abs/2503.14476">DAPO</a>, developed by ByteDance Seed with Tsinghua AIR and collaborators, pushed further by releasing the algorithm, code infrastructure, and dataset for a large-scale reinforcement-learning system. The project also published <a href="https://github.com/BytedTsinghua-SIA/DAPO">reproduction scripts and training records</a>.</p>
<p>This is a particularly meaningful form of openness. It moves beyond “here are the finished weights” toward “here is a substantial part of the workshop used to produce them.”</p>
<p>The broader community benefits even when it does not adopt DAPO itself. Published techniques and working code provide baselines that other researchers can inspect, modify, criticize, and improve.</p>
<h2>5. OpenCSG: Treating Data as Infrastructure</h2>
<p>OpenCSG represents the least glamorous layer of all: datasets and the systems used to manage them.</p>
<p>Its Chinese corpus projects—including <a href="https://opencsg.com/blog/72">Fineweb-Edu-Chinese, Cosmopedia-Chinese, and Smoltalk-Chinese</a>—focus on filtering, scoring, formatting, and preparing text for training. OpenCSG says these datasets contributed to the Chinese training material used for MiniCPM4, offering a concrete example of one open project feeding another.</p>
<p>Its <a href="https://github.com/OpenCSGs/CSGHub">CSGHub platform</a> addresses a different problem: governing models, datasets, code, and related assets throughout their lifecycle.</p>
<p>This work deserves attention because dataset quality often determines whether a training run succeeds. Scale without provenance, deduplication, licensing clarity, and quality control can produce little more than expensive noise.</p>
<p>But OpenCSG also demonstrates why “open” should never be accepted as a blanket description. The license for <a href="https://opencsg.com/datasets/AI-ModelScope/fineweb-edu-chinese-v2.2">Fineweb-Edu-Chinese V2.2</a> asks commercial users to contact the organization and obtain permission. That does not erase the dataset’s value, but it is materially different from unrestricted Apache-licensed reuse.</p>
<p>Recognizing community contributions should not mean abandoning license scrutiny. It should mean examining each artifact individually.</p>
<h2>The Real Story Is an Ecosystem, Not a Secret Conspiracy</h2>
<p>These organizations do not share one governance model or one motive. Shanghai AI Lab and BAAI are institutional research organizations. OpenBMB connects academic and commercial participants. ByteDance Seed belongs to a technology giant. OpenCSG combines community resources with commercial platform ambitions.</p>
<p>Their openness is therefore neither pure altruism nor meaningless marketing. Open releases can attract developers, establish technical standards, recruit researchers, improve domestic infrastructure, and create commercial opportunities—all while providing genuine public value.</p>
<p>The appropriate response is neither uncritical celebration nor automatic suspicion. It is evaluation based on concrete questions:</p>
<ul>
<li>Are the artifacts reusable outside the original organization?</li>
<li>Are the code, data, and training details sufficient for reproduction?</li>
<li>Are the licenses actually permissive?</li>
<li>Is maintenance sustained after the announcement?</li>
<li>Are external developers building on the work?</li>
<li>Are performance claims independently reproduced?</li>
</ul>
<p>By those standards, the five organizations above have made contributions worth serious attention, even if none individually justifies a grand narrative about secretly powering global AI.</p>
<p>The international community should stop treating Chinese open source as a story about a few famous model brands. The deeper story is an expanding network of laboratories, companies, academic teams, and data projects supplying different parts of the AI development process.</p>
<p>Some of their most important releases will never trend like a frontier chatbot. But a parser that makes documents usable, an embedding model that improves retrieval, a training framework that exposes reinforcement-learning recipes, or a dataset that makes experimentation cheaper can influence far more work than its public recognition suggests.</p>
<p>These players are not hidden because their work is unavailable. They are hidden because we have been looking too narrowly at what counts as an AI achievement.</p>
<h2>References</h2>
<ol>
<li><a href="https://github.com/opendatalab/MinerU">MinerU — OpenDataLab’s document-parsing project</a></li>
<li><a href="https://opendatalab.com/">OpenDataLab — Dataset platform</a></li>
<li><a href="https://github.com/InternLM/xtuner">XTuner — Training and fine-tuning framework</a></li>
<li><a href="https://github.com/InternLM/lmdeploy">LMDeploy — Model compression, deployment, and serving toolkit</a></li>
<li><a href="https://github.com/open-compass/opencompass">OpenCompass — Model-evaluation platform</a></li>
<li><a href="https://arxiv.org/abs/2608.03738">Jiesong Zhang, “Codimension-One Holomorphic Anosov Diffeomorphisms”</a></li>
<li><a href="https://thediplomat.com/2020/08/chinas-artificial-intelligence-government-strategy-and-its-capabilities/">The Diplomat — Background on Shanghai AI Laboratory’s government support</a></li>
<li><a href="https://github.com/FlagOpen/FlagEmbedding">FlagEmbedding — Home of the BGE embedding and reranking models</a></li>
<li><a href="https://github.com/FlagOpen/FlagEmbedding/tree/master/FlagEmbedding/abc/inference">BGE-M3 — Multilingual, multi-functionality, and multi-granularity retrieval</a></li>
<li><a href="https://github.com/OpenBMB/MiniCPM">MiniCPM — OpenBMB’s efficient multimodal model family</a></li>
<li><a href="https://artificialanalysis.ai/models/minicpm-v4-6-1-3b">Artificial Analysis — Independent assessment of MiniCPM-V 4.6 1.3B</a></li>
<li><a href="https://github.com/volcengine/verl">verl — Reinforcement-learning training infrastructure for language models</a></li>
<li><a href="https://arxiv.org/abs/2503.14476">DAPO — An Open-Source LLM Reinforcement Learning System at Scale</a></li>
<li><a href="https://github.com/BytedTsinghua-SIA/DAPO">DAPO — Code, reproduction scripts, and training records</a></li>
<li><a href="https://opencsg.com/blog/72">OpenCSG — Chinese-language training datasets and MiniCPM4</a></li>
<li><a href="https://github.com/OpenCSGs/CSGHub">CSGHub — Open-source platform for managing AI assets</a></li>
<li><a href="https://opencsg.com/datasets/AI-ModelScope/fineweb-edu-chinese-v2.2">Fineweb-Edu-Chinese V2.2 — Dataset card and licensing conditions</a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Teaching a Small Local Model to Think in Differentials]]></title><description><![CDATA[A DDXPlus and QLoRA experiment on Apple Silicon, from held-out evaluation to oMLX deployment]]></description><link>https://nightthoughts.me/teaching-a-small-local-model-to-think-in-differentials</link><guid isPermaLink="true">https://nightthoughts.me/teaching-a-small-local-model-to-think-in-differentials</guid><category><![CDATA[LLM's ]]></category><category><![CDATA[qlora]]></category><category><![CDATA[MLX]]></category><category><![CDATA[Python]]></category><category><![CDATA[synthetic data]]></category><category><![CDATA[AI]]></category><category><![CDATA[finetuning]]></category><category><![CDATA[mlops]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Sun, 25 Oct 2026 16:53:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/0a91b585-1f73-4080-a076-f3823849f30b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most fine-tuning tutorials end when training loss decreases.</p>
<p>I wanted to answer a more interesting question: given a synthetic patient’s symptoms, can a small local model learn not only what is most likely—but what else it could be?</p>
<p>I fine-tuned <strong>Qwen2.5-1.5B-Instruct</strong> on <strong>English DDXPlus</strong> using native <strong>MLX LM</strong> and <strong>QLoRA-style adaptation</strong>. Then I compared the base and fine-tuned models on identical held-out cases, removed a finding to test the adapter’s sensitivity, fused the adapter, and deployed the result through <strong>oMLX</strong> and <strong>QwenPaw</strong>.</p>
<p>This is an educational machine-learning experiment on synthetic cases—not a clinical tool and not medical advice.</p>
<h2>Foundation: the local serving stack</h2>
<p>This experiment builds on the always-on local serving foundation described in my <a href="https://nightthoughts.me/complete-guide-always-on-mac-server-with-mlx-omlx-qwenpaw">Complete Guide to an Always-On Mac Server with MLX, oMLX, and QwenPaw</a>. If you still need to install or configure that stack and its background services, start there. This article assumes that foundation for the deployment stage and focuses on the DDXPlus data, QLoRA-style training, held-out evaluation, and reversible integration.</p>
<h2>The mental model before we start</h2>
<p>I did not train a language model from scratch. I started with a pretrained general-purpose instruct model: earlier training had already given it language and instruction-following capabilities. I then specialized its behavior using synthetic DDXPlus examples and kept the original base model unchanged for comparison.</p>
<p>The experiment covers four different questions:</p>
<ul>
<li><strong>Data preparation:</strong> can I turn coded synthetic cases into faithful training examples without mixing the official splits?</li>
<li><strong>Adaptation:</strong> can a small adapter learn the constrained response behavior while the base weights remain frozen?</li>
<li><strong>Behavioral evaluation:</strong> do label agreement and response structure improve on withheld cases, rather than only improving the loss curve?</li>
<li><strong>Deployment:</strong> can I serve and use a standalone artifact, then restore the previous application configuration?</li>
</ul>
<pre><code class="language-text">Pretrained instruct model + decoded DDXPlus examples
                         ↓
               Train a small adapter
                         ↓
Base vs base + adapter on identical held-out cases
                         ↓
      Verified fused model → oMLX → QwenPaw
</code></pre>
<p>“Teaching the model to think in differentials” is an experimental metaphor. The model is trained to produce a most-likely dataset label and ranked alternatives, not a clinician-style reasoning trace.</p>
<h2>The command style</h2>
<p>Each stage uses complete command blocks. Every block enters the experiment directory, activates the environment when needed, performs the operation, verifies its result, and stops on failure. There is no manual script editing between commands.</p>
<p>The implementation is too long to repeat usefully in the article, so the blocks use the reviewed companion source rather than hiding important corrections inside abbreviated examples. The first block checks for that source and stops rather than silently replacing it when unavailable:</p>
<pre><code class="language-text">night-thoughts/
└── experiments/
    └── ddxplus-mlx-lora/
</code></pre>
<p>Keep genuine stdout and stderr under <code>results/logs/</code>. Existing datasets, adapters, and full evaluation responses should be inspected and reused rather than silently overwritten.</p>
<h2>What we will build</h2>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/60c9040d-d744-40fe-9fce-034710b19993.png" alt="The eight-stage DDXPlus workflow, from official data splits through adapter training and fused-model verification to oMLX and QwenPaw" style="display:block;margin:0 auto" />

<p>The requested response contract is deliberately small:</p>
<pre><code class="language-text">Most likely pathology
GERD

Differential diagnoses
1. GERD
2. Bronchitis
3. Possible NSTEMI / STEMI

Uncertainty
This is a synthetic DDXPlus case. The output is an educational prediction, not a clinical diagnosis.
</code></pre>
<p>This illustrates the format, not an experimental result. DDXPlus does not provide clinician-written rationales, recommended investigations, or treatment plans for these cases. I will not manufacture them.</p>
<h2>Prerequisites</h2>
<p>You need:</p>
<ul>
<li>an Apple Silicon Mac;</li>
<li><code>uv</code> and Git;</li>
<li>Python 3.11, installable through <code>uv</code>;</li>
<li>enough disk space for the official data, base model, adapter, and fused artifacts;</li>
<li>oMLX and QwenPaw already configured for the deployment stage.</li>
</ul>
<p>Memory pressure depends on macOS and other running applications. The final run described here used batch size 2. The documented fallback is batch size 1, but that fallback was not used and is not the configuration behind these results.</p>
<h2>Part 1: Create the project and download DDXPlus</h2>
<p>I used the official English release:</p>
<ul>
<li><a href="https://figshare.com/articles/dataset/DDXPlus_Dataset_English_/22687585">DDXPlus Dataset English</a></li>
<li><a href="https://doi.org/10.6084/m9.figshare.22687585.v2">DOI: 10.6084/m9.figshare.22687585.v2</a></li>
<li>License: <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a></li>
</ul>
<h3>What is in a DDXPlus row?</h3>
<p>Each row represents a synthetic patient case, not a real person’s record. The important fields are:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>What it means in this experiment</th>
</tr>
</thead>
<tbody><tr>
<td><code>PATHOLOGY</code></td>
<td>The dataset’s reference label for the case.</td>
</tr>
<tr>
<td><code>DIFFERENTIAL_DIAGNOSIS</code></td>
<td>Source-derived alternative labels used for the reference differential and ranked targets.</td>
</tr>
<tr>
<td><code>EVIDENCES</code> and <code>INITIAL_EVIDENCE</code></td>
<td>Coded findings supplied with the synthetic case.</td>
</tr>
<tr>
<td><code>release_evidences.json</code></td>
<td>The dictionary that translates those codes and their values into readable English questions or findings.</td>
</tr>
</tbody></table>
<p>When I use “ground truth” below, I mean the dataset’s <code>PATHOLOGY</code> reference label—not absolute medical truth or an independently verified diagnosis.</p>
<p>Symptoms describe the case’s current reported findings. Antecedents describe relevant history or background, such as earlier conditions or exposures. Both are supplied as evidence to the model; neither independently proves the reference label.</p>
<p>This block creates the environment, installs the pinned dependencies, downloads all five official files, verifies their MD5 hashes, and extracts the patient records. The extraction uses the real extensionless ZIP member names—not invented <code>.csv</code> filenames.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail

command -v uv &amp;gt;/dev/null
command -v git &amp;gt;/dev/null

PROJECT="$HOME/night-thoughts/experiments/ddxplus-mlx-lora"

if [ ! -f "$PROJECT/experiment_config.py" ]; then
  if [ -e "$HOME/night-thoughts" ]; then
    echo "Companion source is missing; inspect the existing repository before replacing it."
    exit 1
  fi
  git clone --filter=blob:none --sparse \
    https://github.com/hslimi/night-thoughts.git \
    "$HOME/night-thoughts"
  git -C "$HOME/night-thoughts" sparse-checkout set \
    experiments/ddxplus-mlx-lora
fi

cd "$PROJECT"
uv venv --python 3.11 .venv
source .venv/bin/activate
uv pip install -r requirements.txt

mkdir -p raw data evaluation results/logs adapters fused
exec &amp;gt; &amp;gt;(tee -a results/logs/part1.log) 2&amp;gt;&amp;1
cd raw

download() {
  local url="$1"
  local output="$2"
  if [ ! -f "$output" ]; then
    curl --fail --location --retry 3 "$url" --output "$output"
  else
    echo "Reusing downloaded file: $output"
  fi
}

verify_md5() {
  local actual
  actual=$(md5 -q "$1")
  if [ "$actual" != "$2" ]; then
    echo "MD5 mismatch for $1: expected $2, got $actual"
    exit 1
  fi
  echo "Verified: $1"
}

download https://ndownloader.figshare.com/files/40278013 release_evidences.json
download https://ndownloader.figshare.com/files/62561569 release_conditions.json
download https://ndownloader.figshare.com/files/40278019 release_train_patients.zip
download https://ndownloader.figshare.com/files/40278022 release_validate_patients.zip
download https://ndownloader.figshare.com/files/40278016 release_test_patients.zip

verify_md5 release_evidences.json 0660962abe0bbf99e1fb77188c253597
verify_md5 release_conditions.json a992eadcff3099dd72e1820fbd2115aa
verify_md5 release_train_patients.zip f75a78420ccb061951daa4db2d62139b
verify_md5 release_validate_patients.zip e4db88e9082f18410de6fd0cb7e74d18
verify_md5 release_test_patients.zip 6fd53d331cf19ed4439bf4f46b92ee94

for split in train validate test; do
  archive="release_${split}_patients.zip"
  member="release_${split}_patients"
  unzip -Z1 "$archive" | grep -Fx "$member" &amp;gt;/dev/null
  unzip -oq "$archive" "$member"
  test -s "$member"
done

cd ..
python - &amp;lt;&amp;lt;'PY'
import csv
import importlib.metadata as metadata
import json
import platform
from pathlib import Path

expected_rows = {"train": 1_025_602, "validate": 132_448, "test": 134_529}
for split, expected in expected_rows.items():
    with Path(f"raw/release_{split}_patients").open(newline="") as source:
        reader = csv.DictReader(source)
        assert set(reader.fieldnames) == {
            "AGE", "DIFFERENTIAL_DIAGNOSIS", "SEX", "PATHOLOGY",
            "EVIDENCES", "INITIAL_EVIDENCE",
        }
        rows = sum(1 for _ in reader)
    assert rows == expected, (split, rows)
    print(f"{split}: schema and {rows:,} official rows verified")

for filename in ("release_evidences.json", "release_conditions.json"):
    with Path("raw", filename).open() as source:
        value = json.load(source)
    print(f"{filename}: {len(value)} definitions")

print(f"Python: {platform.python_version()}")
print(f"MLX: {metadata.version('mlx')}")
print(f"MLX LM: {metadata.version('mlx-lm')}")
print("Stage 1 complete.")
PY
BASH
</code></pre>
<p>The verified release contains 223 evidence definitions and 49 pathologies. The patient members are CSV-formatted despite having no <code>.csv</code> extension.</p>
<h2>Part 2: Prepare the datasets</h2>
<h3>From a raw row to a training example</h3>
<p>The transformation looks like this:</p>
<pre><code class="language-text">Raw dataset row → decoded evidence → user prompt → target response
</code></pre>
<p>A system message defines the closed label set and required response sections. The user prompt describes the decoded synthetic case: age, sex, symptoms, and antecedents. The target response is the assistant example used during training. For training examples, it places <code>PATHOLOGY</code> in the most-likely section, builds three ranked differential entries from the supplied labels, and ends with the fixed uncertainty statement. I am formatting source-derived labels, not writing a clinician-style rationale.</p>
<p>During training, these prompt-and-target pairs teach the desired behavior. During evaluation, the model receives the system and user messages without the target response; its generated answer is what I score.</p>
<p>I did not train on the full training release. The experiment uses deterministic, stratified subsets sampled inside each official split:</p>
<table>
<thead>
<tr>
<th>Split</th>
<th align="right">Cases per pathology</th>
<th align="right">Total</th>
</tr>
</thead>
<tbody><tr>
<td>Train</td>
<td align="right">40</td>
<td align="right">1,960</td>
</tr>
<tr>
<td>Validation</td>
<td align="right">10</td>
<td align="right">490</td>
</tr>
<tr>
<td>Test</td>
<td align="right">10</td>
<td align="right">490</td>
</tr>
</tbody></table>
<h3>Why the splits stay separate</h3>
<p>Think of training as practice, validation as progress checks, and testing as a final problem set that must stay out of the practice material. In this experiment:</p>
<ul>
<li><strong>Train</strong> examples update the adapter.</li>
<li><strong>Validation</strong> examples monitor training through validation loss; they do not update the adapter.</li>
<li><strong>Test</strong> cases are withheld for the final behavioral comparison.</li>
</ul>
<p>Identical prompts across splits would be data leakage. A test prompt that had already appeared in training could reward memorization and inflate the results instead of measuring behavior on unseen cases.</p>
<p>Stratified sampling means sampling per pathology within each official split. Every one of the 49 labels is represented, rather than relying on an uncontrolled random subset that might miss or underrepresent labels. Equal per-label counts are an experimental design choice, not a claim about real-world prevalence.</p>
<p>The seed is 42. Official test patients are never moved into training. The final preprocessing also replaces duplicate decoded prompts with other eligible rows from the same official split and class, so all three prompt sets are unique and disjoint.</p>
<p><code>prepare_ddxplus.py</code> uses <code>ast.literal_eval</code> for CSV list fields, never <code>eval</code>. Numeric evidence values retain their decoded values, while categorical <code>N</code> becomes <code>No</code>. Symptoms and antecedents stay separate.</p>
<p>One data edge case matters: the dataset spelling <code>Larygospasm</code> has only two usable reference differential labels in the selected validation and test cases. The preprocessing permits a two-item target there rather than inventing a third label. Training targets still contain exactly three source-derived labels. The evaluator still requires exactly three ranked predicted labels for a structured response, so a two-label prediction fails that strict format metric even in these cases.</p>
<p>The preprocessing command verifies and reuses a complete set of valid generated files. It stops if files are incomplete or their metadata, structure, split isolation, or pinned test hash differs. Replacing generated files requires inspecting them and explicitly running <code>python prepare_ddxplus.py --overwrite-generated</code>; that flag was not used for this run.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part2.log) 2&amp;gt;&amp;1

python prepare_ddxplus.py
python - &amp;lt;&amp;lt;'PY'
import json
from collections import Counter
from pathlib import Path
from experiment_config import verify_test_cases

def read_jsonl(path):
    return [json.loads(line) for line in Path(path).read_text().splitlines()]

prompt_sets = {}
for split, expected in {"train": 1960, "valid": 490, "test": 490}.items():
    records = read_jsonl(f"data/{split}.jsonl")
    assert len(records) == expected
    prompt_sets[split] = {r["messages"][1]["content"] for r in records}
    assert len(prompt_sets[split]) == expected
    print(f"{split}: {expected} unique examples")

assert not prompt_sets["train"] &amp; prompt_sets["valid"]
assert not prompt_sets["train"] &amp; prompt_sets["test"]
assert not prompt_sets["valid"] &amp; prompt_sets["test"]

cases = read_jsonl("evaluation/test_cases.jsonl")
counts = Counter(case["ground_truth"] for case in cases)
assert len(cases) == len({case["case_id"] for case in cases}) == 490
assert len(counts) == 49 and set(counts.values()) == {10}
print("Official split prompt overlap: 0")
print(f"test_cases_sha256: {verify_test_cases()}")
print("Stage 2 complete.")
PY
BASH
</code></pre>
<p>The genuine <code>test-0000</code> example makes this transformation concrete. Its coded findings decode to symptoms including fever, sore throat, nasal congestion, and cough; its dataset reference label is <code>URTI</code>. The figure places those coded fields beside the actual decoded prompt used for evaluation. This illustrates what the dataset supplies, not a clinician’s explanation of the case.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/f2f784fa-f4a2-4942-905a-aa7765c1eb4e.png" alt="Official coded DDXPlus fields beside the exact decoded prompt for a synthetic held-out case" style="display:block;margin:0 auto" />

<p><em>Figure: a source-derived view of</em> <code>test-0000</code><em>. The official row and generated prompt were checked against the saved held-out case; no evidence or label was added.</em></p>
<p>&gt; <strong>What just happened?</strong> Coded dataset rows are now prompt-and-target examples. Training and validation examples guide and monitor adaptation, while the 490 test cases remain separate for the behavioral comparison.</p>
<h2>Part 3: Smoke-test generation and evaluate the base model</h2>
<h3>Why measure the base first?</h3>
<p>The base model already has general language and instruction-following capabilities from its earlier training. That does not tell us whether it can follow this particular closed-set differential format or agree with DDXPlus labels. I need to measure that starting point before adding the adapter. Without a baseline, I could not attribute a later improvement to the adapter rather than to the prompt or task setup alone.</p>
<p>The evaluator uses the pinned MLX conversion at revision <code>8b403126fc14f14cfc99bb4cfa72ecbc129ea677</code>. It applies the same chat template, system prompt, greedy generation, and 220-token limit in every mode.</p>
<h3>What the metrics mean</h3>
<ul>
<li><strong>Top-1 accuracy:</strong> was the first predicted label the dataset label?</li>
<li><strong>Top-3 accuracy:</strong> did the dataset label appear among the three ranked alternatives?</li>
<li><strong>Structured-response rate:</strong> did the model follow the requested sections and three-item ranked output contract?</li>
<li><strong>Reference overlap@3:</strong> how many of the predicted alternatives also appear in the source reference differential? The summary reports the mean across cases.</li>
</ul>
<p>Formatting accuracy and label agreement are different. A perfectly formatted answer can still have the wrong top-1 label; a correct label can also appear in a response that fails the format check. I report those behaviors separately.</p>
<p>The first command is only a three-case generation smoke test. Its output is kept under a separate prefix and is not a benchmark result.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part3.log) 2&amp;gt;&amp;1

python evaluate.py --mode base --limit 3 \
  --output-prefix results/base-smoke
python evaluate.py --mode base --limit 0
python - &amp;lt;&amp;lt;'PY'
import json
summary = json.load(open("results/base.summary.json"))
assert summary["cases"] == 490
assert summary["generation"] == {"max_tokens": 220, "temperature": 0.0}
print(json.dumps(summary, indent=2))
print("Stage 3 complete: full baseline saved; smoke results remain separate.")
PY
BASH
</code></pre>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/34731312-d796-406d-ab3c-e49bc749ce8b.png" alt="Base-model evaluation on all 490 held-out DDXPlus cases" style="display:block;margin:0 auto" />

<p><em>Figure: the complete base-model summary, generated from</em> <code>results/base.summary.json</code><em>.</em></p>
<p>The evaluator initially missed labels when headings and content appeared on the same line. I corrected label extraction, retained a separate strict format check, and reapplied the final parser to the preserved responses. All reported modes use that same parser; this correction did not regenerate benchmark responses.</p>
<p>These scores measure agreement with a synthetic dataset—not accuracy on real patients.</p>
<p>&gt; <strong>What just happened?</strong> The original model now has a measured baseline on the same 490 cases used later. This is the comparison point for attributing behavioral changes to the adapter.</p>
<h2>Part 4: Smoke-test training and train the full adapter</h2>
<h3>LoRA and QLoRA in this experiment</h3>
<p>A model’s weights are the numerical parameters it uses to generate responses. Full fine-tuning would update the base model’s weights directly. LoRA instead leaves those weights fixed and trains a much smaller set of additional parameters: the adapter. The adapter is not a standalone model; adapter evaluation loads the base model and adapter together.</p>
<p>Quantization reduces the numerical precision used to store the base weights. In this experiment, “QLoRA-style” means training a LoRA adapter on top of that quantized base. The original base remains available for comparison, while the learned adjustment lives in the separate adapter.</p>
<p>The training smoke test uses a separate adapter directory and only two iterations. It verifies that training and adapter saving work; its losses are not final training results. The full adapter and full training log are guarded against accidental replacement. For fresh reproduction, <code>pinned_base_path()</code> resolves the same pinned model revision to its local snapshot for training and fusion. The saved original training configuration names the upstream hub ID; I did not rerun training to change that record.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part4.log) 2&amp;gt;&amp;1

MODEL="mlx-community/Qwen2.5-1.5B-Instruct-4bit"
BASE_MODEL="$(python -c 'from artifact_identity import pinned_base_path; print(pinned_base_path())')"
export MODEL

if [ -e adapters/smoke ] || [ -e adapters/ddxplus ]; then
  echo "A training adapter already exists; inspect it before replacing anything."
  exit 1
fi

if [ -e results/logs/part4-train-full.log ]; then
  echo "A full training log already exists; inspect it before replacing anything."
  exit 1
fi

mlx_lm.lora \
  --model "$BASE_MODEL" --train --data data \
  --fine-tune-type lora --adapter-path adapters/smoke \
  --batch-size 2 --grad-accumulation-steps 4 --num-layers 8 \
  --iters 2 --learning-rate 1e-5 --max-seq-length 2048 \
  --steps-per-report 1 --steps-per-eval 1 --save-every 2 \
  --mask-prompt --grad-checkpoint --seed 42

test -s adapters/smoke/adapters.safetensors

mlx_lm.lora \
  --model "$BASE_MODEL" --train --data data \
  --fine-tune-type lora --adapter-path adapters/ddxplus \
  --batch-size 2 --grad-accumulation-steps 4 --num-layers 8 \
  --iters 1200 --learning-rate 1e-5 --max-seq-length 2048 \
  --steps-per-report 10 --steps-per-eval 200 --save-every 200 \
  --mask-prompt --grad-checkpoint --seed 42 \
  2&amp;gt;&amp;1 | tee results/logs/part4-train-full.log

test -s adapters/ddxplus/adapters.safetensors
python evaluate.py --mode adapter --limit 0
python analyze_results.py --compare base-adapter
BASH
</code></pre>
<p>The full run used a quantized base with LoRA adapters on eight layers, rank 8, scale 20.0, dropout 0.0, the Adam optimizer, batch size 2, gradient accumulation 4, learning rate <code>1e-5</code>, and maximum sequence length 2048. Prompt masking and gradient checkpointing were enabled. The batch-size-one fallback was not used.</p>
<h3>Reading the training settings</h3>
<ul>
<li><strong>Rank 8</strong> controls the adapter’s capacity: how much trainable flexibility is available for the adaptation.</li>
<li><strong>Eight adapted layers</strong> limit which parts of the network receive adapter components. The base weights remain frozen throughout.</li>
<li><strong>Prompt masking</strong> leaves the patient prompt out of the training loss, so optimization focuses on producing the desired response rather than reproducing the input.</li>
<li><strong>Gradient accumulation</strong> combines gradients from several small batches before an update, simulating a larger effective batch without processing all of those examples simultaneously.</li>
<li><strong>Gradient checkpointing</strong> recomputes some intermediate values instead of retaining them all, trading additional computation for lower training-memory pressure.</li>
</ul>
<p>The first reported training loss was <strong>2.056 at iteration 10</strong>, and the final training loss was <strong>0.057 at iteration 1,200</strong>. Validation loss was <strong>2.257 at iteration 1</strong> and <strong>0.064 at iteration 1,200</strong>. Iteration 1 is a validation measurement, not an initial training-loss report.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/8c328706-a30b-4524-ab62-b780f09183e6.png" alt="Training and validation loss from the full 1,200-iteration run" style="display:block;margin:0 auto" />

<p><em>Figure: loss curves generated only from</em> <code>results/logs/part4-train-full.log</code><em>.</em></p>
<h3>Why we did not stop at the loss curve</h3>
<p>Loss measures token-prediction error under the training objective: how closely the model’s predicted tokens match the target responses. A falling loss says that optimization is fitting that objective better.</p>
<p>It does not directly tell us whether the first predicted pathology is correct, prove that the requested response format is followed, or establish behavior on unseen cases. That is why the held-out evaluation is the more meaningful behavioral result: it checks labels and structure on cases that did not update the adapter.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/ed8728df-bc2a-450a-95c8-0d35fd66b74b.png" alt="Adapter evaluation on all 490 held-out DDXPlus cases" style="display:block;margin:0 auto" />

<p><em>Figure: the complete adapter summary, generated from</em> <code>results/adapter.summary.json</code><em>.</em></p>
<p>I did not measure peak memory and do not claim a total training time or compatibility with a particular memory size. The hardware observation is limited to: <strong>tested locally on Apple Silicon</strong>.</p>
<p>&gt; <strong>What just happened?</strong> The base weights stayed fixed while a smaller adapter learned the response task. I now have training curves and, separately, adapter results on the same 490 held-out cases used for the base evaluation.</p>
<h2>Part 5: Inspect disagreements and run an evidence-ablation probe</h2>
<p>A better aggregate score does not explain every changed prediction. The comparison found <strong>440 top-1 disagreements</strong>, <strong>404 cases improved from incorrect to correct</strong>, and <strong>one regression from correct to incorrect</strong>. Fifty cases retained the same top-1 label.</p>
<h3>What does evidence ablation test?</h3>
<p>The question is simple: <strong>if we remove one relevant finding, does the prediction change?</strong> I compare the original prompt with the same prompt after one controlled edit, keeping the model and generation settings fixed.</p>
<p>This tests sensitivity to that prompt change. An unchanged response is a useful behavioral observation for this case. It does not create a new medical ground truth for the edited case, prove causality, or explain the model’s internal reasoning. It is not a second accuracy benchmark: there is no newly validated label against which to score the edited response.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part5.log) 2&amp;gt;&amp;1

python analyze_results.py --compare base-adapter
python evidence_ablation.py --case-id test-0002 \
  --finding 'Do you have symptoms that are increased with physical exertion but alleviated with rest? Yes.'
BASH
</code></pre>
<p>The ablation code tracks sections and excludes the initial-evidence bullet. For <code>test-0002</code>, it removed this finding from <strong>Symptoms</strong>:</p>
<p>&gt; Do you have symptoms that are increased with physical exertion but alleviated with rest? Yes.</p>
<p>The initial evidence remained present. The adapter returned exactly the same response before and after removal: top-1 <code>Unstable angina</code>, with <code>Possible NSTEMI / STEMI</code> and <code>Stable angina</code> in the differential. The original dataset label was <code>Stable angina</code>.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/5731d3cc-a1ea-41cf-a48c-d69320010953.png" alt="Original and evidence-ablated adapter responses for test-0002" style="display:block;margin:0 auto" />

<p><em>Figure: a genuine unchanged response from</em> <code>results/counterfactual.json</code><em>.</em></p>
<p>The qualitative examples also include both improvement and failure:</p>
<ul>
<li><code>test-0001</code>: base <code>Chronic rhinosinusitis</code> → adapter <code>Anemia</code>, matching the dataset label;</li>
<li><code>test-0000</code>: a shared top-1 failure—base <code>Acute laryngitis</code>, adapter <code>Viral pharyngitis</code>, dataset label <code>URTI</code>;</li>
<li><code>test-0002</code>: a well-formatted but incorrect adapter response—<code>Unstable angina</code> instead of <code>Stable angina</code>.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/dc4324f1-ddf2-4805-960f-66dc3e063a16.png" alt="Improved held-out prediction for test-0001" style="display:block;margin:0 auto" />

<p><em>Figure: genuine base and adapter responses from the same held-out case.</em></p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/9ccce081-8452-4c48-92cf-24d9fdf53ab1.png" alt="A well-formatted but incorrect adapter response and a shared failure" style="display:block;margin:0 auto" />

<p><em>Figure: remaining failures preserved in</em> <code>results/qualitative-examples.json</code><em>.</em></p>
<p>&gt; <strong>What just happened?</strong> The adapter improved many held-out predictions but did not eliminate failures. For the selected case, removing one finding left the response unchanged; that is a recorded sensitivity observation, not a new diagnostic label.</p>
<h2>Part 6: Fuse and independently verify the standalone model</h2>
<h3>Why fuse, and why verify?</h3>
<p>An adapter normally has to accompany its original base model: inference loads the base weights and applies the learned adapter adjustment. Fusion combines that adjustment into a standalone model artifact, which is simpler to copy and deploy because the serving layer no longer needs a separate adapter path.</p>
<p>That packaging change should not be trusted blindly. Numerical conversion can change generated responses, so the standalone artifact needs the same behavioral evaluation as the adapter. The first quantized fused artifact was rejected because its independent results diverged sharply from the adapter’s. I therefore evaluated a separate dequantized artifact instead of assuming that fusion had preserved behavior. Even after that correction, <code>reviewed_with_differences</code> means that known differences passed an explicit review—not that the two models are exactly equivalent.</p>
<p>The original <code>mlx_lm.fuse</code> command produced a quantized fused artifact that behaved very differently from the adapter. I rejected it rather than deploying it. Its full 490-case results were:</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th align="right">Rejected quantized fused</th>
</tr>
</thead>
<tbody><tr>
<td>Top-1 accuracy</td>
<td align="right">16.94%</td>
</tr>
<tr>
<td>Top-3 accuracy</td>
<td align="right">23.88%</td>
</tr>
<tr>
<td>Structured-response rate</td>
<td align="right">0.00%</td>
</tr>
<tr>
<td>Mean reference overlap@3</td>
<td align="right">0.335 / 3</td>
</tr>
</tbody></table>
<p>The correction was to create a <strong>separate dequantized artifact</strong> with <code>--dequantize</code>; I did not retrain or overwrite the full adapter. The following block creates and independently evaluates that artifact, then applies the strict response-identity check. A strict mismatch stops deployment.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part6.log) 2&amp;gt;&amp;1

MODEL="mlx-community/Qwen2.5-1.5B-Instruct-4bit"
BASE_MODEL="$(python -c 'from artifact_identity import pinned_base_path; print(pinned_base_path())')"
ADAPTER="adapters/ddxplus"
FUSED="fused/ddxplus-qwen-dequantized"
export MODEL ADAPTER FUSED

if [ -e "$FUSED" ]; then
  echo "The fused destination exists; inspect it before replacing it."
  exit 1
fi

mlx_lm.fuse \
  --model "$BASE_MODEL" --adapter-path "$ADAPTER" \
  --save-path "$FUSED" --dequantize

test -f "$FUSED/config.json"
test -f "$FUSED/tokenizer.json"
python evaluate.py --mode fused --limit 0 \
  --output-prefix results/fused-dequantized-full
python analyze_results.py --compare adapter-fused \
  --fused-prefix fused-dequantized-full
python verify_fusion.py \
  --fused-prefix fused-dequantized-full \
  --model-path "$FUSED"
BASH
</code></pre>
<p>For this run, strict identity failed: <strong>486 of 490 responses matched exactly</strong>, four differed, and <strong>489 of 490 retained the same top-1 label</strong>. I inspected all four saved differences. Only then did I run the explicit reviewed-differences gate, limited to at most 2% differing responses and at most 0.01 absolute top-1 accuracy change:</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
python verify_fusion.py \
  --fused-prefix fused-dequantized-full \
  --model-path fused/ddxplus-qwen-dequantized \
  --accept-reviewed-differences
BASH
</code></pre>
<p>This is <code>reviewed_with_differences</code>, not exact equivalence. No threshold was changed to obtain a more attractive result.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/49b62d03-5085-4413-98e7-d51b7da14f23.png" alt="Fused-model verification and comparison with the adapter" style="display:block;margin:0 auto" />

<p><em>Figure: rejected quantized output, corrected fused metrics, and the four reviewed response differences.</em></p>
<p>&gt; <strong>What just happened?</strong> The first fused artifact failed behavioral verification and was rejected. A separate dequantized artifact was evaluated independently; only after reviewing its four response differences did I accept it for deployment.</p>
<h2>Part 7: Deploy through oMLX and connect QwenPaw</h2>
<h3>Which component does what?</h3>
<table>
<thead>
<tr>
<th>Component</th>
<th>Role in this experiment</th>
</tr>
</thead>
<tbody><tr>
<td>MLX LM</td>
<td>Training and direct local evaluation</td>
</tr>
<tr>
<td>LoRA adapter</td>
<td>Learned task-specific adjustment</td>
</tr>
<tr>
<td>Fused model</td>
<td>Standalone deployable model artifact</td>
</tr>
<tr>
<td>oMLX</td>
<td>Local inference server and OpenAI-compatible API</td>
</tr>
<tr>
<td>QwenPaw</td>
<td>Agent/application layer that calls the configured model</td>
</tr>
</tbody></table>
<p>In short, the adapter contains the learned adjustment, the fused model packages it for deployment, oMLX serves generation requests, and QwenPaw is the application using that service.</p>
<p>The deployment helper verifies the reviewed fused artifact and its file hashes, installs only the experiment model, and restarts the existing <strong>system LaunchDaemon</strong> directly. It does not use Homebrew services or modify unrelated model registrations. The forced restart briefly interrupts oMLX-served models and active requests. The helper discovers the exact model ID through <code>/v1/models</code> and uses that returned ID in the generation request.</p>
<p>The restart inside the helper is <code>sudo launchctl kickstart -k system/com.omlx.server</code>. If you have just performed that restart yourself, use <code>python deploy_omlx.py --case-id test-0001 --skip-restart</code> instead of restarting it again in the block below.</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part7.log) 2&amp;gt;&amp;1

python deploy_omlx.py --case-id test-0001
python qwenpaw_model.py --sync-omlx-key
python qwenpaw_model.py --agent-id default

python - &amp;lt;&amp;lt;'PY'
import json
from pathlib import Path
metadata = json.loads(Path("evaluation/metadata.json").read_text())
case = next(
    json.loads(line)
    for line in Path("evaluation/test_cases.jsonl").read_text().splitlines()
    if json.loads(line)["case_id"] == "test-0001"
)
Path("results/qwenpaw-console-message.txt").write_text(
    metadata["system_prompt"] + "\n\n" + case["prompt"]
)
print("Synthetic held-out console prompt saved; no credential was printed.")
PY
BASH
</code></pre>
<p>The actual discovered ID was <code>ddxplus-qwen</code>. Direct oMLX returned <code>Anemia</code> for <code>test-0001</code>, matching the dataset label.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/42974db4-5774-4cf0-abb2-636a1018cd04.png" alt="oMLX model discovery and a genuine held-out generation" style="display:block;margin:0 auto" />

<p><em>Figure: sanitized evidence from the real oMLX response; raw API payloads and credentials are not published.</em></p>
<p>The credential synchronization was a separate, explicitly permanent repair for an existing stale QwenPaw oMLX credential. The command used was:</p>
<pre><code class="language-bash">cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
"$HOME/.qwenpaw/venv/bin/python" qwenpaw_provider_state.py --sync-current-key
"$HOME/.qwenpaw/venv/bin/python" qwenpaw_provider_state.py --verify-current-key
</code></pre>
<p>This reads the current key from oMLX’s local settings, updates the saved oMLX provider through QwenPaw’s installed API, verifies the persisted values match, and never prints the key. It preserves the provider URL and protocol. The request uses <code>auto_discover: false</code>; inspection of the installed QwenPaw 2.2.2 code shows that this request-scoped option suppresses a post-save discovery refresh and is not persisted provider configuration. This permanent credential repair is why rollback does <strong>not</strong> restore the old stale credential.</p>
<p>For the chat check, I opened <code>http://localhost:8088/chat</code>, started a clean chat, selected the fused model, and submitted the saved synthetic held-out prompt through the actual console. An HTTP health check alone would not satisfy this step.</p>
<p>A successful agent round trip means that QwenPaw accepted the prompt, called the configured backend, and displayed returned text. That verifies transport; it does not establish equivalence with direct oMLX generation or diagnostic correctness.</p>
<p>QwenPaw completed the round trip, but returned <code>Acute dystonic reactions</code>, not the dataset label <code>Anemia</code>. Its response also differed from direct oMLX. Agent context and existing generation settings may contribute; this check does not isolate the cause. This is a qualitative failure, not a benchmark or direct-equivalence test. I made zero prompt retries for a more attractive answer.</p>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/c4850d4d-0ee4-442f-a4a9-fd5d6435dc76.png" alt="QwenPaw using the fused model in a genuine chat round trip" style="display:block;margin:0 auto" />

<p><em>Figure: two unmodified crops from one real QwenPaw capture. Account identity, conversation history, workspace controls, credentials, and unrelated desktop content are excluded.</em></p>
<h2>Part 8: Test rollback</h2>
<p>Reversibility is part of reproducible engineering. An experiment should not require permanently sacrificing the previous working configuration just to test a new model. A tested rollback gives me a way back to that known state and makes the final system state explicit.</p>
<p>Before changing QwenPaw, the helper saved both the global configuration and the selected agent’s configuration, plus the original provider model registrations and removal list. Rollback restores those saved states, preserves unrelated settings, and removes the experiment’s QwenPaw model registration. It retains the trained adapter and fused model.</p>
<p>The following form uses the same real system daemon restart that I verified. The forced QwenPaw restart briefly interrupts sessions and active requests; the rollback verifier checks that the restarted process began after preparation:</p>
<pre><code class="language-bash">bash &amp;lt;&amp;lt;'BASH'
set -euo pipefail
cd "$HOME/night-thoughts/experiments/ddxplus-mlx-lora"
source .venv/bin/activate
mkdir -p results/logs
exec &amp;gt; &amp;gt;(tee -a results/logs/part8.log) 2&amp;gt;&amp;1

python qwenpaw_model.py --prepare-rollback
sudo launchctl kickstart -k system/com.qwenpaw.app
python qwenpaw_model.py --verify-rollback
BASH
</code></pre>
<p>I also used <strong>Restore default model</strong> in the experiment chat to clear its per-chat override and confirmed that the original response remained visible. No new response was generated. QwenPaw’s original global and per-agent selections were restored, and the configuration files matched their backups exactly.</p>
<p>QwenPaw may refresh only <code>capability_provenance</code>, <code>discovered_at</code>, and <code>released_at</code> during model discovery. Durable model settings and selections must still match. The explicitly requested permanent oMLX credential repair remains synchronized; rollback does not bring back the stale key. The deployed oMLX model was retained, and the optional model-removal block was not run.</p>
<p>&gt; <strong>What just happened?</strong> oMLX served the fused model, and QwenPaw completed a real chat through the configured backend. Rollback then restored the previous model selections while retaining the trained artifacts and the intentional credential repair.</p>
<h2>Results</h2>
<p>Every final column uses <strong>all 490 held-out cases</strong>, the same system prompt, greedy generation, and <code>max_tokens=220</code>.</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th align="right">Base</th>
<th align="right">Adapter</th>
<th align="right">Dequantized fused</th>
</tr>
</thead>
<tbody><tr>
<td>Held-out cases</td>
<td align="right">490</td>
<td align="right">490</td>
<td align="right">490</td>
</tr>
<tr>
<td>Top-1 accuracy</td>
<td align="right">10.41%</td>
<td align="right">92.65%</td>
<td align="right">92.86%</td>
</tr>
<tr>
<td>Top-3 accuracy</td>
<td align="right">12.86%</td>
<td align="right">97.14%</td>
<td align="right">97.14%</td>
</tr>
<tr>
<td>Structured-response rate</td>
<td align="right">0.00%</td>
<td align="right">99.80%</td>
<td align="right">99.80%</td>
</tr>
<tr>
<td>Mean reference overlap@3</td>
<td align="right">0.206 / 3</td>
<td align="right">2.043 / 3</td>
<td align="right">2.049 / 3</td>
</tr>
</tbody></table>
<h3>How to interpret the held-out improvement</h3>
<p>On the same 490 selected held-out cases and with the same generation settings, the adapter raises top-1 agreement from 10.41% to 92.65% and structured-response rate from 0.00% to 99.80%. These are two distinct changes: the first predicted label agrees with the dataset reference more often, and the response follows the requested contract more consistently. The comparison therefore shows more than a formatting change within this experiment.</p>
<p>I also inspected what changed case by case rather than reporting only the aggregate gain. Part 5 preserves the 440 top-1 disagreements, 404 incorrect-to-correct improvements, and one correct-to-incorrect regression.</p>
<p>The scope is deliberately narrow: a balanced, selected DDXPlus subset. These are not results on the complete official test release, real patients, external datasets, or evidence of clinical validation. They demonstrate improved behavior for this constrained setup, not general diagnostic ability.</p>
<p>All three summaries contain:</p>
<pre><code class="language-text">test_cases_sha256 = c5a5b94a3377c78b2ac1209899ca6e8d1df3a9aa25ce0a2e26ad33373f6c5838
</code></pre>
<p>The fused model’s top-1 accuracy was one case higher than the adapter’s; top-3 and structured-response rates were unchanged. Mean reference overlap increased slightly. These small differences do not establish exact behavioral equivalence.</p>
<p>Artifact and runtime identity metadata were backfilled later from the preserved artifacts, with that provenance recorded explicitly. It was not captured during the original generation. The final audit re-parsed every saved response, verified artifact and evaluator hashes, rebuilt all 490 test prompts and targets from official source rows, and recomputed every metric. No-generation resume checks then reused all 490 responses in each mode without loading a model.</p>
<h3>Software observed in this run</h3>
<table>
<thead>
<tr>
<th>Component</th>
<th>Version</th>
</tr>
</thead>
<tbody><tr>
<td>Python</td>
<td>3.11.17</td>
</tr>
<tr>
<td>uv</td>
<td>0.13.0</td>
</tr>
<tr>
<td>MLX</td>
<td>0.32.4</td>
</tr>
<tr>
<td>MLX LM</td>
<td>0.32.2</td>
</tr>
<tr>
<td>NumPy</td>
<td>2.4.6</td>
</tr>
<tr>
<td>pandas</td>
<td>3.1.0</td>
</tr>
<tr>
<td>Transformers</td>
<td>5.20.2</td>
</tr>
<tr>
<td>Tokenizers</td>
<td>0.23.3</td>
</tr>
<tr>
<td>safetensors</td>
<td>0.8.0</td>
</tr>
<tr>
<td>huggingface-hub</td>
<td>2.3.0</td>
</tr>
<tr>
<td>oMLX</td>
<td>0.7.0</td>
</tr>
<tr>
<td>QwenPaw</td>
<td>2.2.2</td>
</tr>
</tbody></table>
<h2>Limitations</h2>
<p>This experiment cannot establish clinical usefulness.</p>
<ul>
<li>DDXPlus patients are synthetic.</li>
<li>The task is limited to the 49 dataset pathology labels.</li>
<li>Real patients may have multiple conditions or incomplete histories.</li>
<li>The stratified subset does not preserve the dataset’s original prevalence.</li>
<li>Agreement with a reference differential is not clinical validation.</li>
<li>Ten held-out <code>Larygospasm</code> cases have two reference labels; no third label was invented.</li>
<li>Edited ablation cases do not automatically have valid labels.</li>
<li>A confident and well-formatted answer can still be wrong.</li>
<li>A successful oMLX or QwenPaw round trip is not a clinical evaluation.</li>
</ul>
<p>The resulting model must not be used to diagnose, triage, or recommend care for a real person.</p>
<h2>Final thoughts</h2>
<p>The goal was not “a doctor on my Mac.” It was a complete local workflow with evidence at every stage, from authentic source data and split isolation through deployment and rollback. That is a much stronger result than an attractive training-loss curve—and a much more honest starting point for experimenting with diagnostic language models locally.</p>
<h3>What this experiment demonstrated</h3>
<ul>
<li>A compact local model can be adapted to a constrained synthetic differential-response task.</li>
<li>Evaluation must measure behavior on held-out cases, not only loss.</li>
<li>Deployment artifacts need independent verification; the rejected fusion shows why.</li>
<li>Local deployment, application integration, and rollback can be tested end to end.</li>
</ul>
<h3>What it did not demonstrate</h3>
<ul>
<li>Clinical validity.</li>
<li>Real-patient performance.</li>
<li>Clinician-style reasoning.</li>
<li>Generalization beyond this selected DDXPlus setup.</li>
<li>Equivalence between QwenPaw and direct oMLX responses.</li>
</ul>
<h2>Compact glossary</h2>
<ul>
<li><strong>Base model:</strong> the pretrained general-purpose instruct model that provides language and instruction-following capabilities before this experiment. It remains the comparison point.</li>
<li><strong>Quantization:</strong> representing model weights with lower numerical precision. This run used a 4-bit MLX conversion of the base model.</li>
<li><strong>LoRA:</strong> Low-Rank Adaptation, a method that trains a relatively small set of additional parameters while leaving the base weights frozen.</li>
<li><strong>QLoRA:</strong> in this experiment, QLoRA-style training means training a LoRA adapter on top of the quantized base.</li>
<li><strong>Adapter:</strong> the learned task-specific adjustment that must normally be loaded together with its base model. It is not a standalone model.</li>
<li><strong>Evidence:</strong> a supplied finding from a synthetic case, such as a symptom or antecedent, decoded from the dataset’s coded fields.</li>
<li><strong>Ground truth:</strong> the dataset’s reference <code>PATHOLOGY</code> label, not absolute medical truth.</li>
<li><strong>Held-out case:</strong> a case withheld from adapter training and used for behavioral evaluation; here, one of the selected 490 test cases.</li>
<li><strong>Fusion:</strong> merging the learned adapter adjustment into a standalone model artifact. The fused artifact still needs independent behavioral verification.</li>
<li><strong>Inference server:</strong> software that loads a model and answers generation requests through an API. oMLX fills that role here.</li>
</ul>
<h2>Dataset and model attribution</h2>
<p>This tutorial adapts <strong>DDXPlus Dataset English</strong> by Tchango et al., released under <strong>CC BY 4.0</strong>:</p>
<ul>
<li><a href="https://figshare.com/articles/dataset/DDXPlus_Dataset_English_/22687585">Official dataset</a></li>
<li><a href="https://doi.org/10.6084/m9.figshare.22687585.v2">DOI</a></li>
<li><a href="https://arxiv.org/abs/2205.09148">DDXPlus paper</a></li>
</ul>
<p>Changes include decoding evidence into English, formatting records as chat examples, creating stratified subsets with duplicate-prompt replacement, and constructing ranked-differential targets from supplied labels without adding a missing third label.</p>
<p>The base model is <a href="https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct">Qwen2.5-1.5B-Instruct</a>, licensed under <a href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>, using the pinned <a href="https://huggingface.co/mlx-community/Qwen2.5-1.5B-Instruct-4bit">MLX Community 4-bit conversion</a>. DDXPlus data and Qwen weights are not included in the companion repository.</p>
<h2>Companion code</h2>
<p>The implementation and reviewed non-sensitive summaries were developed alongside the <a href="https://github.com/hslimi/night-thoughts">Night Thoughts repository</a>. At the time of publication, the DDXPlus experiment directory is not included in that public repository, so this article does not claim to offer a downloadable companion-source package.</p>
<p>Downloaded datasets, generated JSONL datasets, trained adapters, fused models, raw API payloads, credentials, local logs, and full response files are intentionally excluded from version control.</p>
<p>If you reproduce the experiment, I would especially like to see cases where training loss improves while diagnostic behavior does not.</p>
]]></content:encoded></item><item><title><![CDATA[Technical Breakdown of Ornith-1.5-122B: Impressive Data, MoE Architecture, and Licensing Caveats]]></title><description><![CDATA[Ornith-1.5-122B was released on October 20, 2026, positioning itself as an efficient Mixture-of-Experts (MoE) model designed for single-GPU deployment. Its…]]></description><link>https://nightthoughts.me/technical-breakdown-of-ornith-1-5-122b-impressive-data-moe-architecture-and-licensing-caveats</link><guid isPermaLink="true">https://nightthoughts.me/technical-breakdown-of-ornith-1-5-122b-impressive-data-moe-architecture-and-licensing-caveats</guid><category><![CDATA[Open Source]]></category><category><![CDATA[AI]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[MachineLearning]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Wed, 21 Oct 2026 15:16:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/3b17fdde-e942-4ba8-a886-cab7c09a42a9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ornith-1.5-122B was released on October 20, 2026, positioning itself as an efficient Mixture-of-Experts (MoE) model designed for single-GPU deployment. Its marketing centers on three claims: state-of-the-art (SOTA) performance among comparable open-source models, the ability to run on a single NVIDIA DGX card, and an MIT license. </p>
<p>For developers, these claims need to be broken down. Some are supported by clear documentation, while others have significant caveats that are easy to overlook.</p>
<h2>Who is Behind Ornith?</h2>
<p>The Ornith series is developed by <strong>DeepReinforce</strong>, a research-focused startup founded by <strong>Jiwei Li</strong>. Li holds a Ph.D. in Computer Science from Stanford University and previously founded the NLP startup Shannon.AI. DeepReinforce publicly positions itself as focusing on reinforcement-learning-based agentic AI systems. Their previous work includes GrandCode (a multi-agent system that ranked first in Codeforces competitions) and the code optimizer IterX. The first models in the Ornith-1.5 series (397B, 35B-A3B, 9B) were released in August 2026, with the 122B model serving as a subsequent mid-sized addition. </p>
<p><em>(Note: While third-party AI news outlets report this attribution, it is recommended to verify these details directly on the official Hugging Face model card or company site.)</em></p>
<h2>Architecture &amp; Foundation: A MoE on Top of Qwen 3.5</h2>
<p>Ornith-1.5-122B is not a from-scratch model. According to the official model card, the Ornith-1.5 series is built upon the foundation of <strong>Ornith-1.0</strong>, which itself was created through continued pre-training, mid-training, and post-training on top of <strong>Qwen 3.5 and Gemma 4</strong>. </p>
<p>The specific architecture of the 122B version directly follows <strong>Qwen3.5-122B-A10B</strong>: a total parameter count of roughly 122B, with <strong>approximately 10B parameters activated per inference</strong>. </p>
<p>The key here is the <strong>Mixture-of-Experts (MoE)</strong> structure. While the total parameter count is large, only a fraction is activated during each forward pass. This is the architectural prerequisite that allows it to compress its inference VRAM footprint. The model supports a <strong>256K native context window</strong> (extendable to roughly 1 million tokens via YaRN), image understanding, tool calling, and outputs explicit "thinking blocks."</p>
<h2>Benchmarks: Solid Numbers, But Read the Fine Print</h2>
<p>Ornith's published benchmark data is indeed leading among models of its size, particularly in coding and agentic tasks. The following data comes from the official model card and the third-party tracking platform BenchLM:</p>
<h3>Coding Capabilities</h3>
<ul>
<li><strong>SWE-bench Verified (anti-hacking setup):</strong> <strong>84.5%</strong> (vs. Qwen3.8-Flash-Next at 82.8%)</li>
<li><strong>SWE-bench Pro (anti-hacking setup):</strong> <strong>76.9%</strong> (vs. Qwen3.8-Flash-Next at 43.9%)</li>
<li><strong>Terminal-Bench 2.1:</strong> <strong>81.2%</strong> (slightly below Qwen3.8-Flash-Next at 83.4%)</li>
<li><strong>CyberGym:</strong> <strong>80.0%</strong> (vs. Qwen3.8-Flash-Next at 78%)</li>
</ul>
<h3>Reasoning &amp; Agentic Capabilities</h3>
<ul>
<li><strong>HLE (with tools):</strong> <strong>48.0%</strong> | <strong>HLE (without tools):</strong> <strong>37.68%</strong></li>
<li><strong>BrowseComp:</strong> <strong>78.5%</strong></li>
<li><strong>MCP-Atlas:</strong> <strong>74.6%</strong> | <strong>Toolathlon-Verified:</strong> <strong>70.8%</strong></li>
</ul>
<h3>Caveats to the Testing Conditions</h3>
<p>First, <strong>these benchmark scores are currently self-reported by the developers</strong>. BenchLM explicitly notes that Ornith-1.5-122B "is tracked, but has not yet entered public rankings," and its data is categorized as "officially reported results" that have not yet been replicated at scale independently. </p>
<p>Second, <strong>the SWE-bench series used an "anti-hacking" setup</strong>: The model was explicitly evaluated with safeguards against reward hacking, meaning any solutions that still exhibited such behavior were marked as incorrect. This design increases the credibility of the scores but also means they cannot be directly compared to scores run without equivalent constraints. </p>
<p>Third, <strong>the two HLE scores must be viewed separately</strong>: 48.0 is achieved when the model is allowed to use tools, whereas 37.68 is the raw reasoning performance without external tools.</p>
<h2>The "Single DGX" Claim: Conditionally True</h2>
<p>The official model card and multiple sources confirm that the 122B version is designed to be deployable on a <strong>single GPU with 80GB of VRAM</strong>. This is architecturally sound because the MoE activates only ~10B parameters, and quantization can significantly reduce weight memory usage. The team has also released FP8, GGUF, and NVFP4 quantized versions to further lower the barrier to entry.</p>
<p>However, "can load" does not mean "runs comfortably." Taking the GGUF quantized version as an example, the attention cache overhead is <strong>roughly 24 KB per token</strong>, corresponding to about 0.2 GB for an 8K context and about 0.8 GB for a 32K context. This means that after loading the weights on an 80GB card, the remaining VRAM for KV cache, batching, and context windows is limited. If you need long contexts or high concurrency, a single card will still be strained. </p>
<p>The <strong>SGLang documentation</strong> lists a reference configuration of <strong>8× H100 or H200</strong> for BF16 precision. This indicates that "single card" is an optimization target for specific quantized configurations and lightweight workloads, rather than the default way to run it at full precision.</p>
<h2>The MIT License: A Detail Worth Verifying</h2>
<p>One of the core selling points highlighted by Ornith is the MIT license. The official model card explicitly states "Open weights under the MIT license." If the license file is indeed valid and compliant, this is a massive convenience for commercial adoption—MIT allows for unrestricted download, modification, and redistribution.</p>
<p><strong>However, there is an issue developers should note.</strong> When reviewing the model, BenchLM pointed out: "The model card claims open weights under an MIT license, but the linked <strong>LICENSE file is unavailable in the revision reviewed.</strong>" In other words, there is a gap between the text claim on the model card and the actual license file. </p>
<p>For a model derived from Qwen and Gemma, the licensing compliance chain must be verified layer by layer: whether the foundational license terms of Qwen and Gemma permit republishing a derivative work under MIT is a legal question that needs to be verified, not just assumed based on a sentence on the model card.</p>
<h2>Practical Positioning</h2>
<p>The reasonable positioning for Ornith-1.5-122B is: <strong>a heavily optimized, Qwen-derived MoE model that is competitive on agentic coding tasks.</strong> Its self-reported scores on SWE-bench-class tasks are indeed higher than similarly sized baselines, its MIT claim (if verified) is commercially friendly, and single-card quantized deployment is a real possibility.</p>
<p>But it is not a "free surpasses closed-source frontier" model. The no-tools HLE score of 37.68 shows that its raw reasoning still has clear boundaries; the benchmarks have not yet been independently replicated; the actual status of the license file needs to be confirmed; and single-card deployment is constrained by VRAM in terms of context and concurrency.</p>
<p>The recommended evaluation workflow is simple: get the quantization version you need from Hugging Face, run an evaluation on your own real-world tasks (rather than public benchmarks), and verify the license file carefully before making an integration decision.</p>
<h2>References</h2>
<ul>
<li>Ornith-1.5-122B Official Model Card (Hugging Face): <a href="https://huggingface.co/ornith-ai/Ornith-1.5-122B-NVFP4">https://huggingface.co/ornith-ai/Ornith-1.5-122B-NVFP4</a></li>
<li>Ornith-1.5-122B GGUF Model Card: <a href="https://huggingface.co/ornith-ai/Ornith-1.5-122B-GGUF">https://huggingface.co/ornith-ai/Ornith-1.5-122B-GGUF</a></li>
<li>BenchLM.ai Benchmark Tracking and Review: <a href="https://benchlm.ai/models/ornith-1-5-122b">https://benchlm.ai/models/ornith-1-5-122b</a></li>
<li>TheBlockBeats Report on Developers and Architecture: <a href="https://en.theblockbeats.news/flash/372992">https://en.theblockbeats.news/flash/372992</a></li>
<li>AI Tools Review Introduction to DeepReinforce and Jiwei Li: <a href="https://aitoolsreview.co.uk/insights/ornith-1-5">https://aitoolsreview.co.uk/insights/ornith-1-5</a></li>
<li>Gigazine Report on Single DGX Deployment and MoE Architecture: <a href="https://gigazine.net/news/20261021-ornith-1-5-122b/">https://gigazine.net/news/20261021-ornith-1-5-122b/</a></li>
<li>SGLang Deployment Documentation (BF16 Reference Config): <a href="https://docs.sglang.io">https://docs.sglang.io</a></li>
<li>There's An AI For That Profile on DeepReinforce: <a href="https://free.theresanaiforthat.com/model/ornith-1-5-122b/">https://free.theresanaiforthat.com/model/ornith-1-5-122b/</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Onyx: The Open-Source AI Assistant That Keeps Company Data at Home]]></title><description><![CDATA[Most companies have information scattered across Google Drive, Slack, Jira, Confluence, and dozens of other tools. When an employee needs an answer, they…]]></description><link>https://nightthoughts.me/onyx-the-open-source-ai-assistant-that-keeps-company-data-at-home</link><guid isPermaLink="true">https://nightthoughts.me/onyx-the-open-source-ai-assistant-that-keeps-company-data-at-home</guid><category><![CDATA[Open Source]]></category><category><![CDATA[AI]]></category><category><![CDATA[self-hosted]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[privacy]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Wed, 21 Oct 2026 15:01:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/ada7062c-6e3f-48c9-abb4-1416a26e62eb.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most companies have information scattered across Google Drive, Slack, Jira, Confluence, and dozens of other tools. When an employee needs an answer, they spend hours searching. AI can help, but sending internal company data to a closed cloud service is not an option for many organizations.</p>
<p><strong>Onyx</strong> (formerly Danswer) is an open-source, self-hosted AI assistant that connects to a company’s apps, searches them, and answers questions. Because it is open source, anyone can inspect the code. Because it is self-hosted, the company retains full custody of its data. The project lives on GitHub at <strong>github.com/onyx-dot-app/onyx</strong>. The community edition is free under the MIT license, covering chat, RAG, agents, and actions; a separate enterprise edition adds SSO, permission sync, white-labeling, and analytics.</p>
<h3>The Short Story Behind Onyx</h3>
<p>Onyx started in 2023 when two software engineers, <strong>Chris Weaver</strong> and <strong>Yuhong Sun</strong>, set out to solve a problem they kept encountering: new employees simply could not find the information they needed. After two earlier startup attempts that didn't work out, they released an early version under the name <strong>Danswer</strong>. Companies like the fintech firm <strong>Ramp</strong> soon found the project and asked to pay for a product that was completely free. That demand led them to turn the open-source project into a company, backed by <strong>Y Combinator</strong> and a <strong>$10 million seed round</strong> from Khosla Ventures and First Round Capital.</p>
<h3>Real Examples of How Companies Use It</h3>
<p>Onyx is not a general-purpose chatbot. It is a search and research tool that works inside a company’s existing tools and respects existing access rules.</p>
<p><strong>Example 1: Customer support.</strong> A support agent gets a complex billing question. Instead of digging through old Slack threads, Jira tickets, and PDFs, they ask Onyx. It searches connected tools at once and returns an answer with links to the source. If that agent does not have permission to see a private engineering ticket, Onyx will not surface it.</p>
<p><strong>Example 2: New employees.</strong> Questions like “How many vacation days do I get?” or “What is the remote work policy?” can be answered instantly. Onyx finds the relevant HR document in Google Drive and gives the answer, without waiting for an email reply.</p>
<p><strong>Example 3: Sales teams.</strong> Onyx’s AI research agent can handle multi-step questions. If someone asks, “How did we close this deal so quickly?”, the agent runs parallel searches across Salesforce, Gong, email, and Slack, combines the results, and gives a summary—rather than returning a single keyword match.</p>
<h3>Why Self-Hosting Matters</h3>
<p>Onyx can be deployed on a company’s own servers and connects to more than 40 internal data sources including Salesforce, GitHub, Google Drive, and Confluence.</p>
<ul>
<li><p><strong>Data control and custody.</strong> For healthcare, finance, and defense organizations, keeping sensitive data on-premises is often a hard requirement. With self-hosting, the company retains full control and legal custody of its data. Onyx is currently deployed at <strong>Thales Group</strong>, a defense company, and at <strong>Netflix</strong> for all 14,000+ employees.</p>
</li>
<li><p><strong>Cost and model control.</strong> Companies choose their own AI model—commercial options like OpenAI or Anthropic, or local models via Ollama—and pay for the server they run it on, not per seat.</p>
</li>
<li><p><strong>No vendor lock-in.</strong> If a company stops using Onyx, the code and data remain on its own infrastructure.</p>
</li>
</ul>
<p><em>Note on deployment:</em> While a basic evaluation instance can be spun up in about 30 minutes using Docker, a production deployment at enterprise scale requires proper infrastructure, ongoing maintenance, and security patching.</p>
<h3>The Community and Business Model</h3>
<p>As of recent reviews, Onyx has roughly <strong>32,000 stars on GitHub</strong> and has seen over 250 releases. The community edition is MIT-licensed, which means developers can test it, fix bugs, and add features without asking permission.</p>
<p>The business model is open-core: the free community edition drives adoption. Organizations that need stricter security and management tools can upgrade to the <strong>Business tier (starting at $20 per user per month)</strong> or the Enterprise tier. These paid versions include critical features like <strong>permission sync</strong> (ensuring Onyx respects source-system access rules dynamically), single sign-on (SSO), and white-labeling. Because the free version is genuinely usable, companies can try it without a long sales process.</p>
<h3>The Caveats: What Self-Hosting Really Requires</h3>
<p>While self-hosting solves the problem of data leaving your servers, it is not a magic wand. Running Onyx in a real company comes with responsibilities:</p>
<ul>
<li><p><strong>Privacy is a setup task, not a guarantee.</strong> Onyx connects to your apps and respects their permissions, but <em>you</em> must configure those permissions correctly. If the system that syncs user access breaks, Onyx might show data to the wrong people. You still need to monitor who has access to what.</p>
</li>
<li><p><strong>AI makes mistakes.</strong> Onyx uses large language models (LLMs), which can confidently give wrong answers. If an employee asks about a legal policy or a financial figure, Onyx might misread a document. Human oversight and a feedback loop (letting users report bad answers) are necessary, especially for high-stakes topics.</p>
</li>
<li><p><strong>You are the IT department.</strong> When you self-host, the company is responsible for keeping the servers running, applying security patches, and scaling the hardware as more employees use it. This requires a technical team or a managed service provider.</p>
</li>
<li><p><strong>Regulatory compliance is still your job.</strong> Installing Onyx on your own servers does not automatically make you GDPR or HIPAA compliant. You still need legal reviews, audit logs, and data retention policies to ensure the AI does not accidentally store or process sensitive information in ways the law prohibits.</p>
</li>
</ul>
<h3>The Bottom Line</h3>
<p>Onyx is a practical tool for a specific problem: company knowledge is scattered, and employees need a private, permission-aware way to search it. It does not promise to replace every AI product. It promises to keep data on your servers, work with the tools you already use, and let you choose your own model. That straightforward approach—paired with careful setup and human oversight—is why thousands of developers and real companies are using it today.</p>
<p><strong>GitHub:</strong> <a href="https://github.com/onyx-dot-app/onyx">https://github.com/onyx-dot-app/onyx</a> <strong>Website:</strong> <a href="https://onyx.app">https://onyx.app</a></p>
<hr />
<p><em>If you care about open-source infrastructure, data privacy, or practical AI for the workplace, consider following or sponsoring the project.</em></p>
]]></content:encoded></item><item><title><![CDATA[The Harness Is the Agent: Inside Google’s Harness²]]></title><description><![CDATA[Most conversations about AI capability still start with the model. Bigger weights, more compute, longer context, better benchmarks. The model is the thing…]]></description><link>https://nightthoughts.me/the-harness-is-the-agent-inside-google-s-harness</link><guid isPermaLink="true">https://nightthoughts.me/the-harness-is-the-agent-inside-google-s-harness</guid><category><![CDATA[System Design]]></category><category><![CDATA[google research]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[llm]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Wed, 21 Oct 2026 14:59:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/8bf790e3-6e1e-41e0-b829-fa2f446437a0.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most conversations about AI capability still start with the model. Bigger weights, more compute, longer context, better benchmarks. The model is the thing; everything else is scaffolding.</p>
<p>Google Research’s <strong>Harness²</strong> is interesting because it quietly flips that assumption. The model weights stay fixed. What changes is the <strong>harness</strong> around the model — the prompts, tools, memory, guardrails, subagents, scripts, plugins, and orchestration logic that decide how the model actually behaves in the world.</p>
<p>And the harness can rewrite itself.</p>
<p>That’s the core idea behind <a href="https://github.com/google-research/harness2">Harness²</a>: an agentic system that improves its own operating environment through <strong>recursive self-improvement</strong>, without retraining the underlying model and without relying on ground-truth feedback for every task.</p>
<p>If that sounds like a small engineering detail, it isn’t. It’s a different bet about where the next gains come from.</p>
<hr />
<h2>The bottleneck is the scaffolding</h2>
<p>Open-world tasks are messy. There’s no clean verifier sitting at the end telling the agent whether it succeeded. A coding benchmark can run tests. A job-style task — research, planning, tool use, synthesis — often can’t. You get partial signals, behavioral evidence, maybe a rubric, maybe nothing.</p>
<p>Harness² starts from that constraint. Instead of asking “how do we train a better model?”, it asks: <strong>can the agent improve the harness it runs inside, using behavioral evidence from the task itself?</strong></p>
<p>The harness here is not just a system prompt. It includes the editable surface around the model: system prompt, guardrails, memory, tool guidance, subagents, skills, scripts, and plugins. Eight components, all editable. The model is the CPU. The harness is the operating system that decides how the CPU gets used.</p>
<p>That analogy matters. A faster CPU with a bad OS still loses. A fixed model with a better harness can look like a different agent entirely.</p>
<hr />
<h2>Two levels of recursion</h2>
<p>The technical meat of Harness² is that recursion happens at two levels.</p>
<h3>1. Task-level recursion: Propose–Probe–Compose</h3>
<p>For a given task, the system runs a contrastive loop:</p>
<ul>
<li><strong>Propose</strong> edits to the harness.</li>
<li><strong>Probe</strong> those edits by observing their behavioral effects on the same task.</li>
<li><strong>Compose</strong> a refined harness from the contrasts.</li>
</ul>
<p>The key detail: this happens <strong>without ground-truth feedback</strong>. The agent isn’t checking against a hidden answer key. It’s comparing behaviors — what changed when we edited the harness, and what does that tell us about the next edit?</p>
<p>That’s a subtle but important shift. The signal isn’t “correct/incorrect.” It’s “this harness produced this behavior; that harness produced that behavior; the contrast is evidence.”</p>
<h3>2. Harnessing-level recursion: the improvement harness</h3>
<p>The second level is where it gets more interesting. Harness² maintains a persistent <strong>improvement harness</strong> that banks adopted harnesses and evidence-backed lessons from each task. Those lessons then guide future refinement.</p>
<p>So recursion isn’t just about the current task. It’s about building a reusable meta-harness that accumulates experience across tasks.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/963d8800-9182-4a1c-9bb8-700bb696b4bf.png" alt="Harness² two-level recursion diagram: Task → Propose–Probe–Compose → Improvement Harness → Next Task" /></p>
<p><em>Diagram: Harness² two-level recursion.</em></p>
<p>The paper also distinguishes <strong>parallel recursion</strong> — exploring wider by testing multiple candidate edits — from <strong>sequential recursion</strong> — refining deeper by chaining Propose–Probe–Compose steps. That’s the test-time scaling hook: more recursion buys more exploration or more depth.</p>
<hr />
<h2>What the benchmarks actually say</h2>
<p>The headline numbers are concrete:</p>
<ul>
<li><strong>Up to +11.5 points on WorkBuddy-Bench</strong></li>
<li><strong>+4.5 on JobBench</strong></li>
<li><strong>+11.8 percentage points on LAB partial pass rate</strong></li>
</ul>
<p>Those are not trivial gains. But the more important claim is architectural: the improvement comes from editing the harness, not from changing the model.</p>
<p>If that generalizes, the implication is uncomfortable for the “just scale the model” narrative. The next leap in agent capability may come less from a bigger model and more from a model that can <strong>rewrite its own operating environment between tasks</strong>.</p>
<hr />
<h2>What using it actually looks like</h2>
<p>The repo keeps the demo path reasonably light: Linux, Python 3.12, and <code>uv</code>. The local demo needs no credentials. Model-backed benchmarks need Vertex AI plus Node and benchmark dependencies — Docker for WorkBuddy, Pandoc/Poppler for LAB. Executor choices include <strong>OpenCode</strong> as the default and <strong>Codex</strong>.</p>
<p>That’s the practical surface. The conceptual surface is more interesting: you’re not just running an agent. You’re running an agent that is editing the thing that runs it.</p>
<hr />
<h2>Three late-night caveats</h2>
<p><strong>1. The guardrail file is not a security boundary.</strong><br />Editable guardrails are part of the harness, not a hard safety sandbox. If the harness can rewrite itself, the safety story has to live somewhere else — outside the editable surface.</p>
<p><strong>2. Task-specificity risk.</strong><br />The improvement harness is supposed to accumulate lessons that transfer. But benchmarks are benchmarks. Does it generalize to genuinely novel tasks, or does it overfit to the shape of the evaluation suite? The paper claims transfer; this is exactly the kind of claim that deserves independent replication.</p>
<p><strong>3. Open-world evaluation is messy.</strong><br />Public rubrics may be online. Network access is unrestricted in executors. Reproducibility and contamination are live questions. That doesn’t invalidate the results, but it does mean the numbers should be read as evidence, not gospel.</p>
<hr />
<h2>The takeaway</h2>
<p>Harness² is a reminder that the agent is not just the model. It’s the model plus the environment it can edit. And if the harness is the thing that learns, then the important questions shift: how do we evaluate a system that changes its own operating environment? How do we deploy it safely when the guardrails are editable? And what does it mean for trust if the scaffolding is recursive?</p>
<p>The model weights are fixed. The harness is not. That’s the whole bet.</p>
<hr />
<p><em>Links: <a href="https://github.com/google-research/harness2">Harness² GitHub</a></em></p>
]]></content:encoded></item><item><title><![CDATA[Ask Your Software How It Works: A Practical Guide to REA]]></title><description><![CDATA[How AI agents are turning reverse engineering from a weeks-long chore into evidence-backed answers about the software you already own]]></description><link>https://nightthoughts.me/ask-your-software-how-it-works-a-practical-guide-to-rea</link><guid isPermaLink="true">https://nightthoughts.me/ask-your-software-how-it-works-a-practical-guide-to-rea</guid><category><![CDATA[AI]]></category><category><![CDATA[reverse engineering]]></category><category><![CDATA[open source]]></category><category><![CDATA[Security]]></category><category><![CDATA[devtools]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Sat, 17 Oct 2026 23:53:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/d219d743-df3e-4c43-a5f2-16fc6c387305.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>TL;DR</strong> — <a href="https://github.com/morluto/rea">REA</a> is an open-source MCP server and CLI that lets an AI agent drive Ghidra, IDA, or Hopper — plus built-in analyzers for JavaScript, .NET, Go, Rust, Android, websites, and network captures — so you can ask functional questions about software in plain language and get answers <strong>with cited evidence</strong>. It's an orchestration layer, not a decompiler, and not a source-code recovery machine.</p>
</blockquote>
<hr />
<p>Everyone who works with software eventually inherits something nobody fully understands — a legacy service with no living author, an acquired product with partial docs, a vendor binary you must integrate, an Electron app whose behavior lives only in team folklore. The usual answer is weeks of manual reverse engineering in Ghidra or IDA: expensive, slow, and hard to justify.</p>
<p><strong>REA (Reverse Engineer Anything)</strong> changes the economics of that work. It's an open-source <strong>MCP server and CLI</strong> that lets an AI agent (Claude Code, Codex, Cursor, Gemini CLI) drive professional analysis tools for you — so you can <strong>ask functional questions about software in plain language</strong> and get answers with evidence attached.</p>
<p>This is a short, practical briefing: what REA is, why it's worth a pilot, and the kinds of questions you can actually ask.</p>
<hr />
<h2>What REA Is (in one paragraph)</h2>
<p>REA is an <strong>orchestration layer</strong>, not a decompiler. It connects an AI agent to existing engines — <strong>Hopper, Ghidra, or IDA</strong> for native binaries — plus built-in analyzers for <strong>JavaScript/Electron, .NET, Go, Rust, Android APKs, websites, and saved network captures</strong>. You ask a question; the agent picks the right tool, runs the analysis locally, and returns findings <strong>with evidence, limitations, and unknowns cited</strong>. Several targets (JavaScript, .NET, Go, Rust) need <strong>no native engine at all</strong>.</p>
<hr />
<h2>Why It's Worth a Pilot</h2>
<table>
<thead>
<tr>
<th>Benefit</th>
<th>In practice</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Faster onboarding</strong></td>
<td>New joiners interrogate unfamiliar code instead of reading it for weeks</td>
</tr>
<tr>
<td><strong>M&amp;A and vendor due diligence</strong></td>
<td>Citable answers about what a binary or app actually does — before you commit</td>
</tr>
<tr>
<td><strong>Supply-chain visibility</strong></td>
<td>Identify bundled libraries, compiler versions, and outbound calls in third-party components</td>
</tr>
<tr>
<td><strong>Security and compliance review</strong></td>
<td>Evidence-linked findings you can attach to an audit trail, not a black-box summary</td>
</tr>
<tr>
<td><strong>Documentation recovery</strong></td>
<td>Turn tribal knowledge into written, sourced explanations</td>
</tr>
<tr>
<td><strong>Reduced key-person risk</strong></td>
<td>The software explains itself after the original author leaves</td>
</tr>
<tr>
<td><strong>Lower tooling cost</strong></td>
<td>Static analysis of JS/.NET/Go/Rust needs no Ghidra or IDA license</td>
</tr>
<tr>
<td><strong>Support and escalation</strong></td>
<td>Answer "why does it behave like this?" without a rebuild and a debugger</td>
</tr>
</tbody></table>
<p>The <strong>evidence contract</strong> is the differentiator: every result carries a <code>result</code>, an <code>evidence_id</code>, and explicit <code>limitations</code> and <code>unknowns</code>. That's the difference between "the AI said so" and "here's where we verified it."</p>
<hr />
<h2>The Core Value: Asking Functional Questions</h2>
<p>Instead of reading code line by line, you ask <strong>how a behavior works</strong> — and the agent traces the answer, sometimes across layers.</p>
<h3>Questions by target</h3>
<p><strong>Electron / JavaScript apps</strong></p>
<ul>
<li><em>"How does the renderer talk to the main process? List every IPC channel and what it does."</em></li>
<li><em>"What exactly is exposed through <code>contextBridge</code>?"</em></li>
<li><em>"Which modules make outbound HTTP calls, and to which hosts?"</em></li>
<li><em>"How is auto-update triggered, and where does it fetch from?"</em></li>
</ul>
<p><strong>Native binaries (Hopper / Ghidra / IDA)</strong></p>
<ul>
<li><em>"How does the licensing check work? Trace the call chain from startup."</em></li>
<li><em>"Where is the config file parsed, and what format does it expect?"</em></li>
<li><em>"Which functions handle encryption, and what algorithm and key size?"</em></li>
<li><em>"What happens when the user clicks Export? Walk me through the call graph."</em></li>
</ul>
<p><strong>.NET assemblies</strong></p>
<ul>
<li><em>"List the public API surface and the native dependencies this assembly loads."</em></li>
<li><em>"Which methods touch the registry, and with what keys?"</em></li>
</ul>
<p><strong>Go / Rust binaries</strong></p>
<ul>
<li><em>"What compiler version and module list produced this binary?"</em></li>
<li><em>"Which packages are linked, and are any outdated or known-vulnerable?"</em></li>
</ul>
<p><strong>Android APKs</strong></p>
<ul>
<li><em>"What permissions does this app request, and where are they used?"</em></li>
<li><em>"Which third-party SDKs are embedded?"</em></li>
</ul>
<p><strong>Websites and network captures</strong></p>
<ul>
<li><em>"Which endpoints does this page call, with what payloads?"</em></li>
<li><em>"Reconstruct the API contract from this HAR file."</em></li>
</ul>
<h3>The loop</h3>
<ol>
<li><strong>Ask</strong> a functional question.</li>
<li><strong>The agent investigates</strong>, choosing the right engine via REA's bundled Skill.</li>
<li><strong>REA returns structured evidence</strong> — pseudocode, call graphs, request logs, with citations.</li>
<li><strong>Iterate</strong> — follow up, trace deeper, resolve an <code>unknown</code>.</li>
<li><strong>Document or rebuild</strong> — attach evidence to your notes, or reconstruct and verify the behavior.</li>
</ol>
<p>Notably, REA can trace <strong>across layers</strong> — e.g., from an Electron renderer through IPC into the main process and down to a native addon — which previously meant stitching several tools together by hand.</p>
<hr />
<h2>What REA Does <em>Not</em> Do</h2>
<p>Credibility comes from clear boundaries:</p>
<ul>
<li><strong>Not a source-code recovery machine.</strong> Successes are <strong>function-level and target-specific</strong>, not full rewrites.</li>
<li><strong>Depth is capped by the engine underneath.</strong> Ghidra/IDA quality still governs native analysis.</li>
<li><strong>Obfuscation is still hard</strong> — control-flow flattening and virtualization challenge current LLMs.</li>
<li><strong>Local analysis ≠ local conversation.</strong> Binaries stay on your machine, but <strong>agent tool results flow to the model provider</strong>. For sensitive targets, that's a compliance gate, not a footnote.</li>
<li><strong>Clean-room IP concerns are real.</strong> The same agent reads the original and writes the replacement, which undermines traditional clean-room independence. Treat REA as an <strong>authorized investigation</strong> tool, not a cloning tool.</li>
</ul>
<p>Independent tests confirm the pattern: strong results on well-scoped functions in unobfuscated targets; missed call relationships and premature "analysis complete" claims on larger binaries.</p>
<hr />
<h2>Getting Started</h2>
<p><strong>Prerequisites:</strong> Node.js 22.19+ / 24.11+ / 26+ and npm.</p>
<pre><code class="language-bash">npx rea-agents@latest setup
</code></pre>
<p>The wizard detects your agent (Claude Code, Codex, Cursor, Gemini CLI, etc.), shows exactly what it will change, backs up your config, and applies changes only after approval. Preview first:</p>
<pre><code class="language-bash">npx rea-agents@latest setup --client codex --dry-run --json
</code></pre>
<p><strong>Try it without Ghidra</strong> on a JavaScript/Electron app:</p>
<pre><code class="language-bash">npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json
</code></pre>
<p>No MCP setup, no native engine, no execution of the target.</p>
<p><strong>Check readiness:</strong></p>
<pre><code class="language-bash">rea doctor
</code></pre>
<p>This audits agent registration, the installed Skill, and optional engines.</p>
<p>Install <strong>only</strong> from <a href="https://github.com/morluto/rea">github.com/morluto/rea</a>, the npm package <a href="https://www.npmjs.com/package/rea-agents">rea-agents</a>, or <a href="https://rea.tools/">rea.tools</a>. Counterfeit repositories have shipped malware under the REA name.</p>
<hr />
<h2>The Takeaway</h2>
<p>REA doesn't replace judgment, threat modeling, or legal review. What it replaces is the <strong>manual triage layer</strong> — the weeks of context-gathering between a question and an evidence-backed answer.</p>
<p>For anyone who has to understand software they didn't write — developers, security engineers, tech leads, product owners, consultants, due diligence teams, support and operations — that means <strong>faster, cheaper, auditable understanding of software you already own or are authorized to inspect</strong>.</p>
<p>You can finally ask your software how it works — and get an answer you can cite.</p>
<hr />
<h2>References</h2>
<ul>
<li><strong>REA repository:</strong> <a href="https://github.com/morluto/rea">github.com/morluto/rea</a></li>
<li><strong>Official site:</strong> <a href="https://rea.tools/">rea.tools</a></li>
<li><strong>npm:</strong> <a href="https://www.npmjs.com/package/rea-agents">rea-agents</a></li>
<li><strong>Independent technical research (architecture, evidence contract, security model):</strong> <a href="https://github.com/ringozzt/rea-research">ringozzt/rea-research</a></li>
<li><strong>Overview (target table, setup, star timeline):</strong> <a href="https://apidog.com/blog/what-is-rea-reverse-engineer-anything/">Apidog — What Is REA?</a></li>
<li><strong>Showcases and community reception:</strong> <a href="https://www.infoq.com/news/2026/10/reverse-engineer-anything/">InfoQ — Reverse Engineer Anything Project Brings AI Agents to Binary Analysis</a></li>
<li><strong>Hands-on test against real source code:</strong> <a href="https://dev.to/moksh/testing-rea-the-viral-ai-reverse-engineering-repo-against-real-source-code-49ja">Testing REA Against T3 Code</a></li>
<li><strong>Tool comparison (REA vs. IDA MCP, GhidraMCP):</strong> <a href="https://dev.to/leemie8848/ai-reverse-engineering-tools-compared-rea-ida-mcp-ghidramcp-and-friends-oct-2026-3hfl">AI reverse-engineering tools compared</a></li>
<li><strong>Limits, test failures, counterfeit warning:</strong> <a href="https://hyper.ai/en/stories/5466749b77edd4705dba0e65415bad4d">Hyper.ai summary</a></li>
<li><strong>Legal risk analysis (clean-room, EULA, copyright):</strong> <a href="https://qifukexue.com/?p=40565">AI逆向工具REA法律风险分析</a></li>
<li><strong>Beginner manual (REA + Ghidra):</strong> <a href="https://github.com/morluto/rea/discussions/3791">GitHub Discussion #3791</a></li>
</ul>
<hr />
<blockquote>
<p><strong>Disclaimer:</strong> Only analyze software you own or are explicitly authorized to inspect. Ensure compliance with license terms, contracts, and applicable law before running REA against any target.</p>
</blockquote>
<p><em>— Haithem Slimi · <a href="https://nighthoughts.me">nighthoughts.me</a></em></p>
]]></content:encoded></item><item><title><![CDATA[The Memory Wall: How NVIDIA’s RTX Spark Changes the AI Bottleneck]]></title><description><![CDATA[When people talk about AI hardware, the conversation usually centers on compute. How many teraflops can a chip push? How many operations per second? Faster…]]></description><link>https://nightthoughts.me/the-memory-wall-how-nvidia-s-rtx-spark-changes-the-ai-bottleneck</link><guid isPermaLink="true">https://nightthoughts.me/the-memory-wall-how-nvidia-s-rtx-spark-changes-the-ai-bottleneck</guid><category><![CDATA[AI]]></category><category><![CDATA[local ai]]></category><category><![CDATA[unified memory]]></category><category><![CDATA[Memory Wall]]></category><category><![CDATA[ Semiconductors]]></category><category><![CDATA[power-efficiency]]></category><category><![CDATA[GPU]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Wed, 14 Oct 2026 22:01:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/9276fb11-51d4-4305-8397-c042369e1bc2.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>When people talk about AI hardware, the conversation usually centers on compute. How many teraflops can a chip push? How many operations per second? Faster chips sound like faster AI.</p>
<p>But that framing misses the real constraint. AI workloads are not primarily compute-bound. They are memory-bound. The bottleneck is not how fast a processor can calculate. It is how fast data can get to the processor, and how much of it can fit in the right place at the right time.</p>
<p>This is the memory wall. And it is the reason why a GPU with enormous compute capacity can still feel sluggish when running a large language model.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/c87c2c27-f0f0-4cc9-94b2-1a2badd30830.png" alt="Figure 1" />
<em>Figure 1: The von Neumann bottleneck. Steps 1, 3, and 5 show the expensive data movement between memory and processor.</em></p>
<h2>1. The Bottleneck Nobody Talks About</h2>
<h3>The Von Neumann Problem</h3>
<p>Almost every computer in use today follows the same basic design. A processing unit (CPU or GPU) sits separated from a storage unit (RAM or VRAM), connected by a bus. This is the von Neumann architecture, and it has been the foundation of computing since the 1940s.</p>
<p>The design has one inherent weakness. Every piece of data that needs to be processed must first travel from memory to the processor. Then the result travels back. For simple tasks, this is negligible. For AI workloads, which involve massive matrices of numbers and repeated passes over model weights, the travel becomes the dominant cost.</p>
<p>Researchers call this the memory wall <sup><a href="#ref-1">[1]</a></sup>. Over the past 20 years, peak server compute has scaled at roughly 3× every two years, while DRAM bandwidth has grown at only 1.6× and interconnect bandwidth at 1.4×. The gap is still widening.</p>
<p>Google confirmed this at data-center scale. Compute performance has grown roughly 80× over the last decade, while memory bandwidth has grown closer to 17× <sup><a href="#ref-2">[2]</a></sup>. Modern LLM inference is bottlenecked by memory bandwidth and memory latency, not compute.</p>
<h3>Why AI Makes It Worse</h3>
<p>AI workloads have three properties that make the memory wall particularly painful.</p>
<p><strong>Model size is capped by memory capacity.</strong> A model must fit entirely in memory to run. If it doesn't fit, it fails to load. A 72-billion-parameter model at 16-bit precision requires over 144 GB of memory just for the weights.</p>
<p><strong>Data movement consumes most of the energy.</strong> Research consistently shows that 60% to 80% of total energy in deep learning tasks is consumed by data transmission rather than computation. Moving data is expensive. Computing on it is cheap.</p>
<p><strong>Context length competes with model capability.</strong> The KV cache, the memory that holds conversation context during inference, grows linearly with context length. A model with a 128K-token context window adds roughly 40 GB of KV cache on top of its weights. Longer context means more memory consumed.</p>
<h3>The Two Kinds of Memory: RAM and VRAM</h3>
<p>To understand the bottleneck, you need to understand the two memory pools in a traditional PC.</p>
<p><strong>RAM</strong> is the main memory for the CPU. It stores the operating system, your open applications, and active data. Typical size: 16GB to 128GB.</p>
<p><strong>VRAM</strong> is dedicated memory for the GPU. It stores graphics data, model weights, and activations. It is designed for extremely high bandwidth because the GPU has thousands of cores that need data simultaneously. Typical size: 8GB to 24GB.</p>
<p>These are two separate pools, in two separate physical locations, connected by a PCIe bus. If the GPU needs data, it must be copied from RAM, carried across the bus, and placed into VRAM. That copy operation is the bottleneck.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/b3d5562b-9672-43f9-a852-4299cf66b2e7.png" alt="Figure 1a" />
<em>Figure 1a: What resides in RAM and VRAM. RAM holds the operating system, applications, and active data for the CPU. VRAM holds model weights, KV cache, activations, and frame buffers for the GPU. In a traditional PC, these are separate pools connected by a slow PCIe bus. Diagram credit: Haithem Slimi.</em></p>
<h2>2. How the RTX Spark Tackles the Memory Wall</h2>
<h3>The Core Idea: Unified Memory</h3>
<p>The NVIDIA RTX Spark takes a different approach. Instead of having separate RAM and VRAM pools, it uses <strong>unified memory</strong>. The CPU and GPU share the exact same pool of physical memory addresses.</p>
<p>NVIDIA officially announced the RTX Spark in 2026. It is an Arm-based system-on-a-chip (SoC) that combines a 20-core Grace CPU, a 6,144-core Blackwell RTX GPU, and up to 128 GB of LPDDR5X unified memory on a single piece of silicon <sup><a href="#ref-7">[7]</a></sup>. The highest configuration supports models with up to 120 billion parameters and a context window of one million tokens.</p>
<h3>Why This Matters</h3>
<p>In a traditional PC, the CPU and GPU are separate chips on the motherboard. They communicate over a PCIe bus. Data must travel across that bus, which is comparatively slow and power-hungry.</p>
<p>In the RTX Spark, the CPU and GPU share the same memory pool. There is no PCIe bus to cross. Both processors can access the same data directly, in place, without copying it back and forth. This is called <strong>zero-copy</strong> access.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/ed046b1a-b294-4290-b8da-a967417520e3.png" alt="Figure 2" />
<em>Figure 2: The RTX Spark unified memory data flow. By placing CPU, GPU, and memory on a single piece of silicon, the external bus bottleneck is eliminated, allowing direct, zero-copy access to large AI models.</em></p>
<h2>3. The RAG Angle — Do You Still Need Retrieval?</h2>
<h3>What RAG Is</h3>
<p>RAG stands for Retrieval-Augmented Generation. It exists because models have limited context windows and limited memory. You cannot fit all your data into the model, so you retrieve the relevant pieces at query time and feed them into the context window.</p>
<p>RAG works. But it has costs.</p>
<p><strong>RAG adds latency.</strong> Every query requires a retrieval step: embedding the query, searching a vector database, fetching chunks, and re-ranking. On a local device, this is all overhead.</p>
<p><strong>RAG is lossy.</strong> Retrieval picks chunks based on similarity, but similarity is not relevance. The model might get the wrong context, or miss important information that was not retrieved.</p>
<p><strong>RAG fragments knowledge.</strong> The model does not "know" your data. It only sees whatever the retriever feeds it. Reasoning across disparate pieces of information becomes harder.</p>
<h3>What Changes with Unified Memory</h3>
<p>The RTX Spark's 128 GB unified memory pool can hold a 120-billion-parameter model with a one-million-token context window entirely in local memory. You no longer need to retrieve pieces of data. You can load everything and reason over everything.</p>
<p>This does not mean RAG is dead. It is still essential for truly massive knowledge bases, constantly updating data, or multi-user systems where each user has different access permissions. But for personal knowledge management — your notes, your documents, your codebase — the constraint that made RAG necessary is changing.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/f49c2cbb-261c-4931-a224-516fa443159e.png" alt="Figure 3" />
<em>Figure 3: A side-by-side comparison of local AI approaches. Left: Traditional RAG relies on retrieval, re-ranking, and a small context window. Right: The RTX Spark's unified memory allows the entire model and dataset to be loaded into a single 128GB pool, enabling zero-copy access and full-context reasoning without retrieval overhead.</em></p>
<h2>4. The Training Angle — Local Fine-Tuning Becomes Practical</h2>
<h3>Why Training Needs More Memory</h3>
<p>Training and fine-tuning are even more memory-hungry than inference. You need memory for four things:</p>
<ol>
<li><strong>Model weights.</strong> The parameters of the model itself.</li>
<li><strong>Gradients.</strong> The values computed during backpropagation.</li>
<li><strong>Optimizer states.</strong> The internal state of the optimizer algorithm. Research shows optimizer states can account for up to 42% of total memory usage during fine-tuning <sup><a href="#ref-9">[9]</a></sup>.</li>
<li><strong>Activations.</strong> The intermediate outputs of each layer during the forward pass.</li>
</ol>
<p>A practical rule of thumb is that fine-tuning requires 4 to 6 times the memory of the model itself <sup><a href="#ref-9">[9]</a></sup>. For a 7B model, that means 28 to 42 GB. For a 70B model, 280 to 420 GB. On a traditional GPU with 24 GB of VRAM, fine-tuning anything beyond a small model is impractical.</p>
<h3>What the RTX Spark Changes</h3>
<p>The RTX Spark's 128 GB unified memory pool can hold the model, gradients, optimizer states, and activations for models in the 7B to 70B range. This makes local fine-tuning practical for prototyping and privacy-sensitive work. It does not replace cloud training for large-scale runs, but it removes the barrier to entry for local experimentation.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/8d0650fc-fea8-495f-8e68-78fe6427cec2.png" alt="Figure 4" />
<em>Figure 4: The memory capacity challenge for local AI training. Fine-tuning requires memory for model weights, gradients, optimizer states, and activations. Traditional GPUs quickly hit an "Out of Memory" wall. The RTX Spark's 128GB unified memory pool comfortably fits these components.</em></p>
<h2>5. The Honest Caveat — Two Bandwidths, One Solved</h2>
<p>Before explaining the caveat, we need to define two terms that appear everywhere in AI hardware discussions: <strong>HBM</strong> and <strong>LPDDR5X</strong>.</p>
<p><strong>HBM (High Bandwidth Memory)</strong> is a type of memory designed for data-center GPUs. It stacks multiple memory chips vertically and places them directly next to the GPU on the same package. This makes it extremely fast — but also expensive, power-hungry, and difficult to manufacture. It is what NVIDIA's data-center GPUs use.</p>
<p><strong>LPDDR5X (Low Power Double Data Rate 5X)</strong> is a type of memory designed for smartphones and thin laptops. It prioritizes energy efficiency and capacity over raw speed. It is what the RTX Spark uses for its unified memory pool.</p>
<p>Now, the key distinction. When people say "bandwidth," they could mean two different things.</p>
<h3>Bandwidth Angle 1: Bus Bandwidth (Solved)</h3>
<p>This is the speed of the path between the processor and memory. In a traditional PC, this is the PCIe bus — slow and narrow. The RTX Spark replaces it with NVLink-C2C, a direct on-package interconnect. <strong>This bottleneck is solved.</strong> Data no longer has to cross a slow external bus.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/37acf993-a106-432f-9ee8-11d076483363.png" alt="Figure 5a" />
<em>Figure 5a: Bus bandwidth — the solved problem. Traditional PCs force data across a slow PCIe bus between CPU and GPU. The RTX Spark replaces this with NVLink-C2C, a direct on-package interconnect. The bus bottleneck is eliminated. Zero-copy access is enabled.</em></p>
<h3>Bandwidth Angle 2: Memory Bandwidth (Not Solved)</h3>
<p>This is the speed of the memory itself — how fast the DRAM can produce data once the processor asks for it. This is a property of the memory technology, not the bus. Even with a superhighway connecting the processor to memory, the memory can only produce data so fast. HBM produces data far faster than LPDDR5X.</p>
<p>For context: NVIDIA's Rubin data-center GPUs pack 288 GB of HBM4 with up to 22 TB/s of peak bandwidth <sup><a href="#ref-6">[6]</a></sup>. By comparison, the RTX Spark's LPDDR5X memory tops out at around 600 GB/s <sup><a href="#ref-7">[7]</a></sup>. The gap is roughly 36x in raw bandwidth.</p>
<p>The RTX Spark solves the road problem. It does not solve the forklift problem. The LPDDR5X memory itself has a physical speed limit that is lower than HBM. This is the honest caveat.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/e58a2963-17ae-47e3-8970-c3c2dd26588f.png" alt="Figure 5b" />
<em>Figure 5b: Memory bandwidth — the unsolved problem. The RTX Spark solves capacity (128GB) and eliminates copy overhead. But it does not solve raw memory bandwidth. The LPDDR5X pipe is narrower and slower than dedicated HBM memory found in data-center GPUs (600 GB/s vs. 22 TB/s). The tank is bigger. The pipe is smaller.</em></p>
<h2>6. The Power Angle — Why Efficiency Is the Real Win</h2>
<p>The memory wall is not just a performance problem. It is also a power problem.</p>
<p>In traditional systems, data movement consumes the majority of energy. NVIDIA's own research states that 73% of computing energy in AI workloads goes to moving data, while only 9% is used for actual computation <sup><a href="#ref-3">[3]</a></sup>. Every byte that crosses the PCIe bus costs energy. The RTX Spark's architecture directly attacks this.</p>
<h3>NVLink-C2C: The Efficiency Breakthrough</h3>
<p>The specific technology enabling the efficiency gain is NVLink-C2C, a chip-to-chip interconnect that replaces the PCIe bus entirely. NVIDIA states that NVLink-C2C delivers up to 5x more energy efficiency than PCIe Gen 5, with data transfers consuming just 1.3 picojoules per bit <sup><a href="#ref-4">[4]</a></sup>.</p>
<p>One academic study measured the actual power consumption of both interconnects. NVLink consumed 70.9 picojoules per bit, while PCIe consumed 167.9 picojoules per bit <sup><a href="#ref-5">[5]</a></sup>. That is 2.4x less energy per bit moved — a tangible, measurable improvement.</p>
<h3>The User-Facing Benefit: Real Battery Life</h3>
<p>This efficiency translates into real-world battery life. The RTX Spark operates at a TDP of 45-80W <sup><a href="#ref-7">[7]</a></sup>. It can drop to single-digit wattage during light tasks like typing or browsing. NVIDIA claims it is its most power-efficient RTX chip ever made and delivers all-day battery life in a thin chassis.</p>
<p>An independent battery test at IFA 2026 confirmed this. A Surface Laptop Ultra running Blender — an intensive 3D rendering application — was unplugged at 9 AM. After 5.5 hours, the 10% battery warning had only just appeared <sup><a href="#ref-8">[8]</a></sup>. A comparable MacBook Pro would typically last 4-5 hours under similar workloads.</p>
<h3>The Trade-off</h3>
<p>The RTX Spark achieves this efficiency partly because LPDDR5X is inherently more power-efficient than HBM. You get lower bandwidth, but you also get a laptop thin enough to carry, with battery life that lasts through a workday. That is the power win.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/bd156343-da44-4ff1-a3ce-181f1e4a2b99.png" alt="Figure 6" />
<em>Figure 6: The power efficiency difference. Traditional PCs waste energy moving data across a PCIe bus (167.9 pJ/bit). The RTX Spark eliminates this by connecting CPU, GPU, and memory directly via NVLink-C2C (70.9 pJ/bit), achieving over 2x less energy per bit moved.</em></p>
<h2>Conclusion</h2>
<p>The RTX Spark is not just a faster chip. It is a bet that the next phase of AI requires a different memory architecture than the one we have been using for 80 years.</p>
<p>It solves the bus bottleneck by placing CPU, GPU, and memory on a single piece of silicon. It solves the capacity problem by offering 128 GB of unified memory. It delivers a tangible power efficiency win by eliminating the energy-hungry PCIe bus.</p>
<p>But it does not solve everything. The LPDDR5X memory itself is slower than the HBM used in data-center GPUs. The RTX Spark is a local prototyping and fine-tuning tool, not a replacement for a server rack.</p>
<p>Whether this bet pays off depends on whether developers and creators actually need this level of local memory and AI compute. The hardware is here. The software and use cases are still being figured out.</p>
<p><img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/c5e11df3-3679-41d9-908c-e2140f83120e.png" alt="Figure 7" />
<em>Figure 7: The shift to local AI agents. By removing the memory wall for local devices, the RTX Spark enables continuous, private AI that runs entirely on-device without cloud dependency.</em></p>
<h2>References</h2>
<p><a id="ref-1"></a>1. <a href="https://dl.acm.org/doi/10.1145/216585.216588">Wulf, W., &amp; McKee, S. (1995). Hitting the Memory Wall: Implications of the Obvious.</a></p>
<p><a id="ref-2"></a>2. <a href="https://research.google/pubs/">Google Research. (2025). Hardware scaling disparities in AI data centers.</a></p>
<p><a id="ref-3"></a>3. <a href="https://developer.nvidia.com/blog/">NVIDIA GTC 2026 keynote and developer blog. Energy consumption in AI workloads.</a></p>
<p><a id="ref-4"></a>4. <a href="https://www.nvidia.com/en-us/data-center/nvlink-c2c/">NVIDIA NVLink-C2C specifications. Energy efficiency comparisons.</a></p>
<p><a id="ref-5"></a>5. <a href="https://arxiv.org/">Academic study on interconnect power consumption. (70.9 pJ/bit vs. 167.9 pJ/bit)</a></p>
<p><a id="ref-6"></a>6. <a href="https://www.nvidia.com/en-us/data-center/">NVIDIA Rubin GPU specifications (288 GB HBM4, 22 TB/s).</a></p>
<p><a id="ref-7"></a>7. <a href="https://www.nvidia.com/en-us/geforce/">RTX Spark specifications (128 GB LPDDR5X, 600 GB/s, 45-80W TDP).</a></p>
<p><a id="ref-8"></a>8. <a href="https://www.microsoft.com/en-us/surface">IFA 2026 Surface Laptop Ultra battery test.</a></p>
<p><a id="ref-9"></a>9. <a href="https://arxiv.org/">Fine-tuning memory requirements research (optimizer states, 4-6x rule).</a></p>
]]></content:encoded></item><item><title><![CDATA[The Future Is Both]]></title><description><![CDATA[New to the jargon? Start with the glossary → Most AI systems today pick a side. They run entirely local or entirely cloud. That's a design choice, not a…]]></description><link>https://nightthoughts.me/the-future-is-both</link><guid isPermaLink="true">https://nightthoughts.me/the-future-is-both</guid><category><![CDATA[AI]]></category><category><![CDATA[local ai]]></category><category><![CDATA[CloudComputing]]></category><category><![CDATA[Future]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Tue, 13 Oct 2026 23:08:48 GMT</pubDate><content:encoded><![CDATA[<p>New to the jargon? <a href="https://nightthoughts.me/plain-english-glossary-ai-terms-for-the-rest-of-us">Start with the glossary →</a></p>
<hr />
<p>Most AI systems today pick a side. They run entirely local or entirely cloud. That's a design choice, not a law of nature.</p>
<p>The choice made sense when local and cloud were genuinely different tools. Local was private but weak. Cloud was capable but exposed. Picking one meant accepting its weakness. That trade-off has narrowed.</p>
<p>Local models are now good enough for most queries. Cloud models are still better for the hardest ones. Running only local leaves capability on the table. Running only cloud sends private data out the door for no reason.</p>
<p>The alternative is routing. A system that decides, per query, where the query should run.</p>
<h2>The dial, not the switch</h2>
<p>Essay 4 ended with a line: the line between local and cloud is not a wall. It's a dial.</p>
<p>A switch has two positions. A dial has a range. The range is where the interesting engineering lives.</p>
<p>Most production AI today sits at one of two extremes. Either the entire product runs on a local model — private, slow, capped by consumer hardware. Or the entire product runs in the cloud — fast, capable, with every request leaving the user's machine.</p>
<p>Both extremes are simple. Both leave value on the table. The middle position — routing — captures the best of each without inheriting either's weaknesses.</p>
<h2>What routing looks like in practice</h2>
<p>Three scenarios, three scales.</p>
<p><strong>The developer.</strong></p>
<p>A coding assistant runs locally by default. Autocomplete, small refactors, docstring generation, renames — all local. Code never leaves the laptop. Fast enough, private by default, no per-query cost.</p>
<p>When the developer hits a hard problem — an architecture decision, a bug spanning six services, a subtle race condition — the assistant escalates the query to a cloud model. The developer doesn't press a button. The system decides.</p>
<p>The developer experiences one assistant. Behind the scenes, it's two. The split is based on difficulty, privacy, and latency.</p>
<p><strong>The company.</strong></p>
<p>An internal document search tool runs entirely locally. HR files, legal contracts, financial records, internal memos — none of it leaves the building. The model is small and quantized. It doesn't need to be brilliant. It needs to be accurate and private.</p>
<p>Customer-facing chat runs in the cloud. It needs to be fast, capable, and multilingual. The data flowing through it is public — questions from public users.</p>
<p>Two workloads. Two homes. One product. The company never argues about local versus cloud because it stopped treating them as mutually exclusive.</p>
<p><strong>The person.</strong></p>
<p>A phone assistant handles timers, reminders, quick lookups, and short replies on-device. No network round-trip. No data leaving the phone. Instant, private, available offline.</p>
<p>When the user asks something requiring real reasoning — a multi-day trip plan, a comparison of two products, a debugging session — the query escalates to a cloud model. The user sees one assistant. The phone decided the local model couldn't handle it.</p>
<p>The pattern in all three cases: sensitivity and difficulty decide the route. Private and easy goes local. Public and hard goes to the cloud.</p>
<h2>The triangle, revisited</h2>
<p>Essay 3 ended with a triangle. Three forces, two of which you can optimize:</p>
<ul>
<li><strong>Capacity</strong> — how much the model knows</li>
<li><strong>Latency</strong> — how fast it responds</li>
<li><strong>Memory</strong> — how much hardware it needs to run</li>
</ul>
<p>Local and cloud sit at different points on this triangle.</p>
<table>
<thead>
<tr>
<th></th>
<th>Local</th>
<th>Cloud</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Capacity</strong></td>
<td>Limited by your hardware</td>
<td>Frontier-level</td>
</tr>
<tr>
<td><strong>Latency</strong></td>
<td>Slow first token, steady after</td>
<td>Fast, but network-dependent</td>
</tr>
<tr>
<td><strong>Memory</strong></td>
<td>Bounded by your RAM</td>
<td>Effectively unlimited</td>
</tr>
</tbody></table>
<p>Local optimizes memory and privacy, sacrificing capacity. Cloud optimizes capacity and speed, sacrificing privacy and adding dependency.</p>
<p>Routing lets you optimize all three at once — not by building a machine that does everything, but by picking a different point on the triangle for each task. The system is private when privacy matters, capable when capability matters, fast when speed matters. No single machine needs to do all three equally well.</p>
<h2>What this means for builders</h2>
<p>Three practical takeaways.</p>
<p><strong>Design for two homes.</strong></p>
<p>Any serious AI product in 2026 should have a local path and a cloud path. Not for trend reasons. Because the cost structure, the privacy guarantees, and the latency profile are different for each, and pretending otherwise means leaving value on the table.</p>
<p><strong>Make routing invisible.</strong></p>
<p>Users shouldn't have to choose. The system should decide based on sensitivity, complexity, and latency requirements. A product that asks "would you like to use the local model or the cloud model?" has already failed. That's a question the system answers, not the user.</p>
<p><strong>Measure the dial.</strong></p>
<p>Track how often queries actually need cloud capability. Most products find the number is lower than expected. Sometimes much lower. That gap is money saved, data protected, and latency improved at the same time. The only way to find it is to look.</p>
<h2>What this means beyond tech</h2>
<p>Three things shift when routing becomes standard.</p>
<p><strong>Access.</strong> Local AI lowers the barrier. A capable model doesn't require a subscription. It requires a machine. That's a different kind of democratization — one that doesn't depend on a company's pricing page.</p>
<p><strong>Ownership.</strong> When the model runs on your hardware, no one can change the terms. No pricing update, no rate limit, no quiet deprecation. That's a real shift in what it means to have AI. You don't rent it. You have it.</p>
<p><strong>Energy.</strong> Local inference is less efficient per token than a hyperscale data center. It's also less total compute when you only use what you need. The energy math is more complex than either side admits, and nobody has fully worked it out yet. Anyone claiming otherwise is selling something.</p>
<h2>The closing</h2>
<p>The parameter race was never about size. It was about capability, and capability has many shapes.</p>
<p>The local-cloud debate never was about location. It was about trade-offs, and trade-offs have many answers.</p>
<p>The future isn't local. It isn't cloud. It's the system that knows the difference — and chooses well.</p>
]]></content:encoded></item><item><title><![CDATA[The New Shape of AI Models]]></title><description><![CDATA[New to the jargon? Start with the glossary → Here's a riddle. Two AI models are released on the same day. Both have 70 billion parameters. One runs…]]></description><link>https://nightthoughts.me/the-new-shape-of-ai-models</link><guid isPermaLink="true">https://nightthoughts.me/the-new-shape-of-ai-models</guid><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Tue, 13 Oct 2026 22:22:41 GMT</pubDate><content:encoded><![CDATA[<h1>The New Shape of AI Models</h1>
<p>New to the jargon? <a href="https://nightthoughts.me/plain-english-glossary-ai-terms-for-the-rest-of-us">Start with the glossary →</a></p>
<hr />
<p>Here's a riddle. Two AI models are released on the same day. Both have 70 billion parameters. One runs comfortably on a laptop. The other needs a data center. On paper, they are the same size. They are not the same machine.</p>
<p>That gap—between what a model <em>is</em> on paper and what it <em>does</em> when it runs—is the story of this essay. The parameter race didn't just slow down. It split into different questions entirely.</p>
<h2>Size was always a proxy</h2>
<p>In Essay 1, we talked about why "bigger equals smarter" broke. The short version: parameter count was never a direct measure of intelligence. It was a rough proxy, and for a while, that proxy worked well enough.</p>
<p>But it was always a proxy for something else—the model's capacity to learn patterns. More parameters meant more room to store what it learned. That's it. It said nothing about <em>how</em> the model used that space.</p>
<p>Two models with the same parameter count can store their knowledge in completely different ways. One might use every single parameter for every question. The other might use a small fraction, on purpose, every time. Same number on the box. Different machine inside.</p>
<p>That's what changed.</p>
<h2>The model that doesn't use all of itself</h2>
<p>Most people imagine an AI model like a brain where every neuron fires for every thought. An MoE model doesn't work that way. Here's what it actually is: instead of one giant model where every parameter fires for every question, it's made of many smaller specialist sub-networks—the "experts." A router sits on top. When a question comes in, the router decides which experts are best suited to answer. Only those experts wake up. The rest stay dormant.</p>
<p>Think of it like a hospital. You don't need every doctor, nurse, and specialist in the building to look at a sprained ankle. You need the triage nurse and the orthopedic specialist. The rest of the hospital is there, ready if needed, but they're not all crowding into the room.</p>
<p>Mixtral 8x7B illustrates this perfectly. It has roughly 47 billion total parameters. But for any given token, it activates only around 13 billion of them. That's the compute cost of a 13B model, with the capability that comes from something much larger.</p>
<p>The same pattern appears at larger scales. DeepSeek-V3 has 671 billion total parameters. Per token, it activates only about 37 billion. That's the compute footprint of a mid-sized model, running on a system that's 18 times bigger on paper.</p>
<p>Here's the catch that's easy to miss. MoE reduces compute, not memory. The full 671 billion parameters still have to be loaded — all of them, into memory, before the model can answer a single question. The architecture changes what runs per token. It doesn't change what has to live in RAM. That's why a 671B MoE model still needs serious hardware. Quantization is what makes it fit. MoE is what makes it fast.</p>
<h2>The number that actually matters</h2>
<p>This is where the vocabulary splits. We now have to distinguish between two things that used to be the same:</p>
<p><strong>Total parameters</strong> — the number on the box. How much the model <em>can</em> know.</p>
<p><strong>Active parameters</strong> — how much the model <em>uses</em> per answer. How much compute it <em>actually spends</em>.</p>
<p>The first number tells you about capability. The second tells you about cost. And the second is the one you'll feel when you're actually running the thing.</p>
<p>A 671B model with 37B active parameters is not the same as a 37B model. It has more depth to draw from. But it runs at roughly the speed and cost of a 37B model, which is why it fits on hardware that couldn't dream of running a dense 671B model.</p>
<p>This is what people mean when they say MoE "decouples size from cost." It's the same reason a laptop can run a model that looks like it should need a data center.</p>
<p>This connects directly to what we saw in Essay 2. MoE is one piece of the puzzle — it's also what lets a 671B model fit on hardware that couldn't run a dense version at all. Combined with quantization and unified memory, "fits on my machine" becomes a real thing.</p>
<h2>Small specialists vs. big generalists</h2>
<p>There's a second shift happening alongside MoE. Small models got much better — but not because small is inherently better. They got better because they're being taught by larger models.</p>
<p>The technique is distillation. A large teacher model generates answers, reasoning chains, and corrections. A small student model learns from those outputs instead of from raw data. The student doesn't rediscover knowledge from scratch. It copies what the teacher already figured out, at a fraction of the size.</p>
<p>That's why a well-trained 8B model today can outperform a 70B model from two years ago. It's not that the architecture got smarter. It's that the training recipe changed. The student is learning from a better teacher than the older model ever had.</p>
<p>Look at Granite 3.2 8B. IBM trained it to match or exceed models several times its size on math and reasoning benchmarks. Look at Llama 3 8B, which beats the original Llama 2 70B on most tasks. The pattern is everywhere.</p>
<p>But there's a limit worth naming. Small models are excellent at reasoning, style, and structured tasks. They are not as good at factual recall for long-tail queries. Ask a small model about an obscure historical figure, a niche technical detail, or a specific legal precedent, and it's more likely to hallucinate than a larger model that actually stored the fact. Knowledge has to live somewhere, and compression has a ceiling.</p>
<p>The honest version of the story: small models aren't smaller versions of big models. They're differently trained. They got better at some things, and they still can't do others.</p>
<h2>Thinking longer, not bigger</h2>
<p>The third shift is the strangest one. Some models now get smarter by thinking <em>longer</em>, not by being <em>bigger</em>.</p>
<p>Instead of answering immediately, these models produce a chain of reasoning before giving their final response. They check their work. They try approaches and abandon them. They take more time—and in many cases, the extra time translates directly into better answers.</p>
<p>Models like OpenAI's o3 and DeepSeek-R1 don't just answer your question—they think through it first, producing a chain of reasoning before committing to an answer. You give them more time (more tokens), and they beat larger models that fire off instant responses. Extra compute at inference time is the new parameter count arms race.</p>
<p>Think of it like the difference between a quick answer and a considered one. If you ask someone a hard question, the immediate reply and the reply after thirty seconds of thought are not the same quality. Models learned this too.</p>
<p>The practical implication: "how smart is this model?" now depends partly on how long you let it think. That's not a question you can answer by looking at the parameter count at all.</p>
<p>There's a tax here, though, and it's worth naming. Thinking longer means waiting longer. For a research task, a batch job, or a careful analysis you'll read once — fine. For a voice assistant, a real-time coding tool, or anything interactive, that latency is fatal.</p>
<p>The industry is converging on the idea of two modes. A fast, intuitive mode for quick tasks. A slow, deliberate mode for hard ones. The best systems switch between them on demand. Neither replaces the other.</p>
<h2>The new scorecard</h2>
<p>Put those three shifts together—MoE, better small models, test-time compute—and the old scorecard doesn't work anymore.</p>
<p>Parameter count was never enough, but now it's barely a starting point. The questions that actually matter when you're choosing a model are different. You want to know how many parameters it actually uses per answer, not just how many it has. You want to know how well it was trained and on what data. You want to know how many tokens per second it will give you on your hardware, how much it costs per answer, per day, per month, and whether it fits on the machine you already have.</p>
<p>That's a more complicated set of questions than "how big is it?" But it's a more honest one. And every model released in the last two years has been designed with at least one of those questions in mind.</p>
<p>The parameter race didn't disappear. It fragmented. The old race was one-dimensional: who can build the biggest model. The new race is a triangle — capacity, latency, and memory. You can optimize two. The third will always demand a tax. There is no single number that captures a model anymore. There never really was.</p>
<hr />
<p><em>Written in early 2026. Model examples reflect the landscape at that time.</em></p>
]]></content:encoded></item><item><title><![CDATA[TencentDB Agent Memory: A Local-First Memory Layer for AI Agents]]></title><description><![CDATA[A layered semantic pyramid that makes agent memory inspectable, traceable, and local-first]]></description><link>https://nightthoughts.me/tencentdb-agent-memory-a-local-first-memory-layer-for-ai-agents</link><guid isPermaLink="true">https://nightthoughts.me/tencentdb-agent-memory-a-local-first-memory-layer-for-ai-agents</guid><category><![CDATA[AI]]></category><category><![CDATA[agents]]></category><category><![CDATA[open source]]></category><category><![CDATA[database]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Tue, 13 Oct 2026 01:10:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/a9a16d22-665e-4b76-8fe5-ef51d7996f03.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every agent developer knows the feeling. You start a new session, and your agent has amnesia. You re-explain your stack, your preferences, your project conventions. The context you painstakingly built yesterday is gone.</p>
<p>Most memory systems try to solve this by compressing conversation history into a vector pile. Retrieval becomes a black box: when recall goes wrong, you're guessing why.</p>
<p>TencentDB Agent Memory takes a different approach. Open-sourced by Tencent Cloud in May 2026 under the MIT license, it builds memory as a <strong>layered semantic pyramid</strong> — every layer readable Markdown, every conclusion traceable back to its raw source. The project crossed <strong>20,000 GitHub stars in 90 days</strong> and reached No. 1 on GitHub Trending multiple times.</p>
<hr />
<h2>The Problem with Flat Vector Memory</h2>
<p>The standard approach today is straightforward: dump conversation history into a vector database, embed everything, and retrieve the top-K most similar chunks at inference time.</p>
<p>This works for short conversations. It breaks down in long-running agent workflows.</p>
<p>Tencent's team identifies three core issues:</p>
<ul>
<li><p><strong>Cross-session fracture.</strong> Code conventions confirmed yesterday are forgotten today.</p>
</li>
<li><p><strong>Fact-preference conflation.</strong> "I use TypeScript" and "check the weather" get treated with equal weight.</p>
</li>
<li><p><strong>Context bloat.</strong> The longer the task, the more history gets stuffed into the context window. Token costs climb, and model attention degrades.</p>
</li>
</ul>
<p>The deeper issue is that flat vector memory makes recall <strong>opaque</strong>. When retrieval goes wrong — pulling in stale state, conflating old and new decisions — you have no way to trace why.</p>
<hr />
<h2>The Architecture: A Semantic Pyramid</h2>
<p>TencentDB Agent Memory organizes long-term memory into four tiers, each with a distinct role:</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>What It Stores</th>
<th>Format</th>
</tr>
</thead>
<tbody><tr>
<td><strong>L0 Conversation</strong></td>
<td>Raw dialogue and tool-call logs, full fidelity</td>
<td>Complete records</td>
</tr>
<tr>
<td><strong>L1 Atom</strong></td>
<td>Extracted facts, preferences, constraints — each with source links</td>
<td>Structured atomic facts</td>
</tr>
<tr>
<td><strong>L2 Scenario</strong></td>
<td>Aggregated knowledge blocks per task/project</td>
<td>Markdown files</td>
</tr>
<tr>
<td><strong>L3 Persona</strong></td>
<td>Stable long-term user profile and team norms</td>
<td>Key-value pairs</td>
</tr>
</tbody></table>
<p>The key design principle: <strong>nothing is lossy-compressed</strong>. Every layer is readable Markdown. When the agent needs proof for a conclusion, it can drill back through <code>node_id</code> links to the exact raw log at L0.</p>
<p>This is what Tencent calls a <strong>white-box traceable</strong> memory system — you can follow the chain from a stable persona trait down to the specific conversation where it originated.</p>
<h3>Short-Term Memory: Symbolic, Not Stuffed</h3>
<p>For within-session context management, the system uses a <strong>symbolic short-term memory</strong> layer. Current task state is encoded as a Mermaid graph in the agent's context — a lightweight, structured representation of what's happening right now.</p>
<p>Verbose tool logs get offloaded to disk. When the agent needs them, it drills back via node IDs. The context window stays clean; the full history stays accessible.</p>
<hr />
<h2>Benchmark Results</h2>
<p>Tencent reports significant improvements across multiple benchmarks. All figures are vendor-reported and have not yet been independently verified at scale.</p>
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Before</th>
<th>After</th>
<th>Change</th>
</tr>
</thead>
<tbody><tr>
<td><strong>PersonaMem accuracy</strong></td>
<td>48%</td>
<td>76%</td>
<td><strong>+59%</strong></td>
</tr>
<tr>
<td><strong>WideSearch pass rate</strong></td>
<td>33%</td>
<td>50%</td>
<td><strong>+51.52%</strong> (relative)</td>
</tr>
<tr>
<td><strong>WideSearch token usage</strong></td>
<td>221.31M</td>
<td>85.64M</td>
<td><strong>−61.38%</strong></td>
</tr>
<tr>
<td><strong>SWE-bench pass rate</strong></td>
<td>58.4%</td>
<td>64.2%</td>
<td><strong>+9.93%</strong></td>
</tr>
<tr>
<td><strong>SWE-bench token usage</strong></td>
<td>3,474.1M</td>
<td>2,375.4M</td>
<td><strong>−33.09%</strong></td>
</tr>
</tbody></table>
<p>Data from Tencent Cloud's official benchmarks.</p>
<p>The PersonaMem result is the most striking: accuracy nearly doubling while token consumption drops by more than half. The system achieves this by <strong>not</strong> injecting raw history into context — instead, it retrieves structured L1/L2/L3 representations that are denser and more relevant than flat text chunks.</p>
<p>One caveat worth noting: these benchmarks measure performance with the system integrated as an OpenClaw plugin. Results may vary across different agent frameworks and task types.</p>
<hr />
<h2>Multi-Agent and Team Memory</h2>
<p>The most recent major update — <strong>Team Memory</strong>, launched in August 2026 — extends the system from individual use to team collaboration.</p>
<p>The core idea: when team members work alongside agents, the conversations, documents, code, and workflows they produce should become <strong>shared memory assets</strong>, not isolated session histories.</p>
<p>Team Memory introduces four types of assets:</p>
<ul>
<li><p><strong>Chat Memory</strong>: Historical agent conversations, organized for retrieval</p>
</li>
<li><p><strong>LLM-Wiki</strong>: Project documents converted into queryable structured pages</p>
</li>
<li><p><strong>Code Graph</strong>: Code repositories parsed into symbol relationships and call paths</p>
</li>
<li><p><strong>Skill</strong>: Successfully completed workflows distilled into reusable task patterns</p>
</li>
</ul>
<p>These assets are <strong>dynamically assembled based on agent role</strong>. A bug-fixing agent prioritizes Code Graph and past troubleshooting Skills. A requirements-analysis agent loads the project wiki and previous discussions.</p>
<h3>Team Memory API: Scoping and Sharing</h3>
<p>The V3 API introduces a <code>team_id</code> dimension for team-level memory isolation and sharing. The scoping chain runs from largest to smallest: <code>team_id</code> → <code>user_id</code> → <code>agent_id</code> → <code>session_id</code>.</p>
<p>This means the same interface can perform team-level memory sharing or session-level precise retrieval, depending on which dimensions you specify.</p>
<h3>DeepSeek Harness Integration</h3>
<p>TencentDB Agent Memory has been adapted for <strong>DeepSeek Harness (DSH)</strong>. The integration works via a <strong>Memory Proxy</strong> that sits between Harness and the model service — no modifications to the Agent Core or execution loop are required.</p>
<p>For DSH users, this adds four capabilities: long-term memory across sessions, Skill sedimentation and sharing, Wiki and CodeGraph retrieval, and cross-IDE asset sharing with permission controls.</p>
<hr />
<h2>Relationship to Vector Databases</h2>
<p>A common misconception is that this project replaces vector databases. That's not accurate.</p>
<p>TencentDB Agent Memory's <strong>local/free version</strong> runs on plain SQLite with a WASM build of FAISS for local retrieval — no external vector database required. This is a deliberate design choice for individual developers and small teams who don't want to run separate infrastructure just to give an agent memory.</p>
<p>But the <strong>enterprise/pro version</strong> still uses Tencent Cloud VectorDB (TCVDB) as its indexing layer. In Tencent's own testing, the system handles tens of millions of conversation memories with sub-5ms end-to-end retrieval latency.</p>
<p>The architecture is complementary, not competitive. Vector databases solve large-scale retrieval infrastructure — multi-tenancy, high concurrency, governance, backup. Agent Memory solves session-context organization and memory lifecycle management. They operate at different layers of the stack.</p>
<hr />
<h2>Getting Started</h2>
<p>Installation is designed to be straightforward:</p>
<pre><code class="language-bash">git clone https://github.com/TencentCloud/TencentDB-Agent-Memory.git
cd TencentDB-Agent-Memory/deploy/global-images
cp .env.example .env
# Fill in two sets of LLM parameters (memory group + proxy group)
./start-all.sh
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Unlimited OCR: A 3B Local Model for Long-Context PDF Parsing]]></title><description><![CDATA[Baidu has open-sourced a document parsing model called Unlimited OCR. It is a 3B-parameter model designed to run locally. The main difference from many…]]></description><link>https://nightthoughts.me/unlimited-ocr-a-3b-local-model-for-long-context-pdf-parsing</link><guid isPermaLink="true">https://nightthoughts.me/unlimited-ocr-a-3b-local-model-for-long-context-pdf-parsing</guid><category><![CDATA[OCR ]]></category><category><![CDATA[AI]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[llm]]></category><category><![CDATA[Baidu]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Mon, 12 Oct 2026 01:12:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/2e5d48f7-2df9-47e0-bafe-d672d11a760d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Baidu has open-sourced a document parsing model called Unlimited OCR. It is a 3B-parameter model designed to run locally. The main difference from many existing OCR tools is that it processes long PDFs in a single pass instead of splitting them into pages.</p>
<p>Most OCR pipelines treat each page independently. That works for simple extraction, but it can lose cross-page structure and context. Unlimited OCR is positioned around that problem: parse the whole document continuously.</p>
<h2>What was released</h2>
<p>Unlimited OCR was released on June 22, 2026. It is available on GitHub and Hugging Face under an MIT license. The model is also available on ModelScope and Baidu Cloud. The release states support for multiple runtimes, including Transformers, vLLM, SGLang, Docker, Ollama, and llama.cpp.</p>
<p>The model has 3 billion total parameters but activates only about 570 million during inference. It is described as an effort to push DeepSeek OCR one step further.</p>
<h2>How it works</h2>
<p>The core technical contribution is called Reference Sliding Window Attention (R-SWA). The model replaces all attention layers in the decoder with R-SWA.</p>
<p>In standard transformer decoding, the KV cache grows as the output sequence lengthens. This increases memory consumption and progressively slows down generation. R-SWA addresses this by maintaining a constant KV cache throughout the entire decoding process. This allows the model to transcribe dozens of pages in a single forward pass under a standard maximum length of 32K.</p>
<p>The paper notes that R-SWA is a general-purpose parsing attention mechanism and could be applicable beyond OCR to tasks such as ASR and translation.</p>
<h2>Benchmarks</h2>
<p>On OmniDocBench v1.5, Unlimited OCR scored 93.23% overall, which the release describes as end-to-end SOTA, outperforming DeepSeek OCR by 6 percentage points. The release also reports 93.92% on OmniDocBench v1.6.</p>
<p>OmniDocBench is a benchmark that evaluates document parsing across nine document sources, including academic papers, textbooks, handwritten notes, and densely typeset newspapers. It supports multi-level evaluation using 19 layout categories and 15 attribute labels.</p>
<p>The release reports an error rate under 0.11 past 40 pages.</p>
<p><strong>Note on benchmark versions:</strong> v1.5 and v1.6 are different benchmark versions. OmniDocBench v1.6 includes 1,651 pages and adds five acquisition conditions: scanning, warping, screen photography, uneven illumination, and skew. Cross-version comparisons should be treated as directional rather than absolute.</p>
<h2>Cost comparison</h2>
<p>Cloud OCR services price at roughly $1.50 per 1,000 pages for basic text extraction. AWS Textract's DetectDocumentText tier is $1.50 per 1,000 pages for the first million. Structured extraction tiers rise significantly: AnalyzeDocument with Forms costs $50 per 1,000 pages, Tables adds $15 per 1,000, and combining all three reaches $65 per 1,000 pages.</p>
<p>Azure Document Intelligence's Read model (OCR only) is approximately $1.50 per 1,000 pages. Layout and prebuilt models cost around $10.00 per 1,000 pages, and custom models are billed at approximately $30.00 per 1,000 pages.</p>
<p>Google Cloud Vision's text detection is also $1.50 per 1,000 units after the first 1,000 free units per month.</p>
<p>Unlimited OCR does not have a per-page API fee. It runs on local hardware, so the real cost is hardware, electricity, and maintenance.</p>
<h2>Limitations and open questions</h2>
<ul>
<li><p>Hardware requirements are not clearly stated in the release materials. VRAM and throughput on consumer hardware will matter for long documents.</p>
</li>
<li><p>Accuracy on tables, formulas, handwriting, and low-quality scans needs independent testing. The benchmark covers these categories, but the reported scores are from the release itself.</p>
</li>
<li><p>Language coverage details need verification. The model card lists "multilingual" but does not specify which languages.</p>
</li>
<li><p>The 32K context window is large, but very long PDFs may still require chunking.</p>
</li>
<li><p>Local inference shifts cost from API fees to hardware and electricity.</p>
</li>
<li><p>The 93.23% and 93.92% figures come from the release materials. Independent reproductions would strengthen confidence in these numbers.</p>
</li>
</ul>
<h2>Conclusion</h2>
<p>Unlimited OCR is notable because it targets long-context document parsing in a relatively small 3B model that can run locally. The R-SWA mechanism addresses a real bottleneck in long-sequence decoding: growing memory consumption and generation slowdown. If the reported results hold up in independent tests, it could simplify OCR pipelines that currently depend on page-by-page processing or cloud APIs.</p>
<hr />
<h2>References</h2>
<p><strong>Official sources</strong></p>
<p>Baidu. "Unlimited OCR Works: Welcome the Era of One-shot Long-horizon Parsing." GitHub repository. <a href="https://github.com/baidu/Unlimited-OCR">https://github.com/baidu/Unlimited-OCR</a></p>
<p>Baidu. "Unlimited-OCR." Hugging Face model card. <a href="https://huggingface.co/baidu/Unlimited-OCR">https://huggingface.co/baidu/Unlimited-OCR</a></p>
<p>Yin, Youyang, et al. "Unlimited OCR Works." arXiv:2606.23050, June 22, 2026. <a href="https://arxiv.org/abs/2606.23050">https://arxiv.org/abs/2606.23050</a></p>
<p>Baidu. "Unlimited-OCR." ModelScope. <a href="https://modelscope.cn/models/PaddlePaddle/Unlimited-OCR">https://modelscope.cn/models/PaddlePaddle/Unlimited-OCR</a></p>
<p><strong>Benchmark</strong></p>
<p>"OmniDocBench: Benchmarking Diverse PDF Document Parsing with Comprehensive Annotations." IEEE Xplore, August 13, 2025. <a href="https://ieeexplore.ieee.org/abstract/document/11091844">https://ieeexplore.ieee.org/abstract/document/11091844</a></p>
<p>Dataset and code: <a href="https://github.com/opendatalab/OmniDocBench">https://github.com/opendatalab/OmniDocBench</a></p>
<p><strong>Cloud OCR pricing</strong></p>
<p>"Google Vision vs AWS Textract vs Azure: Cloud OCR Comparison 2026." ImageToTable, June 30, 2026. <a href="https://imagetotable.ai/blog/google-vs-aws-vs-azure-ocr-2026">https://imagetotable.ai/blog/google-vs-aws-vs-azure-ocr-2026</a></p>
<p>"Azure Document Intelligence pricing." Microsoft Q&amp;A, July 2, 2026. <a href="https://learn.microsoft.com/en-au/answers/questions/5927427/azure-document-intelligence-pricing">https://learn.microsoft.com/en-au/answers/questions/5927427/azure-document-intelligence-pricing</a></p>
<p><strong>Community forks and additional references</strong></p>
<p>"Unlimited-OCR-Universal." Hugging Face (Apple Silicon/MPS fork). <a href="https://huggingface.co/sabafallah/Unlimited-OCR-Universal">https://huggingface.co/sabafallah/Unlimited-OCR-Universal</a></p>
<p>"unlimited-ocr-max." PyPI package for OpenAI-compatible serving. <a href="https://pypi.org/project/unlimited-ocr-max">https://pypi.org/project/unlimited-ocr-max</a></p>
<p>Baidu Cloud deployment documentation. <a href="https://cloud.baidu.com/doc/OCR/s/fmr1p39gb">https://cloud.baidu.com/doc/OCR/s/fmr1p39gb</a></p>
<hr />
<p><strong>Note on citations:</strong> The release date, GitHub repository, Hugging Face model card, arXiv paper, OmniDocBench paper, and cloud pricing pages cited above are the primary sources. The 93.23% and 93.92% figures and the 0.11 error rate come from the release materials and should be treated as vendor-reported until independently reproduced.</p>
]]></content:encoded></item><item><title><![CDATA[Funding Rate Arbitrage on macOS: Multi-Exchange Scanner]]></title><description><![CDATA[Scan Bitget, Binance, Bybit, OKX, and Gate in parallel and find both perp-spot and perp-perp funding opportunities" slug…]]></description><link>https://nightthoughts.me/funding-rate-arbitrage-on-macos-multi-exchange-scanner</link><guid isPermaLink="true">https://nightthoughts.me/funding-rate-arbitrage-on-macos-multi-exchange-scanner</guid><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Sun, 11 Oct 2026 00:19:44 GMT</pubDate><content:encoded><![CDATA[<p><em>Disclaimer: This is not financial advice. Crypto trading involves risk. Start with paper trading and only use capital you can afford to lose.</em></p>
<h2>What changed from the single-exchange scanner</h2>
<p>The earlier Phase 1 scanner only queried Bitget. This version covers <strong>five exchanges simultaneously</strong>: Bitget, Binance USDT-M, Bybit, OKX, and Gate. It runs the initial data fetch in parallel across venues, so total wall time stays roughly the same as querying one exchange.</p>
<p>It produces two kinds of opportunities in a single CSV:</p>
<ul>
<li><p><strong>Single-exchange (perp-spot)</strong>: buy spot, short perp on the same venue, collect funding. Delta-neutral. Fee model uses spot maker + perp taker.</p>
</li>
<li><p><strong>Cross-exchange (perp-perp)</strong>: long the perp on the venue with the lowest funding, short the perp on the venue with the highest funding. No spot leg needed. Fee model uses two perp takers.</p>
</li>
</ul>
<p>The analyzer reads that CSV and ranks both opportunity types.</p>
<h2>Prerequisites</h2>
<ul>
<li><p><strong>macOS</strong> with Python 3.11 installed.</p>
</li>
<li><p>No exchange accounts, no API keys, no deposits. Everything below uses public endpoints.</p>
</li>
</ul>
<h2>Step 1: Environment setup</h2>
<pre><code class="language-bash">mkdir -p ~/funding-arb-bot
cd ~/funding-arb-bot
python3.11 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install ccxt pandas numpy
mkdir -p data scripts logs
</code></pre>
<h2>Step 2: Multi-exchange scanner</h2>
<p>Create <code>scripts/scan_funding.py</code>:</p>
<pre><code class="language-bash">cat &gt; scripts/scan_funding.py &lt;&lt; 'PYEOF'
import ccxt
import pandas as pd
import numpy as np
import time
import random
import sys
import argparse
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed

# --- Configuration ---
EXCHANGES = ['bitget', 'binanceusdm', 'bybit', 'okx', 'gate']
QUOTE = 'USDT'
DAYS_BACK = 30
MIN_24H_VOLUME_USD = 5_000_000
TOP_N_PER_EXCHANGE = 15
OUT_DIR = 'data'

# Perp taker fees per exchange (adjust to your VIP tier)
PERP_TAKER_FEES = {
    'bitget': 0.0006,
    'binanceusdm': 0.0005,
    'bybit': 0.00055,
    'okx': 0.0005,
    'gate': 0.0005,
    'hyperliquid': 0.00035,
}
DEFAULT_PERP_TAKER = 0.0006

# Spot leg fees (Binance with BNB discount)
SPOT_MAKER_FEE = 0.00075
SLIPPAGE_BPS = 5

def perp_fee(ex_id):
    return PERP_TAKER_FEES.get(ex_id, DEFAULT_PERP_TAKER)

def round_trip_single(ex_id):
    # spot buy maker + perp short taker, then exit both
    return (SPOT_MAKER_FEE + perp_fee(ex_id) + SLIPPAGE_BPS / 10000) * 2

# --- Retry helper ---
def with_retry(fn, *args, max_retries=5, **kwargs):
    for attempt in range(max_retries):
        try:
            return fn(*args, **kwargs)
        except ccxt.RateLimitExceeded:
            wait = (2 ** attempt) + random.uniform(0, 0.5)
            time.sleep(wait)
        except ccxt.NetworkError:
            wait = (2 ** attempt) + random.uniform(0, 0.5)
            time.sleep(wait)
    raise RuntimeError("max retries exceeded")

# --- Exchange lifecycle ---
def load_exchange(ex_id):
    ex = getattr(ccxt, ex_id)({'enableRateLimit': True, 'timeout': 30000})
    ex.load_markets()
    return ex_id, ex

def snapshot_exchange(ex_id, ex):
    funding = with_retry(ex.fetch_funding_rates)
    tickers = with_retry(ex.fetch_tickers)
    rows = []
    for sym, data in funding.items():
        m = ex.markets.get(sym)
        if not m or not m.get('active'):
            continue
        if not (m.get('swap') and m.get('linear')
                and m.get('quote') == QUOTE and m.get('settle') == QUOTE):
            continue
        fr = data.get('fundingRate')
        if fr is None:
            continue
        vol = float(tickers.get(sym, {}).get('quoteVolume') or 0)
        rows.append({
            'exchange': ex_id,
            'symbol': sym,
            'base': m['base'],
            'cur_fr_pct': float(fr) * 100,
            'vol_24h_usd': vol,
        })
    return rows

# --- Historical deep-dive ---
def fetch_history(ex, symbol, since):
    out, cursor = [], since
    while True:
        batch = with_retry(ex.fetch_funding_rate_history, symbol, since=cursor, limit=100)
        if not batch:
            break
        out.extend(batch)
        if len(batch) &lt; 100:
            break
        cursor = batch[-1]['timestamp'] + 1
        time.sleep(ex.rateLimit / 1000 + random.uniform(0, 0.05))
    return out

def deep_dive(ex_id, ex, row, since):
    symbol = row['symbol']
    hist = fetch_history(ex, symbol, since)
    if len(hist) &lt; 10:
        return None
    rates = pd.Series([float(h['fundingRate']) for h in hist])
    avg_fr = rates.mean()
    std = rates.std()
    neg_count = int((rates &lt; 0).sum())
    cur, max_neg = 0, 0
    for r in rates:
        if r &lt; 0:
            cur += 1
            max_neg = max(max_neg, cur)
        else:
            cur = 0
    rt = round_trip_single(ex_id)
    net_8h = avg_fr - rt / (DAYS_BACK * 3)
    return {
        'exchange': ex_id,
        'symbol': symbol,
        'base': row['base'],
        'cur_fr_pct': row['cur_fr_pct'],
        'vol_24h_musd': row['vol_24h_usd'] / 1e6,
        'avg_fr_8h_pct': avg_fr * 100,
        'median_fr_8h_pct': rates.median() * 100,
        'min_fr_8h_pct': rates.min() * 100,
        'max_fr_8h_pct': rates.max() * 100,
        'std_fr_pct': std * 100,
        'pct_pos': (rates &gt; 0).mean() * 100,
        'neg_count': neg_count,
        'max_neg_streak': max_neg,
        'ann_fund_pct': avg_fr * 3 * 365 * 100,
        'net_8h_pct': net_8h * 100,
        'ann_net_pct': net_8h * 3 * 365 * 100,
        'sharpe': (rates.mean() / std) * np.sqrt(3 * 365) if std &gt; 0 else 0,
        'n_obs': len(hist),
    }

# --- Main ---
parser = argparse.ArgumentParser()
parser.add_argument('--out', default=None)
args, _ = parser.parse_known_args()

print("Loading exchanges...")
exchanges = {}
with ThreadPoolExecutor(max_workers=len(EXCHANGES)) as pool:
    futures = {pool.submit(load_exchange, ex_id): ex_id for ex_id in EXCHANGES}
    for f in as_completed(futures):
        try:
            ex_id, ex = f.result()
            exchanges[ex_id] = ex
            print(f"  OK  {ex_id}: {len(ex.markets)} markets")
        except Exception as e:
            print(f"  ERR {futures[f]}: {e}")

if not exchanges:
    print("No exchanges loaded. Exiting.")
    sys.exit(1)

print("\nFetching funding rates + tickers across all exchanges...")
all_rows = []
with ThreadPoolExecutor(max_workers=len(exchanges)) as pool:
    futures = {pool.submit(snapshot_exchange, ex_id, ex): ex_id
               for ex_id, ex in exchanges.items()}
    for f in as_completed(futures):
        try:
            rows = f.result()
            all_rows.extend(rows)
            print(f"  OK  {futures[f]}: {len(rows)} linear perps")
        except Exception as e:
            print(f"  ERR {futures[f]}: {e}")

df = pd.DataFrame(all_rows)
print(f"\nTotal linear perps across all exchanges: {len(df)}")
df = df[(df['vol_24h_usd'] &gt;= MIN_24H_VOLUME_USD) &amp; (df['cur_fr_pct'] &gt; 0)]
print(f"After volume + positive-funding filter: {len(df)}")

# Deep-dive top N per exchange
since = int((datetime.now() - timedelta(days=DAYS_BACK)).timestamp() * 1000)
results = []
for ex_id, ex in exchanges.items():
    subset = (df[df['exchange'] == ex_id]
              .sort_values('cur_fr_pct', ascending=False)
              .head(TOP_N_PER_EXCHANGE))
    if len(subset) == 0:
        continue
    print(f"\nDeep-diving {len(subset)} symbols on {ex_id}...")
    for i, (_, row) in enumerate(subset.iterrows(), 1):
        print(f"  [{i}/{len(subset)}] {row['symbol']} ...", end=' ', flush=True)
        try:
            r = deep_dive(ex_id, ex, row, since)
            if r:
                results.append(r)
                print(f"ok  avg {r['avg_fr_8h_pct']:.4f}%/8h  ann_net {r['ann_net_pct']:.2f}%")
            else:
                print("skipped (insufficient history)")
        except Exception as e:
            print(f"error: {e}")

if not results:
    print("\nNo valid results.")
    sys.exit(1)

res_df = (pd.DataFrame(results)
          .sort_values('ann_net_pct', ascending=False)
          .reset_index(drop=True))

stamp = datetime.now().strftime('%Y%m%d_%H%M%S')
out_path = args.out or f"{OUT_DIR}/scan_multi_{stamp}.csv"
res_df.to_csv(out_path, index=False)

print(f"\nSaved {len(res_df)} rows to {out_path}")
print("\nTop 10 by annualized net carry (single-exchange perp-spot):")
print(res_df.head(10).to_string(index=False))
print(f"\nNext: python scripts/analyze_scan_multi.py {out_path}")
PYEOF
</code></pre>
<h2>Step 3: Multi-exchange analyzer</h2>
<p>Create <code>scripts/analyze_scan_multi.py</code>:</p>
<pre><code class="language-bash">cat &gt; scripts/analyze_scan_multi.py &lt;&lt; 'PYEOF'
import pandas as pd
import numpy as np
import sys
import json
import argparse
from pathlib import Path
from datetime import datetime

# --- Thresholds ---
MIN_SHARPE = 1.0
MIN_VOL_MUSD = 20.0
MIN_NET_8H = 0.005           # single-exchange per 8h net carry
MIN_PCT_POS = 60.0
MIN_OBS = 60

# Cross-exchange thresholds
MIN_RATE_DIFF_8H = 0.01      # 0.01% per 8h difference between venues
MIN_X_VOL_MUSD = 10.0        # min volume on BOTH venues

CAPITAL_HKD = 10_000
HKD_USD = 0.128
DEPLOY_FRACTION = 0.6
MAX_SYMBOLS = 3
DAYS_BACK = 30

PERP_TAKER_FEES = {
    'bitget': 0.0006,
    'binanceusdm': 0.0005,
    'bybit': 0.00055,
    'okx': 0.0005,
    'gate': 0.0005,
    'hyperliquid': 0.00035,
}
DEFAULT_PERP_TAKER = 0.0006
SLIPPAGE_BPS = 5

def perp_fee(ex_id):
    return PERP_TAKER_FEES.get(ex_id, DEFAULT_PERP_TAKER)

def round_trip_cross(ex_long, ex_short):
    return (perp_fee(ex_long) + perp_fee(ex_short) + SLIPPAGE_BPS / 10000) * 2

# --- CLI ---
parser = argparse.ArgumentParser(description='Analyze multi-exchange funding scan.')
parser.add_argument('csv', help='Path to scan_multi_*.csv')
parser.add_argument('--json', action='store_true', help='Also emit JSON summary')
args = parser.parse_args()

CSV = Path(args.csv)
if not CSV.exists():
    print(f"ERROR: {CSV} not found.")
    sys.exit(1)

df = pd.read_csv(CSV)
scan_time = CSV.stem

# --- Helpers ---
def hr(ch='=', n=78): print(ch * n)
def section(t): print(); hr(); print(t); hr()
def pct(x, d=4): return f"{x:.{d}f}%"

# --- Header ---
hr('#', 78)
print("# MULTI-EXCHANGE FUNDING RATE REPORT")
print(f"# Source:    {CSV}")
print(f"# Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"# Exchanges: {', '.join(sorted(df['exchange'].unique()))}")
hr('#', 78)

# --- Section 1: Overview ---
section("1. OVERVIEW")
print(f"Rows scanned:                 {len(df)}")
print(f"Exchanges covered:            {df['exchange'].nunique()}")
print(f"Unique base symbols:          {df['base'].nunique()}")
print(f"Best  ann_net (single):       {pct(df['ann_net_pct'].max(), 2)}")
print(f"Median ann_net (single):      {pct(df['ann_net_pct'].median(), 2)}")
print(f"Rows with ann_net &gt; 0:        {(df['ann_net_pct'] &gt; 0).sum()}")
print()
print("Per-exchange counts:")
for ex_id, cnt in df['exchange'].value_counts().items():
    print(f"  {ex_id:&lt;15} {cnt:&gt;4} symbols")

# --- Section 2: Single-exchange shortlist ---
section("2. SINGLE-EXCHANGE (PERP-SPOT) SHORTLIST")
print(f"Filters: sharpe &gt;= {MIN_SHARPE}, vol &gt;= {MIN_VOL_MUSD}M, "
      f"net_8h &gt;= {MIN_NET_8H}%, pct_pos &gt;= {MIN_PCT_POS}%")

s = df[
    (df['sharpe'] &gt;= MIN_SHARPE) &amp;
    (df['vol_24h_musd'] &gt;= MIN_VOL_MUSD) &amp;
    (df['net_8h_pct'] &gt;= MIN_NET_8H) &amp;
    (df['pct_pos'] &gt;= MIN_PCT_POS) &amp;
    (df['n_obs'] &gt;= MIN_OBS)
].sort_values('ann_net_pct', ascending=False).reset_index(drop=True)

if len(s) == 0:
    print("\nNo single-exchange symbols pass all filters.")
else:
    print()
    cols = ['exchange', 'symbol', 'ann_net_pct', 'net_8h_pct',
            'avg_fr_8h_pct', 'pct_pos', 'sharpe', 'vol_24h_musd']
    print(s[cols].to_string(index=False))

# --- Section 3: Cross-exchange (perp-perp) opportunities ---
section("3. CROSS-EXCHANGE (PERP-PERP) OPPORTUNITIES")

# Group by base symbol
x_rows = []
for base, group in df.groupby('base'):
    if group['exchange'].nunique() &lt; 2:
        continue
    # short the venue with highest funding, long the venue with lowest
    short_row = group.loc[group['avg_fr_8h_pct'].idxmax()]
    long_row = group.loc[group['avg_fr_8h_pct'].idxmin()]
    if short_row['exchange'] == long_row['exchange']:
        continue

    rate_diff = short_row['avg_fr_8h_pct'] - long_row['avg_fr_8h_pct']
    if rate_diff &lt;= 0:
        continue

    rt = round_trip_cross(long_row['exchange'], short_row['exchange'])
    net_8h = rate_diff - (rt * 100) / (DAYS_BACK * 3)
    ann_net = net_8h * 3 * 365

    x_rows.append({
        'base': base,
        'short_exchange': short_row['exchange'],
        'short_symbol': short_row['symbol'],
        'short_avg_fr': short_row['avg_fr_8h_pct'],
        'short_pct_pos': short_row['pct_pos'],
        'short_vol': short_row['vol_24h_musd'],
        'long_exchange': long_row['exchange'],
        'long_symbol': long_row['symbol'],
        'long_avg_fr': long_row['avg_fr_8h_pct'],
        'long_pct_pos': long_row['pct_pos'],
        'long_vol': long_row['vol_24h_musd'],
        'rate_diff_8h_pct': rate_diff,
        'net_8h_pct': net_8h,
        'ann_net_pct': ann_net,
        'round_trip_cost_pct': rt * 100,
    })

x_df = pd.DataFrame(x_rows)

if len(x_df) == 0:
    print("\nNo cross-exchange pairs found.")
else:
    x_df = (x_df[
                (x_df['rate_diff_8h_pct'] &gt;= MIN_RATE_DIFF_8H) &amp;
                (x_df['short_vol'] &gt;= MIN_X_VOL_MUSD) &amp;
                (x_df['long_vol'] &gt;= MIN_X_VOL_MUSD)
            ]
            .sort_values('ann_net_pct', ascending=False)
            .reset_index(drop=True))
    print(f"\nFilters: rate_diff &gt;= {MIN_RATE_DIFF_8H}%, "
          f"vol on both venues &gt;= {MIN_X_VOL_MUSD}M")
    print()
    if len(x_df) == 0:
        print("No cross-exchange pairs pass the filters.")
    else:
        cols = ['base', 'short_exchange', 'long_exchange',
                'rate_diff_8h_pct', 'net_8h_pct', 'ann_net_pct',
                'short_vol', 'long_vol']
        print(x_df[cols].to_string(index=False))

# --- Section 4: Deep dive top cross-exchange pairs ---
section("4. TOP CROSS-EXCHANGE PAIRS - DEEP DIVE")
if len(x_df) &gt; 0:
    for _, r in x_df.head(MAX_SYMBOLS).iterrows():
        print(f"  {r['base']}")
        print(f"    SHORT {r['short_exchange']:&lt;12} "
              f"({r['short_symbol']})  avg {r['short_avg_fr']:.4f}%/8h  "
              f"vol ${r['short_vol']:.0f}M  pos {r['short_pct_pos']:.1f}%")
        print(f"    LONG  {r['long_exchange']:&lt;12} "
              f"({r['long_symbol']})  avg {r['long_avg_fr']:.4f}%/8h  "
              f"vol ${r['long_vol']:.0f}M  pos {r['long_pct_pos']:.1f}%")
        print(f"    Rate diff:              {r['rate_diff_8h_pct']:.4f}% per 8h")
        print(f"    Round-trip cost:        {r['round_trip_cost_pct']:.4f}%")
        print(f"    Net per 8h:             {r['net_8h_pct']:.4f}%")
        print(f"    Annualized net:         {r['ann_net_pct']:.2f}%")
        print()
else:
    print("  No cross-exchange pairs to deep-dive.")

# --- Section 5: Allocation ---
section("5. SUGGESTED ALLOCATION")

capital_usd = CAPITAL_HKD * HKD_USD
deployable = capital_usd * DEPLOY_FRACTION

print(f"  Capital:            {CAPITAL_HKD:,} HKD (~{capital_usd:.0f} USD)")
print(f"  Deploy fraction:    {DEPLOY_FRACTION*100:.0f}%")
print(f"  Deployable:         {deployable:.0f} USD")

# Pick the best pool of opportunities
use_cross = len(x_df) &gt;= 1
if use_cross:
    picks = x_df.head(MAX_SYMBOLS)
    per_symbol = deployable / len(picks)
    print(f"\n  Strategy:           CROSS-EXCHANGE PERP-PERP")
    print(f"  Symbols:            {len(picks)}")
    print(f"  Per symbol:         {per_symbol:.0f} USD notional per leg")
    print()
    print(f"  {'Base':&lt;10}{'Short':&lt;14}{'Long':&lt;14}"
          f"{'Notional':&gt;12}{'Est. annual':&gt;14}{'Est. monthly':&gt;14}")
    for _, r in picks.iterrows():
        ann = per_symbol * r['ann_net_pct'] / 100
        mon = ann / 12
        print(f"  {r['base']:&lt;10}{r['short_exchange']:&lt;14}{r['long_exchange']:&lt;14}"
              f"{per_symbol:&gt;10.0f} $  {ann:&gt;11.2f} $  {mon:&gt;11.2f} $")
elif len(s) &gt;= 1:
    picks = s.head(MAX_SYMBOLS)
    per_symbol = deployable / len(picks)
    print(f"\n  Strategy:           SINGLE-EXCHANGE PERP-SPOT")
    print(f"  Symbols:            {len(picks)}")
    print(f"  Per symbol:         {per_symbol:.0f} USD notional per leg")
    print()
    print(f"  {'Exchange':&lt;14}{'Symbol':&lt;20}"
          f"{'Notional':&gt;12}{'Est. annual':&gt;14}{'Est. monthly':&gt;14}")
    for _, r in picks.iterrows():
        ann = per_symbol * r['ann_net_pct'] / 100
        mon = ann / 12
        print(f"  {r['exchange']:&lt;14}{r['symbol']:&lt;20}"
              f"{per_symbol:&gt;10.0f} $  {ann:&gt;11.2f} $  {mon:&gt;11.2f} $")
else:
    print("\n  No viable opportunities to allocate.")

# --- Section 6: Verdict ---
section("6. VERDICT")
verdict = 'NOT_VIABLE'
if len(x_df) &gt;= 1:
    print(f"  STATUS: VIABLE (cross-exchange)")
    print(f"  {len(x_df)} perp-perp pair(s) pass filters.")
    print(f"  Top picks: " + ", ".join(
        f"{r['base']} ({r['short_exchange']} vs {r['long_exchange']})"
        for _, r in x_df.head(3).iterrows()))
    verdict = 'VIABLE_CROSS'
elif len(s) &gt;= 1:
    print(f"  STATUS: VIABLE (single-exchange)")
    print(f"  {len(s)} perp-spot symbol(s) pass filters.")
    print(f"  Top picks: " + ", ".join(
        f"{r['symbol']}@{r['exchange']}" for _, r in s.head(3).iterrows()))
    verdict = 'VIABLE_SINGLE'
else:
    print("  STATUS: NOT VIABLE")
    print("  No opportunity passes thresholds on any exchange.")
    print("  Wait for higher funding regimes or lower fee assumptions.")

# --- Section 7: JSON summary ---
if args.json:
    section("7. JSON SUMMARY")
    summary = {
        'scan_file': str(CSV),
        'generated': datetime.now().isoformat(),
        'exchanges': sorted(df['exchange'].unique().tolist()),
        'total_rows': int(len(df)),
        'single_shortlist': s.to_dict(orient='records') if len(s) &gt; 0 else [],
        'cross_opportunities': x_df.to_dict(orient='records') if len(x_df) &gt; 0 else [],
        'capital_hkd': CAPITAL_HKD,
        'deployable_usd': round(deployable, 2),
        'verdict': verdict,
    }
    print(json.dumps(summary, indent=2, default=str))

print()
hr('#', 78)
print("# END OF REPORT")
hr('#', 78)
PYEOF
</code></pre>
<h2>Step 4: Run the full pipeline</h2>
<p>One command, no script changes:</p>
<pre><code class="language-bash">python scripts/scan_funding.py &amp;&amp; python scripts/analyze_scan_multi.py "$(ls -t data/scan_multi_*.csv | head -1)"
</code></pre>
<p>With JSON summary:</p>
<pre><code class="language-bash">python scripts/scan_funding.py &amp;&amp; python scripts/analyze_scan_multi.py "$(ls -t data/scan_multi_*.csv | head -1)" --json
</code></pre>
<h2>What each section of the report tells you</h2>
<table>
<thead>
<tr>
<th>Section</th>
<th>Content</th>
</tr>
</thead>
<tbody><tr>
<td>1. Overview</td>
<td>Total rows, exchanges covered, unique bases, per-exchange counts</td>
</tr>
<tr>
<td>2. Single-exchange shortlist</td>
<td>Perp-spot candidates ranked by annualized net carry after spot+perp fees</td>
</tr>
<tr>
<td>3. Cross-exchange opportunities</td>
<td>Perp-perp pairs where the funding differential exceeds fees</td>
</tr>
<tr>
<td>4. Deep dive</td>
<td>Per-pair breakdown: both venues, rate diff, round-trip cost, net carry</td>
</tr>
<tr>
<td>5. Allocation</td>
<td>Concrete notional per symbol for 10k HKD with estimated annual and monthly returns</td>
</tr>
<tr>
<td>6. Verdict</td>
<td>Clear VIABLE_CROSS / VIABLE_SINGLE / NOT_VIABLE with top picks</td>
</tr>
<tr>
<td>7. JSON</td>
<td>Machine-readable summary for downstream pipelines</td>
</tr>
</tbody></table>
<h2>How the parallel fetching works</h2>
<p>The scanner uses <code>ThreadPoolExecutor</code> to load all five exchanges and fetch their funding rates + tickers simultaneously. Per CCXT's documentation, rate limits are enforced <strong>per exchange instance</strong>, so parallel requests across different venues do not interfere. Deep-dive history fetches run sequentially to keep per-exchange rate limits comfortable.</p>
<p>Wall time for a full scan</p>
]]></content:encoded></item><item><title><![CDATA[Building an AI Trading Team on Your Mac: A Deep Dive into TradingAgents with Gemini 3]]></title><description><![CDATA[TradingAgents is an open-source multi-agent LLM framework that simulates a real-world trading firm. It deploys specialized agents — fundamental analysts…]]></description><link>https://nightthoughts.me/building-an-ai-trading-team-on-your-mac-a-deep-dive-into-tradingagents-with-gemini-3</link><guid isPermaLink="true">https://nightthoughts.me/building-an-ai-trading-team-on-your-mac-a-deep-dive-into-tradingagents-with-gemini-3</guid><category><![CDATA[AI]]></category><category><![CDATA[langchain]]></category><category><![CDATA[llm]]></category><category><![CDATA[Python]]></category><category><![CDATA[trading, ]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Sat, 10 Oct 2026 07:47:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/50e84288-2f90-4a75-b504-c9edbe928689.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>TradingAgents is an open-source multi-agent LLM framework that simulates a real-world trading firm. It deploys specialized agents — fundamental analysts, sentiment experts, technical analysts, researchers, traders, and risk managers — that collaboratively evaluate market conditions and debate optimal strategies before producing a final trading decision.</p>
<p>Built on <strong>LangGraph</strong> for stateful orchestration, the framework supports multiple LLM providers including Google Gemini, OpenAI, Anthropic, and more. This guide walks you through a complete production-grade setup on a Mac Mini: <strong>Gemini 3</strong> as the inference backend, <strong>LangGraph Studio</strong> for visual debugging, <strong>uv</strong> for Python environment management, <strong>yfinance</strong> for market data, and a <strong><code>launchd</code> scheduled job</strong> that runs the analysis twice daily and pushes the report to <strong>Telegram</strong>.</p>
<p><strong>What you'll build:</strong></p>
<ul>
<li>A Python 3.11 virtual environment managed by <code>uv</code></li>
<li>TradingAgents with Gemini 3 models</li>
<li>A centralized <code>.env</code> file — one place for every secret and setting</li>
<li>LangGraph Studio for step-by-step visual debugging</li>
<li>A <code>launchd</code> job running at 6:00 AM and 3:00 PM HKT</li>
<li>Automatic Telegram notifications after each run</li>
</ul>
<h2>Project Layout</h2>
<p>Everything lives in a single repository with a predictable structure. All configuration is centralized in <code>.env</code>; the <code>launchd</code> job calls the wrapper script, which sources <code>.env</code> at runtime.</p>
<pre><code>~/TradingAgents/
├── .env                     ← ALL configuration lives here
├── .venv/                   ← Python 3.11 virtual environment (uv-managed)
├── trade.py                 ← analysis runner
├── scripts/
│   ├── run_analysis.sh      ← wrapper: sources .env, runs trade.py, sends Telegram
│   └── send_telegram.py     ← Telegram notification script
└── trading_data/
    └── reports/             ← output: markdown report trees per ticker
</code></pre>
<p><strong>Why this layout matters:</strong> You only edit <code>.env</code> when you rotate an API key or change a model, and you only touch the plist when you change the schedule. Everything else is automated. The wrapper script exists specifically because <code>launchd</code> does not expand <code>$HOME</code> in plists and freezes its <code>EnvironmentVariables</code> at load time — the wrapper resolves <code>$HOME</code> at runtime and re-sources <code>.env</code> on every run.</p>
<h2>Architecture: How the Virtual Trading Firm Works</h2>
<p>TradingAgents mirrors a real trading firm's organizational structure, implemented as a LangGraph <code>StateGraph</code> where each agent is a node and edges define information flow.</p>
<p><strong>Four-layer workflow:</strong></p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Agents</th>
<th>Role</th>
<th>Think Level</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Analyst Team</strong></td>
<td>Fundamentals, Sentiment, News, Technical</td>
<td>Gather data, produce initial reports</td>
<td>Quick Think</td>
</tr>
<tr>
<td><strong>Researcher Debate</strong></td>
<td>Bull Researcher ↔ Bear Researcher</td>
<td>Structured debate on analyst findings</td>
<td>Deep Think</td>
</tr>
<tr>
<td><strong>Trading</strong></td>
<td>Trader Agent</td>
<td>Composes reports into a trading plan</td>
<td>Deep Think</td>
</tr>
<tr>
<td><strong>Risk Management</strong></td>
<td>Aggressive ↔ Conservative ↔ Neutral Analyst, Portfolio Manager</td>
<td>Debates risk, approves/rejects the trade</td>
<td>Deep Think</td>
</tr>
</tbody></table>
<p>Each analyst runs a conditional tool-call loop: the agent calls a data tool (e.g., <code>get_stock_data</code>), receives the result, loops back, and advances when it has enough data. The debate phase uses bidirectional loops — Bull and Bear researchers alternate until the debate count reaches <code>2 × max_debate_rounds</code>. The risk phase rotates three analysts until <code>3 × max_risk_discuss_rounds</code>.</p>
<p><strong>What runs where:</strong></p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Location</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>LangGraph orchestration</td>
<td><strong>Local</strong> (Mac Mini)</td>
<td>State graph compilation, node routing, checkpoint persistence</td>
</tr>
<tr>
<td>TradingAgents framework</td>
<td><strong>Local</strong></td>
<td>Agent definitions, tool nodes, memory logs</td>
</tr>
<tr>
<td>yfinance data fetching</td>
<td><strong>Local</strong> (network)</td>
<td>HTTP requests to Yahoo Finance APIs</td>
</tr>
<tr>
<td>Gemini inference</td>
<td><strong>Remote</strong> (Google Cloud)</td>
<td>The actual LLM reasoning — each agent node sends a prompt to Gemini</td>
</tr>
<tr>
<td>Telegram delivery</td>
<td><strong>Remote</strong> (Telegram API)</td>
<td>HTTP POST to <code>api.telegram.org</code> — no local server needed</td>
</tr>
</tbody></table>
<p>When you call <code>ta.propagate("NVDA", date)</code>, LangGraph compiles the graph locally, then streams execution node by node. Each agent node makes a remote API call to Gemini for reasoning, merges the response back into the shared <code>AgentState</code>, and LangGraph routes to the next node based on conditional logic. The final decision is written to disk as markdown and pushed to Telegram by a small wrapper script.</p>
<h2>Why Gemini 3</h2>
<p><strong>Native Google client support.</strong> TradingAgents has a dedicated <code>GoogleClient</code> that handles Gemini's unique content format — Gemini 3 models return content as a list of typed blocks rather than plain strings, and the client normalizes this so downstream agents don't break.</p>
<p><strong>Thinking level control.</strong> Gemini 3 models support <code>thinking_level</code> parameters (<code>low</code>, <code>high</code>, and <code>minimal</code> for Flash models), letting you control the reasoning budget per role.</p>
<p><strong>Single-provider simplicity.</strong> Using Gemini for both Quick Think and Deep Think roles avoids cross-provider routing bugs that can cause API key mismatches or silent fallbacks.</p>
<p><strong>Model selection for this project:</strong></p>
<ul>
<li><strong>Deep Think</strong> — <code>gemini-3.8-flash</code> : Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows. Used for the Researcher debate, Trader, and Risk Management agents.</li>
<li><strong>Quick Think</strong> — <code>gemini-3.1-flash-lite</code> : Frontier-class performance rivaling larger models at a fraction of the cost. Used for the four Analyst agents, which are high-throughput data gathering tasks.</li>
</ul>
<h2>Step 1: Install Homebrew</h2>
<p>Homebrew is the missing package manager for macOS. Install it with the official one-liner:</p>
<pre><code class="language-bash">/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
</code></pre>
<p><strong>Expected output:</strong> Installation progress messages, followed by:</p>
<pre><code>==&gt; Installation successful!
==&gt; Homebrew has enabled anonymous aggregate formulae and cask analytics.
...
==&gt; Next steps:
- Run these commands in your terminal to add Homebrew to your PATH:
  echo &gt;&gt; ~/.zprofile
  echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' &gt;&gt; ~/.zprofile
  eval "$(/opt/homebrew/bin/brew shellenv)"
</code></pre>
<p>Follow the printed Next steps to add Homebrew to your PATH (Apple Silicon uses <code>/opt/homebrew</code>; Intel uses <code>/usr/local</code>):</p>
<pre><code class="language-bash">echo &gt;&gt; ~/.zprofile
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' &gt;&gt; ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
</code></pre>
<p>Verify:</p>
<pre><code class="language-bash">brew --version
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>Homebrew 4.x.x
</code></pre>
<p><strong>Note:</strong> If Homebrew is already installed, this command will detect it and skip installation. You can safely run it again.</p>
<h2>Step 2: Install uv</h2>
<pre><code class="language-bash">brew install uv
</code></pre>
<p>Verify:</p>
<pre><code class="language-bash">uv --version
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>uv 0.x.x
</code></pre>
<h2>Step 3: Verify System Timezone is HKT</h2>
<p><code>launchd</code>'s <code>StartCalendarInterval</code> uses the system timezone. Since we're scheduling for 6:00 AM and 3:00 PM HKT, the system timezone must be <code>Asia/Hong_Kong</code>.</p>
<pre><code class="language-bash">sudo systemsetup -gettimezone
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>Time Zone: Asia/Hong_Kong
</code></pre>
<p>If it's not HKT, set it:</p>
<pre><code class="language-bash">sudo systemsetup -settimezone Asia/Hong_Kong
</code></pre>
<h2>Step 4: Clone TradingAgents and Create the Environment</h2>
<pre><code class="language-bash">git clone https://github.com/TauricResearch/TradingAgents.git
cd TradingAgents
uv venv --python 3.11
source .venv/bin/activate
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>Using CPython 3.11.x
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
</code></pre>
<p>Python 3.11 is recommended for best performance and compatibility — TradingAgents supports 3.10–3.12, with 3.11 being the sweet spot. uv downloads Python 3.11 automatically if it's not already on your system.</p>
<h2>Step 5: Install TradingAgents and LangGraph CLI</h2>
<p>For the official LangGraph installation reference, see the <a href="https://docs.langchain.com/oss/python/langgraph/install">LangGraph install documentation</a>. For CLI and Studio setup, see the <a href="https://docs.langchain.com/langsmith/cli">LangGraph CLI documentation</a> and the <a href="https://docs.langchain.com/langsmith/quick-start-studio">Studio quickstart</a>.</p>
<pre><code class="language-bash">uv pip install -e .
uv pip install -U "langgraph-cli[inmem]"
</code></pre>
<p><strong>Expected result:</strong> Both installations complete without errors. The <code>-e</code> flag installs TradingAgents in editable mode.</p>
<p>Verify:</p>
<pre><code class="language-bash">python -c "from tradingagents.graph.trading_graph import TradingAgentsGraph; print('TradingAgents OK')"
python -c "from langgraph.graph import StateGraph; print('LangGraph OK')"
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>TradingAgents OK
LangGraph OK
</code></pre>
<h2>Step 6: Create the Centralized <code>.env</code> File</h2>
<p>This is your <strong>single source of truth</strong>. Every secret and configuration value lives here.</p>
<pre><code class="language-bash">vim .env
</code></pre>
<p>Paste:</p>
<pre><code class="language-bash"># ============================================================
# TradingAgents Centralized Configuration
# ============================================================

# --- LLM Provider ---
TRADINGAGENTS_LLM_PROVIDER=google
GOOGLE_API_KEY=your-google-api-key-here

# --- Models ---
TRADINGAGENTS_DEEP_THINK_LLM=gemini-3.8-flash
TRADINGAGENTS_QUICK_THINK_LLM=gemini-3.1-flash-lite

# --- Trading ---
TRADINGAGENTS_DATA_DIR=./trading_data
TICKER=NVDA
MAX_DEBATE_ROUNDS=2

# --- Telegram Notification ---
TELEGRAM_BOT_TOKEN=123456789:ABC-your-bot-token
TELEGRAM_CHAT_ID=987654321

# --- Logging ---
LOG_LEVEL=INFO
</code></pre>
<p>Save and exit: press <code>Esc</code>, type <code>:wq</code>, press <code>Enter</code>.</p>
<p><strong>Replacing values:</strong> Edit with <code>vim .env</code> and replace the placeholders. Get your Google API key from <a href="https://aistudio.google.com/apikey">Google AI Studio</a>. Get your Telegram bot token from <code>@BotFather</code> and your chat ID from <code>@userinfobot</code> on Telegram.</p>
<p>TradingAgents automatically loads <code>.env</code> files on import — any <code>TRADINGAGENTS_*</code> variable overrides the matching key in <code>DEFAULT_CONFIG</code>.</p>
<h2>Step 7: Create the Telegram Notification Script</h2>
<p>Telegram is <strong>not</strong> integrated natively in the main TradingAgents repository. You do <strong>not</strong> need MLX or any local inference server — Telegram is just an HTTP API call.</p>
<pre><code class="language-bash">mkdir -p scripts
vim scripts/send_telegram.py
</code></pre>
<p>Paste:</p>
<pre><code class="language-python">import os
import requests
from pathlib import Path
from datetime import date

BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
TICKER = os.environ.get("TICKER", "NVDA")

def send_telegram(text: str) -&gt; None:
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    resp = requests.post(url, data={
        "chat_id": CHAT_ID,
        "text": text[:4000],
        "parse_mode": "Markdown",
        "disable_web_page_preview": True,
    }, timeout=30)
    resp.raise_for_status()
    print("Telegram report sent.")

report_dir = Path.home() / "TradingAgents" / "trading_data" / "reports" / TICKER / date.today().isoformat()
decision_file = report_dir / "5_portfolio" / "decision.md"

if decision_file.exists():
    decision = decision_file.read_text()
    send_telegram(f"*{TICKER} — {date.today().isoformat()}*\n\n{decision}")
else:
    send_telegram(f"{TICKER} analysis for {date.today().isoformat()} completed, but no decision file was found.")
    print("Decision file missing; sent fallback notice.")
</code></pre>
<p>Save and exit.</p>
<h2>Step 8: Create the Wrapper Script</h2>
<pre><code class="language-bash">vim scripts/run_analysis.sh
</code></pre>
<p>Paste:</p>
<pre><code class="language-bash">#!/bin/bash
set -euo pipefail

REPO="$HOME/TradingAgents"
VENV="$REPO/.venv/bin/python"
ENV_FILE="$REPO/.env"

# Load centralized .env into this process's environment
set -a
source "$ENV_FILE"
set +a

cd "$REPO"

# Step 1: Run the analysis
"$VENV" "$REPO/trade.py"

# Step 2: Send the Telegram report
"$VENV" "$REPO/scripts/send_telegram.py"
</code></pre>
<p>Make it executable:</p>
<pre><code class="language-bash">chmod +x scripts/run_analysis.sh
</code></pre>
<p><strong>Why the wrapper exists:</strong> <code>launchd</code> does not expand <code>$HOME</code> in plist strings, and its <code>EnvironmentVariables</code> dict is static at load time. The wrapper resolves <code>$HOME</code> at runtime and sources <code>.env</code> fresh on every run. This means <strong>you can rotate your Google API key or Telegram token by editing <code>.env</code> alone</strong> — no plist reload required.</p>
<h2>Step 9: Create the <code>trade.py</code> Script</h2>
<pre><code class="language-bash">vim trade.py
</code></pre>
<p>Paste:</p>
<pre><code class="language-python">import os
from datetime import date
from dotenv import load_dotenv
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

load_dotenv()

config = DEFAULT_CONFIG.copy()
config["llm_provider"] = os.getenv("TRADINGAGENTS_LLM_PROVIDER", "google")
config["quick_think_llm"] = os.getenv("TRADINGAGENTS_QUICK_THINK_LLM")
config["deep_think_llm"] = os.getenv("TRADINGAGENTS_DEEP_THINK_LLM")
config["data_vendors"] = {
    "core_stock_apis": "yfinance",
    "technical_indicators": "yfinance",
    "fundamental_data": "yfinance",
    "news_data": "yfinance"
}
config["max_debate_rounds"] = int(os.getenv("MAX_DEBATE_ROUNDS", "2"))

ta = TradingAgentsGraph(debug=True, config=config)

ticker = os.getenv("TICKER", "NVDA")
today = date.today().isoformat()
print(f"Starting Analysis for {ticker} ({today})...")

state, decision = ta.propagate(ticker, today)
ta.save_reports(state, ticker)

print("\n" + "="*60)
print("FINAL DECISION:")
print("="*60)
print(decision)
</code></pre>
<p>Save and exit.</p>
<p>Run it manually once to verify:</p>
<pre><code class="language-bash">python trade.py
</code></pre>
<p><strong>Expected result:</strong> The graph executes node by node. Reports are written to <code>./trading_data/reports/NVDA/&lt;DATE&gt;/</code>, and the final decision prints to the terminal.</p>
<h2>Step 10: Create the <code>launchd</code> Job</h2>
<pre><code class="language-bash">vim ~/Library/LaunchAgents/com.tradingagents.schedule.plist
</code></pre>
<p>Paste:</p>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;Label&lt;/key&gt;
    &lt;string&gt;com.tradingagents.schedule&lt;/string&gt;

    &lt;key&gt;ProgramArguments&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;/bin/bash&lt;/string&gt;
        &lt;string&gt;-c&lt;/string&gt;
        &lt;string&gt;"$HOME/TradingAgents/scripts/run_analysis.sh"&lt;/string&gt;
    &lt;/array&gt;

    &lt;key&gt;StartCalendarInterval&lt;/key&gt;
    &lt;array&gt;
        &lt;dict&gt;
            &lt;key&gt;Hour&lt;/key&gt;
            &lt;integer&gt;6&lt;/integer&gt;
            &lt;key&gt;Minute&lt;/key&gt;
            &lt;integer&gt;0&lt;/integer&gt;
        &lt;/dict&gt;
        &lt;dict&gt;
            &lt;key&gt;Hour&lt;/key&gt;
            &lt;integer&gt;15&lt;/integer&gt;
            &lt;key&gt;Minute&lt;/key&gt;
            &lt;integer&gt;0&lt;/integer&gt;
        &lt;/dict&gt;
    &lt;/array&gt;

    &lt;key&gt;StandardOutPath&lt;/key&gt;
    &lt;string&gt;/tmp/tradingagents.out.log&lt;/string&gt;
    &lt;key&gt;StandardErrorPath&lt;/key&gt;
    &lt;string&gt;/tmp/tradingagents.err.log&lt;/string&gt;

    &lt;key&gt;RunAtLoad&lt;/key&gt;
    &lt;false/&gt;
&lt;/dict&gt;
&lt;/plist&gt;
</code></pre>
<p>Save and exit.</p>
<p><strong>How the schedule works:</strong> <code>StartCalendarInterval</code> uses the system timezone — which you verified is HKT in Step 3. <code>Hour 6</code> means 6:00 AM HKT, <code>Hour 15</code> means 3:00 PM HKT. If the Mac is asleep at those times, <code>launchd</code> coalesces the missed intervals and fires once on wake.</p>
<p><strong>Why <code>RunAtLoad</code> is <code>false</code>:</strong> Setting it to <code>true</code> would trigger a run immediately when the plist is loaded — including after every reboot. With <code>false</code>, the job only runs at the scheduled times.</p>
<h2>Step 11: Load and Test the Job</h2>
<pre><code class="language-bash">launchctl load ~/Library/LaunchAgents/com.tradingagents.schedule.plist
</code></pre>
<p>Verify registration:</p>
<pre><code class="language-bash">launchctl list | grep tradingagents
</code></pre>
<p><strong>Expected output:</strong> A line showing <code>com.tradingagents.schedule</code> with a PID (or <code>-</code>) and an exit code.</p>
<p>Force a test run immediately without waiting for 6am:</p>
<pre><code class="language-bash">launchctl start com.tradingagents.schedule
</code></pre>
<p>Watch the logs:</p>
<pre><code class="language-bash">tail -f /tmp/tradingagents.out.log /tmp/tradingagents.err.log
</code></pre>
<p><strong>Expected result:</strong> The analysis runs, reports are written to disk, and a Telegram message arrives in your chat.</p>
<p>To reload after editing the plist:</p>
<pre><code class="language-bash">launchctl unload ~/Library/LaunchAgents/com.tradingagents.schedule.plist
launchctl load ~/Library/LaunchAgents/com.tradingagents.schedule.plist
</code></pre>
<h2>Checkpoint/Resume</h2>
<p>TradingAgents supports checkpointing to save state after each node to a per-ticker SQLite database. If a run crashes, it resumes from the last successful node instead of restarting.</p>
<p><strong>How it works:</strong> Each ticker's run is stored at <code>~/.tradingagents/cache/checkpoints/&lt;TICKER&gt;.db</code>. The <code>thread_id</code> is deterministic, based on the ticker, date, and a signature hash of graph-shape-affecting choices. If you change the configuration in a way that alters the graph's structure, a new checkpoint thread ID is generated, preventing resumption from an incompatible prior state.</p>
<p>Enable it in <code>trade.py</code>:</p>
<pre><code class="language-python">config["checkpoint_enabled"] = True
</code></pre>
<p>On resume, the framework prints <code>Resuming from step N for &lt;TICKER&gt; on &lt;date&gt;</code> instead of restarting from scratch. After successful completion, the checkpoint is automatically cleaned up.</p>
<p><strong>CLI alternative:</strong> The TradingAgents CLI accepts <code>--checkpoint</code> as a command-line argument.</p>
<h2>LangGraph Studio: Visual Debugging</h2>
<p>LangGraph Studio gives you a live, interactive view of the graph as it executes. You can set breakpoints, inspect state at any node, view exact prompts sent to Gemini, and debug failures without re-running the entire pipeline. For the official reference, see the <a href="https://docs.langchain.com/langsmith/quick-start-studio">LangGraph Studio documentation</a>.</p>
<h3>Setup</h3>
<p>Create <code>langgraph.json</code> at the repo root:</p>
<pre><code class="language-bash">vim langgraph.json
</code></pre>
<p>Paste:</p>
<pre><code class="language-json">{
  "dependencies": ["."],
  "graphs": {
    "trading_agents": {
      "path": "tradingagents/graph/trading_graph.py:TradingAgentsGraph",
      "config": {
        "debug": true
      }
    }
  },
  "env": ".env"
}
</code></pre>
<p>Save and exit.</p>
<p>Start the dev server:</p>
<pre><code class="language-bash">langgraph dev
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>Server started at http://localhost:2024
</code></pre>
<p>Open Studio in your browser. Safari and Brave block plain HTTP on localhost — if you're using either, add the <code>--tunnel</code> flag to get an HTTPS-accessible endpoint.</p>
<h3>What Studio Gives You</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>What It Does</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Interactive graph visualization</strong></td>
<td>See all nodes and edges rendered as a live graph</td>
</tr>
<tr>
<td><strong>Step-by-step execution</strong></td>
<td>Pause at any node, inspect input state, then resume</td>
</tr>
<tr>
<td><strong>State inspection</strong></td>
<td>View the full <code>AgentState</code> at any point — messages, reports, debate counts</td>
</tr>
<tr>
<td><strong>Breakpoints</strong></td>
<td>Set breakpoints on specific nodes to halt execution</td>
</tr>
<tr>
<td><strong>Prompt &amp; tool debugging</strong></td>
<td>View exact prompts sent to Gemini, tool arguments, token usage, latency</td>
</tr>
<tr>
<td><strong>State editing &amp; re-run</strong></td>
<td>Modify state at a breakpoint and re-run from that point</td>
</tr>
<tr>
<td><strong>LangSmith integration</strong></td>
<td>Import traced runs from production for debugging</td>
</tr>
</tbody></table>
<h3>Debugging Workflow: A Practical Example</h3>
<p><strong>Step 1: Launch and load the graph.</strong> Open Studio. You'll see the full TradingAgents graph rendered — Market Analyst, Social Media Analyst, News Analyst, Fundamentals Analyst, Bull Researcher, Bear Researcher, Research Manager, Trader, and the Risk Analysts.</p>
<p><strong>Step 2: Run a test input.</strong> In the input panel, provide:</p>
<pre><code class="language-json">{
  "company_of_interest": "NVDA",
  "trade_date": "2026-10-10",
  "messages": []
}
</code></pre>
<p>Click <strong>Run</strong>. Studio begins executing node by node, highlighting the current node.</p>
<p><strong>Step 3: Inspect state at each node.</strong> When execution pauses at the Market Analyst node (if you set a breakpoint), click <strong>Inspect State</strong>. You'll see the <code>AgentState</code> with all fields: <code>messages</code>, <code>company_of_interest</code>, <code>trade_date</code>, <code>market_report</code>, <code>sentiment_report</code>, <code>news_report</code>, <code>fundamentals_report</code>, <code>investment_debate_state</code>, and <code>risk_debate_state</code>.</p>
<p><strong>Step 4: Check tool calls and prompts.</strong> Click the <strong>Trace</strong> tab to see the exact prompt sent to Gemini for this node — system prompt, user message, tool definitions, and the model's response.</p>
<p><strong>Step 5: Debug a failure.</strong> If the Bull Researcher node fails with a Gemini API error, Studio captures the exception with full context. You can inspect the input state, modify the state (e.g., adjust <code>max_debate_rounds</code>), and re-run from that point.</p>
<p><strong>Step 6: Attach a line-level debugger (optional).</strong> For breakpoints and variable inspection:</p>
<pre><code class="language-bash">uv pip install debugpy
langgraph dev --debug-port 5678
</code></pre>
<p>Then attach VS Code or PyCharm to port 5678.</p>
<h2>Data Vendors: yfinance and Alternatives</h2>
<p>TradingAgents ships with <strong>yfinance</strong> as the default data vendor. It requires no API keys and covers core stock APIs, technical indicators, fundamentals, and news.</p>
<p><strong>Configuration:</strong></p>
<pre><code class="language-python">config["data_vendors"] = {
    "core_stock_apis": "yfinance",
    "technical_indicators": "yfinance",
    "fundamental_data": "yfinance",
    "news_data": "yfinance"
}
</code></pre>
<p><strong>Supported alternatives:</strong></p>
<table>
<thead>
<tr>
<th>Vendor</th>
<th>Category</th>
<th>API Key Required</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td><code>alpha_vantage</code></td>
<td>Core stock, fundamentals</td>
<td>Yes</td>
<td>Free tier: 25 requests/day</td>
</tr>
<tr>
<td><code>sec_edgar</code></td>
<td>Fundamentals</td>
<td>No</td>
<td>SEC asks callers to identify themselves</td>
</tr>
<tr>
<td><code>fred</code></td>
<td>Macro data</td>
<td>Yes</td>
<td>Federal Reserve economic data</td>
</tr>
<tr>
<td><code>polymarket</code></td>
<td>Prediction markets</td>
<td>No</td>
<td>Optional enrichment category</td>
</tr>
</tbody></table>
<p>To switch vendors, replace the value in the <code>data_vendors</code> dict:</p>
<pre><code class="language-python">config["data_vendors"]["core_stock_apis"] = "alpha_vantage"
config["data_vendors"]["fundamental_data"] = "sec_edgar,yfinance"
</code></pre>
<p>You can specify comma-separated fallback chains. If the first vendor is unavailable, the system automatically tries the next in the chain.</p>
<h2>Output: What You Actually Get</h2>
<p>When you call <code>ta.propagate("NVDA", today)</code>, you get two things back:</p>
<ol>
<li><strong>A tuple:</strong> <code>(state, decision)</code> — where <code>state</code> is the full <code>AgentState</code> dict and <code>decision</code> is the Portfolio Manager's final text.</li>
<li><strong>A 5-tier rating</strong> extracted deterministically from that decision text: <code>Buy</code>, <code>Overweight</code>, <code>Hold</code>, <code>Underweight</code>, or <code>Sell</code>.</li>
</ol>
<p>The <code>ta.save_reports(state, ticker)</code> call writes a <strong>structured directory tree</strong> of markdown files:</p>
<pre><code>trading_data/reports/NVDA/2026-10-10/
├── 1_analysts/
│   ├── market.md
│   ├── sentiment.md
│   ├── news.md
│   └── fundamentals.md
├── 2_research/
│   ├── bull.md
│   ├── bear.md
│   └── manager.md
├── 3_trading/
│   └── trader.md
├── 4_risk/
│   ├── aggressive.md
│   ├── conservative.md
│   └── neutral.md
├── 5_portfolio/
│   └── decision.md
└── complete_report.md
</code></pre>
<p>The Telegram script reads <code>5_portfolio/decision.md</code> and pushes it to your chat.</p>
<h2>Risks and Limitations</h2>
<table>
<thead>
<tr>
<th>Risk</th>
<th>Severity</th>
<th>Mitigation</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Gemini rate limits</strong></td>
<td>High</td>
<td>Free tier is 15 RPM. A single trade run can exceed this. Enable billing or throttle with <code>max_debate_rounds = 1</code></td>
</tr>
<tr>
<td><strong>yfinance single point of failure</strong></td>
<td>Medium</td>
<td>Web scraping tool, subject to Yahoo page changes. Use fallback chains</td>
</tr>
<tr>
<td><strong>Context growth during debate</strong></td>
<td>Medium</td>
<td>Set <code>max_debate_rounds</code> and <code>max_risk_discuss_rounds</code> conservatively</td>
</tr>
<tr>
<td><strong>No broker execution</strong></td>
<td>—</td>
<td>TradingAgents is a research framework. It does not place real orders — output is a decision, not a trade</td>
</tr>
<tr>
<td><strong><code>launchd</code> timezone</strong></td>
<td>Low</td>
<td>Schedule uses system timezone. Verify with <code>sudo systemsetup -gettimezone</code></td>
</tr>
</tbody></table>
<p><strong>Important disclaimer:</strong> TradingAgents is designed for research purposes. Trading performance may vary based on many factors, including the chosen backbone language models, model temperature, trading periods, and data quality. It is not intended as financial, investment, or trading advice.</p>
<h2>Troubleshooting: When Things Fail</h2>
<table>
<thead>
<tr>
<th>Symptom</th>
<th>Likely Cause</th>
<th>Fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>launchctl start</code> runs but nothing happens</td>
<td>Wrapper script not executable</td>
<td><code>chmod +x ~/TradingAgents/scripts/run_analysis.sh</code></td>
</tr>
<tr>
<td>Telegram message not received</td>
<td><code>TELEGRAM_CHAT_ID</code> wrong</td>
<td>Message <code>@userinfobot</code> on Telegram to get your correct ID</td>
</tr>
<tr>
<td><code>GOOGLE_API_KEY not set</code> in logs</td>
<td><code>.env</code> not sourced</td>
<td>Verify wrapper has <code>source "$ENV_FILE"</code> before running</td>
</tr>
<tr>
<td>Analysis runs but no report files</td>
<td><code>save_reports</code> not called</td>
<td>Ensure <code>ta.save_reports(state, ticker)</code> is in <code>trade.py</code></td>
</tr>
<tr>
<td>Job runs at wrong time</td>
<td>System timezone not HKT</td>
<td><code>sudo systemsetup -settimezone Asia/Hong_Kong</code></td>
</tr>
<tr>
<td><code>uv: command not found</code> in launchd logs</td>
<td>PATH not set</td>
<td>Use the venv Python directly (absolute path)</td>
</tr>
</tbody></table>
<h2>Conclusion</h2>
<p>You now have a fully operational multi-agent trading firm running on your Mac, scheduled twice daily, with Telegram delivery. The architecture is:</p>
<ul>
<li><strong>LangGraph</strong> runs locally, orchestrating the entire workflow</li>
<li><strong>Gemini 3</strong> provides remote inference — <code>gemini-3.8-flash</code> for deep reasoning, <code>gemini-3.1-flash-lite</code> for high-throughput analysts</li>
<li><strong>yfinance</strong> fetches market data with no API keys required</li>
<li><strong>LangGraph Studio</strong> gives you step-by-step visual debugging</li>
<li><strong><code>launchd</code></strong> runs the analysis at 6:00 AM and 3:00 PM HKT</li>
<li><strong>Telegram</strong> receives the final decision after each run</li>
<li><strong>One <code>.env</code> file</strong> holds every secret — rotate keys without touching the plist</li>
</ul>
<p><strong>Next steps:</strong></p>
<ul>
<li>Experiment with different Gemini model combinations for Quick Think and Deep Think</li>
<li>Add fallback data vendors (SEC EDGAR for fundamentals, Alpha Vantage for stock data)</li>
<li>Explore broker integration forks if you want live execution — but understand they are separate codebases</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Inside the AI Kitchen: How LLMs Actually Run on Your Machine]]></title><description><![CDATA[Your GPU performs trillions of calculations per second — yet when you run an AI model at home, it writes... one... word... at... a... time. That gap…]]></description><link>https://nightthoughts.me/inside-the-ai-kitchen-how-llms-actually-run-on-your-machine</link><guid isPermaLink="true">https://nightthoughts.me/inside-the-ai-kitchen-how-llms-actually-run-on-your-machine</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[Explain like I am five]]></category><category><![CDATA[hardware]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Fri, 09 Oct 2026 21:43:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/20dbeeeb-a86d-46a4-8285-3cabd316d746.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Your GPU performs trillions of calculations per second — yet when you run an AI model at home, it writes... one... word... at... a... time. That gap between raw power and felt speed is the whole story of this article. To tell it, we'll use one metaphor: the AI restaurant.</p>
<table>
<thead>
<tr>
<th>Character</th>
<th>Real thing</th>
<th>Role in the kitchen</th>
</tr>
</thead>
<tbody><tr>
<td>The Recipe Book</td>
<td>The model file (weights)</td>
<td>Everything the kitchen knows, frozen on paper</td>
</tr>
<tr>
<td>The Manager</td>
<td>CPU</td>
<td>Smart, versatile, works step-by-step — but can't do the heavy cooking</td>
</tr>
<tr>
<td>The Chef</td>
<td>GPU</td>
<td>Thousands of short-order cooks doing simple math simultaneously</td>
</tr>
<tr>
<td>Counter &amp; Fridge</td>
<td>RAM / VRAM</td>
<td>Fast workspace; the Chef can't cook from the grocery store (hard drive)</td>
</tr>
<tr>
<td>The Expeditor</td>
<td>Inference Engine</td>
<td>Runs the pass: decides what happens, when</td>
</tr>
</tbody></table>
<p><strong>The promise:</strong> by the end, you'll know why prompts start fast but answers trickle, why chats slow down as they grow, and why a small GPU can run a surprisingly large model.</p>
<h2>1. The Ingredients: What a Model Actually Is</h2>
<p>A model is not a brain. It's a giant static list of numbers — billions of weights, like a warehouse-sized amplifier with billions of knob positions. A static file can do nothing on its own: no kitchen, no service.</p>
<p>Two facts to carry forward:</p>
<ul>
<li><strong>Tokens, not words.</strong> The book stores word-pieces. "The quick brown wolf jumps" is five words but perhaps six or seven tokens. (We'll treat them as interchangeable below.)</li>
<li><strong>Editions matter.</strong> The full-precision book is enormous; quantized editions (8-bit, 4-bit, "Q4") record the knob positions less precisely at a quarter of the size — with nearly identical output. Remember this. Book size is destiny.</li>
</ul>
<h2>2. The Kitchen Crew</h2>
<table>
<thead>
<tr>
<th>Manager (CPU)</th>
<th>Chef (GPU)</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Strength:</strong> Any job, good judgment</td>
<td><strong>Strength:</strong> One simple calculation, done thousands of times at once</td>
</tr>
<tr>
<td><strong>Weakness:</strong> Sequential; no brute force</td>
<td><strong>Weakness:</strong> No judgment; can't manage anything</td>
</tr>
<tr>
<td><strong>AI fit:</strong> Orchestration, housekeeping</td>
<td><strong>AI fit:</strong> 99% of an LLM's math is exactly its specialty</td>
</tr>
</tbody></table>
<p>The workspace rule governs everything: the Chef cannot cook from the grocery store. The model file sits on your hard drive (a warehouse across town); it must be hauled into fast memory — RAM, or the GPU's private counter, VRAM — before service. That "loading model..." bar is the haul. It happens once.</p>
<p><strong>The reveal:</strong> the bottleneck in AI is rarely the Chef's speed. It's the walk to the fridge — memory bandwidth, how fast pages move between storage and the Chef's hands. Nearly every performance mystery in this article is that walk.</p>
<h2>3. Phase One — Prefill: Reading the Ticket</h2>
<p>You hit Enter on: <strong>"The quick brown wolf jumps"</strong></p>
<p>The Chef reads the entire ticket in one pass — all tokens simultaneously. This is the GPU's native gift: parallel processing. Long prompt? Slightly longer pause before the first word. Prefill scales with prompt size; it's a reading problem, and the Chef reads fast.</p>
<p>While reading, the Chef takes shorthand notes on a scratchpad — not sentences, but symbols recording what each word is and relates to. This scratchpad is the <strong>KV Cache</strong>: the AI's short-term memory (full treatment in Section 5).</p>
<p>At the end of the pass, the Chef predicts the most likely next word and writes the first word of the answer: <strong>"over"</strong></p>
<h2>4. Phase Two — Decode: Plating Course by Course</h2>
<p>Now the kitchen enters a loop, because each word depends on all the words before it:</p>
<table>
<thead>
<tr>
<th>Loop</th>
<th>Consults</th>
<th>Writes</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Ticket + scratchpad</td>
<td>"the"</td>
</tr>
<tr>
<td>2</td>
<td>+ "the" added to scratchpad</td>
<td>"lazy"</td>
</tr>
<tr>
<td>3</td>
<td>+ "lazy" added to scratchpad</td>
<td>"dog"</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>... until the dish is complete</td>
</tr>
</tbody></table>
<p><strong>Why so slow?</strong> Every loop requires consulting the entire recipe book — billions of knob-positions — and the book lives in the fridge. Writing one word means hauling the whole book to the counter; the next word, again. The Chef could flip pages in microseconds; the walk is the bottleneck.</p>
<p>The GPU isn't idle during decode — it's <strong>starved</strong>, on a job that barely uses its parallel power.</p>
<ul>
<li><strong>Prefill is a reading problem (compute-bound).</strong></li>
<li><strong>Decode is a hauling problem (bandwidth-bound).</strong></li>
</ul>
<p>And the condensed editions snap into focus: a 4-bit book is a quarter of the walking per word. That's how an 8GB GPU runs a model whose original wouldn't fit on a shelf.</p>
<p><em>(Aside: the Chef actually computes probabilities for every possible next word and draws one; "temperature" dials in how adventurous the draw is. Everything else works the same.)</em></p>
<h2>5. The Scratchpad: KV Cache — and Why Chats Crash</h2>
<p>Without the scratchpad, every new word would require re-reading the entire conversation from the beginning. The KV Cache is what the Chef has already noted down — one entry per token — so each loop only consults the notes rather than reconstructing them.</p>
<p>The catch, in hardware terms:</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Consequence</th>
</tr>
</thead>
<tbody><tr>
<td>Scratchpad lives on the counter (VRAM) — consulted every loop</td>
<td>It competes for the same fast memory as the recipe book</td>
</tr>
<tr>
<td>It grows — one entry per token, prompt and answer</td>
<td>Long conversations eat counter space</td>
</tr>
<tr>
<td>Every book has a max scratchpad size — the context window</td>
<td>Past it, the kitchen literally can't take more notes</td>
</tr>
</tbody></table>
<p>Three familiar failure modes fall straight out:</p>
<ul>
<li><strong>Chats slow down</strong> — each loop wades through a longer scratchpad.</li>
<li><strong>Chats crash</strong> — scratchpad + book overflow VRAM. That's "out of memory."</li>
<li><strong>AI "forgets" your early messages</strong> — you hit the context ceiling. It's a design limit, not a bug.</li>
</ul>
<p>"It worked fine for twenty messages, then died" is a memory story.</p>
<h2>6. The Expeditor: What the Inference Engine Actually Does</h2>
<p>Hardware is the staff; the engine is the discipline of running the pass. (It's a role the Manager steps into — software on your CPU directing the GPU — not a sixth employee.)</p>
<p>Its job, by phase:</p>
<table>
<thead>
<tr>
<th>Job</th>
<th>What it means</th>
</tr>
</thead>
<tbody><tr>
<td>Translates the book</td>
<td>Compiles the generic model file into your hardware's dialect (CUDA, Metal...), choosing the exact math routines (kernels) for every step</td>
</tr>
<tr>
<td>Stages the kitchen</td>
<td>Decides what gets hauled to the counter, when, and how much space to reserve — memory doesn't organize itself</td>
</tr>
<tr>
<td>Runs the pass</td>
<td>Tokenizes your prompt, launches Prefill, drives the Decode loop, watches for the "dish complete" token, serves the result</td>
</tr>
<tr>
<td>Seats multiple tables</td>
<td>Batches several requests so the Chef cooks in parallel — boosts throughput (customers/hour), not any single meal's speed</td>
</tr>
</tbody></table>
<p>Notice what it never does: cook. Every dish is still the Chef's, from the same book, on the same counter. The engine determines whether the Chef works in rhythm or in a traffic jam. Hardware sets what the kitchen can do. The inference engine determines what it actually does.</p>
<h2>7. Closing Time</h2>
<p>A model is a recipe book — inert until service. The CPU manages, the GPU cooks in parallel, and the walk to the fridge sets the pace of everything. Work splits into Prefill (fast parallel read) and Decode (slow sequential loop hauling the whole book per word). The KV Cache spares the kitchen from re-reading everything — at the cost of your counter space. Above it all, the inference engine runs the pass.</p>
<p>The diagnostic payoff:</p>
<table>
<thead>
<tr>
<th>Symptom</th>
<th>What's happening</th>
<th>What helps</th>
</tr>
</thead>
<tbody><tr>
<td>Pause before the first word</td>
<td>Prefill still reading a long ticket</td>
<td>Nothing's broken; shorter prompt</td>
</tr>
<tr>
<td>Slow word-by-word output</td>
<td>Decode hauling the book per word</td>
<td>A smaller edition (quantized model)</td>
</tr>
<tr>
<td>Crash mid-conversation</td>
<td>Scratchpad + book overflowed VRAM</td>
<td>Shorter history, smaller book</td>
</tr>
<tr>
<td>Long "loading model..."</td>
<td>The haul from the warehouse</td>
<td>One-time cost; smaller books load faster</td>
</tr>
<tr>
<td>AI ignores early messages</td>
<td>Context window ceiling</td>
<td>Trim the conversation</td>
</tr>
</tbody></table>
<p>You don't need a supercomputer — you need to know that the speed limit is the walk to the fridge, and that the expeditor, the scratchpad, and the edition you choose decide how smoothly the kitchen runs.</p>
<p>Now you do.</p>
]]></content:encoded></item><item><title><![CDATA[Complete Guide: Always-On Mac Server with MLX, oMLX & QwenPaw]]></title><description><![CDATA[Headless MLX inference with oMLX, QwenPaw, Caddy, Tailscale, and Cloudflare — verified end to end.]]></description><link>https://nightthoughts.me/complete-guide-always-on-mac-server-with-mlx-omlx-qwenpaw</link><guid isPermaLink="true">https://nightthoughts.me/complete-guide-always-on-mac-server-with-mlx-omlx-qwenpaw</guid><category><![CDATA[AI]]></category><category><![CDATA[MLX]]></category><category><![CDATA[qwenpaw]]></category><category><![CDATA[MacMini]]></category><category><![CDATA[cloudflare]]></category><category><![CDATA[tailscale]]></category><category><![CDATA[omlx]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Fri, 09 Oct 2026 21:01:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/e8731940-c0fb-4aa5-b7be-8ba95a19041e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>The foundation guide for local AI on Apple Silicon.</strong></p>
<p>This guide builds a headless, always-on Mac mini that survives reboot without any GUI intervention, serves local models through oMLX with persistent API keys, runs the QwenPaw agent framework as a system service, and exposes everything through Caddy + Cloudflare Tunnel with Tailscale for SSH (and optionally HTTPS) access. The whole stack runs at zero marginal inference cost and never sends data off the machine.</p>
<hr />
<h2>Tested Environment</h2>
<p>Everything in this guide was verified on the following setup. If your versions are close, the commands should work unchanged.</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Version</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td><strong>macOS</strong></td>
<td>15.x (Sequoia) or later</td>
<td>Required for oMLX</td>
</tr>
<tr>
<td><strong>Chip</strong></td>
<td>Apple Silicon (M1/M2/M3/M4/M5)</td>
<td>Required for MLX and oMLX</td>
</tr>
<tr>
<td><strong>Homebrew</strong></td>
<td>4.x or later</td>
<td>Package manager for oMLX, Caddy, and Tailscale</td>
</tr>
<tr>
<td><strong>uv</strong></td>
<td>0.8.x or later</td>
<td>Python version + package manager</td>
</tr>
<tr>
<td><strong>Python (MLX venv)</strong></td>
<td>3.11.x</td>
<td>Managed by uv at <code>~/.mlx-venv</code></td>
</tr>
<tr>
<td><strong>Python (QwenPaw)</strong></td>
<td>3.12.x</td>
<td>Bundled by QwenPaw's installer</td>
</tr>
<tr>
<td><strong>MLX</strong></td>
<td>0.32.x</td>
<td>Apple's ML framework</td>
</tr>
<tr>
<td><strong>mlx-lm</strong></td>
<td>0.32.x</td>
<td>LLM extensions for MLX</td>
</tr>
<tr>
<td><strong>oMLX</strong></td>
<td>latest via <code>jundot/omlx</code></td>
<td>Inference server + admin dashboard</td>
</tr>
<tr>
<td><strong>QwenPaw</strong></td>
<td>latest via <code>agentscope.io</code></td>
<td>Agent framework + web console</td>
</tr>
<tr>
<td><strong>Caddy</strong></td>
<td>2.x</td>
<td>Reverse proxy + authentication layer</td>
</tr>
<tr>
<td><strong>Tailscale</strong></td>
<td>latest via <code>--cask</code></td>
<td>Mesh VPN, SSH, TLS termination</td>
</tr>
<tr>
<td><strong>cloudflared</strong></td>
<td>latest via Homebrew</td>
<td>Public access via custom domain</td>
</tr>
<tr>
<td><strong>jq</strong></td>
<td>latest via Homebrew</td>
<td>JSON processor (used throughout)</td>
</tr>
<tr>
<td><strong>yq</strong></td>
<td>latest via Homebrew</td>
<td>YAML processor (used later)</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>Note:</strong> Version numbers above reflect the state of the ecosystem as of <strong>2026-10</strong>, the date this guide was last verified end-to-end. Run <code>brew --version</code>, <code>uv --version</code>, or the relevant <code>--version</code> flag after each install to confirm what you have.</p>
</blockquote>
<hr />
<h2>Part 1: Prepare macOS for Headless Server Mode</h2>
<p>These steps ensure your Mac never sleeps, is accessible remotely, and boots into a usable state without manual intervention.</p>
<h3>1.1 Prevent System Sleep</h3>
<p>Run this in Terminal to disable all sleep modes permanently:</p>
<pre><code class="language-bash">sudo pmset -a disablesleep 1 sleep 0 disksleep 0 displaysleep 0 standby 0 autopoweroff 0 powernap 0
</code></pre>
<p><strong>Expected output:</strong> You'll be prompted for your password. After entry, no confirmation message appears — that's normal.</p>
<p>Verify with:</p>
<pre><code class="language-bash">pmset -g
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">System-wide power settings:
 SleepDisabled		1
Currently in use:
 standby              0
 Sleep On Power Button 1
 autorestartatconnect 0
 autorestart          0
 SleepServices        0
 powernap             0
 networkoversleep     0
 disksleep            0
 sleep                0 (sleep prevented by powerd, bluetoothd)
 ttyskeepawake        1
 displaysleep         0
 tcpkeepalive         1
 powermode            0
 womp                 1
</code></pre>
<blockquote>
<p><strong>Note:</strong> On macOS Ventura (13) and later, <code>pmset</code> reports the disablesleep setting as <code>SleepDisabled 1</code> instead of <code>disablesleep 1</code>. This is expected — it means the same thing.</p>
<p>The annotation <code>(sleep prevented by powerd, bluetoothd)</code> next to <code>sleep 0</code> is <strong>informational, not an error</strong>. It simply means that in addition to your <code>pmset</code> settings, system daemons are also actively preventing sleep. Your server will stay awake.</p>
</blockquote>
<h3>1.1b Prevent App Nap with caffeinate</h3>
<p><code>pmset</code> stops the system from sleeping, but macOS can still throttle background processes via <strong>App Nap</strong>. On an always-on server, App Nap causes services to respond slowly — a request that should take milliseconds can hang for seconds while the process is deprioritized. This is especially noticeable on MLX inference: token generation rate can drop dramatically when macOS decides the process is "idle" between requests.</p>
<p>The <code>caffeinate</code> command prevents App Nap by holding IOKit power assertions:</p>
<pre><code class="language-bash">caffeinate -dimsu -t 2147483647
</code></pre>
<table>
<thead>
<tr>
<th>Flag</th>
<th>Effect</th>
</tr>
</thead>
<tbody><tr>
<td><code>-d</code></td>
<td>Prevent the display from sleeping</td>
</tr>
<tr>
<td><code>-i</code></td>
<td>Prevent idle system sleep — this is what blocks App Nap</td>
</tr>
<tr>
<td><code>-m</code></td>
<td>Prevent disk idle sleep</td>
</tr>
<tr>
<td><code>-s</code></td>
<td>Prevent system sleep on AC power</td>
</tr>
<tr>
<td><code>-u</code></td>
<td>Declare the user is active</td>
</tr>
<tr>
<td><code>-t 2147483647</code></td>
<td>Hold the assertion for the maximum duration (~68 years)</td>
</tr>
</tbody></table>
<p>To make it persistent across reboots, create a dedicated launch agent. This runs independently of your other services, so it survives their restarts:</p>
<pre><code class="language-bash">cat &gt; ~/Library/LaunchAgents/com.caffeinate.server.plist &lt;&lt; 'EOF'
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.caffeinate.server&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;/usr/bin/caffeinate&lt;/string&gt;
    &lt;string&gt;-dimsu&lt;/string&gt;
    &lt;string&gt;-t&lt;/string&gt;
    &lt;string&gt;2147483647&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF
</code></pre>
<p>Load it:</p>
<pre><code class="language-bash">launchctl bootout gui/$(id -u)/com.caffeinate.server 2&gt;/dev/null
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.caffeinate.server.plist
</code></pre>
<p>Verify it's running:</p>
<pre><code class="language-bash">launchctl list | grep caffeinate
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">-	0	com.caffeinate.server
</code></pre>
<p>Confirm the assertions are active:</p>
<pre><code class="language-bash">pmset -g assertions | grep -A 5 "caffeinate"
</code></pre>
<p><strong>Expected output:</strong> A list showing <code>PreventUserIdleSystemSleep</code>, <code>PreventUserIdleDisplaySleep</code>, and related assertions attributed to <code>caffeinate</code>.</p>
<blockquote>
<p><strong>Note:</strong> Some reports suggest that <code>pmset -g assertions</code> on certain macOS versions no longer lists all assertions. Even if the output is sparse, the <code>caffeinate</code> process running under <code>launchctl</code> is sufficient — the assertions are held at the kernel level regardless of what <code>pmset</code> displays.</p>
</blockquote>
<h3>1.2 Enable SSH (Remote Login)</h3>
<p>On macOS Catalina (10.15) and later, the <code>systemsetup</code> command requires <strong>Full Disk Access</strong> to toggle Remote Login. Running it without that permission will fail with:</p>
<pre><code class="language-plaintext">setremotelogin: Turning Remote Login on or off requires Full Disk Access privileges.
</code></pre>
<p>This is a macOS security feature (TCC), and <code>sudo</code> alone does not bypass it. Follow these steps to fix it permanently.</p>
<p><strong>Step 1: Grant Full Disk Access to Terminal</strong></p>
<ol>
<li><p>Open <strong>System Settings</strong>.</p>
</li>
<li><p>Go to <strong>Privacy &amp; Security</strong> → <strong>Full Disk Access</strong>.</p>
</li>
<li><p>Click the <strong>+</strong> button.</p>
</li>
<li><p>Navigate to <strong>Applications</strong> → <strong>Utilities</strong> and select <strong>Terminal.app</strong> (or your terminal of choice, e.g., iTerm).</p>
</li>
<li><p>Toggle Terminal <strong>on</strong> in the list.</p>
</li>
<li><p><strong>Quit Terminal completely</strong> (<code>Cmd+Q</code>) and reopen it. The permission only takes effect for new sessions.</p>
</li>
</ol>
<p><strong>Step 2: Enable Remote Login</strong></p>
<p>Now run the command. It will succeed without the permission error:</p>
<pre><code class="language-bash">sudo systemsetup -setremotelogin on
</code></pre>
<p><strong>Expected output:</strong> <code>setremotelogin: remote login is now on</code></p>
<p>Verify:</p>
<pre><code class="language-bash">sudo systemsetup -getremotelogin
</code></pre>
<p><strong>Expected output:</strong> <code>Remote Login: On</code></p>
<p>Now you can SSH from another Mac: <code>ssh username@your-mac-ip</code></p>
<h3>1.3 Enable Auto-Login (Required for LaunchAgents)</h3>
<p>launchd user agents only start after a user logs in. Without auto-login, your services won't run after a reboot.</p>
<ol>
<li><p>Open <strong>System Settings</strong> → <strong>Users &amp; Groups</strong></p>
</li>
<li><p>Click <strong>Automatic Login</strong> → select your user account</p>
</li>
<li><p>Enter your password when prompted</p>
</li>
</ol>
<blockquote>
<p><strong>Note:</strong> FileVault must be OFF for auto-login to work. Go to <strong>System Settings → Privacy &amp; Security → FileVault</strong> and turn it off if it's enabled. This is acceptable for a physically secure home server.</p>
</blockquote>
<h3>1.4 LaunchAgents vs. LaunchDaemons (Understanding the Difference)</h3>
<p>As you build this server, you'll encounter two types of background services. It's important to know the difference:</p>
<ul>
<li><p><strong>LaunchAgents</strong> (<code>~/Library/LaunchAgents/</code>) run <strong>only after you log in</strong> to the Mac. The graphical user interface (<code>WindowServer</code> and <code>loginwindow</code>) must be running. If the Mac boots headless and fails to start the GUI, LaunchAgents never start. Examples in this guide: <strong>caffeinate</strong>.</p>
</li>
<li><p><strong>LaunchDaemons</strong> (<code>/Library/LaunchDaemons/</code>) run <strong>at system boot</strong>, long before any user logs in. They run in the background and do not need a GUI. Examples in this guide: <strong>Caddy</strong>, <strong>oMLX</strong>, <strong>QwenPaw</strong>, and <strong>cloudflared</strong>.</p>
</li>
</ul>
<p><strong>Why does this matter?</strong> If your Mac mini reboots but the desktop session gets stuck (which happens on headless Macs), your LaunchAgents won't load. By installing the core external-access services (oMLX, Caddy, QwenPaw, and cloudflared) as LaunchDaemons, we guarantee you can reach the server from the internet even if the GUI hangs.</p>
<p>If the GUI <em>does</em> fail to start, SSH in and run this diagnostic to see what's happening:</p>
<pre><code class="language-bash">echo "=== Login window running? ===" &amp;&amp; pgrep -l loginwindow
echo "=== WindowServer running? ===" &amp;&amp; pgrep -l WindowServer
</code></pre>
<p>If both return nothing, the GUI never started. Check that FileVault is OFF, auto-login is enabled, and consider adding an HDMI dummy plug (a cheap hardware trick that forces the Mac to output a video signal so <code>WindowServer</code> starts).</p>
<blockquote>
<p><strong>Managing LaunchDaemons:</strong> Because they run in the system domain, you must use <code>sudo</code> and the <code>system/</code> path to manage them. For example: <code>sudo launchctl kickstart -k system/com.caddy.server</code>. Attempting to use <code>gui/$(id -u)</code> will fail with <code>Could not find service</code>.</p>
</blockquote>
<h3>1.5 Optional: Menu Bar Server Mode Toggle</h3>
<p>For quick control without terminal, install the <code>mac-server-mode</code> menu bar app:</p>
<pre><code class="language-bash">git clone https://github.com/thairc-dev/mac-server-mode.git &amp;&amp; cd mac-server-mode &amp;&amp; ./build.sh &amp;&amp; nohup ./mac-server-mode &gt;/dev/null 2&gt;&amp;1 &amp; ./install-launch-agent.sh
</code></pre>
<p>A ⚡ icon appears in your menu bar. Press <code>Ctrl + Option + Cmd + S</code> to toggle server mode (screen off, system awake).</p>
<hr />
<h2>Part 2: Install uv &amp; Python 3.11</h2>
<h3>2.1 Install uv</h3>
<p><code>uv</code> is a fast, all-in-one Python package and version manager written in Rust. Install it via the official one-liner:</p>
<pre><code class="language-bash">curl -LsSf https://astral.sh/uv/install.sh | sh &amp;&amp; source ~/.zshrc &amp;&amp; uv --version
</code></pre>
<p><strong>Expected output:</strong> Installation progress bars, then <code>uv 0.x.x</code>.</p>
<h3>2.2 Install Python 3.11 with uv</h3>
<p>Install Python 3.11 as a uv-managed Python:</p>
<pre><code class="language-bash">uv python install 3.11 &amp;&amp; uv python list | grep 3.11
</code></pre>
<p><strong>Expected output:</strong> Download progress, then the installed Python 3.11 version.</p>
<h3>2.3 Create a Virtual Environment for MLX</h3>
<p>Create a dedicated virtual environment, activate it, and verify the version in one go:</p>
<pre><code class="language-bash">uv venv --python 3.11 ~/.mlx-venv &amp;&amp; source ~/.mlx-venv/bin/activate &amp;&amp; python --version &amp;&amp; python -c "import platform; print(platform.processor())"
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">Python 3.11.x
arm
</code></pre>
<blockquote>
<p><strong>Critical:</strong> If you see <code>i386</code> instead of <code>arm</code>, you have a Rosetta (x86) Python. Reinstall Python 3.11 through uv and start over.</p>
</blockquote>
<hr />
<h2>Part 3: Install MLX Framework</h2>
<p>MLX is Apple's native machine learning framework for Apple Silicon.</p>
<p>With your virtual environment activated, install the framework and verify it:</p>
<pre><code class="language-bash">source ~/.mlx-venv/bin/activate &amp;&amp; uv pip install mlx mlx-lm &amp;&amp; python -c "import mlx.core as mx; print(mx.__version__)"
</code></pre>
<p><strong>Expected output:</strong> <code>Successfully installed mlx-x.x.x mlx-lm-x.x.x ...</code> followed by <code>0.32.x</code>.</p>
<blockquote>
<p><strong>Note:</strong> The top-level <code>mlx</code> module does <strong>not</strong> export <code>__version__</code>. If you try <code>python -c "import mlx; print(mlx.__version__)"</code>, you'll get <code>AttributeError: module 'mlx' has no attribute '__version__'</code>. The version attribute lives on <code>mlx.core</code>. Alternatively, you can read the version from package metadata:</p>
<pre><code class="language-bash">python -c "import importlib.metadata as md; print(md.version('mlx'))"
</code></pre>
</blockquote>
<hr />
<h2>Part 4: Install oMLX (Web Dashboard + Background Service)</h2>
<p>oMLX is an LLM inference server optimized for Apple Silicon, built on the MLX framework. It provides continuous batching, tiered KV caching (hot in-memory + cold SSD), and a web-based admin dashboard for managing models. It is actively maintained and ships as a Homebrew formula with native launchd service integration.</p>
<blockquote>
<p><strong>Note:</strong> oMLX is a community project maintained by <code>jundot</code>. It is built directly on top of Apple's MLX framework (which <em>is</em> official).</p>
</blockquote>
<blockquote>
<p><strong>Platform requirement:</strong> oMLX requires <strong>Apple Silicon</strong> (M1/M2/M3/M4/M5) and <strong>macOS 15.0 (Sequoia) or later</strong>. Intel Macs and earlier macOS versions are rejected during installation.</p>
</blockquote>
<h3>4.1 Install Homebrew</h3>
<p>If you don't already have Homebrew, install it and set up your PATH in one command:</p>
<pre><code class="language-bash">/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" &amp;&amp; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' &gt;&gt; ~/.zprofile &amp;&amp; eval "$(/opt/homebrew/bin/brew shellenv)" &amp;&amp; brew --version
</code></pre>
<p><strong>Expected output:</strong> Installation progress messages, then <code>Homebrew 4.x.x</code>.</p>
<blockquote>
<p><strong>Note:</strong> If Homebrew is already installed, the installer will detect it and skip installation. You can safely run this command again.</p>
</blockquote>
<h3>4.1b Install <code>jq</code> and <code>yq</code></h3>
<p>This guide uses <code>jq</code> heavily for JSON manipulation (oMLX keys, QwenPaw config) and <code>yq</code> for YAML (useful for Cloudflare tunnel config and future service edits). Install both now so later steps don't fail with <code>jq: command not found</code> or <code>yq: command not found</code>.</p>
<pre><code class="language-bash">brew install jq yq
</code></pre>
<p><strong>Expected output:</strong> Homebrew installs both formulae, ending with <code>jq</code> and <code>yq</code> version numbers.</p>
<p>Verify:</p>
<pre><code class="language-bash">jq --version
yq --version
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">jq-1.7.x
yq (https://github.com/mikefarah/yq/) version v4.x.x
</code></pre>
<blockquote>
<p><strong>Why here?</strong> <code>jq</code> is first used in §4.3 to inject the oMLX API keys into <code>~/.omlx/settings.json</code>. Installing it before that step avoids the most common “command not found” error in this guide. <code>yq</code> is not strictly required by the commands below, but it's the right YAML companion for editing <code>~/.cloudflared/config.yml</code> and other configs later.</p>
</blockquote>
<h3>4.2 Tap, Trust, and Install oMLX</h3>
<p>Run all three steps in one command:</p>
<pre><code class="language-bash">brew tap jundot/omlx https://github.com/jundot/omlx &amp;&amp; brew trust jundot/omlx &amp;&amp; brew install jundot/omlx/omlx
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">==&gt; Tapping jundot/omlx
Cloning into '/opt/homebrew/Library/Taps/jundot/homebrew-omlx'...
Tapped 1 formula.
==&gt; Successfully trusted tap jundot/omlx.
==&gt; Installing omlx from jundot/omlx
/opt/homebrew/Cellar/omlx/x.x.x: ...
</code></pre>
<blockquote>
<p><strong>Why</strong> <code>brew trust</code> <strong>is needed:</strong> Recent versions of Homebrew refuse to load formulas from third-party taps unless you explicitly trust them — a security feature to prevent arbitrary code execution from untrusted sources. If you skip this, you'll see <code>Error: Refusing to load formula jundot/omlx/omlx from untrusted tap jundot/omlx.</code></p>
</blockquote>
<h3>4.3 Set the API Keys (The Right Way)</h3>
<p>oMLX uses <strong>two distinct keys</strong>, and confusing them is the most common setup error:</p>
<table>
<thead>
<tr>
<th>Key</th>
<th>Purpose</th>
<th>Where It's Used</th>
</tr>
</thead>
<tbody><tr>
<td><code>api_key</code></td>
<td>Authenticates inference requests.</td>
<td>The <code>/v1/*</code> endpoints (clients send this as a Bearer token).</td>
</tr>
<tr>
<td><code>secret_key</code></td>
<td>Signs the session cookies for the Admin Dashboard.</td>
<td>The web UI at <code>/admin</code>. Prevents you from being logged out on restart.</td>
</tr>
</tbody></table>
<p><strong>The correct home for these keys is</strong> <code>~/.omlx/settings.json</code><strong>.</strong> While oMLX can read an environment variable (<code>OMLX_API_KEY</code>), putting it in a Homebrew-managed plist is fragile. The next time you run <code>brew upgrade omlx</code>, Homebrew will rewrite the plist and wipe your key, locking you out.</p>
<blockquote>
<p><strong>Prerequisite:</strong> This step requires <code>jq</code>, which you installed in §4.1b.</p>
</blockquote>
<p>Run this block to generate strong cryptographic keys and inject them directly into oMLX's configuration file:</p>
<pre><code class="language-bash"># 1. Generate keys (api_key gets a suffix, secret_key is base hex)
BASE_KEY=$(openssl rand -hex 32)
API_KEY="${BASE_KEY}@81"

# 2. Ensure the directory exists
mkdir -p ~/.omlx

# 3. Inject into settings.json (creating it if missing)
if [ -f ~/.omlx/settings.json ]; then
    jq --arg ak "$API_KEY" --arg sk "$BASE_KEY" \
       '.auth = {api_key: $ak, secret_key: $sk}' \
       ~/.omlx/settings.json &gt; ~/.omlx/settings.json.tmp &amp;&amp; mv ~/.omlx/settings.json.tmp ~/.omlx/settings.json
else
    jq -n --arg ak "$API_KEY" --arg sk "$BASE_KEY" \
       '{auth: {api_key: $ak, secret_key: $sk}}' &gt; ~/.omlx/settings.json
fi

# 4. Lock down file permissions
chmod 600 ~/.omlx/settings.json

# 5. Print the keys so you can save them for QwenPaw
echo "API Key:    $(jq -r '.auth.api_key' ~/.omlx/settings.json)"
echo "Secret Key: $(jq -r '.auth.secret_key' ~/.omlx/settings.json)"
</code></pre>
<p><strong>Expected output:</strong> Two long random strings. Save the <code>API Key</code> (the one ending in <code>@81</code>) — you will need it for QwenPaw in §5.2.</p>
<h3>4.3b Rotating the API Key Later</h3>
<p>If you ever need to change the keys, do not edit <code>settings.json</code> manually or use the admin UI (which might desync your QwenPaw config). Re-run the generation block from §4.3.</p>
<p>Because we are using a custom LaunchDaemon (see §4.4) that does not hardcode the keys in the plist, you simply need to restart oMLX and update QwenPaw:</p>
<pre><code class="language-bash">sudo launchctl kickstart -k system/com.omlx.server
jq -r '.auth.api_key' ~/.omlx/settings.json # Copy this into QwenPaw's config
</code></pre>
<h3>4.4 Start oMLX as an Always-On Background Service</h3>
<p>Because we want oMLX to start at boot (even if the GUI fails), we will run it as a LaunchDaemon. But instead of relying on Homebrew's <code>brew services</code> (which wipes custom env vars on upgrade), we create our own daemon that simply points to the Homebrew binary. oMLX will read the keys directly from <code>settings.json</code>.</p>
<p>First, completely remove the old Homebrew LaunchAgent to prevent port conflicts:</p>
<pre><code class="language-bash">brew services stop omlx 2&gt;/dev/null
launchctl bootout gui/$(id -u)/sh.brew.omlx 2&gt;/dev/null
rm -f ~/Library/LaunchAgents/sh.brew.omlx.plist
</code></pre>
<p>Now create the LaunchDaemon:</p>
<pre><code class="language-bash">USER_NAME=$(whoami)
HOME_DIR=$HOME

sudo tee /Library/LaunchDaemons/com.omlx.server.plist &gt; /dev/null &lt;&lt; EOF
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.omlx.server&lt;/string&gt;
  &lt;key&gt;UserName&lt;/key&gt;
  &lt;string&gt;${USER_NAME}&lt;/string&gt;
  &lt;key&gt;GroupName&lt;/key&gt;
  &lt;string&gt;staff&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;/opt/homebrew/bin/omlx&lt;/string&gt;
    &lt;string&gt;serve&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;WorkingDirectory&lt;/key&gt;
  &lt;string&gt;${HOME_DIR}&lt;/string&gt;
  &lt;key&gt;EnvironmentVariables&lt;/key&gt;
  &lt;dict&gt;
    &lt;key&gt;HOME&lt;/key&gt;
    &lt;string&gt;${HOME_DIR}&lt;/string&gt;
    &lt;key&gt;PATH&lt;/key&gt;
    &lt;string&gt;/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:${HOME_DIR}/.local/bin&lt;/string&gt;
  &lt;/dict&gt;
  &lt;key&gt;StandardOutPath&lt;/key&gt;
  &lt;string&gt;/tmp/omlx.out.log&lt;/string&gt;
  &lt;key&gt;StandardErrorPath&lt;/key&gt;
  &lt;string&gt;/tmp/omlx.err.log&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF

sudo launchctl bootout system/com.omlx.server 2&gt;/dev/null
# Wait for the previous instance to fully unload before reloading
# (prevents `Bootstrap failed: 5: Input/output error` from a SIGTERM race)
for _ in 1 2 3 4 5; do
  sudo launchctl list 2&gt;/dev/null | grep -q "com.omlx.server" || break
  sleep 1
done
sudo launchctl bootstrap system /Library/LaunchDaemons/com.omlx.server.plist
sleep 3
sudo launchctl list | grep omlx
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.omlx.server
</code></pre>
<p>Verify the migration actually landed — no leftover Homebrew state, no legacy plist:</p>
<pre><code class="language-bash"># The three checks below should all print ✅
brew services list | grep -i omlx &amp;&amp; echo "⚠️  brew still tracks omlx" || echo "✅ brew no longer tracks omlx"
[ -f ~/Library/LaunchAgents/sh.brew.omlx.plist ] &amp;&amp; echo "⚠️  legacy plist still exists" || echo "✅ legacy plist removed"
sudo launchctl list | grep -q "com.omlx.server" &amp;&amp; echo "✅ com.omlx.server loaded" || echo "❌ com.omlx.server NOT loaded"
</code></pre>
<p>Confirm the process is listening on port 8000:</p>
<pre><code class="language-bash">lsof -nP -iTCP:8000 -sTCP:LISTEN | tail -1
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">Python  12345  night-thoughts  ...  TCP 127.0.0.1:8000 (LISTEN)
</code></pre>
<blockquote>
<p><strong>A note on process names.</strong> You'll see <code>Python</code> instead of <code>omlx</code> in the <code>lsof</code> output. That's because <code>/opt/homebrew/bin/omlx</code> is a Python shebang script — <code>lsof</code> reports the kernel's process name (the interpreter for shebang scripts), not the <code>argv[0]</code> basename. If you want the actual command name, run <code>ps -p 12345 -o comm,args</code> and you'll see <code>omlx-server</code> with the full path. Same process, different tools, different names. Don't be alarmed.</p>
<p><strong>If</strong> <code>bootstrap</code> <strong>fails with</strong> <code>5: Input/output error</code><strong>:</strong> the previous instance hadn't fully exited when the new plist was loaded. The bounded polling loop above prevents this in normal use. If you hit it anyway, <code>sudo launchctl list | grep omlx</code> will show whether the label is still registered — wait 3 seconds and re-run the <code>bootstrap</code> line.</p>
</blockquote>
<h3>4.4b Upgrading oMLX Later (Homebrew + LaunchDaemon Notice)</h3>
<p>oMLX is installed via Homebrew but runs under <strong>our custom LaunchDaemon</strong> (<code>com.omlx.server</code>), not under <code>brew services</code>. This has an important consequence you must remember every time you upgrade it.</p>
<p><code>brew upgrade omlx</code> does <strong>three</strong> things:</p>
<ol>
<li><p>It downloads and installs the new oMLX release into <code>/opt/homebrew/Cellar/omlx/&lt;new-version&gt;/</code>.</p>
</li>
<li><p>It atomically repoints the stable symlink <code>/opt/homebrew/bin/omlx</code> to the new version.</p>
</li>
<li><p>It <strong>does not</strong> restart your custom LaunchDaemon, and it <strong>does not</strong> touch <code>/Library/LaunchDaemons/com.omlx.server.plist</code>.</p>
</li>
</ol>
<p>So immediately after <code>brew upgrade omlx</code> finishes, the following is true:</p>
<ul>
<li><p><code>sudo launchctl list | grep omlx</code> still shows <code>com.omlx.server</code> running.</p>
</li>
<li><p>Your oMLX API still responds on <code>http://localhost:8000</code>.</p>
</li>
<li><p>But the running process is still executing the <strong>old</strong> binary image from memory.</p>
</li>
<li><p>The new version on disk is <strong>not in use</strong> until launchd restarts the process.</p>
</li>
</ul>
<p>Because our plist points to the symlink <code>/opt/homebrew/bin/omlx</code> (not a versioned Cellar path), the upgrade itself is safe — it will not break the daemon on next start. But you must <strong>manually restart the daemon</strong> for the new version to actually run.</p>
<p><strong>After every</strong> <code>brew upgrade omlx</code><strong>, run:</strong></p>
<pre><code class="language-bash">sudo launchctl kickstart -k system/com.omlx.server
</code></pre>
<p>Then verify that the daemon came back up and the new version is live:</p>
<pre><code class="language-bash">sudo launchctl list | grep omlx
tail -20 /tmp/omlx.err.log
API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)
curl -s -H "Authorization: Bearer $API_KEY" http://localhost:8000/v1/models
</code></pre>
<p>The expected output:</p>
<ul>
<li><p><code>launchctl list</code> shows <code>com.omlx.server</code> with a PID and exit code <code>0</code>.</p>
</li>
<li><p>The error log shows a clean startup with the new version string.</p>
</li>
<li><p>The <code>curl</code> call returns a <code>200</code> JSON body like <code>{"object":"list","data":[...]}</code>, <strong>not</strong> <code>{"detail":"API key required"}</code> or a <code>401</code>.</p>
</li>
</ul>
<p><strong>Do not use</strong> <code>brew services restart omlx</code><strong>.</strong> You removed the Homebrew-managed service in §4.4 on purpose. Using <code>brew services</code> at this point would recreate its own plist, reintroduce port conflicts, and potentially wipe configuration.</p>
<p>If you prefer to combine upgrade and restart in one command:</p>
<pre><code class="language-bash">brew upgrade omlx &amp;&amp; sudo launchctl kickstart -k system/com.omlx.server
</code></pre>
<p>A full reboot also loads the new version (because launchd re-reads the plist and resolves the symlink at boot), but a <code>kickstart</code> is faster and lets you inspect logs immediately.</p>
<h3>4.5 Open the Admin Dashboard</h3>
<p>oMLX binds to <code>http://localhost:8000</code> by default. Open the admin dashboard in your browser:</p>
<pre><code class="language-plaintext">http://localhost:8000/admin
</code></pre>
<blockquote>
<p><strong>Note:</strong> The dashboard lives at <code>/admin</code>, not <code>/</code>. Hitting the root URL returns a 404 by design. Log in using the <code>secret_key</code> you generated in §4.3.</p>
</blockquote>
<h3>4.6 Verify the API Key Works</h3>
<p>Before moving on, confirm the key is accepted:</p>
<pre><code class="language-bash">API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)
curl -s -H "Authorization: Bearer $API_KEY" http://localhost:8000/v1/models
</code></pre>
<p><strong>Expected output:</strong> <code>{"object":"list","data":[]}</code> — an empty list is correct at this stage because no model is loaded yet. The important thing is that you don't see <code>{"detail":"API key required"}</code> or a <code>401</code>.</p>
<h3>4.7 Download &amp; Deploy a Model</h3>
<ol>
<li><p>In the admin dashboard (<code>http://localhost:8000/admin</code>), go to the <strong>Models</strong> section</p>
</li>
<li><p>Search Hugging Face for MLX models (e.g., <code>mlx-community/Qwen3.5-4B-8bit</code>)</p>
</li>
<li><p>Click <strong>Download</strong> — watch the progress bar</p>
</li>
<li><p>Configure per-model settings (sampling parameters, context length, etc.)</p>
</li>
<li><p>Click <strong>Load</strong> to start serving</p>
</li>
</ol>
<p>Verify the model is live:</p>
<pre><code class="language-bash">API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)
curl -s -H "Authorization: Bearer $API_KEY" http://localhost:8000/v1/models
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-json">{"object":"list","data":[{"id":"mlx-community/Qwen3.5-4B-8bit","object":"model"}]}
</code></pre>
<blockquote>
<p><strong>Note:</strong> oMLX provides both OpenAI-compatible (<code>/v1/chat/completions</code>) and Anthropic-compatible (<code>/v1/messages</code>) endpoints. It also supports <code>/v1/embeddings</code>, <code>/v1/rerank</code>, and <code>/v1/responses</code> for broader compatibility.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/2cf4e346-d538-46b3-9247-bcad2487131a.png" alt="oMLX admin dashboard with a model loaded and serving" style="display:block;margin:0 auto" />

<hr />
<h2>Part 5: Install QwenPaw (Agent Framework)</h2>
<p>QwenPaw is a local-first AI agent framework that can connect to your oMLX-served models.</p>
<h3>5.1 Install via One-Line Script</h3>
<p>The installer writes a <code>qwenpaw</code> wrapper to <code>~/.qwenpaw/bin/</code> and adds it to your <code>PATH</code> via <code>~/.zshrc</code>. Because your current shell session hasn't re-read that file yet, the command needs a <code>source ~/.zshrc</code> in between:</p>
<pre><code class="language-bash">curl -fsSL https://qwenpaw.agentscope.io/install.sh | bash &amp;&amp; source ~/.zshrc &amp;&amp; qwenpaw init --defaults
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">[qwenpaw] QwenPaw installed successfully
[qwenpaw] Wrapper created at /Users/&lt;you&gt;/.qwenpaw/bin/qwenpaw
[qwenpaw] Updated /Users/&lt;you&gt;/.zshrc
✅ Configuration initialized at ~/.qwenpaw/config.json
✅ Default model backend configured
</code></pre>
<blockquote>
<p><strong>If you already ran the installer and got</strong> <code>command not found: qwenpaw</code><strong>:</strong> the install itself succeeded — you just need to reload your shell. Run <code>source ~/.zshrc &amp;&amp; qwenpaw init --defaults</code> and continue.</p>
</blockquote>
<p>This script installs QwenPaw into <code>~/.qwenpaw</code> with a self-contained <code>uv</code>-managed Python environment. It automatically installs <code>uv</code>, creates a virtual environment, and downloads dependencies without requiring manual Python setup.</p>
<h3>5.2 Configure QwenPaw to Use oMLX</h3>
<p>Write the QwenPaw config in one command. Note that the <code>api_key</code> here <strong>must match</strong> the <code>api_key</code> in <code>~/.omlx/settings.json</code>:</p>
<pre><code class="language-bash">API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)

cat &gt; ~/.qwenpaw/config.json &lt;&lt; EOF
{
  "model": {
    "backend": "openai",
    "base_url": "http://localhost:8000/v1",
    "api_key": "${API_KEY}",
    "model_name": "mlx-community/Qwen3.5-4B-8bit"
  }
}
EOF
</code></pre>
<blockquote>
<p><strong>If</strong> <code>~/.qwenpaw/config.json</code> <strong>already exists</strong> — for example, if QwenPaw has written preferences or other settings — do <strong>not</strong> overwrite it with this heredoc. Use <code>jq</code> to update just the <code>api_key</code> field:</p>
<pre><code class="language-bash">API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)
jq --arg key "$API_KEY" '.model.api_key = $key' ~/.qwenpaw/config.json &gt; ~/.qwenpaw/config.json.tmp &amp;&amp; mv ~/.qwenpaw/config.json.tmp ~/.qwenpaw/config.json
</code></pre>
</blockquote>
<blockquote>
<p><strong>Path note:</strong> <code>base_url</code> must include the <code>/v1</code> suffix. QwenPaw's OpenAI client appends <code>/models</code>, <code>/chat/completions</code>, etc. after <code>base_url</code>, so a missing <code>/v1</code> sends requests to the wrong paths.</p>
</blockquote>
<h3>5.3 Start QwenPaw</h3>
<pre><code class="language-bash">source ~/.zshrc &amp;&amp; qwenpaw app
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">QwenPaw Console running at http://127.0.0.1:8088/
</code></pre>
<p>Open <code>http://localhost:8088</code> to access the QwenPaw web console.</p>
<h3>5.4 Make QwenPaw Persistent (LaunchDaemon)</h3>
<p>Because QwenPaw is the service you'll rely on most for remote access, we install it as a <strong>LaunchDaemon</strong>. This means it starts at boot, before you log in, and doesn't depend on the desktop GUI starting successfully.</p>
<p>We also pin QwenPaw's internal log rotation to <strong>2 MiB × 2 backups</strong> via <code>EnvironmentVariables</code> so the log directory can never exceed ~6 MiB.</p>
<p>Copy and paste the entire block. It dynamically pulls your current username and home directory to avoid placeholder errors:</p>
<pre><code class="language-bash">USER_NAME=$(whoami)
HOME_DIR=$HOME

sudo tee /Library/LaunchDaemons/com.qwenpaw.app.plist &gt; /dev/null &lt;&lt; EOF
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.qwenpaw.app&lt;/string&gt;
  &lt;key&gt;UserName&lt;/key&gt;
  &lt;string&gt;${USER_NAME}&lt;/string&gt;
  &lt;key&gt;GroupName&lt;/key&gt;
  &lt;string&gt;staff&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;${HOME_DIR}/.qwenpaw/bin/qwenpaw&lt;/string&gt;
    &lt;string&gt;app&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;WorkingDirectory&lt;/key&gt;
  &lt;string&gt;${HOME_DIR}&lt;/string&gt;
  &lt;key&gt;EnvironmentVariables&lt;/key&gt;
  &lt;dict&gt;
    &lt;key&gt;HOME&lt;/key&gt;
    &lt;string&gt;${HOME_DIR}&lt;/string&gt;
    &lt;key&gt;PATH&lt;/key&gt;
    &lt;string&gt;/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:${HOME_DIR}/.local/bin&lt;/string&gt;
    &lt;key&gt;QWENPAW_LOG_MAX_SIZE&lt;/key&gt;
    &lt;string&gt;2MiB&lt;/string&gt;
    &lt;key&gt;QWENPAW_LOG_MAX_BACKUPS&lt;/key&gt;
    &lt;string&gt;2&lt;/string&gt;
  &lt;/dict&gt;
  &lt;key&gt;StandardOutPath&lt;/key&gt;
  &lt;string&gt;/tmp/qwenpaw.out.log&lt;/string&gt;
  &lt;key&gt;StandardErrorPath&lt;/key&gt;
  &lt;string&gt;/tmp/qwenpaw.err.log&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF

sudo launchctl bootout system/com.qwenpaw.app 2&gt;/dev/null
# Wait for the previous instance to fully unload before reloading
for _ in 1 2 3 4 5; do
  sudo launchctl list 2&gt;/dev/null | grep -q "com.qwenpaw.app" || break
  sleep 1
done
sudo launchctl bootstrap system /Library/LaunchDaemons/com.qwenpaw.app.plist
sleep 5
sudo launchctl list | grep qwenpaw
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.qwenpaw.app
</code></pre>
<p>The first column is the PID (a number means it's running), the second is the last exit status (<code>0</code> = clean), and the third is the label.</p>
<p><strong>Useful launcher management commands:</strong></p>
<pre><code class="language-bash">sudo launchctl list | grep qwenpaw                                           # check status
sudo launchctl bootout system/com.qwenpaw.app                                # stop and unregister
sudo launchctl bootstrap system /Library/LaunchDaemons/com.qwenpaw.app.plist # start and register
sudo launchctl kickstart -k system/com.qwenpaw.app                           # restart in place
</code></pre>
<blockquote>
<p><strong>After editing the plist</strong>, you must <code>bootout</code> then <code>bootstrap</code> for changes to take effect — launchd caches the plist at load time. Add the polling loop above between the two commands to avoid the <code>Bootstrap failed: 5</code> race on heavy daemons.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/gql/6a92730f9a9aa7f72e74fdf4/f3ac7a7b-3fd4-48fd-8e72-b138b735fc34.png" alt="QwenPaw web console with an agent conversation open" style="display:block;margin:0 auto" />

<hr />
<h2>Part 6: Verify Everything Survives a Reboot</h2>
<p>Restart your Mac:</p>
<pre><code class="language-bash">sudo reboot
</code></pre>
<p>After reboot, wait 30 seconds, then SSH in from another machine:</p>
<pre><code class="language-bash">ssh your-username@your-mac-ip
</code></pre>
<p>Check all services in one command:</p>
<pre><code class="language-bash">API_KEY=$(jq -r '.auth.api_key' ~/.omlx/settings.json)
sudo launchctl list | grep -E "caddy|omlx|qwenpaw" &amp;&amp; curl -s -H "Authorization: Bearer $API_KEY" http://localhost:8000/v1/models &amp;&amp; curl -s -o /dev/null -w "QwenPaw HTTP %{http_code}\n" http://localhost:8088/
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.caddy.server
12345	0	com.omlx.server
12345	0	com.qwenpaw.app
{"object":"list","data":[...]}
QwenPaw HTTP 200
</code></pre>
<p>All services should return healthy responses without any manual intervention.</p>
<hr />
<h2>Part 7: Remote Access from Anywhere</h2>
<p>This part sets up secure access to both oMLX and QwenPaw from anywhere. <strong>Tailscale</strong> provides encrypted SSH access to your Mac; <strong>Cloudflare Tunnel</strong> provides public HTTPS via your own domain. <strong>Caddy</strong> runs locally as a reverse proxy in front of both services.</p>
<h3>7.0 Create a Tailscale Account</h3>
<p>If you don't already have a Tailscale account, sign up first. It's free for personal use and takes about a minute.</p>
<ol>
<li><p>Go to <a href="https://tailscale.com/">tailscale.com</a> and click <strong>Get Started</strong>.</p>
</li>
<li><p>Sign up using a <strong>single sign-on (SSO) identity provider</strong> — Google, GitHub, Microsoft, Apple, or a custom email address.</p>
</li>
<li><p>After signing in, choose <strong>Personal use</strong>.</p>
</li>
<li><p>You land on the <strong>Admin Console</strong> at <a href="https://console.tailscale.com/admin">console.tailscale.com/admin</a>.</p>
</li>
</ol>
<blockquote>
<p><strong>Tip:</strong> The same account must be used on every device you want on your tailnet.</p>
</blockquote>
<h3>7.1 Install Tailscale on Your Mac Server</h3>
<pre><code class="language-bash">brew install --cask tailscale
</code></pre>
<p><strong>Expected output:</strong> <code>tailscale-app was successfully installed!</code></p>
<p>Open the Tailscale app from your Applications folder or menu bar, and sign in with the same account you just created. Once authenticated, the Tailscale icon appears in your menu bar and shows a green "Connected" status.</p>
<blockquote>
<p><strong>Note:</strong> The <code>--cask</code> version installs the GUI app but does <strong>not</strong> add the <code>tailscale</code> CLI to your <code>$PATH</code>. See §7.1b below to enable it.</p>
</blockquote>
<h3>7.1b Enable the Tailscale CLI</h3>
<p>The cask bundles the CLI inside the app binary. <strong>Do not symlink the app binary</strong> — it crashes with <code>Fatal error: The current bundleIdentifier is unknown to the registry</code>. Instead, add a shell alias:</p>
<pre><code class="language-bash">echo 'alias tailscale="/Applications/Tailscale.app/Contents/MacOS/Tailscale"' &gt;&gt; ~/.zshrc &amp;&amp; source ~/.zshrc &amp;&amp; tailscale status
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">100.x.x.x    my-mac-mini     user@example.com  macOS    -
100.x.x.x    my-laptop       user@example.com  macOS    -
</code></pre>
<h3>7.2 SSH Config for Tailnet Access (No MagicDNS Required)</h3>
<p>MagicDNS is convenient but it isn't always compatible with other DNS setups on your Mac — particularly when Cloudflare is managing a public domain. The fix is a <strong>per-client SSH config file</strong>.</p>
<p><strong>Get the Tailscale IP first</strong> (from the server or any tailnet device):</p>
<pre><code class="language-bash">tailscale status | grep night-thoughts | awk '{print $1}'
</code></pre>
<p><strong>Expected output:</strong> Something like <code>100.64.x.x</code> — the Tailscale IP of your Mac server.</p>
<p><strong>Then, on every client device you SSH from</strong> (not the server itself), append the alias to <code>~/.ssh/config</code>:</p>
<pre><code class="language-bash">mkdir -p ~/.ssh &amp;&amp; cat &gt;&gt; ~/.ssh/config &lt;&lt; 'EOF'

Host nt
    HostName 100.64.x.x
    User your-macos-username
EOF
</code></pre>
<p>Replace:</p>
<ul>
<li><p><code>100.64.x.x</code> with the actual Tailscale IP from above</p>
</li>
<li><p><code>your-macos-username</code> with the account you log in as on the Mac server</p>
</li>
</ul>
<p><strong>Verify:</strong></p>
<pre><code class="language-bash">ssh nt
</code></pre>
<blockquote>
<p><strong>Why not</strong> <code>/etc/hosts</code><strong>?</strong> It requires <code>sudo</code>, breaks on OS updates that re-generate the file, and is global to the machine. <code>~/.ssh/config</code> is scoped to SSH, requires no elevated privileges, and survives system updates.</p>
</blockquote>
<h3>7.2b Remote Desktop Access via Tailscale (Screen Sharing)</h3>
<p>While SSH gives you terminal access, sometimes you need to see the actual macOS desktop—to configure a GUI app, troubleshoot a display issue, or use the Admin Dashboard. macOS has a built-in VNC server (Screen Sharing), and Tailscale provides the secure tunnel to reach it from anywhere without exposing port 5900 to the public internet.</p>
<h4>Step 1: Enable Screen Sharing on the Mac mini</h4>
<ol>
<li>On the Mac mini, open <strong>System Settings → General → Sharing</strong>.</li>
<li>Toggle <strong>Screen Sharing</strong> to <strong>ON</strong>.</li>
<li>Click the <strong>(i)</strong> icon next to Screen Sharing. </li>
<li>Ensure <strong>"VNC viewers may control screen with password"</strong> is checked, and set a strong password. <em>(You will need this password for Windows/Linux clients).</em></li>
<li>Note the <strong>Local hostname</strong> displayed at the top of the Sharing menu (e.g., <code>night-thoughts.local</code>).</li>
</ol>
<h4>Step 2: Connect from macOS (Native)</h4>
<p>If you are connecting from another Mac on your tailnet, Apple's built-in Screen Sharing app is all you need. </p>
<p><strong>Option A: From Finder</strong></p>
<ol>
<li>Press <code>Cmd + K</code> to open "Connect to Server".</li>
<li>Enter your Mac mini's Tailscale IP: <code>vnc://100.x.y.z</code> (replace with your actual Tailscale IP from <code>tailscale status</code>).</li>
<li>If you have MagicDNS enabled, you can use the hostname instead: <code>vnc://night-thoughts.&lt;your-tailnet&gt;.ts.net</code>.</li>
<li>Click <strong>Connect</strong> and enter your macOS login credentials.</li>
</ol>
<p><strong>Option B: From Terminal</strong></p>
<pre><code class="language-bash">open "vnc://100.x.y.z"
</code></pre>
<h4>Step 3: Connect from Windows</h4>
<p>Windows does not have a built-in VNC client, so you need to install one. <strong>RealVNC Viewer</strong> is the most reliable choice.</p>
<ol>
<li>Download and install <strong>RealVNC Viewer</strong> from the official website.</li>
<li>Open RealVNC Viewer and click <strong>File → New connection</strong>.</li>
<li>In the <strong>VNC Server</strong> field, enter your Mac mini's Tailscale IP: <code>100.x.y.z:5900</code> (the <code>:5900</code> is the default VNC port).</li>
<li>Give the connection a friendly name (e.g., "Mac Mini").</li>
<li>Double-click the connection. When prompted, enter the <strong>VNC password</strong> you set in Step 1.</li>
</ol>
<h4>Step 4: Connect from Linux</h4>
<p>Linux users can use <strong>RealVNC Viewer</strong> (same as Windows) or <strong>Remmina</strong> (a popular open-source remote desktop client). </p>
<p><strong>Using Remmina:</strong></p>
<ol>
<li>Install Remmina via your package manager (e.g., <code>sudo apt install remmina remmina-plugin-vnc</code>).</li>
<li>Open Remmina and click the <strong>+</strong> button to create a new profile.</li>
<li>Set <strong>Protocol</strong> to <code>VNC - Virtual Network Computing</code>.</li>
<li>In the <strong>Server</strong> field, enter <code>100.x.y.z:5900</code>.</li>
<li>Enter your <strong>VNC password</strong> and click <strong>Save and Connect</strong>.</li>
</ol>
<h4>⚠️ Headless Mac mini Note</h4>
<p>If your Mac mini has no physical monitor attached, macOS may not generate a virtual display, resulting in a black screen when you connect. To fix this, plug a cheap <strong>HDMI dummy plug</strong> (headless display emulator) into the Mac mini's HDMI port. This tricks macOS into thinking a monitor is attached, forcing it to render the desktop for Screen Sharing.</p>
<blockquote>
<p><strong>Security Note:</strong> VNC traffic itself is not encrypted. However, because both machines are on your Tailscale tailnet, the entire session is wrapped inside the WireGuard tunnel. The connection is safe, and no ports are exposed to the public internet.</p>
</blockquote>
<h3>7.3 Optional: Enable HTTPS Certificates</h3>
<blockquote>
<p><strong>When you need this.</strong> Only if you plan to enable §7.7 (<code>tailscale serve --https=443</code>), which gives HTTPS access to your services over the tailnet. <strong>If you plan to use SSH-only access</strong> — authenticating as your Mac user and running <code>curl</code> on the Mac's loopback — <strong>skip this section.</strong> The commands here are for readers who want HTTPS-over-Tailscale as a convenience.</p>
</blockquote>
<p>Tailscale Serve needs HTTPS certificates enabled for your tailnet before it can terminate TLS on port 443.</p>
<ol>
<li><p>Go to the <a href="https://console.tailscale.com/admin/dns"><strong>DNS page</strong></a> of the Tailscale admin console.</p>
</li>
<li><p>Under the <strong>HTTPS Certificates</strong> section, click <strong>Enable HTTPS</strong>.</p>
</li>
</ol>
<blockquote>
<p><strong>If you enable this and later disable</strong> <code>tailscale serve</code><strong>,</strong> the certificates become inert. You can leave them enabled (harmless) or disable them on the same DNS page. They only matter if a <code>serve --https</code> or <code>funnel</code> rule exists.</p>
</blockquote>
<h3>7.4 Install Caddy</h3>
<p>Caddy is the always-on reverse proxy that routes each service and provides a single entry point. Install it via Homebrew:</p>
<pre><code class="language-bash">brew install caddy
</code></pre>
<p><strong>Expected output:</strong> <code>caddy was successfully installed!</code></p>
<p>Verify:</p>
<pre><code class="language-bash">caddy version
</code></pre>
<p><strong>Expected output:</strong> <code>v2.x.x</code></p>
<h3>7.5 Configure Caddy</h3>
<p>Caddy handles two routing modes at once:</p>
<ol>
<li><p><strong>Subdomain routing</strong> for Cloudflare — <code>omlx.nightthoughts.dev</code> and <code>qwenpaw.nightthoughts.dev</code> each map to their service at the root.</p>
</li>
<li><p><strong>Path routing</strong> for Tailscale Serve (only if you enable §7.7) — a single hostname (<code>night-thoughts.&lt;your-tailnet&gt;.ts.net</code>) with <code>/omlx/*</code> and <code>/console/*</code> prefixes.</p>
</li>
</ol>
<pre><code class="language-bash">sudo mkdir -p /opt/homebrew/etc &amp;&amp; sudo tee /opt/homebrew/etc/Caddyfile &gt; /dev/null &lt;&lt; 'EOF'
# ── Cloudflare subdomains (plain HTTP, tunnel forwards here) ──
http://omlx.nightthoughts.dev:9080 {
    # Paths oMLX actually owns — pass through to the backend
    @known path /admin /admin/* /v1 /v1/* /static/* /health /favicon.ico
    handle @known {
        reverse_proxy localhost:8000
    }

    # Root and any unmatched path → redirect to the dashboard
    handle {
        redir * /admin 302
    }
}

http://qwenpaw.nightthoughts.dev:9080 {
    reverse_proxy localhost:8088
}

# ── Tailscale Serve target (path-based, single hostname) ──────
# NOTE: This block is only used if you enable §7.7 (Tailscale Serve).
# If you're using SSH-only access, this block is dead code — you can
# safely remove it.
:9080 {
    # oMLX entry point
    @omlx_bare path /omlx
    redir @omlx_bare /omlx/admin 302

    handle_path /omlx/* {
        reverse_proxy localhost:8000
    }

    # oMLX absolute paths (dashboard + assets + API)
    @omlx_absolute path /admin /admin/* /static/* /v1 /v1/* /health
    handle @omlx_absolute {
        reverse_proxy localhost:8000
    }

    # QwenPaw: full console + backend
    @qwenpaw path /console/* /api/* /assets/* /login /logout /voice/* /favicon.ico
    handle @qwenpaw {
        reverse_proxy localhost:8088
    }

    # QwenPaw: public files (SVG, PNG) at root
    @qwenpaw_public path_regexp \.(svg|png|ico|gif|jpg|jpeg|webp|woff|woff2|ttf|eot)$
    handle @qwenpaw_public {
        reverse_proxy localhost:8088
    }

    # Fallback: oMLX
    handle {
        reverse_proxy localhost:8000
    }
}
EOF
</code></pre>
<blockquote>
<p><strong>Why both blocks?</strong> The subdomain blocks (<code>http://omlx.nightthoughts.dev:9080</code>) only match requests where the <code>Host</code> header is that subdomain — which is what Cloudflare sends. The <code>:9080</code> block catches everything else, which is what Tailscale Serve sends.</p>
</blockquote>
<blockquote>
<p><strong>The</strong> <code>:9080</code> <strong>block is conditional.</strong> Its only purpose is to serve <code>tailscale serve</code> in §7.7. If you skip §7.7 (SSH-only), this block receives no traffic — the two subdomain blocks alone handle Cloudflare. Keeping it is harmless; removing it is cleaner if you know you're going SSH-only.</p>
</blockquote>
<blockquote>
<p><strong>Why</strong> <code>http://</code> <strong>on the subdomains?</strong> Without it, Caddy would try to provision its own TLS certificate for <code>omlx.nightthoughts.dev</code>, which fails because Cloudflare already holds one for that hostname and Caddy can't complete the ACME challenge. The <code>http://</code> prefix tells Caddy to serve that hostname over plain HTTP only.</p>
</blockquote>
<blockquote>
<p><strong>The</strong> <code>*</code> <strong>matcher in</strong> <code>redir * /admin 302</code> <strong>is essential.</strong> Caddy's <code>redir</code> directive is ambiguous when the destination starts with <code>/</code>: without an explicit matcher, Caddy can interpret <code>/admin</code> as a <strong>path matcher</strong> rather than the destination.</p>
</blockquote>
<p>Verify the syntax:</p>
<pre><code class="language-bash">caddy validate --config /opt/homebrew/etc/Caddyfile
</code></pre>
<p><strong>Expected output:</strong> <code>Valid configuration</code></p>
<h3>7.6 Start Caddy as an Always-On Service</h3>
<p>To ensure Caddy starts at boot—even if the desktop session fails to load—we will run it as a LaunchDaemon. Just like we did for oMLX, we stop the Homebrew service, remove its plist, and create our own system-level daemon.</p>
<p>First, completely remove the old Homebrew LaunchAgent to prevent port conflicts:</p>
<pre><code class="language-bash">brew services stop caddy 2&gt;/dev/null
launchctl bootout gui/$(id -u)/homebrew.mxcl.caddy 2&gt;/dev/null
rm -f ~/Library/LaunchAgents/homebrew.mxcl.caddy.plist
</code></pre>
<p>Now create the LaunchDaemon:</p>
<pre><code class="language-bash">USER_NAME=$(whoami)
HOME_DIR=$HOME

sudo tee /Library/LaunchDaemons/com.caddy.server.plist &gt; /dev/null &lt;&lt; EOF
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.caddy.server&lt;/string&gt;
  &lt;key&gt;UserName&lt;/key&gt;
  &lt;string&gt;${USER_NAME}&lt;/string&gt;
  &lt;key&gt;GroupName&lt;/key&gt;
  &lt;string&gt;staff&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;/opt/homebrew/bin/caddy&lt;/string&gt;
    &lt;string&gt;run&lt;/string&gt;
    &lt;string&gt;--config&lt;/string&gt;
    &lt;string&gt;/opt/homebrew/etc/Caddyfile&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;WorkingDirectory&lt;/key&gt;
  &lt;string&gt;${HOME_DIR}&lt;/string&gt;
  &lt;key&gt;EnvironmentVariables&lt;/key&gt;
  &lt;dict&gt;
    &lt;key&gt;HOME&lt;/key&gt;
    &lt;string&gt;${HOME_DIR}&lt;/string&gt;
    &lt;key&gt;PATH&lt;/key&gt;
    &lt;string&gt;/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:${HOME_DIR}/.local/bin&lt;/string&gt;
  &lt;/dict&gt;
  &lt;key&gt;StandardOutPath&lt;/key&gt;
  &lt;string&gt;/tmp/caddy.out.log&lt;/string&gt;
  &lt;key&gt;StandardErrorPath&lt;/key&gt;
  &lt;string&gt;/tmp/caddy.err.log&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF

sudo launchctl bootout system/com.caddy.server 2&gt;/dev/null
# Wait for the previous instance to fully unload before reloading
for _ in 1 2 3 4 5; do
  sudo launchctl list 2&gt;/dev/null | grep -q "com.caddy.server" || break
  sleep 1
done
sudo launchctl bootstrap system /Library/LaunchDaemons/com.caddy.server.plist
sleep 3
sudo launchctl list | grep caddy
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.caddy.server
</code></pre>
<p>Verify the migration actually landed:</p>
<pre><code class="language-bash">brew services list | grep -i caddy &amp;&amp; echo "⚠️  brew still tracks caddy" || echo "✅ brew no longer tracks caddy"
[ -f ~/Library/LaunchAgents/homebrew.mxcl.caddy.plist ] &amp;&amp; echo "⚠️  legacy plist still exists" || echo "✅ legacy plist removed"
sudo launchctl list | grep -q "com.caddy.server" &amp;&amp; echo "✅ com.caddy.server loaded" || echo "❌ com.caddy.server NOT loaded"
</code></pre>
<p>Confirm it's listening on port 9080:</p>
<pre><code class="language-bash">lsof -nP -iTCP:9080 -sTCP:LISTEN | tail -1
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">caddy   12345    yourname    ...  TCP *:9080 (LISTEN)
</code></pre>
<blockquote>
<p><strong>After editing the Caddyfile</strong>, you must reload Caddy with <code>sudo launchctl kickstart -k system/com.caddy.server</code>. The <code>kickstart -k</code> restarts the process with the new config file — you do <strong>not</strong> need <code>bootout</code> + <code>bootstrap</code> here because only an external file (the Caddyfile) changed, not the plist.</p>
<p><strong>If</strong> <code>bootstrap</code> <strong>fails with</strong> <code>5: Input/output error</code><strong>:</strong> same race as §4.4 — wait 3 seconds and re-run the <code>bootstrap</code> line, or re-run the whole block (the polling loop will handle it).</p>
</blockquote>
<h3>7.6b Upgrading Caddy Later (Homebrew + LaunchDaemon Notice)</h3>
<p>Caddy is installed via Homebrew but runs under <strong>our custom LaunchDaemon</strong> (<code>com.caddy.server</code>), not under <code>brew services</code>. This has an important consequence you must remember every time you upgrade it.</p>
<p><code>brew upgrade caddy</code> does <strong>three</strong> things:</p>
<ol>
<li><p>It downloads and installs the new Caddy release into <code>/opt/homebrew/Cellar/caddy/&lt;new-version&gt;/</code>.</p>
</li>
<li><p>It atomically repoints the stable symlink <code>/opt/homebrew/bin/caddy</code> to the new version.</p>
</li>
<li><p>It <strong>does not</strong> restart your custom LaunchDaemon, and it <strong>does not</strong> touch <code>/Library/LaunchDaemons/com.caddy.server.plist</code>.</p>
</li>
</ol>
<p>So immediately after <code>brew upgrade caddy</code> finishes, the following is true:</p>
<ul>
<li><p><code>sudo launchctl list | grep caddy</code> still shows <code>com.caddy.server</code> running.</p>
</li>
<li><p>Your sites (<code>omlx.nightthoughts.dev</code>, <code>qwenpaw.nightthoughts.dev</code>, Tailscale Serve) continue to serve traffic without interruption.</p>
</li>
<li><p>But the running process is still executing the <strong>old</strong> binary image from memory.</p>
</li>
<li><p>The new version on disk is <strong>not in use</strong> until launchd restarts the process.</p>
</li>
</ul>
<p>Because our plist points to the symlink <code>/opt/homebrew/bin/caddy</code> (not a versioned Cellar path), the upgrade itself is safe — it will not break the daemon on next start. But you must <strong>manually restart the daemon</strong> for the new version to actually run.</p>
<p>Unlike oMLX, Caddy has one extra risk: a new major/minor release may reject Caddyfile syntax that the previous version accepted. Always validate the config before restarting the daemon.</p>
<p><strong>After every</strong> <code>brew upgrade caddy</code><strong>, run:</strong></p>
<pre><code class="language-bash">caddy validate --config /opt/homebrew/etc/Caddyfile
sudo launchctl kickstart -k system/com.caddy.server
</code></pre>
<p>Then verify that the daemon came back up, is listening on port 9080, and is serving traffic:</p>
<pre><code class="language-bash">sudo launchctl list | grep caddy
lsof -i :9080 | grep caddy
tail -20 /tmp/caddy.err.log
curl -s -o /dev/null -w "Local → HTTP %{http_code}\n" http://localhost:9080/
</code></pre>
<p>The expected output:</p>
<ul>
<li><p><code>launchctl list</code> shows <code>com.caddy.server</code> with a PID and exit code <code>0</code>.</p>
</li>
<li><p><code>lsof</code> shows Caddy listening on <code>*:9080</code>.</p>
</li>
<li><p>The error log contains no <code>loading Caddyfile</code> errors.</p>
</li>
<li><p>The local <code>curl</code> returns a non-<code>502</code> status (typically <code>302</code> for the oMLX redirect, or <code>200</code> for a proxied request).</p>
</li>
</ul>
<p><strong>Do not use</strong> <code>brew services restart caddy</code><strong>.</strong> You removed the Homebrew-managed service in §7.6 on purpose. Using <code>brew services</code> would recreate its own plist, reintroduce port conflicts on 9080, and potentially overwrite your Caddyfile configuration path.</p>
<p>If you prefer to combine validation, upgrade, and restart in one chain:</p>
<pre><code class="language-bash">caddy validate --config /opt/homebrew/etc/Caddyfile \
  &amp;&amp; brew upgrade caddy \
  &amp;&amp; caddy validate --config /opt/homebrew/etc/Caddyfile \
  &amp;&amp; sudo launchctl kickstart -k system/com.caddy.server
</code></pre>
<p>The first <code>validate</code> runs against the currently installed version, so if the existing config is already broken you catch that before you touch the package. The second <code>validate</code> runs against the newly installed version.</p>
<p>A full reboot also loads the new version (because launchd re-reads the plist and resolves the symlink at boot), but a <code>kickstart</code> is faster and lets you inspect logs immediately.</p>
<h3>7.7 Optional: Point Tailscale Serve at Caddy (Convenience — Bypasses Auth)</h3>
<blockquote>
<p><strong>Security note.</strong> This step gives you HTTPS access to your services over your tailnet by <strong>bypassing Caddy entirely</strong>. Anyone on your tailnet — verified at the WireGuard layer, not by any password — can reach <code>https://&lt;hostname&gt;.&lt;tailnet&gt;.ts.net/</code> without going through Caddy's <code>basicauth</code> or the upstream service's own auth. This is fine if your tailnet contains only devices you personally own. If your tailnet contains shared devices, family machines, or other users, <strong>skip this section</strong> and use <code>ssh nt 'curl http://127.0.0.1:...'</code> to reach services instead.</p>
<p><strong>DNS note.</strong> Some users have seen MagicDNS conflict with Cloudflare-managed DNS on the local machine — <code>dig</code> resolves fine but <code>curl</code> returns <code>Could not resolve host</code>. If that happens, run <code>tailscale set --accept-dns=false</code> and flush the resolver:</p>
<pre><code class="language-bash">tailscale set --accept-dns=false
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
</code></pre>
<p>If you enable this step now and decide to go SSH-only later, disable it with <code>tailscale serve reset</code> and remove the <code>:9080</code> block from the Caddyfile (§7.5).</p>
</blockquote>
<p>Tailscale Serve exposes your services to devices on your tailnet — encrypted, private, and without requiring a public domain.</p>
<pre><code class="language-bash">tailscale serve reset
tailscale serve --bg --https=443 http://localhost:9080
</code></pre>
<p>Verify:</p>
<pre><code class="language-bash">tailscale serve status
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">https://night-thoughts.&lt;your-tailnet&gt;.ts.net (tailnet only)
|-- / proxy http://localhost:9080
</code></pre>
<blockquote>
<p><strong>Important — Tailscale DNS hijack:</strong> If <code>dig</code> resolves your Cloudflare subdomains but <code>curl</code> from the server returns <code>Could not resolve host</code>, Tailscale's MagicDNS resolver is capturing all system DNS queries. Fix it with:</p>
<pre><code class="language-bash">tailscale set --accept-dns=false
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
</code></pre>
</blockquote>
<h3>7.8 Enable QwenPaw Authentication</h3>
<p>Tailscale controls network-level access, but <strong>anyone on your tailnet — and anyone on the internet once §7.9 is set up — can reach QwenPaw</strong>. Enabling QwenPaw's built-in web authentication adds a login prompt.</p>
<p>Rewrite the plist with the auth variables added, then reload the service. Replace <code>your-secure-password</code> with a strong password of your choice:</p>
<pre><code class="language-bash">USER_NAME=$(whoami)
HOME_DIR=$HOME

sudo launchctl bootout system/com.qwenpaw.app 2&gt;/dev/null
# Wait for the previous instance to fully unload before reloading
for _ in 1 2 3 4 5; do
  sudo launchctl list 2&gt;/dev/null | grep -q "com.qwenpaw.app" || break
  sleep 1
done

sudo tee /Library/LaunchDaemons/com.qwenpaw.app.plist &gt; /dev/null &lt;&lt; EOF
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.qwenpaw.app&lt;/string&gt;
  &lt;key&gt;UserName&lt;/key&gt;
  &lt;string&gt;${USER_NAME}&lt;/string&gt;
  &lt;key&gt;GroupName&lt;/key&gt;
  &lt;string&gt;staff&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;${HOME_DIR}/.qwenpaw/bin/qwenpaw&lt;/string&gt;
    &lt;string&gt;app&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;WorkingDirectory&lt;/key&gt;
  &lt;string&gt;${HOME_DIR}&lt;/string&gt;
  &lt;key&gt;EnvironmentVariables&lt;/key&gt;
  &lt;dict&gt;
    &lt;key&gt;HOME&lt;/key&gt;
    &lt;string&gt;${HOME_DIR}&lt;/string&gt;
    &lt;key&gt;PATH&lt;/key&gt;
    &lt;string&gt;/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:${HOME_DIR}/.local/bin&lt;/string&gt;
    &lt;key&gt;QWENPAW_LOG_MAX_SIZE&lt;/key&gt;
    &lt;string&gt;2MiB&lt;/string&gt;
    &lt;key&gt;QWENPAW_LOG_MAX_BACKUPS&lt;/key&gt;
    &lt;string&gt;2&lt;/string&gt;
    &lt;key&gt;QWENPAW_AUTH_ENABLED&lt;/key&gt;
    &lt;string&gt;true&lt;/string&gt;
    &lt;key&gt;QWENPAW_AUTH_USERNAME&lt;/key&gt;
    &lt;string&gt;admin&lt;/string&gt;
    &lt;key&gt;QWENPAW_AUTH_PASSWORD&lt;/key&gt;
    &lt;string&gt;your-secure-password&lt;/string&gt;
  &lt;/dict&gt;
  &lt;key&gt;StandardOutPath&lt;/key&gt;
  &lt;string&gt;/tmp/qwenpaw.out.log&lt;/string&gt;
  &lt;key&gt;StandardErrorPath&lt;/key&gt;
  &lt;string&gt;/tmp/qwenpaw.err.log&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF

sudo launchctl bootstrap system /Library/LaunchDaemons/com.qwenpaw.app.plist
sleep 3
sudo launchctl list | grep qwenpaw
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.qwenpaw.app
</code></pre>
<p>Verify auth is active by checking that the console redirects to a login page:</p>
<pre><code class="language-bash">curl -s -o /dev/null -w "QwenPaw HTTP %{http_code}\n" http://localhost:8088/
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">QwenPaw HTTP 200
</code></pre>
<blockquote>
<p><strong>Forgot the password?</strong> Reset it with:</p>
<pre><code class="language-bash">QWENPAW_AUTH_ENABLED=true qwenpaw auth reset-password
</code></pre>
</blockquote>
<h3>7.9 Public Access with Subdomains</h3>
<p>This section extends your setup from tailnet-only access to the public internet. After completing these steps, your services become reachable from any browser — no Tailscale client required — using subdomains on your own domain.</p>
<p>The result:</p>
<table>
<thead>
<tr>
<th>Service</th>
<th>Public URL</th>
</tr>
</thead>
<tbody><tr>
<td><strong>oMLX admin dashboard</strong></td>
<td><code>https://omlx.nightthoughts.dev/admin</code></td>
</tr>
<tr>
<td><strong>oMLX API</strong></td>
<td><code>https://omlx.nightthoughts.dev/v1/models</code></td>
</tr>
<tr>
<td><strong>QwenPaw web console</strong></td>
<td><code>https://qwenpaw.nightthoughts.dev/</code></td>
</tr>
</tbody></table>
<blockquote>
<p><strong>Security warning:</strong> These URLs are reachable by <strong>anyone on the internet</strong>. You <strong>must</strong> have authentication enabled on both services before exposing them publicly.</p>
</blockquote>
<p><strong>Step 1: Add your domain to Cloudflare</strong></p>
<ol>
<li><p>Sign up at <a href="https://cloudflare.com">cloudflare.com</a> (free tier is enough).</p>
</li>
<li><p>Click <strong>Add a site</strong> and enter <code>nightthoughts.dev</code>.</p>
</li>
<li><p>Choose the <strong>Free</strong> plan.</p>
</li>
<li><p>Cloudflare will scan your existing DNS records and display <strong>two nameservers</strong> assigned to your account.</p>
</li>
</ol>
<p><strong>Step 2: Point the domain to Cloudflare at your registrar</strong></p>
<p>Cloudflare needs to be the authoritative DNS provider for your domain. This means replacing your registrar's default nameservers with the two Cloudflare nameservers shown in Step 1.</p>
<p>The process is the same for every registrar:</p>
<ol>
<li><p>Log in to your registrar account and find the DNS or nameserver settings for <code>nightthoughts.dev</code>.</p>
</li>
<li><p>Locate the current nameservers.</p>
</li>
<li><p><strong>Delete</strong> them.</p>
</li>
<li><p><strong>Paste</strong> the two Cloudflare nameservers.</p>
</li>
<li><p><strong>Save</strong> your changes.</p>
</li>
</ol>
<blockquote>
<p><strong>Important:</strong> If DNSSEC is enabled at your registrar, disable it before changing nameservers. DNSSEC conflicts with the new authoritative DNS provider.</p>
</blockquote>
<p><strong>Verify propagation</strong></p>
<p>After saving, check that the new nameservers are live:</p>
<pre><code class="language-bash">dig +short NS nightthoughts.dev @1.1.1.1
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">april.ns.cloudflare.com.
damien.ns.cloudflare.com.
</code></pre>
<p><strong>Step 3: Install cloudflared</strong></p>
<pre><code class="language-bash">brew install cloudflared
</code></pre>
<p><strong>Step 4: Authenticate</strong></p>
<pre><code class="language-bash">cloudflared tunnel login
</code></pre>
<p>This opens a browser — select <code>nightthoughts.dev</code> and authorize.</p>
<p><strong>Step 5: Create the tunnel</strong></p>
<pre><code class="language-bash">cloudflared tunnel list | grep -q night-thoughts || cloudflared tunnel create night-thoughts
</code></pre>
<p><strong>Step 6: Route DNS for both subdomains</strong></p>
<pre><code class="language-bash">cloudflared tunnel route dns night-thoughts omlx.nightthoughts.dev
cloudflared tunnel route dns night-thoughts qwenpaw.nightthoughts.dev
</code></pre>
<p>Each command creates a <strong>proxied CNAME</strong> at Cloudflare pointing the subdomain to your tunnel.</p>
<p><strong>Step 7: Configure the tunnel</strong></p>
<pre><code class="language-bash">TUNNEL_ID=$(cloudflared tunnel list | awk '/night-thoughts/ {print $1}') &amp;&amp; \
cat &gt; ~/.cloudflared/config.yml &lt;&lt; EOF
tunnel: $TUNNEL_ID
credentials-file: $HOME/.cloudflared/$TUNNEL_ID.json

ingress:
  - hostname: omlx.nightthoughts.dev
    service: http://localhost:9080
  - hostname: qwenpaw.nightthoughts.dev
    service: http://localhost:9080
  - service: http_status:404
EOF
</code></pre>
<p><strong>Step 8: Install the tunnel as a LaunchDaemon</strong></p>
<blockquote>
<p><strong>Do not use</strong> <code>sudo cloudflared service install</code> <strong>on macOS.</strong> It writes a broken launchd plist that omits the <code>tunnel run</code> subcommand, so the daemon exits immediately with <code>use cloudflared tunnel run to start tunnel &lt;UUID&gt;</code> in a loop.</p>
</blockquote>
<p>Just like QwenPaw, cloudflared should be a LaunchDaemon so it starts at boot, before login. This block dynamically injects your username and home path. It also sets <code>WorkingDirectory</code> and <code>EnvironmentVariables</code> to match the other three LaunchDaemons in this guide — <code>HOME</code> makes the <code>~/.cloudflared/config.yml</code> resolution deterministic (Go's <code>os.UserHomeDir()</code> falls back to <code>getpwuid</code> when <code>$HOME</code> is unset, but making it explicit removes the ambiguity), and <code>PATH</code> is included for consistency with the <code>omlx</code> / <code>qwenpaw</code> / <code>caddy</code> plists even though cloudflared doesn't spawn subprocesses:</p>
<pre><code class="language-bash">USER_NAME=$(whoami)
HOME_DIR=$HOME

sudo tee /Library/LaunchDaemons/com.cloudflare.cloudflared.plist &gt; /dev/null &lt;&lt; EOF
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
  &lt;key&gt;Label&lt;/key&gt;
  &lt;string&gt;com.cloudflare.cloudflared&lt;/string&gt;
  &lt;key&gt;UserName&lt;/key&gt;
  &lt;string&gt;${USER_NAME}&lt;/string&gt;
  &lt;key&gt;GroupName&lt;/key&gt;
  &lt;string&gt;staff&lt;/string&gt;
  &lt;key&gt;ProgramArguments&lt;/key&gt;
  &lt;array&gt;
    &lt;string&gt;/opt/homebrew/bin/cloudflared&lt;/string&gt;
    &lt;string&gt;tunnel&lt;/string&gt;
    &lt;string&gt;run&lt;/string&gt;
  &lt;/array&gt;
  &lt;key&gt;RunAtLoad&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;KeepAlive&lt;/key&gt;
  &lt;true/&gt;
  &lt;key&gt;WorkingDirectory&lt;/key&gt;
  &lt;string&gt;${HOME_DIR}&lt;/string&gt;
  &lt;key&gt;EnvironmentVariables&lt;/key&gt;
  &lt;dict&gt;
    &lt;key&gt;HOME&lt;/key&gt;
    &lt;string&gt;${HOME_DIR}&lt;/string&gt;
    &lt;key&gt;PATH&lt;/key&gt;
    &lt;string&gt;/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:${HOME_DIR}/.local/bin&lt;/string&gt;
  &lt;/dict&gt;
  &lt;key&gt;StandardOutPath&lt;/key&gt;
  &lt;string&gt;/tmp/cloudflared.out.log&lt;/string&gt;
  &lt;key&gt;StandardErrorPath&lt;/key&gt;
  &lt;string&gt;/tmp/cloudflared.err.log&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
EOF

sudo launchctl bootout system/com.cloudflare.cloudflared 2&gt;/dev/null
# Wait for the previous instance to fully unload before reloading
for _ in 1 2 3 4 5; do
  sudo launchctl list 2&gt;/dev/null | grep -q "com.cloudflare.cloudflared" || break
  sleep 1
done
sudo launchctl bootstrap system /Library/LaunchDaemons/com.cloudflare.cloudflared.plist
sleep 5
sudo launchctl list | grep cloudflared
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.cloudflare.cloudflared
</code></pre>
<blockquote>
<p><strong>Already running an older cloudflared plist?</strong> If you ran Part 0 before this version, your existing plist lacks <code>WorkingDirectory</code> and <code>EnvironmentVariables</code>. The <code>bootout</code> + <code>bootstrap</code> above replaces it wholesale — the <code>tee</code> overwrites the file, then launchd re-reads it. Confirm with <code>sudo plutil -p /Library/LaunchDaemons/com.cloudflare.cloudflared.plist | grep -A2 WorkingDirectory</code> — you should see <code>"/Users/&lt;you&gt;"</code>. If it's missing, the <code>tee</code> failed (usually a permissions issue; re-run with the <code>sudo</code> at the start).</p>
</blockquote>
<p><strong>Step 8b: Upgrading cloudflared Later (Homebrew + LaunchDaemon Notice)</strong></p>
<p>cloudflared is installed via Homebrew but runs under <strong>our custom LaunchDaemon</strong> (<code>com.cloudflare.cloudflared</code>), not under <code>brew services</code> (which is not used for it in this guide at all). This has an important consequence you must remember every time you upgrade it.</p>
<p><code>brew upgrade cloudflared</code> does <strong>three</strong> things:</p>
<ol>
<li><p>It downloads and installs the new cloudflared release into <code>/opt/homebrew/Cellar/cloudflared/&lt;new-version&gt;/</code>.</p>
</li>
<li><p>It atomically repoints the stable symlink <code>/opt/homebrew/bin/cloudflared</code> to the new version.</p>
</li>
<li><p>It <strong>does not</strong> restart your custom LaunchDaemon, and it <strong>does not</strong> touch <code>/Library/LaunchDaemons/com.cloudflare.cloudflared.plist</code>.</p>
</li>
</ol>
<p>So immediately after <code>brew upgrade cloudflared</code> finishes, the following is true:</p>
<ul>
<li><p><code>sudo launchctl list | grep cloudflared</code> still shows <code>com.cloudflare.cloudflared</code> running.</p>
</li>
<li><p>Your public tunnels for <code>omlx.nightthoughts.dev</code> and <code>qwenpaw.nightthoughts.dev</code> continue to work.</p>
</li>
<li><p>But the running process is still executing the <strong>old</strong> binary image from memory.</p>
</li>
<li><p>The new version on disk is <strong>not in use</strong> until launchd restarts the process.</p>
</li>
</ul>
<p>Because our plist points to the symlink <code>/opt/homebrew/bin/cloudflared</code> (not a versioned Cellar path), the upgrade itself is safe — it will not break the tunnel on next start. But you must <strong>manually restart the daemon</strong> for the new version to actually run.</p>
<p><strong>After every</strong> <code>brew upgrade cloudflared</code><strong>, run:</strong></p>
<pre><code class="language-bash">sudo launchctl kickstart -k system/com.cloudflare.cloudflared
</code></pre>
<p>Then verify that the daemon came back up and that both tunnel connections re-registered:</p>
<pre><code class="language-bash">sudo launchctl list | grep cloudflared
sleep 10
tail -30 /tmp/cloudflared.err.log
</code></pre>
<p>The expected output:</p>
<ul>
<li><p><code>launchctl list</code> shows <code>com.cloudflare.cloudflared</code> with a PID and exit code <code>0</code>.</p>
</li>
<li><p>The log shows a fresh health precheck and at least two <code>Registered tunnel connection connIndex=...</code> lines (typically <code>connIndex=0</code> and <code>connIndex=1</code>).</p>
</li>
<li><p>No repeating <code>use cloudflared tunnel run to start tunnel &lt;UUID&gt;</code> loop, and no <code>failed to connect</code> errors.</p>
</li>
</ul>
<p><strong>Do not use</strong> <code>sudo cloudflared service install</code><strong>.</strong> As noted in Step 8, it writes a broken macOS plist that omits the <code>tunnel run</code> subcommand. Sticking with your custom LaunchDaemon is the correct upgrade path.</p>
<p>If you prefer to combine upgrade and restart in one command:</p>
<pre><code class="language-bash">brew upgrade cloudflared &amp;&amp; sudo launchctl kickstart -k system/com.cloudflare.cloudflared
</code></pre>
<p>A full reboot also loads the new version (because launchd re-reads the plist and resolves the symlink at boot), but a <code>kickstart</code> is faster and lets you inspect tunnel logs immediately.</p>
<p><strong>Step 9: Verify</strong></p>
<p>Now check the log to confirm the tunnel is actually connected:</p>
<pre><code class="language-bash">tail -20 /tmp/cloudflared.err.log
</code></pre>
<p><strong>Expected output:</strong> A health precheck summary followed by connection logs:</p>
<pre><code class="language-plaintext">INF |  SUMMARY: Environment is healthy. cloudflared will use 'quic' as primary protocol.  |
INF precheck complete hard_fail=false run_id=... suggested_protocol=quic
INF Registered tunnel connection connIndex=0 connection=... location=hkg
INF Registered tunnel connection connIndex=1 connection=... location=hkg
</code></pre>
<p>Then test publicly. The first test checks that unmatched paths redirect properly:</p>
<pre><code class="language-bash">curl -sL -o /dev/null -w "/typo → %{http_code} %{url_effective}\n" https://omlx.nightthoughts.dev/typo
curl -s -o /dev/null -w "/ → %{http_code}\n" https://omlx.nightthoughts.dev/
curl -s -o /dev/null -w "/admin → %{http_code}\n" https://omlx.nightthoughts.dev/admin
curl -s -o /dev/null -w "/v1/models → %{http_code}\n" https://omlx.nightthoughts.dev/v1/models
curl -s -o /dev/null -w "QwenPaw / → %{http_code}\n" https://qwenpaw.nightthoughts.dev/
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">/typo → 200 https://omlx.nightthoughts.dev/admin
/ → 302
/admin → 200
/v1/models → 401    (no key sent)
QwenPaw / → 200
</code></pre>
<p><strong>Useful commands:</strong></p>
<pre><code class="language-bash"># Check tunnel status
sudo launchctl list | grep cloudflared

# View cloudflared logs
tail -20 /tmp/cloudflared.err.log

# Restart the tunnel after config changes
sudo launchctl kickstart -k system/com.cloudflare.cloudflared

# Remove the tunnel entirely
sudo launchctl bootout system/com.cloudflare.cloudflared
sudo rm /Library/LaunchDaemons/com.cloudflare.cloudflared.plist
cloudflared tunnel delete night-thoughts
</code></pre>
<h3>7.10 Verify Everything Survives Reboot</h3>
<p>Restart your Mac:</p>
<pre><code class="language-bash">sudo reboot
</code></pre>
<p>After reboot, wait 30 seconds, then SSH in from another machine:</p>
<pre><code class="language-bash">ssh nt
</code></pre>
<p>Check all services in one command:</p>
<pre><code class="language-bash">sudo launchctl list | grep -E "caddy|omlx|qwenpaw|cloudflared" &amp;&amp; tailscale serve status
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code class="language-plaintext">12345	0	com.caddy.server
12345	0	com.omlx.server
12345	0	com.qwenpaw.app
12345	0	com.cloudflare.cloudflared
https://night-thoughts.&lt;your-tailnet&gt;.ts.net (tailnet only)
|-- / proxy http://localhost:9080
</code></pre>
<blockquote>
<p><strong>If you skipped §7.7 (SSH-only),</strong> <code>tailscale serve status</code> will print nothing. That's expected. Verify SSH-only access instead:</p>
<pre><code class="language-bash">ssh nt 'curl -s -o /dev/null -w "oMLX: %{http_code}\n" http://127.0.0.1:8000/v1/models'
</code></pre>
</blockquote>
<p>All components should be running without any manual intervention:</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Managed by</th>
<th>Domain</th>
<th>Auto-starts on login?</th>
<th>Auto-starts at boot?</th>
</tr>
</thead>
<tbody><tr>
<td><strong>oMLX</strong></td>
<td><code>launchd</code></td>
<td><strong>System</strong></td>
<td>✅</td>
<td><strong>✅</strong></td>
</tr>
<tr>
<td><strong>Caddy</strong></td>
<td><code>launchd</code></td>
<td><strong>System</strong></td>
<td>✅</td>
<td><strong>✅</strong></td>
</tr>
<tr>
<td><strong>QwenPaw</strong></td>
<td><code>launchd</code></td>
<td><strong>System</strong></td>
<td>✅</td>
<td><strong>✅</strong></td>
</tr>
<tr>
<td><strong>cloudflared</strong></td>
<td><code>launchd</code></td>
<td><strong>System</strong></td>
<td>✅</td>
<td><strong>✅</strong></td>
</tr>
<tr>
<td><strong>Tailscale Serve</strong> <em>(§7.7 only)</em></td>
<td>Tailscale daemon</td>
<td>System</td>
<td>✅</td>
<td>✅</td>
</tr>
</tbody></table>
<p>Then verify public access works end-to-end:</p>
<pre><code class="language-bash">curl -s -o /dev/null -w "Public oMLX:    HTTP %{http_code}\n" https://omlx.nightthoughts.dev/admin
curl -s -o /dev/null -w "Public QwenPaw: HTTP %{http_code}\n" https://qwenpaw.nightthoughts.dev/
</code></pre>
<hr />
<h2>Troubleshooting Quick Reference</h2>
<table>
<thead>
<tr>
<th>Symptom</th>
<th>Fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>systemsetup: Turning Remote Login on or off requires Full Disk Access privileges</code></td>
<td>Grant Terminal Full Disk Access in System Settings → Privacy &amp; Security → Full Disk Access, then <strong>quit and reopen Terminal</strong></td>
</tr>
<tr>
<td><code>pmset -g</code> shows <code>SleepDisabled 1</code> instead of <code>disablesleep 1</code></td>
<td>Normal on macOS Ventura+. Same setting, different label</td>
</tr>
<tr>
<td><code>sleep 0 (sleep prevented by powerd, bluetoothd)</code></td>
<td>Informational, not an error. Sleep is disabled as intended</td>
</tr>
<tr>
<td>Services respond slowly or hang under load</td>
<td>App Nap is throttling them. Verify <code>caffeinate</code> is running: `launchctl list</td>
</tr>
<tr>
<td><strong>Services don't start after reboot</strong></td>
<td>The GUI session didn't load. All services (oMLX, Caddy, QwenPaw, cloudflared) will still start because they are LaunchDaemons. See §1.4 for diagnosis</td>
</tr>
<tr>
<td><code>Could not find service "com.qwenpaw.app" in domain for user gui: 501</code></td>
<td>QwenPaw is a LaunchDaemon. Use <code>sudo launchctl kickstart -k system/com.qwenpaw.app</code> instead of the <code>gui/</code> domain. See §1.4</td>
</tr>
<tr>
<td><code>Could not find service "com.caddy.server" in domain for user gui: 501</code></td>
<td>Caddy is a LaunchDaemon. Use <code>sudo launchctl kickstart -k system/com.caddy.server</code> instead of the <code>gui/</code> domain.</td>
</tr>
<tr>
<td><code>brew: command not found</code></td>
<td>Run <code>eval "$(/opt/homebrew/bin/brew shellenv)"</code> or add it to <code>~/.zprofile</code></td>
</tr>
<tr>
<td><code>jq: command not found</code> <strong>or</strong> <code>yq: command not found</code></td>
<td>Run <code>brew install jq yq</code> (see §4.1b). Both are installed early because later steps depend on them.</td>
</tr>
<tr>
<td><code>Error: Refusing to load formula ... from untrusted tap</code></td>
<td>Run <code>brew trust jundot/omlx</code>, then retry <code>brew install jundot/omlx/omlx</code></td>
</tr>
<tr>
<td>oMLX install rejected on Intel Mac or macOS 14</td>
<td>oMLX requires Apple Silicon and macOS 15.0 (Sequoia) or later</td>
</tr>
<tr>
<td><code>AttributeError: module 'mlx' has no attribute '__version__'</code></td>
<td>Expected — version lives on <code>mlx.core</code>. Use <code>python -c "import mlx.core as mx; print(mx.__version__)"</code></td>
</tr>
<tr>
<td>Admin dashboard shows 404 at <code>localhost:8000</code></td>
<td>The correct path is <code>/admin</code>, not <code>/</code>.</td>
</tr>
<tr>
<td><code>omlx.nightthoughts.dev/typo</code> <strong>returns a blank page instead of redirecting to</strong> <code>/admin</code></td>
<td>The <code>redir</code> directive is missing its <code>*</code> matcher. Change <code>redir /admin 302</code> to <code>redir * /admin 302</code> in the oMLX subdomain block</td>
</tr>
<tr>
<td><code>401 Unauthorized</code> from oMLX</td>
<td>The <code>api_key</code> in QwenPaw's config doesn't match the key in <code>~/.omlx/settings.json</code>. Both must be <strong>exactly</strong> the same string</td>
</tr>
<tr>
<td><strong>Need to change the oMLX API key</strong></td>
<td>Re-run the generation block in §4.3, then restart the daemon (<code>sudo launchctl kickstart -k system/com.omlx.server</code>) and update QwenPaw</td>
</tr>
<tr>
<td><code>Bootstrap failed: 5: Input/output error</code> <strong>after</strong> <code>bootout</code></td>
<td>The previous instance hasn't fully exited yet. The polling loop in §4.4/§5.4/§7.6/§7.8/§7.9 prevents this — if you hit it anyway, wait 3 seconds and re-run the <code>bootstrap</code> line</td>
</tr>
<tr>
<td><code>lsof -i :8000</code> <strong>shows</strong> <code>Python</code> <strong>instead of</strong> <code>omlx</code></td>
<td>Normal — <code>/opt/homebrew/bin/omlx</code> is a Python shebang script, and <code>lsof</code> reports the kernel's process name. <code>ps -p &lt;PID&gt; -o comm</code> shows <code>omlx-server</code>. Same process, different tools, different names</td>
</tr>
<tr>
<td><strong>Upgraded Caddy via</strong> <code>brew upgrade caddy</code> <strong>but</strong> <code>caddy version</code> <strong>still shows the old version</strong></td>
<td><code>brew upgrade</code> does not restart custom LaunchDaemons. Run <code>sudo launchctl kickstart -k system/com.caddy.server</code>. See §7.6b</td>
</tr>
<tr>
<td><strong>Upgraded oMLX via</strong> <code>brew upgrade omlx</code> <strong>but the running process is still the old version</strong></td>
<td><code>brew upgrade</code> does not restart custom LaunchDaemons. Run <code>sudo launchctl kickstart -k system/com.omlx.server</code>. See §4.4b</td>
</tr>
<tr>
<td><strong>Upgraded cloudflared via</strong> <code>brew upgrade cloudflared</code> <strong>but the tunnel is still the old version</strong></td>
<td><code>brew upgrade</code> does not restart custom LaunchDaemons. Run <code>sudo launchctl kickstart -k system/com.cloudflare.cloudflared</code>. See §7.9 Step 8b</td>
</tr>
<tr>
<td><code>brew services restart caddy</code> <strong>/</strong> <code>brew services restart omlx</code> <strong>breaks the service or creates a duplicate plist</strong></td>
<td>Do not use <code>brew services</code> for Caddy or oMLX. They are managed by custom LaunchDaemons. Use <code>sudo launchctl kickstart -k system/com.&lt;service&gt;</code> instead</td>
</tr>
<tr>
<td>Forgot the QwenPaw password</td>
<td>Run <code>QWENPAW_AUTH_ENABLED=true qwenpaw auth reset-password</code>, or delete <code>~/.qwenpaw.secret/auth.json</code> and restart the daemon</td>
</tr>
<tr>
<td><strong>QwenPaw login fails with "Invalid credentials"</strong></td>
<td>The username in <code>auth.json</code> doesn't match the plist. Check <code>cat ~/.qwenpaw.secret/auth.json</code> — if it says <code>night-thoughts</code> but you're typing <code>admin</code>, either log in as <code>night-thoughts</code> or delete the file and restart to regenerate it from the plist</td>
</tr>
<tr>
<td><strong>QwenPaw daemon exits with code 78 (</strong><code>EX_CONFIG</code><strong>)</strong></td>
<td>A placeholder value was left in the plist. Check with <code>sudo plutil -p /Library/LaunchDaemons/com.qwenpaw.app.plist</code> and fix <code>UserName</code> and <code>WorkingDirectory</code></td>
</tr>
<tr>
<td><strong>Telegram:</strong> <code>Conflict: terminated by other getUpdates request</code></td>
<td>Two QwenPaw instances are polling the same bot token. Kill the duplicate with <code>sudo pkill -9 -f qwenpaw</code>, remove <code>~/.qwenpaw/desktop_backend.pid</code>, and revoke the token via <code>@BotFather</code></td>
</tr>
<tr>
<td><strong>Telegram:</strong> <code>invalid bot token — not retrying</code></td>
<td>The token was revoked. Get a fresh one from <code>@BotFather</code> and paste it into the QwenPaw console at Channels → Telegram</td>
</tr>
<tr>
<td><code>cloudflared tunnel route dns</code> says "neither the ID nor the name of any of your tunnels"</td>
<td>Run <code>cloudflared tunnel list</code> to see actual tunnel names, then retry with the exact name or ID</td>
</tr>
<tr>
<td>cloudflared log spams <code>use cloudflared tunnel run to start tunnel &lt;UUID&gt;</code></td>
<td><code>sudo cloudflared service install</code> wrote a broken plist. Use the LaunchDaemon block in §7.9 Step 8 instead</td>
</tr>
<tr>
<td>Nameserver change at your registrar isn't propagating</td>
<td>Confirm DNSSEC is disabled at your registrar. Check status with <code>dig +short NS &lt;domain&gt; @1.1.1.1</code></td>
</tr>
<tr>
<td><code>dig</code> works but <code>curl</code> returns <code>Could not resolve host</code></td>
<td>Tailscale MagicDNS is hijacking the system resolver. Run <code>tailscale set --accept-dns=false</code> then <code>sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder</code></td>
</tr>
<tr>
<td><code>ssh nt</code> returns <code>Could not resolve hostname</code></td>
<td>Your <code>~/.ssh/config</code> entry is missing or malformed</td>
</tr>
<tr>
<td><code>ssh nt</code> returns <code>Permission denied</code></td>
<td>Wrong username in <code>~/.ssh/config</code>. Verify with <code>whoami</code> on the server</td>
</tr>
<tr>
<td><code>tailscale serve status</code> <strong>still shows a rule after</strong> <code>tailscale serve reset</code></td>
<td>Same-user identity mismatch, or a second <code>tailscale serve</code> process added a new rule. Re-run <code>tailscale serve reset</code>, then `tailscale debug prefs</td>
</tr>
<tr>
<td><strong>Decided to go SSH-only and want to remove the Caddy</strong> <code>:9080</code> <strong>block</strong></td>
<td>The block is only used by <code>tailscale serve</code> (§7.7). After <code>tailscale serve reset</code>, remove the block from <code>/opt/homebrew/etc/Caddyfile</code>, validate with <code>caddy validate --config /opt/homebrew/etc/Caddyfile</code>, then <code>sudo launchctl kickstart -k system/com.caddy.server</code></td>
</tr>
</tbody></table>
<hr />
<p>If you build this stack, tag me — I want to see what agents and local workflows you are running on your Mac. And if you are working on local LLM inference, Apple Silicon optimization, or self-hosted AI, let us talk in the comments or connect directly.</p>
<p>— Haithem Slimi, nightthoughts.me (blog) · nightthoughts.dev (work)</p>
]]></content:encoded></item><item><title><![CDATA[Running LLMs Locally: How to Pick the Right Tool and Model for Your Machine]]></title><description><![CDATA[A practical guide for getting your first local model running — and choosing one that actually fits the hardware you already own.]]></description><link>https://nightthoughts.me/running-llms-locally-how-to-pick-the-right-tool-and-model-for-your-machine</link><guid isPermaLink="true">https://nightthoughts.me/running-llms-locally-how-to-pick-the-right-tool-and-model-for-your-machine</guid><category><![CDATA[llm]]></category><category><![CDATA[ollama]]></category><category><![CDATA[gguf]]></category><category><![CDATA[AI]]></category><category><![CDATA[Local LLM]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Fri, 09 Oct 2026 05:45:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/fe942459-d087-49d0-9769-0ec5136af2f9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Before you start: what local LLMs can and can't do</h2>
<p>Running a model on your own machine buys you privacy, offline access, no rate limits, and no per-token bill. It does not buy you frontier-level intelligence. A 7B model running on your laptop is roughly "a competent assistant for drafts, summaries, translations, simple code, and offline Q&amp;A." It is not a substitute for the largest cloud models on hard reasoning tasks. Set that expectation first, because most disappointment with local LLMs comes from comparing a 4 GB model to a trillion-parameter cloud service.</p>
<p><strong>Minimum viable hardware.</strong> If you are below these numbers, you can still run something, but the experience will be limited. This is the honest floor:</p>
<table>
<thead>
<tr>
<th>Your RAM / VRAM</th>
<th>What you can realistically run</th>
<th>What to expect</th>
</tr>
</thead>
<tbody><tr>
<td>Under 8 GB</td>
<td>1–3B models, Q4</td>
<td>Works, but slow and shallow. Fine for autocomplete or toy chat.</td>
</tr>
<tr>
<td>8 GB</td>
<td>3–4B comfortably; 7–8B at Q4 is tight</td>
<td>Usable for light chat. Close other apps.</td>
</tr>
<tr>
<td>16 GB</td>
<td>7–8B at Q4 comfortably; 13B at Q4 tight</td>
<td>The realistic starting point for a useful local assistant.</td>
</tr>
<tr>
<td>32 GB</td>
<td>13B comfortable; 30B at Q4 possible on Apple Silicon</td>
<td>Good quality without cloud.</td>
</tr>
<tr>
<td>64 GB+</td>
<td>70B at Q4 on Apple Silicon; 30B+ on a 24 GB GPU</td>
<td>Near-cloud quality for everyday tasks.</td>
</tr>
</tbody></table>
<p>Two things eat memory beyond the model file: the <strong>context window</strong> (longer conversations cost more RAM) and the <strong>KV cache</strong> that grows with it. A model that "fits" at 4K context may not fit at 32K.</p>
<hr />
<h2>The landscape in one page</h2>
<p>People compare tools that operate at different layers. Sort them before comparing:</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Examples</th>
<th>What it means for you</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Inference engine</strong></td>
<td>llama.cpp, MLX, ExLlamaV2, uzu</td>
<td>The thing that actually runs the math. Maximum control, minimum hand-holding.</td>
</tr>
<tr>
<td><strong>Wrapper / launcher</strong></td>
<td>Ollama</td>
<td>Sits on top of an engine, adds model management, an API, and one-command installs.</td>
</tr>
<tr>
<td><strong>Desktop app</strong></td>
<td>LM Studio, Jan, GPT4All, Mirai</td>
<td>A GUI on top of an engine. Point, click, download, chat.</td>
</tr>
<tr>
<td><strong>Serving stack</strong></td>
<td>vLLM, SGLang, TensorRT-LLM</td>
<td>Built for many concurrent users. Out of scope for a personal machine, but you'll see the names.</td>
</tr>
</tbody></table>
<p>Ollama is not a competitor to llama.cpp — it <em>contains</em> llama.cpp. LM Studio wraps llama.cpp and MLX. Knowing this stops a lot of confused forum arguments.</p>
<hr />
<h2>Step 1: Know your machine</h2>
<p>The single most important spec is memory, not CPU speed. Then it's which accelerator you have, because that determines which engine backends are available to you.</p>
<table>
<thead>
<tr>
<th>Your chip</th>
<th>Backend you get</th>
<th>Practical consequence</th>
</tr>
</thead>
<tbody><tr>
<td>Apple Silicon (M1–M4)</td>
<td>Metal</td>
<td>Unified memory means the GPU can use most of your RAM. Excellent for local LLMs.</td>
</tr>
<tr>
<td>NVIDIA GPU</td>
<td>CUDA</td>
<td>Best-supported path. Almost every tool works.</td>
</tr>
<tr>
<td>AMD GPU (Linux)</td>
<td>ROCm / HIP</td>
<td>Works well with recent ROCm.</td>
</tr>
<tr>
<td>AMD GPU (Windows)</td>
<td>Vulkan (ROCm limited)</td>
<td>Vulkan works everywhere but is slower than ROCm.</td>
</tr>
<tr>
<td>Intel Arc / integrated</td>
<td>SYCL / Vulkan</td>
<td>Supported in llama.cpp; expect modest performance.</td>
</tr>
<tr>
<td>CPU only</td>
<td>AVX2 / AVX-512 / NEON</td>
<td>Works, but expect single-digit tokens/sec on 7B models.</td>
</tr>
<tr>
<td>Intel Mac (pre-M1)</td>
<td>CPU only</td>
<td>No GPU acceleration. Treat as CPU-only.</td>
</tr>
</tbody></table>
<p>The rule of thumb for model sizing at 4-bit quantization is roughly <strong>0.6–0.8 GB per billion parameters</strong>, plus 1–2 GB overhead, plus context. That gives you this:</p>
<table>
<thead>
<tr>
<th>Model size</th>
<th>Q4 file size</th>
<th>Comfortable RAM/VRAM</th>
</tr>
</thead>
<tbody><tr>
<td>1–3B</td>
<td>0.7–2 GB</td>
<td>4 GB</td>
</tr>
<tr>
<td>7–8B</td>
<td>4–5 GB</td>
<td>8 GB</td>
</tr>
<tr>
<td>13–14B</td>
<td>7–9 GB</td>
<td>12–16 GB</td>
</tr>
<tr>
<td>30–34B</td>
<td>18–20 GB</td>
<td>24–32 GB</td>
</tr>
<tr>
<td>70B</td>
<td>40–42 GB</td>
<td>48 GB+</td>
</tr>
</tbody></table>
<hr />
<h2>Step 2: Pick your tool</h2>
<p>No single tool wins everywhere. Here is the neutral comparison:</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Type</th>
<th>Runs on</th>
<th>Best for</th>
<th>Watch out for</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Ollama</strong></td>
<td>Wrapper</td>
<td>Mac, Windows, Linux</td>
<td>Easiest setup, model library, OpenAI-compatible API</td>
<td>Slightly slower than raw llama.cpp; less control over flags</td>
</tr>
<tr>
<td><strong>LM Studio</strong></td>
<td>Desktop app</td>
<td>Mac, Windows, Linux</td>
<td>GUI, model discovery, shows what fits your RAM</td>
<td>Proprietary (free to use); heavier footprint</td>
</tr>
<tr>
<td><strong>llama.cpp</strong></td>
<td>Engine</td>
<td>Almost everything</td>
<td>Maximum control, fastest on CPU, widest backend support</td>
<td>Command line; you configure everything yourself</td>
</tr>
<tr>
<td><strong>Jan</strong></td>
<td>Desktop app</td>
<td>Mac, Windows, Linux</td>
<td>Lightweight, open source, clean UI</td>
<td>Smaller model selection than LM Studio</td>
</tr>
<tr>
<td><strong>GPT4All</strong></td>
<td>Desktop app</td>
<td>Mac, Windows, Linux</td>
<td>Very lightweight, good on old hardware</td>
<td>Limited to smaller models</td>
</tr>
<tr>
<td><strong>MLX</strong></td>
<td>Engine (Apple)</td>
<td>Apple Silicon only</td>
<td>Apple-native, fast on Macs, growing model ecosystem</td>
<td>Apple-only; models must be in MLX format</td>
</tr>
<tr>
<td><strong>uzu / Mirai</strong></td>
<td>Engine (Apple)</td>
<td>Apple Silicon only (iPhone, iPad, Mac)</td>
<td>Claimed fastest inference on Macs; Rust-based, MIT licensed</td>
<td>Narrow model ecosystem; models must be converted with lalamo; no GGUF</td>
</tr>
<tr>
<td><strong>ExLlamaV2</strong></td>
<td>Engine</td>
<td>NVIDIA only</td>
<td>Fast on consumer GPUs with EXL2 models</td>
<td>Narrow model format support</td>
</tr>
<tr>
<td><strong>Text Gen WebUI</strong></td>
<td>Web GUI</td>
<td>Mac, Windows, Linux</td>
<td>Power users who want many backends in one UI</td>
<td>Setup is more involved</td>
</tr>
</tbody></table>
<p>Now map that to your machine. Both columns are legitimate choices — the trade-off is stated so you can decide:</p>
<table>
<thead>
<tr>
<th>Your machine</th>
<th>Easiest path</th>
<th>More control</th>
<th>What you trade</th>
</tr>
</thead>
<tbody><tr>
<td>Mac M1–M4, 16 GB+</td>
<td>Ollama or LM Studio</td>
<td>uzu, MLX, or llama.cpp</td>
<td>uzu claims the fastest Mac inference but has the smallest model library; MLX is Apple-native with more models; llama.cpp needs manual setup</td>
</tr>
<tr>
<td>Windows + NVIDIA</td>
<td>LM Studio or Ollama</td>
<td>llama.cpp</td>
<td>GUI convenience vs. flag-level control and slightly more speed</td>
</tr>
<tr>
<td>Windows + AMD</td>
<td>LM Studio (Vulkan)</td>
<td>llama.cpp</td>
<td>ROCm on Windows is unreliable; Vulkan is the safe path</td>
</tr>
<tr>
<td>Linux + NVIDIA</td>
<td>Ollama</td>
<td>llama.cpp</td>
<td>Ollama is simpler; llama.cpp is faster and scriptable</td>
</tr>
<tr>
<td>CPU only, 16 GB</td>
<td>Ollama</td>
<td>llama.cpp</td>
<td>Ollama manages models for you; llama.cpp is the fastest CPU path</td>
</tr>
<tr>
<td>Old laptop, 8 GB</td>
<td>Jan or GPT4All</td>
<td>Ollama with a 3B model</td>
<td>Ollama's library is bigger but the app itself is heavier</td>
</tr>
</tbody></table>
<p><strong>One footnote:</strong> vLLM and SGLang are excellent tools, but they are built for serving many users at once, are Linux-first, and vLLM has no native Windows build. You do not need them for personal use. Note the names and move on.</p>
<hr />
<h2>"Ready to run" vs. raw engine</h2>
<p>Some tools ship with the model's context length, chat template, sampling parameters, and quant level already chosen. Others make you specify all of it. This is the convenience-versus-control axis, and it matters more than most beginners realize.</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>What's pre-configured</th>
<th>What you can still change</th>
</tr>
</thead>
<tbody><tr>
<td>Ollama</td>
<td>Chat template, context length, sampling defaults, system prompt — all in a Modelfile</td>
<td>Anything, by editing the Modelfile</td>
</tr>
<tr>
<td>LM Studio</td>
<td>Chat template, context length, GPU offload, sampling presets</td>
<td>All of it, via the UI</td>
</tr>
<tr>
<td>llama.cpp</td>
<td>Almost nothing. You pass flags yourself.</td>
<td>Everything</td>
</tr>
<tr>
<td>MLX</td>
<td>Sensible defaults per model</td>
<td>Most parameters via Python</td>
</tr>
<tr>
<td>uzu / Mirai</td>
<td>Chat template, sampling defaults, quant level per curated model</td>
<td>Limited — the curated library is opinionated</td>
</tr>
</tbody></table>
<p>The trade-off is real. A "ready to run" bundle gets you chatting in two minutes but may silently cap context at 4K or pick a quant that doesn't suit your RAM. A raw engine gives you exactly what you ask for — including the mistakes.</p>
<hr />
<h2>A note on uzu (Mac only)</h2>
<p>uzu is worth knowing about if you're on Apple Silicon. It's a Rust-based inference engine, MIT licensed, and it claims to be the fastest option on Macs — ahead of both MLX and llama.cpp in its own benchmarks. The catch is the model ecosystem. uzu does not read GGUF. Models are converted through a companion toolkit called <strong>lalamo</strong> into uzu's own format, and the curated library is much smaller than what you'll find on Hugging Face. If you want maximum Mac speed and you're happy with the models in their library, uzu is the pick. If you want the widest model selection, stick with GGUF and a tool that reads it.</p>
<p>Install is simple: <code>brew install mirai</code> gives you both the Mac app and a <code>mirai</code> CLI.</p>
<p>Two honest caveats. The performance numbers are self-reported by the Mirai team, and their llama.cpp comparison uses quant selections they chose — so read "fastest" as "fastest in their benchmarks," not as an independent verdict. And the model library is the real constraint. For most beginners, GGUF plus Ollama or LM Studio still gives the widest choice. uzu is for Mac users who've decided speed is the priority.</p>
<hr />
<h2>Step 3: Model types, minus the math</h2>
<p>Two distinctions matter for choosing.</p>
<p><strong>Dense vs. Mixture-of-Experts (MoE).</strong> A dense model activates all its parameters for every token. An MoE model has many "experts" but only activates a few per token, so a 30B MoE might only use 3B parameters at a time.</p>
<table>
<thead>
<tr>
<th></th>
<th>Dense</th>
<th>MoE</th>
</tr>
</thead>
<tbody><tr>
<td>Parameters active per token</td>
<td>All</td>
<td>A subset</td>
</tr>
<tr>
<td>Memory needed</td>
<td>Proportional to total size</td>
<td>Proportional to total size (all experts must be loaded)</td>
</tr>
<tr>
<td>Speed</td>
<td>Predictable</td>
<td>Can be much faster than its size suggests</td>
</tr>
<tr>
<td>Quality per GB of RAM</td>
<td>Usually better at small sizes</td>
<td>Better at large total sizes</td>
</tr>
<tr>
<td>When to pick it</td>
<td>Single consumer machine</td>
<td>Large RAM or multi-GPU</td>
</tr>
</tbody></table>
<p>The practical takeaway: an MoE model is faster than a dense model of the <em>same total size</em>, but not better than a dense model of the <em>same active size</em>. On a single laptop, a well-trained dense model is often the safer pick. On a 64 GB Mac, a large MoE can feel surprisingly quick.</p>
<p><strong>Base vs. instruct (chat) models.</strong> Base models complete text; instruct models follow instructions. Beginners want <strong>instruct</strong> or <strong>chat</strong> variants, usually marked <code>-instruct</code>, <code>-it</code>, or <code>-chat</code>. Downloading a base model and wondering why it won't answer questions is a rite of passage — skip it.</p>
<hr />
<h2>Step 4: What "optimized" means</h2>
<p>Four techniques show up in the wild. Only one of them is something you'll actively choose.</p>
<table>
<thead>
<tr>
<th>Technique</th>
<th>One-line explanation</th>
<th>Do you choose it?</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Quantization</strong></td>
<td>Store weights at lower precision (16-bit → 4-bit)</td>
<td>Yes — this is the main lever you control</td>
</tr>
<tr>
<td><strong>Pruning</strong></td>
<td>Remove unimportant weights or whole layers</td>
<td>No — it's baked into the model by its authors</td>
</tr>
<tr>
<td><strong>Distillation</strong></td>
<td>Train a small model to imitate a large one</td>
<td>No — it's how the model was made</td>
</tr>
<tr>
<td><strong>Low-rank approximation</strong></td>
<td>Factorize weight matrices into smaller pieces</td>
<td>No — usually folded into a quantized release</td>
</tr>
</tbody></table>
<p>Quantization is where your decisions live. Lower bits mean smaller files and faster inference, at the cost of quality. This table is the one to internalize:</p>
<table>
<thead>
<tr>
<th>Quant</th>
<th>Size vs. FP16</th>
<th>Quality</th>
<th>Use when</th>
</tr>
</thead>
<tbody><tr>
<td>Q8_0</td>
<td>~50%</td>
<td>Near-lossless</td>
<td>You have memory to spare</td>
</tr>
<tr>
<td>Q6_K</td>
<td>~40%</td>
<td>Excellent</td>
<td>Good balance</td>
</tr>
<tr>
<td>Q5_K_M</td>
<td>~35%</td>
<td>Very good</td>
<td>Safe default</td>
</tr>
<tr>
<td><strong>Q4_K_M</strong></td>
<td><strong>~28%</strong></td>
<td><strong>Good</strong></td>
<td><strong>Most people, most of the time</strong></td>
</tr>
<tr>
<td>Q3_K_M</td>
<td>~22%</td>
<td>Noticeable degradation</td>
<td>Tight memory</td>
</tr>
<tr>
<td>Q2_K</td>
<td>~15%</td>
<td>Poor, often broken</td>
<td>Last resort</td>
</tr>
</tbody></table>
<p>A note on the naming: <code>Q</code> = quantized, the number = bits, <code>K</code> = K-quant (better quality at the same size), <code>_S</code>/<code>_M</code>/<code>_L</code> = small/medium/large variant, <code>IQ</code> = importance-matrix quant (slower to produce, better quality at the same size). <strong>Q4_K_M is the sweet spot</strong> for almost everyone. IQ quants are worth trying if you're squeezing a model onto a device where Q4_K_M just barely doesn't fit.</p>
<hr />
<h2>Step 5: File formats</h2>
<p>This is where most beginners get stuck, because a model you download may or may not work with the tool you installed.</p>
<table>
<thead>
<tr>
<th>Format</th>
<th>Type</th>
<th>CPU?</th>
<th>NVIDIA</th>
<th>AMD</th>
<th>Apple</th>
<th>Read by</th>
</tr>
</thead>
<tbody><tr>
<td><strong>GGUF</strong></td>
<td>Single file</td>
<td>Yes — best CPU path</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>Ollama, LM Studio, llama.cpp, Jan, GPT4All</td>
</tr>
<tr>
<td><strong>GPTQ</strong></td>
<td>safetensors directory</td>
<td>No</td>
<td>Yes</td>
<td>Limited</td>
<td>No</td>
<td>vLLM, ExLlamaV2</td>
</tr>
<tr>
<td><strong>AWQ</strong></td>
<td>safetensors directory</td>
<td>No</td>
<td>Yes</td>
<td>Limited</td>
<td>No</td>
<td>vLLM</td>
</tr>
<tr>
<td><strong>EXL2</strong></td>
<td>safetensors directory</td>
<td>No</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
<td>ExLlamaV2</td>
</tr>
<tr>
<td><strong>MLX</strong></td>
<td>safetensors directory</td>
<td>No</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
<td>MLX only</td>
</tr>
<tr>
<td><strong>uzu</strong></td>
<td>Converted via lalamo</td>
<td>No</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
<td>uzu / Mirai only</td>
</tr>
<tr>
<td><strong>bitsandbytes</strong></td>
<td>Various</td>
<td>No</td>
<td>Yes</td>
<td>Limited</td>
<td>Limited</td>
<td>transformers, some others</td>
</tr>
</tbody></table>
<p>Two things to take from this table.</p>
<p>First, <strong>GGUF is the only format that runs everywhere</strong>, including CPU. If you are on a personal machine and not sure what you're doing, GGUF is the answer. It is also the format Ollama, LM Studio, and llama.cpp all natively consume.</p>
<p>Second, <strong>GGUF is a single file</strong>; the others are directories of <code>safetensors</code> shards plus config files, or in uzu's case a converted representation. If you download a GPTQ model and point Ollama at it, it will not work — not because something is broken, but because you have the wrong kind of file for that tool.</p>
<hr />
<h2>Step 6: Finding models in practice</h2>
<h3>On Hugging Face</h3>
<ol>
<li>Go to <strong>huggingface.co/models</strong>.</li>
<li>In the left filter panel, open <strong>Libraries</strong> and select <strong>GGUF</strong>.</li>
<li>Search by base model family (e.g., <code>Qwen</code>, <code>Llama</code>, <code>Gemma</code>, <code>Mistral</code>).</li>
<li>Sort by <strong>Trending</strong> for what's current, or <strong>Most downloads</strong> for what's proven.</li>
<li>Open a model page and check the <strong>Files</strong> tab — GGUF repos list every quant with its file size. Pick the one that fits your RAM.</li>
<li>Many pages have a <strong>"Use this model"</strong> dropdown that offers one-click import to Ollama or LM Studio.</li>
</ol>
<p>The model card is worth reading. Good ones include a quant table with file sizes, a recommended context length, and sometimes a perplexity comparison so you can see how much quality each quant step costs.</p>
<h3>Trusted uploaders</h3>
<p>Quantization quality varies by who did it. These accounts have good reputations: <strong>bartowski</strong>, <strong>unsloth</strong>, <strong>lmstudio-community</strong>, <strong>mradermacher</strong>, and the now-archived <strong>TheBloke</strong> collections (still useful as references). The model's original authors also frequently publish their own GGUF builds.</p>
<h3>Other places to look</h3>
<table>
<thead>
<tr>
<th>Source</th>
<th>What you get</th>
<th>Best for</th>
</tr>
</thead>
<tbody><tr>
<td>Hugging Face</td>
<td>The largest catalog, all formats</td>
<td>Everything, especially GGUF</td>
</tr>
<tr>
<td>Ollama library (ollama.com/library)</td>
<td>Curated models, one-command pull</td>
<td>Fastest path from zero to chatting</td>
</tr>
<tr>
<td>LM Studio's built-in search</td>
<td>Models filtered by what fits your RAM</td>
<td>Beginners who want a GUI</td>
</tr>
<tr>
<td>Mirai model library (trymirai.com/models)</td>
<td>Curated uzu-format models</td>
<td>Mac users who've chosen speed over selection</td>
</tr>
<tr>
<td>ModelScope</td>
<td>Large catalog, strong on Chinese-language models</td>
<td>Non-English models</td>
</tr>
</tbody></table>
<hr />
<h2>Step 7: The cheat sheet</h2>
<p>Find your machine, pick the column that matches your appetite for setup, and run the model class listed. Speed figures are rough and depend heavily on the specific model and context length.</p>
<table>
<thead>
<tr>
<th>Your machine</th>
<th>Tool</th>
<th>Model class</th>
<th>Format / quant</th>
<th>Rough speed</th>
</tr>
</thead>
<tbody><tr>
<td>MacBook Air M1, 8 GB</td>
<td>Ollama or LM Studio</td>
<td>3–4B instruct</td>
<td>GGUF Q4_K_M</td>
<td>15–25 tok/s</td>
</tr>
<tr>
<td>MacBook Pro M3 Pro, 18 GB</td>
<td>LM Studio or Mirai (uzu)</td>
<td>7–8B instruct</td>
<td>GGUF Q4_K_M or uzu 4-bit</td>
<td>25–50 tok/s</td>
</tr>
<tr>
<td>Mac Studio M2 Ultra, 64 GB</td>
<td>Mirai (uzu) or Ollama</td>
<td>27B dense, or 70B at Q3</td>
<td>uzu 4-bit or GGUF Q4</td>
<td>15–40 tok/s</td>
</tr>
<tr>
<td>Windows laptop, 16 GB, no dGPU</td>
<td>Jan or llama.cpp</td>
<td>3–7B instruct</td>
<td>GGUF Q4_K_M</td>
<td>5–12 tok/s</td>
</tr>
<tr>
<td>Windows desktop, RTX 3060 12 GB</td>
<td>LM Studio</td>
<td>7–8B instruct</td>
<td>GGUF Q4_K_M</td>
<td>30–50 tok/s</td>
</tr>
<tr>
<td>RTX 4090, 24 GB</td>
<td>LM Studio or llama.cpp</td>
<td>30B at Q4, or 8B at Q8</td>
<td>GGUF</td>
<td>60–100 tok/s</td>
</tr>
<tr>
<td>Linux + RTX 3090/4090</td>
<td>llama.cpp or Ollama</td>
<td>30B at Q4</td>
<td>GGUF</td>
<td>50–90 tok/s</td>
</tr>
<tr>
<td>CPU-only server, 32 GB</td>
<td>llama.cpp</td>
<td>7–8B instruct</td>
<td>GGUF Q4_K_M</td>
<td>3–8 tok/s</td>
</tr>
</tbody></table>
<p>If you take nothing else from this article: <strong>GGUF, Q4_K_M, an instruct model that fits in your RAM.</strong> That combination works on every platform and every tool mentioned here.</p>
<hr />
<h2>Three quick-start recipes</h2>
<p><strong>Ollama (any platform, easiest):</strong></p>
]]></content:encoded></item><item><title><![CDATA[Memory Mosaics: The AI That Learns Faster by Reading Less]]></title><description><![CDATA[A new research paper from Meta and NYU proves we might not need to keep making AI models bigger to make them smarter.]]></description><link>https://nightthoughts.me/memory-mosaics-the-ai-that-learns-faster-by-reading-less</link><guid isPermaLink="true">https://nightthoughts.me/memory-mosaics-the-ai-that-learns-faster-by-reading-less</guid><category><![CDATA[AI]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[llm]]></category><category><![CDATA[Meta]]></category><category><![CDATA[research]]></category><dc:creator><![CDATA[Haithem Slimi]]></dc:creator><pubDate>Thu, 08 Oct 2026 23:15:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a92730f9a9aa7f72e74fdf4/a54d189e-7455-49e0-8a56-1f3745a805d1.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Imagine you want to teach a new employee how to do a specific task.</p>
<p>The current way we train AI is like handing that employee a massive, million-page manual and saying, <em>"Memorize this, and you'll be able to do the job."</em> This is how today's AI models, called <strong>Transformers</strong> (the technology behind ChatGPT and Gemini), learn. They are incredibly powerful, but they are also incredibly "thirsty"—they need to consume trillions of words to learn new things.</p>
<p>But what if that employee could learn a new task just by watching you do it once?</p>
<p>That is the promise of a new research paper called <strong>"Memory Mosaics at scale"</strong> by researchers at Meta and New York University. They have built a new type of AI that can learn new tasks on the fly and, amazingly, a smaller version of it can outperform a massive, standard AI trained on <strong>8 times more data</strong>.</p>
<p>Let's break down this fascinating research in simple terms.</p>
<h2>🧠 The Problem: Transformers Are Data-Hungry Monsters</h2>
<p>The AI behind ChatGPT is built on an architecture called the <strong>Transformer</strong>. It's incredibly powerful, but it has a major downside: it's a <strong>data-hungry monster</strong>. To learn how to do something new, it needs to be trained on massive amounts of text—often <strong>trillions</strong> of words.</p>
<p><strong>Simple Analogy:</strong> Think of a Transformer as a student who can ace a test but only after reading the entire library. If you give them a new book, they have to read the whole thing to answer a question about it.</p>
<p>Researchers have long wanted an AI that could learn "in-context"—that is, learn a new task on the fly, just from a few examples in the prompt, without needing to re-read the whole internet. The problem was, no one had proven a different architecture could achieve this at the same massive scale as Transformers.</p>
<h2>👥 Who Are the Researchers?</h2>
<p>The research was led by <strong>Jianyu Zhang</strong> (New York University and Meta's Fundamental AI Research, FAIR) and <strong>Léon Bottou</strong> (FAIR, Meta, and NYU). Léon Bottou is a highly respected AI scientist, so this work carries significant weight in the AI community.</p>
<h2>📄 Is It Just a Paper, or Is There Concrete Code?</h2>
<p><strong>It's both.</strong> This is a research paper, but the researchers also released the code on GitHub so other developers and researchers can test, use, and build upon their work.</p>
<ul>
<li><p><strong>Read the Research Paper:</strong> <a href="https://arxiv.org/abs/2507.03285">https://arxiv.org/abs/2507.03285</a></p>
</li>
<li><p><strong>Check out the Code:</strong> <a href="https://github.com/facebookresearch/MemoryMosaics">https://github.com/facebookresearch/MemoryMosaics</a></p>
</li>
</ul>
<h2>🔬 What They Did and Found</h2>
<p>The researchers took an alternative AI architecture called <strong>Memory Mosaics</strong> and scaled it up for the first time.</p>
<p><strong>What are Memory Mosaics?</strong> Instead of using "attention" like Transformers (which looks at everything at once), Memory Mosaics use a network of <strong>associative memories</strong>. Think of it as a set of filing cabinets where you store key-value pairs. You give it a "key" (a question), and it retrieves the "value" (the answer).</p>
<p>They built a <strong>10-billion-parameter</strong> version (roughly the size of Meta's LLaMA-8B model) and trained it on <strong>1 trillion tokens</strong> of real-world text. They then tested it against standard Transformers on three key skills:</p>
<ol>
<li><p><strong>Remembering What It Learned:</strong> The Memory Mosaics matched Transformers. They were just as good at remembering the knowledge from their training data.</p>
</li>
<li><p><strong>Learning New Tasks on the Fly (In-Context Learning):</strong> This is where the results were stunning. The Memory Mosaics <strong>significantly outperformed</strong> Transformers at learning a new task from just a few examples in the prompt.</p>
</li>
<li><p><strong>Efficiency – The Big Surprise:</strong> This is the most important finding. A Memory Mosaic trained on just <strong>1 trillion tokens</strong> performed <strong>better</strong> at new tasks than a Transformer trained on <strong>8 trillion tokens</strong>.</p>
</li>
</ol>
<p><strong>Simple Analogy:</strong> It's like a student (Memory Mosaic) who read <strong>1 book</strong> and can solve a new problem better than a student (Transformer) who read <strong>8 books</strong>. The Memory Mosaic is simply a more efficient learner.</p>
<h2>🔧 How They Improved the Existing Method</h2>
<p>The original Memory Mosaics were tested only on small, synthetic data. To scale them up, the researchers introduced <strong>"Memory Mosaics v2"</strong> with key architectural improvements:</p>
<ul>
<li><p><strong>Adaptive Bandwidth:</strong> This acts like a "focus" knob, letting the model decide how broadly or narrowly to search its memories for an answer. This makes it better at handling real-world data, which is messy and varied.</p>
</li>
<li><p><strong>Hierarchical Memory:</strong> They split memory into <strong>short-term</strong> and <strong>long-term</strong> components. Short-term memory handles recent information (like the current conversation), while long-term memory stores more permanent knowledge. This is similar to how our brains process information.</p>
</li>
</ul>
<p>Here is a simplified visual of how the Memory Mosaics v2 architecture works:</p>
<pre><code class="language-mermaid">graph TD
    A[User Input / Prompt] --&gt; B{Adaptive Bandwidth Router}
    B --&gt;|Focus Broadly| C[Short-Term Memory]
    B --&gt;|Focus Narrowly| D[Long-Term Memory]
    C --&gt; E((Associative Retrieval))
    D --&gt; E
    E --&gt; F[Generated Output / Prediction]
    
    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#ff9,stroke:#333,stroke-width:2px
    style C fill:#dfd,stroke:#333,stroke-width:2px
    style D fill:#dfd,stroke:#333,stroke-width:2px
    style E fill:#bbf,stroke:#333,stroke-width:2px
    style F fill:#f9f,stroke:#333,stroke-width:2px
</code></pre>
]]></content:encoded></item></channel></rss>