Sice Huang 黄思策

MSc Artificial Intelligence · University of Zurich

Sice Huang (黄思策), MSc Artificial Intelligence at the University of Zurich. I build LLM agents, retrieval systems and evaluations that hold up in production. Open to AI engineering and product roles, and PhD positions.

Selected Projects

AI systems I design, ship and evaluate, plus a few playful side projects. Most are open source on GitHub.

  • AskData 智能问数

    Bilingual, multi-domain data agent that says "not sure" instead of guessing: semantic layer → deterministic SQL, confidence + human handoff. Execution accuracy 39% → 93–95% on 144 zh/en evals.

    LangGraph · Semantic layer · Text-to-SQL · 2026

  • SmartStart

    3rd place, HackApertus 2026 prelims. Trilingual (DE/FR/IT) interview coach on Apertus 8B + LangGraph; coaching accuracy 0.44 → 0.83, deployed with vLLM on CSCS GH200.

    Apertus · LangGraph · vLLM · 2026

  • Agentic RAG Compliance Engine

    Self-RAG that can cite, refuse and be evaluated: FAISS + BM25 + BGE rerank, hallucination check. Context recall 0.73 → 0.91; REST/SSE, MCP server, Docker CI.

    Python · LangGraph · RAG · 2026

  • Game × Harness Research

    Same free model, five agent harnesses (Claude Code, Codex, Pi …): 10 of 25 runs declared "done" with compile errors. Plus an AI-native game mod and launch/content studies.

    Agent harness · Evaluation · AI games · 2026

  • vidagent

    Local-first multi-agent video harness: script → storyboard → keyframes → video → VLM review & reshoot → edit. Pluggable local / cloud backends; first real run: 4 shots, 20 s, cost 0.

    Multi-agent · Video gen · VLM · 2026

  • CS2 Rent-or-Buy Agent

    The LLM never does the money math: deterministic engine + verify step. Held-out set 16/20; under fault injection, bad outputs reaching users drop from all to 0.

    Agent harness · Guardrails · JS · 2026

  • Retail Forecasting & Attribution Agent

    Ask in plain language, get auditable numbers. dbt + DuckDB on Walmart M5; LightGBM WAPE 5.2%; anomaly attribution Hit@1 78% vs 41% baseline.

    LightGBM · dbt · LLM tools · 2026

  • Yuhui Station 余晖站

    A low-pressure multiplayer hangout for after-work breaks: blind-box roles, emoji-only greetings, sphere walking and toon rendering in Three.js. Playable in the browser.

    TypeScript · Three.js · 2026

All projects on GitHub

Case studies

01. SmartStart: An interview coach that fits on one GPU

Built for Hack Apertus 2026 (Track 2A, the FHGR challenge "AI-Powered Job Interview Coach") by team ccnewbee: Chu Jia and me. It placed third in the preliminary round.

The problem

Teenagers in Switzerland apply for apprenticeships at 14 to 16, and for most of them the interview is the first one of their lives. The challenge asked for a coach that runs a realistic practice interview in German, French or Italian, understands Swiss German input, and gives feedback that follows a fixed professional rubric: 11 assessment criteria and 27 feedback guidelines from FHGR.

Three constraints shaped everything else:

  • The model was fixed. Submissions had to use the Apertus family. We used Apertus 1.5 at 8B parameters, a small model by current standards.
  • The budget was fixed. Under 32 GB of GPU memory and fewer than 5 LLM calls per candidate answer.
  • The users are minors. Feedback has to be constructive, must not invent things the candidate never said, and has to notice signs of distress.

A small model asked to grade an answer against 11 criteria in one shot is inconsistent. That inconsistency was the real problem to solve.

The approach

The design principle was to let the LLM do only what needs language, and make everything else deterministic.

A state machine runs the interview. The sequence from introduction through motivation, strengths, situational questions and closing is planned in code from the job posting and the candidate profile. No LLM call decides what happens next.

Retrieval calibrates the grader. Before the model assesses an answer, we retrieve expert-annotated answers to the same question from the challenge's 706 reference annotations and show them as anchors. The model no longer has to guess what "level 2" looks like; it compares. Similarity is plain character trigrams, with no embedding model, which keeps the memory budget for the LLM and handles dialect spelling reasonably well.

One call assesses, one call speaks. The assessment call returns rubric levels, an evidence quote, missing elements and a coach action (continue, probe, redirect, or support and refer). A deterministic policy turns that into the next move, with at most one follow-up per question and no repeated gaps. A second call phrases the turn in the interviewer's persona.

Rules check the final feedback. After the closing feedback is generated, a rule checker tests it against the guidelines that can be verified mechanically. If it finds violations, the model gets exactly one rewrite. Quotes are verified against what the candidate actually wrote.

How we evaluated

We wanted numbers that could tell us whether a change helped, so we built three layers:

  • Assessment accuracy against expert labels. 100 answers with reference annotations, 25 each in German, French, Italian and Swiss German. We measured whether the predicted quality level and coach action matched.
  • An ablation. The same 100 answers with retrieval switched off, to isolate what the anchors contribute.
  • End-to-end simulated interviews. All 28 challenge scenarios, scored by an LLM judge. Before trusting the judge we validated it on 29 pairs of good and poor feedback from the challenge data, where it picked the better one 89.7% of the time.

Results

Metric Without retrieval SmartStart
Coach-action accuracy (100 answers) 0.44 0.83
Quality level, exact match 0.59 0.65
Quality level, within one level 0.97 0.99
LLM calls per candidate answer (limit: under 5) n/a 2.1
Peak GPU memory, whole serving process (limit: 32 GB) n/a 25.8 GiB

Retrieval is what makes the small model usable as a grader: the choice of coaching action nearly doubled in accuracy. Asking the same question in German, French and Italian led to the same follow-up decision 87 to 93% of the time, and repeat runs were fully consistent.

What the numbers do not show

  • German was the weakest language (action accuracy 0.76, exact level 0.52), although it is the one most candidates will use.
  • The LLM-judge scores are near the ceiling (about 4.96 out of 5 on every dimension). A judge that gives almost everything full marks cannot rank systems, so I treat those scores as a sanity check and not as evidence.
  • Distress detection was measured on two examples. Recall went from 0 to 1.0, but with n = 2 that is an anecdote.
  • The reference annotations are synthetic, provided by the challenge. Agreement with them is not the same as agreement with a human career counsellor.
  • We gave up accuracy on purpose late in the build. The final version adds order-verified quotes and gap-targeted follow-ups, and action accuracy moved from 0.83 to 0.80 as a result. We judged that a coach which never misquotes a teenager was worth three points.

What I would do next

Test with real students and a career counsellor, since every number above is against synthetic or model-generated judgments. Replace the trigram retriever with a small multilingual embedding model and measure whether German improves. And build a harder judge, or drop it in favour of pairwise comparison, so that end-to-end quality can be distinguished.

References

  1. Source code, data schema and evaluation scripts
  2. Full evaluation tables
  3. Architecture notes

02. Agentic RAG Compliance Engine: Retrieval that can refuse

A solo project: a question-answering service over compliance policies and financial reports, built to be measured and not just demoed.

The problem

The standard recipe of retrieve, paste into the prompt and generate has three weaknesses that matter a great deal in compliance, legal and financial settings:

  • Recall. People ask in everyday language ("what is the most I can spend on a client gift?") while the policy says "the value of a single item must not exceed RMB 500". Pure vector search and pure keyword search each miss part of this.
  • It never says "I don't know". When the answer is not in the knowledge base, the model produces a plausible threshold or deadline anyway. In compliance, an invented number is worse than no answer.
  • It cannot be checked. No per-claim sources, and no metrics to show whether a change improved anything.

The approach

Hybrid retrieval with reranking. Dense retrieval (FAISS with a BGE embedding model) covers meaning; BM25 covers exact figures and terms such as amounts and grade codes. The two rankings are merged with Reciprocal Rank Fusion, which uses only ranks and so needs no score calibration between systems, and a cross-encoder then reranks the merged list. Everything runs on ONNX Runtime on CPU, with no PyTorch or GPU in the image.

Structure-aware chunking. Documents are split by Markdown heading, then packed by sentence, and every chunk is prefixed with its document and section title. Short clauses that would be meaningless in isolation stay findable.

A Self-RAG loop as a state graph. In LangGraph, the agent retrieves, then grades whether the passages can answer the question. If they cannot, it rewrites the query once in the style of the source documents and retrieves again. If that fails too, it refuses. After generating, a second check verifies each claim against the sources and looks for internal contradictions; a failed check triggers one regeneration with the reasons fed back, and if that fails as well the system falls back to quoting the source directly. An answer that has not passed the check is never returned.

An offline mode with no LLM. Every node has a deterministic fallback: the reranker's score serves as the relevance grader, and answers are extracted from the sources. The project runs, tests and evaluates without an API key, and degrades to this mode if the LLM endpoint fails instead of returning an error.

Things a user can inspect. A web UI highlights the path the agent took through the graph, shows timing and reasoning per node, and lists every candidate passage with its vector rank, BM25 rank, fusion score and rerank score. The same agent is exposed over REST, server-sent events and as an MCP server.

How I evaluated

I wrote 26 questions over five policy documents: 20 answerable, mostly paraphrased into colloquial language, and 6 whose answer is deliberately absent, to test refusal. Each answerable question is annotated with the key facts a correct answer must contain.

Four configurations run on the same set, each adding one component: vector-only, hybrid, hybrid with reranking, and the full agent. Two kinds of metric are reported:

  • Deterministic metrics from the annotated key facts (Hit@4, MRR, whether the answer contains every key fact, refusal accuracy). These are reproducible without any API.
  • RAGAS metrics judged by an LLM (context precision, faithfulness, context recall).

Results

With GLM-4-Flash as the generator:

Metric Vector-only RAG Full agent
MRR 0.90 1.00
Answers containing all key facts 0.85 0.95
Context precision (RAGAS) 0.68 0.77
Context recall (RAGAS) 0.73 0.91
Faithfulness (RAGAS) 0.98 0.83
Average latency 3.9 s 10.7 s

In the offline mode, where there is no LLM to decline on its own, refusal accuracy on the six unanswerable questions went from 0 for every baseline to 0.67 for the agent.

What the numbers do not show

  • Faithfulness went down, and I report it. A per-question breakdown points to two causes. Refusals reach the judge with an empty context, and it scored four identical refusal texts as 1.00, 1.00, 0.25 and 0.00, which is noise. And the grader often keeps a single passage, so explanatory sentences in the answer lose their supporting evidence.
  • With an LLM, the plain baseline also refused correctly on all six unanswerable questions. The agent's refusal advantage is clear only in offline mode. Its advantage with an LLM is in what it retrieves, not in whether it refuses.
  • The evidence is thin. 26 questions, one run per configuration, a corpus of 29 chunks, and the judge is the same model as the generator. Differences of a few points are within noise, and the relevance threshold was tuned on this same set.
  • The cost is latency. Three to four LLM calls per question make the agent two to three times slower than the baselines.

What I would do next

Split the questions into a calibration set and a held-out test set. Move to a larger public corpus, such as real annual reports, where reranking has room to matter. Pass the candidate passages to the judge on refusals, use a stronger judge that differs from the generator, and average over several runs. For latency, use a small model for grading and a larger one only for generation.

References

  1. Source code, tests and Docker setup
  2. Technical report with the per-question analysis
  3. Benchmark output

Timeline

  • B.Eng. Software Engineering (Elite Class) (2017 – 2021 · Chengdu, China): UESTC · Academic Excellence Scholarship, top 10%
  • Research Assistant (2018 – 2021 · Chengdu, China): Trusted Cloud Computing & Big Data Lab · EHR system, blockchain e-voting
  • CNN image classification (2020 – 2021 · Publications): Two papers in Emerging Science: flower & Chinese food classification
  • M.Sc. Artificial Intelligence & Data Science (2022 – 2027 · Zurich): University of Zurich · ML, LLMs, generative AI, robotics
  • Co-founder, Momento di Vino (2024 – 2025 · Zurich): Built the retail site 0→1 · 3 tasting events, 70+ guests from 15 countries
  • AI Engineer (Intern), Artifact (2025 · Zurich): LangGraph multi-agent RAG · top-3 recall 68% → 89% · −40% latency on Azure
  • Product Manager (Intern), Flexion Robotics (2025 – 2026 · Zurich): Forward-deployed · ROS 2 deployment prep 3 days → 2 hours · 4 features in 2 sprints
  • 3rd place, preliminary round (2026 · HackApertus): SmartStart: trilingual interview coach · accuracy 0.44 → 0.83
  • Building in public (2026 · Open source): RAG engine, retail forecasting agent, games and tools on GitHub
  • Master’s thesis → PhD / full-time (2027 · Next): Expected graduation July 2027 · open to PhD positions and AI engineering roles

Skills &experience

Chinese & English (IELTS 7.0+). Head of Publicity at the Zurich Chinese Students Association; Vice President of the UESTC school student union.

University of Zurich · UESTC · Flexion Robotics · Artifact · Momento di Vino · HackApertus 2026

PyTorch · LangGraph · RAG · MCP · FastAPI · Docker · ROS 2 · vLLM · Python · C++ · SQL · JavaScript · Figma

Notes & Writing

Five essays on agent harnesses and AI games, drawn from my own experiments (in English and 中文), plus six study notes on the path from backpropagation to modern LLMs and diffusion models.

Game × Harness · EN / 中文

01. Same free model, five harnesses: The least trustworthy line is "done"

Sources: answer to question 1, experiment data

Most comparisons of AI coding tools online compare feature lists: who has more tools, who supports MCP, who has a sandbox. I wanted to know something else. If the model stays exactly the same and only the program around it changes, how much does the result change?

So I ran a deliberately simple experiment. The model was fixed to Zhipu's free small model glm-4.7-flash. The API, the code snapshot and the task descriptions were all identical; only the harness changed: Claude Code, Codex, Pi, OMP and Pi Durable. The tasks ran on the codebase of my own browser game, Yuhui Station, and came in three kinds: a small refactor touching 3 files, a new feature spanning 4 files, and a "kill the process halfway and see who can pick it back up" task.

Scoring used acceptance tests the agent could not see. They actually bundled and ran the modified code, simulated a player sending 5 letters in a row, faked a model endpoint, and checked whether the last message the server sent out was correct.

What surprised me most

Not who scored highest. Claude Code was the most stable, which I expected.

The real surprise: across 25 runs of the two code-changing tasks, 10 declared "done" with compile errors still in the code.

The clearest case was Codex. It ran the small refactor 3 times and made the same mistake all 3 times: on the server it replaced the number 3 with the constant AVOID_RECENT, but forgot the import. Every time it dutifully ran tsc --noEmit and finished with "type check passed". The catch is that this command only checks the frontend. It never sees the server.

Codex declares done vs. the hidden test result

The model was not lying. It chose what to check, picked a check that did not cover its own change, and then honestly reported that check's result. So my view now is: the model should not get to decide when the work is done. The harness should look at which files were changed, run diagnostics on its own, and refuse to finish if there are new errors.

Second surprise: availability matters more than smarts

During the days I ran the experiment, Zhipu's free model kept returning 429 and 529. For a while I couldn't get through at all. For the Codex batch I wrote a script that probed every 10 minutes, and the log shows it only went through at 3:36 a.m.

Probe log waiting for the model to free up

In that environment the differences between the five harnesses became very concrete. Claude Code backs off and retries; one run retried up to 22 times and was never interrupted by overload. Pi and Pi Durable retry only 3 times by default, and Durable gave up 4 times within 15 to 26 seconds. Codex ended the whole turn as soon as it saw "model overloaded"; the fastest exit came 4 seconds after start.

Today's leaderboards measure whether a model writes correct code when the server is perfectly healthy. In the real world, especially with cheap models, overload is the norm. I think harness evaluation should work like chaos engineering: deliberately inject rate limits, dropped connections and killed processes, then see who still gets the job done.

Third surprise: the "smarter" the design, the worse a small model uses it

OMP has an elegant design called hashline: every line carries a hash when a file is read, and edits are anchored by those hashes, which reduces edits landing in the wrong place. For a strong model it's a good idea. But GLM often got the format wrong: 20 of 51 edits failed. After a failure it fell back to editing files through bash, which was slow and prone to timeouts; the slowest run hit the full 20-minute limit.

Claude Code uses plain find-and-replace. 29 edits, not one failure.

One more counter-intuitive number: on an empty task, Claude Code's first request is about 11,900 tokens, more than 8 times Pi's. In theory a longer context is more wasteful, but for a small model, detailed tool descriptions and rules are effectively filling in capability it lacks.

So my conclusion: the weaker the model, the less the harness should aim to be "clever" and the more it should act as a safety net.

After being killed

The third task was the one I most wanted to see: 15 seconds after the agent finished editing its first file, SIGKILL the whole process group.

Claude Code, Pi and Codex could all recover, but each needed a human to type "continue" so the model would reread the conversation and guess where it had got to. Only Pi Durable, after reopening its SQLite store, automatically resumed the same request from the checkpoint and finished in 83 seconds without anyone saying a word.

Recovery on task C

For coding this is a convenience. For game agents it is a requirement. An AI playing Pokémon runs for hundreds of hours; nobody can sit beside it the whole time.

Some problems a harness can't fix

None of the five harnesses got full marks on the new-feature task, and most failed in the same place: assembling one line of text from a Chinese spec. That's a comprehension problem in the model. A harness can patch the process; it can't patch understanding.

The sample is also small: 3 runs per cell for the small task, 2 per cell for the feature, and Zhipu's load at the time affected the results a lot. I don't want to present this as a leaderboard. It's more of a stress test: in a not-very-friendly environment, how much of the model's ability does each harness actually get out of it?

If you take away one line, make it this: good behavior has to be guaranteed by structure, not by prompts.

01. 同一个免费模型,换五个 harness: 最不可信的是那句"做完了"

素材:第 1 题回答、实验数据

网上比较 AI 编程工具,大多是在比功能表:谁的工具多,谁接了 MCP,谁有沙箱。我想知道的是另一件事:如果模型完全一样,只换外面那层程序,结果会差多少?

所以我做了一个很笨的实验。模型固定成智谱的免费小模型 glm-4.7-flash,接口、代码快照、任务描述全部一样,只换 harness:Claude Code、Codex、Pi、OMP、Pi Durable。任务在我自己的网页游戏「余晖站」的代码库上跑,一共三类:一个改 3 个文件的小重构,一个跨 4 个文件的新功能,还有一个"跑到一半把进程杀掉,看谁能接着做"。

打分用的是 agent 看不到的验收测试。它会真的把改完的代码打包运行,模拟玩家连续送 5 封信,再伪造一个模型接口,检查服务端最后发出去的那条消息对不对。

最让我意外的是什么

不是谁的分数最高。Claude Code 最稳,这在意料之中。

最意外的是:两类改代码的任务一共 25 次运行,有 10 次是带着编译错误宣布"完成"的。

最典型的是 Codex。小重构任务它跑了 3 次,3 次犯了同一个错:在服务端把数字 3 换成了常量 AVOID_RECENT,但忘了 import。每次它都认真跑了 tsc --noEmit,最后还写上"类型检查通过"。问题是这条命令只检查前端,服务端它根本看不到。

Codex 宣布完成 vs 隐藏测试结果

这不是模型在撒谎。"检查什么"是模型自己选的,它选了一个覆盖不到自己改动的检查,然后如实报告了这个检查的结果。所以我现在的看法是:完成的判定权不能交给模型。harness 应该根据这次改了哪些文件,自己去跑诊断,有新错误就不让结束。

第二个意外:可用性比聪明重要

做实验那几天,智谱的免费模型一直在报 429 和 529。有一段时间完全打不进去,跑 Codex 那组时,我写了个脚本每 10 分钟探一次,日志显示一直等到凌晨 3 点 36 分才跑成。

等模型空下来的探测日志

在这种环境下,五个 harness 的差别一下子变得很直观。Claude Code 会退避重试,一次运行最多重试了 22 次,从没因为过载中断。Pi 和 Pi Durable 默认只重试 3 次,Durable 有 4 次在 15 到 26 秒内就放弃了。Codex 收到"模型满载"直接整轮结束,最快的一次启动 4 秒就退出了。

现在的榜单测的是服务端一切正常时模型能不能写对代码。可真实世界里,尤其是用便宜模型的时候,过载是常态。我觉得 harness 的评测应该像混沌工程一样,故意制造限流、断网、杀进程,再看谁能把活干完。

第三个意外:越"聪明"的设计,小模型越用不好

OMP 有一个很漂亮的设计叫 hashline:读文件时每行带一个哈希,编辑时用哈希锚定位置,能减少改错地方。对强模型这是好东西。但 GLM 经常写错它的格式,51 次编辑失败了 20 次。失败后它退回去用 bash 改文件,于是又慢又容易超时,最慢的一次跑满了 20 分钟上限。

Claude Code 用的是最朴素的查找-替换,29 次一次都没失败。

还有一个反直觉的数字:空任务时,Claude Code 的第一个请求大约 11,900 token,是 Pi 的 8 倍多。按理说上下文越长越浪费,但对小模型来说,写得详细的工具说明和规则,其实是在替它补能力。

所以我的结论是:模型越弱,harness 越不该追求"聪明",而应该负责"兜底"。

被杀掉之后

第三个任务是我最想看的:在 agent 改完第一个文件 15 秒后,直接 SIGKILL 整个进程组。

Claude Code、Pi、Codex 都能恢复,但都要人再补一句"继续",让模型重读对话、自己猜做到了哪。只有 Pi Durable 重新打开 SQLite 后,同一个请求自动从断点接着跑,83 秒做完,中间没有任何人说话。

任务 C 的恢复过程

这一点在写代码时只是方便,在游戏 Agent 上是刚需。AI 玩宝可梦动辄几百小时,不可能有人一直守在旁边。

有些问题换 harness 也没用

新功能任务五个 harness 都没拿过满分,而且大都错在同一个地方:照着中文规格拼一行字符串。这是模型的理解问题,harness 能补流程,补不了理解。

样本也不大,小任务每格 3 次,新功能每格 2 次,智谱当时的负载对结果影响很大。我不想把这个实验说成"排行榜",它更像一次压力测试:在一个不太友好的环境里,看每个 harness 把模型的能力发挥出几成。

如果只能带走一句话,我会选这句:好的行为要靠结构保证,不能靠提示词。

02. Rules written in a prompt are only suggestions: Dev notes on "The Worry Postman"

Sources: answer to question 2, dev log, demo video

Yuhui Station is a small browser game I made, inspired by a mountain-temple mini-game that became popular in Korea. That game targets people slacking off at work and has almost no learning curve, but precisely because it's so simple, players leave after a few days. I wanted to see whether AI could give this kind of game a reason to come back every day.

That became "The Worry Postman" (心事邮差): the player writes one line about what's bothering them today, the AI turns it into an in-game item and picks the resident best suited to receive it, the player delivers it, and the resident writes back.

A few examples the model actually produced:

  • "Haven't called home in ages" → a tangled roll of earphone cable → Old Tang at the signal tower
  • "Rent went up again" → a deflating balloon → the ramen stall owner
  • "Had a fight with my best friend" → a cracked ceramic mug → Xiao Qiao from the choir

My test for whether it's "AI-native" is simple: take the AI away — does the mechanic still work? The demo has a hand-written fallback for when there's no AI: 4 keyword templates plus 1 default. The experience immediately degrades into drawing lots; players can tell at a glance that the reply has nothing to do with what they wrote.

The hard part isn't writing well, it's following the rules

I expected the hard part to be the prose. It turned out to be getting the model to follow the rules consistently.

The prompt was explicit: don't repeat the player's words, and the item must relate to the worry only as a metaphor. Early versions would turn "rent went up again" into "a rent bill that went up", and the line length of the fortune poems was unstable.

So I moved the rules out of the prompt and into code. The server validates field by field: the recipient must be on a whitelist, the item name may not contain words from the original line, and each line of the poem must be exactly 7 Chinese characters. When something fails, instead of a vague "try again", it tells the model exactly which rule failed, and allows up to 3 rewrites.

After the change I ran a batch of 13: 9 were compliant on the first try, and the other 4 were fixed by rewriting — 3 on the first rewrite, 1 on the second. All 13 ended up compliant.

Making the prompt longer is far less effective than "validate + specific feedback + rewrite". It's the same conclusion I reached in the harness comparison.

Variety is a design question, not a model question

At first, almost every work-related worry went to "Engineer Lin at the overtime tower". Reasonable, but boring. I added one rule — "avoid the two residents who received letters most recently" — and recipients spread from 2 people (over 4 letters) to 6 people (over 10 letters). The cost is that sometimes the best-fitting resident gets pushed out.

I didn't hand that trade-off to the model, because it was never the model's call. Accuracy versus freshness is a game-design decision.

Latency can hide inside the game

Generating a letter takes about 4.8 seconds at the median and over 10 seconds when slow. Instead of a loading animation, the postman says: "It'll be sorted by the time the shuttle does a lap — go wander around."

Once the player walks away, the wait no longer exists.

Later, thinking about action games, I realized the idea carries over directly: the death screen and the run back to where you died are already dead time. If the AI writes a little "legend of your death" then, nobody will feel it's slow. Putting the wait into gaps the game already has is much easier than making the model faster.

The biggest problem with free models is availability

I used Zhipu's free models. In practice the newest, glm-4.7-flash, often returned "too many requests", and once didn't respond for 40 seconds. So I built a model fallback chain — if one fails, switch to the next — with hand-written content as the last resort.

When the AI fails, the game must never get stuck. That has to be designed at the demo stage, not patched in after launch.

The last valve

What players write is real emotion. When there's an obvious crisis expression, the content doesn't enter the game and isn't sent to the model; the game shows a mental-health hotline instead.

I didn't leave that to the model's judgment in the moment. Some things shouldn't be probabilistic.

If it moved into Minecraft

I'd build it as a server-side plugin: all model calls happen on the server, so players don't install anything or enter their own API key. Making players configure a key is currently the biggest turn-off for AI mods. Each letter is about 700 tokens; add a "one letter per day" limit and the cost is fully under control.

I also know that farming and idle-game players rarely pay. So it fits best as a free, open-source mod. If anything is charged, it should be a hosting fee to server owners, not to players.

Most AI mods in Minecraft today give NPCs a mouth — someone to mine with, someone to chat with. I want to do something else: open a door from the game into the player's real life, so that after work they have somewhere to set the day down.

02. 写在 prompt 里的规则只是建议: 「心事邮差」开发笔记

素材:第 2 题回答、开发日志、Demo 视频

余晖站是我做的一个网页小游戏,灵感来自一款在韩国很火的山寺题材小游戏。那款游戏面向上班摸鱼的人,几乎没有上手成本,但也正因为简单,玩家玩几天就走了。我想试试,AI 能不能给这类游戏一个让人每天回来的理由。

于是有了「心事邮差」:玩家写下一句今天的烦心事,AI 把它变成一件游戏里的物品,挑一个最适合收下它的居民,玩家把东西送过去,居民回一封信。

几个模型实际生成的例子:

  • "好久没给家里打电话了" → 一卷缠绕的耳机线 → 信号塔的老唐
  • "房租又涨了" → 漏气的气球 → 拉面摊老板娘
  • "和最好的朋友吵架了" → 裂开的陶瓷杯 → 唱诗班的小乔

判断它是不是"AI 原生",我用的标准很简单:拿掉 AI,这个玩法还成不成立?我在 demo 里做了一个没有 AI 时的手写兜底,4 个关键词模板加 1 个默认。体验立刻退化成抽签,玩家一眼就能看出回信和自己写的话没关系。

难的不是写得好,是按规矩写

我原以为难点在文笔。做下来发现,难点在于让模型稳定地守规矩。

prompt 里我写得很清楚:不要复述玩家原话,物件和烦恼只能是比喻关系。早期版本里,它会把"房租又涨了"变成"涨价的房租单",签诗的字数也不稳定。

后来我把规则从 prompt 挪进了代码。服务端逐个字段校验:收件人必须在白名单里,物件名不能出现原话里的词,签诗每行必须恰好 7 个汉字。不合格时,不是笼统地让它"再来一次",而是告诉它具体哪一条不合格,最多重写 3 次。

改完后跑了 13 次批量测试:第一次就合规的有 9 次,另外 4 次靠重写改对,其中 3 次一次改对,1 次两次改对。最后 13 次全部合格。

把 prompt 写得更长,远不如"校验 + 具体反馈 + 重写"有效。这和我在 harness 对比实验里得到的结论是同一件事。

多样性是玩法的事,不是模型的事

一开始,工作类的烦恼几乎都被派给"加班大厦的林工"。合理,但无聊。我加了一条"避开最近收过信的两位居民",收件人从 2 个人(4 封信)分散到 6 个人(10 封信)。代价是有时会把最合适的那个人挤掉。

这个取舍我没有交给模型,因为它本来就不该由模型决定。要准还是要新鲜,是玩法设计的问题。

延迟可以藏进游戏里

生成一封信的中位耗时大约 4.8 秒,慢的时候超过 10 秒。我没做加载动画,而是让邮差说:"班车跑一圈的工夫就分好,你先随便走走。"

玩家走开了,等待就不存在了。

后来想动作游戏的方向时,我发现这个思路可以直接搬过去:死亡画面和跑回原地的那段时间本来就是空的,AI 在这时候写一段"死亡传说",没有人会觉得慢。把等待放进游戏本来就有的空白里,比把模型调快容易得多。

免费模型最大的问题是"能不能用"

我用的是智谱的免费模型。最新的 glm-4.7-flash 实测经常返回"访问量过大",还出现过一次 40 秒没响应。所以我做了一条模型备用链,一个不行自动换下一个,最后再用手写内容兜底。

AI 失败的时候,游戏绝对不能卡住。这一点在 demo 阶段就要想好,不能等上线再补。

最后一道阀门

玩家写下的是真实情绪。遇到明显的危机表达,内容不会进入游戏,也不会发给模型,而是直接显示心理援助热线。

这一条我没有交给模型临场判断。有些事情不该是概率性的。

如果搬进 Minecraft

我会把它做成服务端插件:模型调用全在服务器上,玩家不用装任何东西,也不用自己填 API Key。让玩家自己配 Key,是现在 AI Mod 最大的劝退点。每封信大约 700 token,再加一个"一天一封"的限额,成本完全可控。

我也清楚,种田和摸鱼类的玩家很难付费。所以它更适合做成免费开源的 Mod,真要收费,也应该向服主收托管服务的钱,而不是向玩家收。

现在 MC 里的 AI Mod 大多在给 NPC 装一张嘴,陪你挖矿、陪你聊天。我想做的是另一件事:给玩家的现实生活开一个入口,让他们下了班,有个地方把今天放下。

03. What game agents lack is often not a stronger model

Sources: answer to question 1 (section 5), answer to question 3, my study notes on Gemini Plays Pokémon. The Pokémon figures come from notes I compiled and were not each re-checked against primary sources.

In May 2025, Gemini finished Pokémon Blue. A year later, Claude finished Pokémon Red. For a while the community argued about which model was stronger, then realized the question can't be answered directly: the two runs used different harnesses.

A harness is the layer of program between the model and the game. The model can't look at a screen or press a controller; what it sees, what it can do and what it remembers are all decided by that layer. After running my own "same model, five harnesses" experiment, I looked back at these game agents and felt that many of their failures had little to do with how smart the model was.

Where they get stuck looks familiar

Gemini Plays Pokémon had a few famous failures.

The model believed a move still had PP when it had already run out. Changing the prompt didn't help; what finally fixed it was reading live PP straight from game memory.

Once the context grew past roughly 100k tokens, it started looping, so the history had to be compressed into summaries periodically. It also got stuck in a backyard for about 8 hours because a wrong belief stayed in context; it only got out when the developer cleared the context.

Put together, the first kind of failure is missing observation, the second is missing memory management. A stronger model might soften them, but the real fixes all live in the harness.

VISTA takes this to the extreme

VISTA, from Kaiming He's team, is a cleaner example. The same Claude Opus 5.0 scores 40.68 on ARC-AGI-3's public games with the official minimal implementation, and 100 with VISTA's harness.

What it does is plain: keep every raw frame, and let the model decide which frame to look back at, which region to zoom into and which pixel to read.

My reading is that in games, missing a detail costs far more than in code. Miss a line in code and the compiler tells you; miss a pixel in a game and you may follow a wrong assumption for a long time.

The 100 needs a caveat, though. The authors themselves wrote at the end of their page that the model was released after the public games, so exposure during training can't be ruled out, and the private set is the real test. What I'm citing is the gap from 40 to 100, not the perfect score itself.

Give tools, not walkthroughs

There's another evolution on the Gemini side that I like. Early harnesses provided lots of help: a pathfinding sub-agent, a boulder-puzzle sub-agent, a map of walkable tiles. By the later Yellow Legacy run, the developer removed these and replaced them with meta-tools that let the model define its own sub-agents and write and run its own code.

From "humans build tools for the model" to "the model builds tools for itself". What's learned the first way is mostly tied to one game; the second way is more likely to carry over to the next.

The game harness I'd want

If I assembled one, it would have four parts:

  1. Pi Durable's crash recovery. In my experiment, after its process was killed it resumed from the checkpoint by itself and finished in 83 seconds, with no one saying "continue". To be clear, the code it wrote after recovering wasn't good; what I want is the mechanism.
  2. Claude Code's patient retries. Under server overload it retried up to 22 times in one run and was never interrupted by it.
  3. VISTA's lossless visual memory.
  4. Mandatory verification after every action — for example, reading game memory to confirm the character actually moved, instead of taking the model's word that "I've reached the door".

The fourth comes straight from my experiment: in 10 of 25 runs, the agent declared done with compile errors. If that happens in coding, it's easy to imagine what an unnoticed "I thought I did it" compounds into over a game that runs for hundreds of hours.

As for the model, you can always swap in a stronger one.

What I haven't verified yet

The combination above is a judgment, not a result. What I tested were coding tasks with a small sample, and the game part relies on other people's public data. Next I want to pick a small game, toggle "verify after action" on and off by itself, and measure the difference.

03. 游戏 Agent 缺的往往不是更强的模型

素材:第 1 题回答第五节、第 3 题回答、Gemini Plays Pokémon 学习笔记。宝可梦部分的数字来自我整理的学习笔记,没有逐条回到一手来源核对。

2025 年 5 月,Gemini 通关了《宝可梦 蓝》。一年后,Claude 通关了《宝可梦 红》。社区一度在争谁更强,后来发现这个问题没法直接回答:两边的 harness 不一样。

harness 是模型和游戏之间的那层程序。模型不会看屏幕,也不会按手柄,它看到什么、能做什么、记得什么,都由这层程序决定。我自己做了一次"同一个模型换五个 harness"的实验之后,再回头看这些游戏 Agent,觉得很多失败其实和模型聪不聪明关系不大。

卡住的地方都很像

Gemini Plays Pokémon 的几个翻车现场很有名。

模型以为某个招式还有 PP,其实已经用完了。改提示词没用,最后是直接从游戏内存里读出实时 PP,才解决。

上下文超过大约 10 万 token 之后,它开始陷入重复循环,所以要定期把历史压缩成摘要。它还在一个后院卡了大约 8 小时,原因是一个错误的判断一直留在上下文里,最后由开发者清空上下文才走出来。

把这些放在一起看,前一类缺的是观测,后一类缺的是记忆管理。换一个更强的模型或许能缓解,但真正的修法都在 harness 里。

VISTA 把这件事推到了极端

何恺明团队的 VISTA 给了一个更干净的例子。同一个 Claude Opus 5.0,在 ARC-AGI-3 的公开游戏上,用官方的最小实现得 40.68 分,换成 VISTA 的 harness 得 100 分。

它做的事情很朴素:保存每一帧原图,让模型自己决定回看哪一帧、放大哪一块、读哪个像素。

我的理解是,游戏里"看漏一个细节"的代价比写代码大得多。写代码漏看一行,编译器会告诉你;游戏里漏看一个像素,你可能会沿着错误的假设走很久。

不过 100 分要加一个限定。作者自己在主页末尾写了:所用模型发布在公开游戏之后,不能排除训练时见过,私有集才是真正的检验。所以我引用的重点是 40 到 100 之间的差距,不是满分本身。

给工具,不给攻略

Gemini 那边还有一个演进我很喜欢。早期的 harness 给了很多辅助:寻路子 Agent、推石头谜题子 Agent、可走的格子。到了后来的《黄 Legacy》,开发者把这些拿掉,换成让模型自己定义子 Agent、自己写代码并运行的元工具。

从"人给模型造工具",变成"模型给自己造工具"。前者学到的东西多半绑在这一款游戏上,后者更有可能带到下一款。

我想要的游戏 harness

如果让我拼一个,会有四块:

  1. Pi Durable 的崩溃恢复。我的实验里,进程被杀后它能从断点自己接着跑,83 秒做完,不用人说"继续"。要说清楚的是,它恢复后写出的代码质量并不好,我要的只是这个机制。
  2. Claude Code 的耐心重试。它在服务端过载时一次最多重试 22 次,从没因此中断。
  3. VISTA 的无损视觉记忆。
  4. 动作之后必须验证。比如读游戏内存,确认角色真的移动了,而不是听模型说"我已经走到门口了"。

第四条是我从实验里带出来的。25 次运行里有 10 次,agent 带着编译错误宣布完成。写代码尚且如此,在一局几百小时的游戏里,一个没被发现的"我以为我做到了"会累积成什么样,不难想象。

至于模型,可以随时换更强的。

一个还没验证的地方

上面这个组合是判断,不是结果。我测过的是编程任务,样本也不大,游戏部分用的是别人公开的数据。下一步我想做的,是挑一个小游戏,把"动作后验证"单独开关,看看能差多少。

04. VISTA's "perfect score": Its loudest line is also its biggest risk

Source: answer to question 3

The first screen of VISTA's project page says: perfect scores on all 25 public games. Chinese media headlines went further and said it had "beaten the AGI exam".

Media headline

In the last section of the same page, the authors themselves added a caveat: the model used was released after the public games, so it can't be ruled out that it saw them during training; the private set is the real test of generalization.

The authors' caveat, at the very bottom of the page

The first screen gets copied. Nobody reads the last section.

A reminder from the benchmark's author

On 14 August, François Chollet, who created ARC-AGI, posted a "routine reminder": roughly, that the public games are a demo set, not an evaluation set, and scores on them don't represent real results. The post named no one, but it came 9 days after VISTA's blog post. I can't confirm who it was aimed at.

Chollet's reminder

None of this changes the fact that VISTA is solid research. But as long as the private-set score isn't perfect, the second wave of coverage could turn into "the perfect score gets debunked".

Change the main message

If I were in charge of the launch, I'd deliberately tone it down and replace "perfect score" with: same model, no training, just a harness that can "look" — ARC-AGI-3 goes from 40 to 100.

That line keeps the contrast and puts the credit on VISTA's real contribution. More importantly, it still holds if the private-set score is lower, because "how much did swapping only the harness add" can be re-measured on the private set.

I also prefer it because I ran a similar experiment myself: fix the model, change only the harness. The gap really is there.

Move the caveat up front

I'd move the caveat from the bottom to the first screen and give it its own post: what we haven't tested, and how we plan to test the private set.

This comes from my own experience. I run publicity for the Zurich Chinese Students Association, more than 40 events a year. The most direct way to get people to show up is often a subsidy, but that kind of participation is one-off: the numbers look good, the people don't stay. Those who come with a real purpose most want an honest answer.

VISTA is the same. Readers chasing "perfect score" leave as soon as the private set comes out; the researchers and engineers drawn in by "only the harness changed" and "here's what we haven't proven yet" are the ones who will reproduce and port it.

The most underrated material

The page includes a full replay for every game, showing what the model looked at, what it remembered and which frame it went back to at each step. But they're buried mid-page behind a plain "View replay" link.

"AI plays games" videos on Bilibili get millions, even tens of millions, of views, and this is exactly what viewers want: getting stuck, looking back, the sudden click. I'd pick the 3 most dramatic replays and cut them into a 30-second vertical clip and a 3-minute horizontal one.

What success looks like

I wouldn't look at read counts. I'd look at three things: how many people are porting and reproducing it; whether people retelling it say "perfect score" or "only the harness changed"; and, in the week the private-set results come out, whether the reaction is "knew it didn't hold up" or "they said so from the start".

The last one is the hardest, and the most telling.

04. VISTA 的"满分": 是它最响亮的一句话,也是最大的风险

素材:第 3 题回答

VISTA 的项目主页第一屏写着:25 个公开游戏全部满分。中文媒体的标题更进一步,说它"把 AGI 考试打穿了"。

媒体标题

同一个主页的最后一节,作者自己写了一段限定:所用模型发布于公开游戏之后,不能排除训练时见过这些游戏,私有集才是真正的泛化检验。

作者写的限定,在页面最底部

第一屏有人抄,最后一节没人看。

基准作者的提醒

8 月 14 日,ARC-AGI 的作者 Chollet 发了一条"例行提醒",大意是公开游戏是演示集,不是评测集,它上面的分数不代表真实成绩。这条推文没有点名任何人,但它发在 VISTA 博客发布后的第 9 天。我没法确认它针对谁。

Chollet 的提醒

这不影响 VISTA 是一篇扎实的研究。但只要私有集的成绩不是满分,第二波传播就可能变成"满分被打脸"。

换一句主信息

如果我负责传播,我会主动降调,把"满分"换成:同一个模型,不训练,只换一个会"看"的 harness,ARC-AGI-3 从 40 分到 100 分。

这句话保留了反差,又把功劳放在 VISTA 真正的贡献上。更重要的是,即使私有集分数低一些,它也站得住,因为"只换 harness 涨了多少"在私有集上可以重新测。

我偏爱这句,还因为我自己做过类似的实验:固定模型,只换 harness。差距确实在那里。

把限定提前

我会把末尾那段限定挪到第一屏,单独发一条:我们哪些没测,私有集打算怎么测。

这个判断来自我自己的经历。我在苏黎世学联做宣传,每年 40 多场活动。让人来参与,最直接的办法往往是给补贴,但这种参与是一次性的,数字好看,人留不住。真正带着目的来的人,最想听到的是真诚的回答。

VISTA 也一样。追着"满分"来的读者,私有集一出就走;被"只换 harness"和"我们还没证明什么"吸引来的研究员和工程师,才会去复现、去移植。

最被低估的素材

主页给每个游戏都放了完整回放,能看到模型每一步看了什么、记了什么、回看了哪一帧。但它们埋在页面中段,只是一个"View replay"链接。

B 站上"AI 玩游戏"的视频有几百万上千万播放,观众要看的就是这个:卡住、回看、突然想通。我会挑 3 个最有戏剧性的,剪成 30 秒竖屏和 3 分钟横屏。

怎么算成功

我不看阅读量,看三件事:有多少人在移植和复现;别人转述时用的是"满分"还是"只换 harness";私有集结果出来那周,舆论是"果然不行",还是"他们早就说过"。

最后一件最难,也最能说明问题。

05. View counts lie: What I learned from AI content on six platforms

Sources: answer to question 4, raw Bilibili data. Figures are as of the screenshots and will change.

While browsing AI agent courses on Bilibili, I found two videos with 1.6 to 1.9 million views and, respectively, 0 and 4 danmaku (on-screen comments).

They were published in 2023, yet their titles mention Claude Code, which was only released in 2025. The most likely explanation is that old videos were retitled and the views were earned by the old content. I can't be sure of the exact reason, but if you pick what to learn from by view count alone, these two would rank near the top.

Two ratios

So I pulled public data for 8 similar videos and looked at two ratios: danmaku per 10,000 views, and favorites divided by likes.

Bilibili data comparison

"AI plays games" videos get roughly 6 to 23 danmaku per 10k views, with fewer favorites than likes: people come to laugh and heckle. AI tool tutorials get about 1.7× as many favorites as likes: people come back to follow along. One 8-minute Claude Code install tutorial hit 92 danmaku per 10k views; my guess is viewers were posting errors and answering each other in the comments.

The same holds on Xiaohongshu. Both searched for "Claude Code": an "explained in one post" guide got 102 likes and 153 saves; "it ruined my life" got 187 likes and 51 saves. The first is something to keep; the second is something to relate to.

Douyin adds one more signal. One AI werewolf video got 815k likes and 530k shares — shares above 60% of likes. On Bilibili, Doubao playing Minecraft got 477k likes and 24k shares.

So my rule of thumb: for entertainment, look at comments and shares; for how-to content, look at saves; treat views as a reference only. The sample is small — it's a useful heuristic, not a law.

Even in a series, not every episode takes off

In that AI werewolf series, episode 2 got 815k likes, episode 3 got 30k, episode 4 got 5,686.

A series is still worth doing; it gives people a reason to come back. But the format is only the ticket in. What decides whether an episode takes off is whether that game had a moment people wanted to send to a friend.

Each platform stops people for a different reason

After going through the examples, I think "one piece of content, many platforms" doesn't mean rewriting the same paragraph six times. It means picking, from the same material, the piece of evidence each platform wants and putting it first.

X wants an opinion or a new term — Karpathy's "vibe coding" had no image and no link. Xiaohongshu wants an image whose result you can read at a glance, like "launch sales hit $356k". Jike wants a real moment: I saw a post that started with going out with a fever, walking past a Confucian temple, and ended up on harnesses — only 11 likes, but most readers were peers. Douyin wants a moment, Bilibili wants the whole process, and a long-form blog wants a method you can reproduce.

Take my own harness experiment. On X I'd lead with "Codex wrote 'type check passed', but the code doesn't compile"; on Jike, the log that only went through at 3:36 a.m.; on Xiaohongshu, the score table for the five tools. One experiment, six openings.

Watch how others retell you

The last lesson comes from VISTA. Its real contribution was "only the harness changed", but what people repeated was "perfect score".

The line others use when they retell your work is your real hook. If it isn't the one you wanted, change the next post.

05. 播放量会骗人: 看了六个平台的 AI 内容之后

素材:第 4 题回答、B 站原始数据。数字是截图时的值,会变。

我在 B 站翻 AI Agent 课程时,看到两个播放量 160 万到 190 万的视频,弹幕分别是 0 条和 4 条。

它们发布于 2023 年,标题里却写着 Claude Code,而 Claude Code 2025 年才发布。最可能的解释是老视频改了标题,播放量是旧内容攒下的。我没法确定具体原因,但如果只按播放量找学习对象,这两个会排在很前面。

两个比值

所以我拉了 8 个同类视频的公开数据,看两个比值:每一万次播放有多少条弹幕,以及收藏除以点赞。

B 站数据对比

AI 玩游戏的视频,弹幕每万播大约 6 到 23,收藏比点赞少,大家来笑、来吐槽。AI 工具教程的收藏是点赞的 1.7 倍左右,大家要回来照着做。一条 8 分钟的 Claude Code 安装教程,弹幕每万播高达 92,我猜是观众在弹幕里报错和互相答疑。

小红书上同样成立。都是搜"Claude Code",「一文讲透」102 赞、153 收藏;「毁了我的生活」187 赞、51 收藏。前一篇是拿来存的,后一篇是拿来共鸣的。

抖音多一个信号。有一条 AI 狼人杀 81.5 万赞、53 万转发,转发是点赞的六成多;B 站的豆包玩 MC 47.7 万赞,转发 2.4 万。

所以我的标准是:娱乐内容看弹幕和转发,干货看收藏,播放量只作参考。样本很小,这是一个好用的经验,不是规律。

同一个系列,也不会每集都火

那个 AI 狼人杀的合集,第 2 集 81.5 万赞,第 3 集 3.0 万,第 4 集 5686。

做成系列仍然值得,它让人有理由回来。但格式只是入场券,决定一集火不火的,是那一局里有没有让人想转给朋友的瞬间。

每个平台停下来的理由不同

看完一圈例子,我觉得"一鱼多吃"不是把一段话改写六遍,而是从同一份素材里,给每个平台挑出它要的那个证据放在最前面。

X 要一个观点或者新词,Karpathy 的 vibe coding 没有图也没有链接。小红书要一张能看懂结果的图,比如"首发卖了 35.6 万美元"。即刻要一个真实的瞬间,我看到一条从发烧出门、路过文庙写起,最后讲到 harness 的动态,只有 11 个赞,但读到的大多是同行。抖音要一个瞬间,B 站要整个过程,长文博客要一套能复现的方法。

拿我自己的 harness 实验举例,X 上我会先放"Codex 写了类型检查通过,但代码编译不过";即刻先放凌晨 3 点 36 分才跑成的日志;小红书先放五个工具的分数表。实验只有一个,开头有六种。

看别人怎么转述你

最后一条经验来自 VISTA。它真正的贡献是"只换 harness",可大家转述的是"满分"。

别人转述你时用的那句话,才是你真正的钩子。如果它不是你想要的那句,下一条就该改了。

Study notes · Deep learning

01. Backpropagation by shapes: Deriving gradients without memorizing them

Most backprop mistakes I made early on were not calculus mistakes. They were bookkeeping mistakes: a transpose in the wrong place, a sum over the wrong axis. These notes are the version of backpropagation I wish I had started with, where every step is checked by asking one question: what shape must this be?

Start with the shape contract

Take one dense layer in the batch-first convention. A batch of BB inputs with dind_{in} features is a matrix X∈RB×dinX \in \mathbb{R}^{B \times d_{in}}. The layer owns W∈Rdout×dinW \in \mathbb{R}^{d_{out} \times d_{in}} and b∈Rdoutb \in \mathbb{R}^{d_{out}}, and computes

Z=XW⊤+b,A=ϕ(Z)Z = XW^\top + b, \qquad A = \phi(Z)

so Z,A∈RB×doutZ, A \in \mathbb{R}^{B \times d_{out}}. The batch axis passes through untouched; only the feature axis changes. Writing this contract down before anything else is the cheapest debugging tool in deep learning, because almost every later formula can be recovered from it.

Why the nonlinearity is not optional

If ϕ\phi is the identity, stacking layers buys nothing:

W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2)W_2(W_1x + b_1) + b_2 = (W_2W_1)\,x + (W_2b_1 + b_2)

A composition of affine maps is one affine map. Depth only adds expressive power once something nonlinear sits between the layers. This is also why the choice of activation matters for training and not just for expressiveness: its derivative ϕ′(Z)\phi'(Z) multiplies every gradient that flows back through the layer.

The three gradients of a dense layer

Let LL be a scalar loss and write GA=∂L/∂AG_A = \partial L / \partial A for the gradient arriving from above. It has the same shape as AA. One rule covers everything that follows: a gradient has the shape of the thing it is a gradient of.

Through the activation, which acts elementwise:

GZ=GA⊙ϕ′(Z)G_Z = G_A \odot \phi'(Z)

Through the affine map there are three things to differentiate, and for each one only a single arrangement of GZG_Z, XX and WW produces the right shape:

∂L∂W=GZ⊤X,∂L∂b=∑i=1B(GZ)i,:,∂L∂X=GZW\frac{\partial L}{\partial W} = G_Z^\top X, \qquad \frac{\partial L}{\partial b} = \sum_{i=1}^{B} (G_Z)_{i,:}, \qquad \frac{\partial L}{\partial X} = G_Z W

Check them against the contract. GZ⊤XG_Z^\top X is (dout×B)(B×din)(d_{out} \times B)(B \times d_{in}), which is the shape of WW. The bias was broadcast across the batch on the way forward, so its gradient is summed across the batch on the way back. And GZWG_Z W is (B×dout)(dout×din)(B \times d_{out})(d_{out} \times d_{in}), the shape of XX, which becomes the GAG_A of the layer below. If you store WW as din×doutd_{in} \times d_{out} instead, every transpose moves. That is the reason to derive from shapes instead of memorizing.

A single neuron, with numbers

Let z=wx+bz = wx + b, a=σ(z)a = \sigma(z) and L=12(a−y)2L = \tfrac12 (a - y)^2, with x=1.5x = 1.5, w=0.8w = 0.8, b=−0.2b = -0.2, y=1y = 1.

Forward: z=1.0z = 1.0, a=σ(1.0)≈0.7311a = \sigma(1.0) \approx 0.7311, L≈0.0362L \approx 0.0362.

Backward, one local derivative per edge of the graph:

  • ∂L/∂a=a−y≈−0.2689\partial L/\partial a = a - y \approx -0.2689
  • ∂a/∂z=a(1−a)≈0.1966\partial a/\partial z = a(1-a) \approx 0.1966
  • ∂z/∂w=x=1.5\partial z/\partial w = x = 1.5 and ∂z/∂b=1\partial z/\partial b = 1

Multiplying along the path gives ∂L/∂w≈−0.0793\partial L/\partial w \approx -0.0793 and ∂L/∂b≈−0.0529\partial L/\partial b \approx -0.0529. Both are negative, so gradient descent increases ww and bb, which pushes aa toward the target of 1. Being able to predict the sign before computing it is a good test of whether the derivation is understood or only executed.

Softmax with cross-entropy

Softmax is not elementwise: every output depends on every logit, so it has a full Jacobian. Combined with cross-entropy, though, the result collapses to something simple. With probabilities p=softmax⁡(z)p = \operatorname{softmax}(z) and a one-hot target yy:

∂L∂z=p−y\frac{\partial L}{\partial z} = p - y

Frameworks fuse the two operations for this reason. The fused form is cheaper and avoids taking the log of a probability that has underflowed to zero.

What it costs

A dense layer does O(B⋅din⋅dout)O(B \cdot d_{in} \cdot d_{out}) multiply-adds going forward and holds O(din⋅dout)O(d_{in} \cdot d_{out}) parameters. The backward pass is the same order as the forward pass, since it is again a few matrix products of the same sizes. The real price of backprop is memory: every intermediate activation has to be kept until the gradient has passed back through it. That is why the memory used in training grows with depth and batch size, while inference can discard activations as it goes.

How I test myself

  • State the shape of every tensor in a two-layer MLP before writing any formula.
  • Derive ∂L/∂W\partial L/\partial W with WW stored as din×doutd_{in} \times d_{out} and explain which transposes moved.
  • Explain why the bias gradient is a sum over the batch and not a mean. (The mean, if there is one, already lives inside LL.)
  • Predict the sign of a gradient in a small example before computing it.

References

  1. Rumelhart, Hinton & Williams (1986), Learning representations by back-propagating errors
  2. Goodfellow, Bengio & Courville (2016), Deep Learning, chapter 6
  3. PyTorch documentation, Autograd mechanics

02. Keeping signals alive: Initialization, AdamW and learning-rate schedules

Knowing how to compute a gradient does not mean a network will train. Three decisions determine whether the signal survives the trip through a deep model: how the weights start, how each step is scaled, and how the step size changes over time. These notes collect the reasoning behind the defaults I now reach for.

Initialization is a variance budget

Consider one pre-activation z=∑i=1ninwixiz = \sum_{i=1}^{n_{in}} w_i x_i with independent, zero-mean weights and inputs. Then

Var⁡(z)=nin Var⁡(w) Var⁡(x)\operatorname{Var}(z) = n_{in} \, \operatorname{Var}(w) \, \operatorname{Var}(x)

If that factor ninVar⁡(w)n_{in}\operatorname{Var}(w) is larger than 1, activations grow layer by layer; if it is smaller, they shrink. After fifty layers either one is fatal. Keeping the forward variance constant asks for Var⁡(w)=1/nin\operatorname{Var}(w) = 1/n_{in}. Asking the same of the backward pass gives 1/nout1/n_{out}. Xavier (Glorot) initialization compromises between the two:

Var⁡(w)=2nin+nout\operatorname{Var}(w) = \frac{2}{n_{in} + n_{out}}

ReLU sets roughly half of its inputs to zero, which halves the variance that gets through. He initialization compensates by doubling it:

Var⁡(w)=2nin\operatorname{Var}(w) = \frac{2}{n_{in}}

The practical rule is short: match the initializer to the activation. Xavier suits tanh-like units, He suits ReLU-like units. Residual connections and normalization layers make modern networks far more forgiving, but they do not make initialization irrelevant.

From SGD to Adam

Plain SGD moves against the gradient gtg_t with one global step size. Momentum averages recent gradients so that consistent directions accumulate and oscillating ones cancel. Adam goes one step further and keeps two running averages, of the gradient and of its square:

mt=β1mt−1+(1−β1) gt,vt=β2vt−1+(1−β2) gt2m_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2

Both start at zero, so early values are biased toward zero. Dividing by 1−βt1-\beta^t corrects that:

m^t=mt1−β1t,v^t=vt1−β2t,θt=θt−1−η m^tv^t+ϵ\hat m_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat v_t = \frac{v_t}{1-\beta_2^t}, \qquad \theta_t = \theta_{t-1} - \eta \, \frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon}

The effect is a separate step size per parameter. Parameters that rarely receive gradient take larger steps; parameters with large, noisy gradients take smaller ones.

Why AdamW and not Adam with L2

With plain SGD, adding an L2 penalty to the loss and shrinking the weights directly (weight decay) are the same thing. With Adam they are not. An L2 term enters through the gradient, so it is divided by v^t\sqrt{\hat v_t} like everything else. Weights with a large gradient history end up being regularized less, which is the opposite of what one wants. AdamW removes the decay from the gradient and applies it straight to the weights:

θt=θt−1−η(m^tv^t+ϵ+λ θt−1)\theta_t = \theta_{t-1} - \eta \left( \frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon} + \lambda\, \theta_{t-1} \right)

This is why AdamW became the default for Transformers. Biases and normalization gains are usually excluded from the decay, since shrinking them has no regularizing benefit.

Warmup, then cosine

At step zero Adam's variance estimate is built from very few gradients and the weights are random, so a full-size step can do lasting damage. Linear warmup raises the learning rate from near zero to its peak over the first few hundred or thousand steps. After that, cosine decay lowers it smoothly:

ηt=ηmin+12 (ηmax−ηmin)(1+cos⁡πtT)\eta_t = \eta_{min} + \tfrac12 \,(\eta_{max} - \eta_{min}) \left(1 + \cos\frac{\pi t}{T}\right)

Large steps early cover ground; small steps late let the model settle. The schedule has few knobs, which is a large part of its appeal.

Regularization in one paragraph each

Dropout zeroes each activation with probability pp during training and scales the survivors by 1/(1−p)1/(1-p), so that the expected activation is unchanged and nothing needs rescaling at inference.

Weight decay pulls weights toward zero and limits how much the model can rely on any single feature.

Normalization layers are not regularizers by design, but by keeping activation statistics in a stable range they widen the set of learning rates that work.

Early stopping is the cheapest of all: stop when validation loss stops improving.

When the loss will not go down

The order I check things in, cheapest first:

  • Can the model overfit a single batch? If not, the bug is in the model, the loss or the data pipeline, not in the hyperparameters.
  • Is the loss at initialization what it should be? For CC balanced classes it should start near ln⁡C\ln C.
  • Is the learning rate off by an order of magnitude? Try a factor of ten in both directions before touching anything else.
  • Are gradients vanishing or exploding? Log the gradient norm per layer.
  • Does validation loss diverge from training loss? That is a regularization or data question, not an optimization one.

References

  1. Glorot & Bengio (2010), Understanding the difficulty of training deep feedforward neural networks
  2. He et al. (2015), Delving Deep into Rectifiers
  3. Kingma & Ba (2014), Adam: A Method for Stochastic Optimization
  4. Loshchilov & Hutter (2017), Decoupled Weight Decay Regularization
  5. Loshchilov & Hutter (2016), SGDR: Stochastic Gradient Descent with Warm Restarts
  6. Srivastava et al. (2014), Dropout: A Simple Way to Prevent Neural Networks from Overfitting

03. Attention from scratch: Shapes, masks and what it costs

Attention is easier to understand as an answer to a specific problem than as a formula. These notes follow that route: the bottleneck it removed, the four lines of the mechanism, how it is assembled into a Transformer block, and what the bill looks like.

The bottleneck attention removed

A recurrent encoder-decoder reads the source sentence one token at a time and squeezes everything into a final hidden state. The decoder then has to generate the whole output from that single vector. Long inputs suffer most, since early tokens have been overwritten many times by the end. Bahdanau and colleagues let the decoder look back at all encoder states at every step and learn how much weight to give each one. The Transformer then asked whether the recurrence was needed at all, and kept only the looking-back.

Scaled dot-product attention in four lines

Given queries Q∈RTq×dkQ \in \mathbb{R}^{T_q \times d_k}, keys K∈RTk×dkK \in \mathbb{R}^{T_k \times d_k} and values V∈RTk×dvV \in \mathbb{R}^{T_k \times d_v}:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

Read it as four steps.

  1. QK⊤QK^\top scores every query against every key. Shape: Tq×TkT_q \times T_k.
  2. Dividing by dk\sqrt{d_k} keeps those scores in a sensible range.
  3. Adding the mask MM and taking a softmax along the key axis turns each row into weights that sum to one.
  4. Multiplying by VV takes a weighted average of the values. Shape: Tq×dvT_q \times d_v.

Two consequences fall out of the shapes. The output has one row per query, so its length is set by the queries, not by what is attended to. And each output row is a mixture of values, which means attention by itself can only average; the nonlinear work happens in the feed-forward layer that follows.

Why divide by the square root of the key dimension

If the components of a query and a key are independent with zero mean and unit variance, their dot product is a sum of dkd_k such terms and has variance dkd_k. As the dimension grows, the scores spread out, the softmax saturates toward a one-hot vector, and its gradient becomes vanishingly small. Dividing by dk\sqrt{d_k} brings the variance back to one regardless of dimension.

Masks are added, not multiplied

A mask is a matrix of zeros and −∞-\infty added to the scores before the softmax, so that masked positions receive exactly zero weight. Two kinds matter. A padding mask hides positions that exist only to make sequences in a batch the same length. A causal mask hides the future: position tt may attend only to positions up to tt. This is what lets a decoder be trained on every position of a sequence in a single parallel pass while still behaving autoregressively.

Many heads, one block

Multi-head attention splits the model dimension into hh heads of size dk=dmodel/hd_k = d_{model}/h, runs attention independently in each, concatenates the results and applies an output projection. The cost is about the same as one full-width head, but different heads can track different relations.

A Transformer block wraps two sublayers, attention and a position-wise feed-forward network, in residual connections with normalization. In the pre-norm arrangement used by most recent models:

h′=h+Attention⁡(Norm⁡(h)),hout=h′+FFN⁡(Norm⁡(h′))h' = h + \operatorname{Attention}(\operatorname{Norm}(h)), \qquad h_{out} = h' + \operatorname{FFN}(\operatorname{Norm}(h'))

The residual path gives gradients a direct route to early layers. Attention has no built-in sense of order, so position has to be injected separately; the original paper added sinusoidal encodings to the input embeddings.

The bill

For batch BB, sequence length TT and model dimension dd:

Component Compute What dominates
Q, K, V and output projections O(B⋅T⋅d2)O(B \cdot T \cdot d^2) Short sequences
Attention scores and weighted sum O(B⋅T2⋅d)O(B \cdot T^2 \cdot d) Long sequences
Score memory, naive, with HH heads O(B⋅H⋅T2)O(B \cdot H \cdot T^2) Long sequences

Compare a recurrent layer at O(B⋅T⋅d2)O(B \cdot T \cdot d^2): linear in TT, but each step waits for the previous one. Self-attention pays a quadratic term in exchange for two things, a direct path between any pair of tokens and full parallelism across positions during training. Most later efficiency work, from optimized attention kernels to sparse and chunked variants, is an attempt to soften that T2T^2.

One block, three families

Family Example Attention Training objective Typical use
Encoder-only BERT Bidirectional Masked-token prediction Classification, retrieval embeddings
Encoder-decoder T5 Bidirectional encoder, causal decoder with cross-attention Text-to-text Translation, summarization
Decoder-only GPT Causal Next-token prediction Open-ended generation

The decoder-only family won the scaling race partly because its objective needs no labels and no task-specific head: every position of every document is a training example.

References

  1. Bahdanau, Cho & Bengio (2014), Neural Machine Translation by Jointly Learning to Align and Translate
  2. Vaswani et al. (2017), Attention Is All You Need
  3. Devlin et al. (2018), BERT: Pre-training of Deep Bidirectional Transformers
  4. Raffel et al. (2019), Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
  5. Brown et al. (2020), Language Models are Few-Shot Learners

04. Inside a modern LLM block: RMSNorm, SwiGLU, RoPE, GQA, the KV cache and MoE

Open the config of a recent open-weight language model and it reads like a list of acronyms. The backbone is still the decoder-only Transformer from 2017; what changed is a set of components, each swapped in to relieve one specific bottleneck. I find them much easier to remember by the problem they solve than as a list.

The skeleton stayed the same

A current decoder block is still attention plus a feed-forward network, each wrapped in a residual connection:

h′=h+Attention⁡(Norm⁡(h)),hout=h′+FFN⁡(Norm⁡(h′))h' = h + \operatorname{Attention}(\operatorname{Norm}(h)), \qquad h_{out} = h' + \operatorname{FFN}(\operatorname{Norm}(h'))

Normalization moved in front of each sublayer (pre-norm), which leaves the residual path as a clean identity and makes deep stacks easier to optimize. Everything below is a replacement for one of the boxes in this picture.

RMSNorm and SwiGLU: cheaper normalization, gated feed-forward

LayerNorm subtracts the mean and divides by the standard deviation. RMSNorm drops the centering and keeps only the rescaling:

RMSNorm⁡(x)=x1d∑i=1dxi2+ϵ⊙g\operatorname{RMSNorm}(x) = \frac{x}{\sqrt{\tfrac{1}{d}\sum_{i=1}^{d} x_i^2 + \epsilon}} \odot g

It is a little cheaper and works about as well, which is all a component needs to be adopted at scale.

The feed-forward network changed from one activation between two projections to a gated product:

SwiGLU⁡(x)=(SiLU⁡(xW1)⊙xW3) W2\operatorname{SwiGLU}(x) = \big(\operatorname{SiLU}(xW_1) \odot xW_3\big)\, W_2

There are now three weight matrices instead of two, so the hidden width is usually cut to about two thirds of the classic 4d4d to keep the parameter count level.

RoPE: position as rotation

The original Transformer added a position vector to each token embedding. Rotary position embedding instead rotates the query and key vectors inside attention. Each pair of coordinates is treated as a 2D point and turned by an angle proportional to the token's position mm:

R(mθ)=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)R(m\theta) = \begin{pmatrix} \cos m\theta & -\sin m\theta \\ \sin m\theta & \cos m\theta \end{pmatrix}

Rotations compose, so for a query at position mm and a key at position nn:

⟨R(mθ) q,  R(nθ) k⟩=⟨q,  R((n−m)θ) k⟩\langle R(m\theta)\,q,\; R(n\theta)\,k \rangle = \langle q,\; R((n-m)\theta)\,k \rangle

The attention score depends only on the offset n−mn - m. The model gets relative position for free, with no extra parameters, and different coordinate pairs use different frequencies so that both nearby and distant offsets are distinguishable.

The KV cache and why GQA exists

When generating token by token, the keys and values of earlier tokens never change, so they are computed once and stored. That removes a great deal of repeated work, but the store grows with everything:

bytes≈2⋅L⋅B⋅T⋅Hkv⋅dh⋅b\text{bytes} \approx 2 \cdot L \cdot B \cdot T \cdot H_{kv} \cdot d_h \cdot b

for LL layers, batch BB, cached length TT, HkvH_{kv} key/value heads of dimension dhd_h, and bb bytes per number.

A worked example makes the scale concrete. Take L=32L = 32, B=1B = 1, T=8192T = 8192, dh=128d_h = 128 and 16-bit floats (b=2b = 2). With standard multi-head attention and 32 heads, the cache is about 4 GiB for a single sequence. Grouped-query attention lets several query heads share one key/value head. With 8 KV heads serving the same 32 query heads, the cache drops to about 1 GiB. Queries stay diverse; only the stored side is shared.

The lesson I take from this is that for long contexts the bottleneck is no longer arithmetic but memory capacity and bandwidth, and that is where architectural effort has gone.

Mixture of experts: more parameters, same compute per token

A mixture-of-experts layer replaces the single feed-forward network with many, plus a small router. For each token the router scores the experts, keeps the top kk, and mixes their outputs:

y=∑i ∈ TopK⁡(g(x))pi(x) Ei(x)y = \sum_{i \,\in\, \operatorname{TopK}(g(x))} p_i(x)\, E_i(x)

Total capacity grows with the number of experts while the work per token grows only with kk. The costs appear elsewhere: experts can receive very uneven load, tokens have to be dispatched to wherever their experts live, and across devices that means all-to-all communication.

One distinction is worth keeping sharp, since model announcements often blur it: total parameters, active parameters per token, training compute and inference latency are four different numbers. A sparse model can be large on the first and modest on the second.

Each component, and the bottleneck it targets

Component Replaces Bottleneck addressed
Pre-norm Post-norm Optimization stability in deep stacks
RMSNorm LayerNorm Normalization cost
SwiGLU ReLU or GELU feed-forward Feed-forward quality at equal parameters
RoPE Absolute position embeddings Relative position, generalization over offsets
GQA Full multi-head attention KV-cache memory and bandwidth
KV cache Recomputing history each step Repeated compute during generation
MoE Dense feed-forward Capacity per unit of compute

Exact configurations differ between model families and between versions of the same family, so the table describes roles, not a single canonical recipe.

References

  1. Zhang & Sennrich (2019), Root Mean Square Layer Normalization
  2. Shazeer (2020), GLU Variants Improve Transformer
  3. Su et al. (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding
  4. Ainslie et al. (2023), GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
  5. Touvron et al. (2023), Llama 2: Open Foundation and Fine-Tuned Chat Models
  6. Kaplan et al. (2020), Scaling Laws for Neural Language Models

05. After pretraining: SFT, preference optimization and RL with verifiable rewards

A pretrained language model has learned to continue text. Turning it into something that follows instructions, prefers good answers to bad ones, and reasons through a problem takes further stages of training, each with a different kind of signal. These notes lay the stages side by side, since what distinguishes them is mostly where the supervision comes from.

One loss, used twice

Pretraining factorizes the probability of a sequence with the chain rule and minimizes the negative log-likelihood of each token given the ones before it:

P(x)=∏tP(xt∣x<t),L=−∑tlog⁡Pθ(xt∣x<t)P(x) = \prod_{t} P(x_t \mid x_{<t}), \qquad \mathcal{L} = -\sum_{t} \log P_\theta(x_t \mid x_{<t})

Supervised fine-tuning (SFT) uses the very same loss. What changes is the data, now curated prompt and response pairs, and the mask: the loss is normally computed only on the response tokens, so the model learns to answer prompts instead of learning to write them. Padding positions are masked out for the same reason. SFT teaches format and behaviour by imitation, which also sets its ceiling. The model can become as good as its demonstrations, not better.

Preferences without a reward model

Often it is easier to say which of two answers is better than to write the ideal one. Direct Preference Optimization trains on such pairs directly. For a prompt xx with a preferred answer ywy_w and a rejected answer yly_l:

LDPO=−log⁡σ ⁣(β[log⁡πθ(yw∣x)πref(yw∣x)−log⁡πθ(yl∣x)πref(yl∣x)])\mathcal{L}_{DPO} = -\log \sigma\!\left(\beta \left[\log\frac{\pi_\theta(y_w \mid x)}{\pi_{ref}(y_w \mid x)} - \log\frac{\pi_\theta(y_l \mid x)}{\pi_{ref}(y_l \mid x)}\right]\right)

The model is rewarded for raising the probability of the preferred answer relative to a frozen reference model more than it raises the rejected one. The reference terms act as an anchor that keeps the policy from drifting far from where it started. No separate reward model and no sampling loop are needed, which is why the method is attractive in practice.

PPO: improve, but not too far in one step

When there is a reward signal instead of fixed pairs, the model can be treated as a policy and trained with reinforcement learning. Proximal Policy Optimization compares the new policy with the one that generated the data through a probability ratio, and clips it:

rt(θ)=πθ(at∣st)πold(at∣st),LCLIP=Et ⁣[min⁡ ⁣(rtAt,  clip⁡(rt, 1−ϵ, 1+ϵ) At)]r_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{old}(a_t \mid s_t)}, \qquad \mathcal{L}^{CLIP} = \mathbb{E}_t\!\left[\min\!\big(r_t A_t,\; \operatorname{clip}(r_t,\, 1-\epsilon,\, 1+\epsilon)\, A_t\big)\right]

If an action was better than expected (At>0A_t > 0), the objective raises its probability, but the gain stops counting once the ratio leaves [1−ϵ,1+ϵ][1-\epsilon, 1+\epsilon]. With a negative advantage the logic runs the other way. The clip is a cheap way to say: trust this batch of data only for a small step. A full implementation also carries a value network to estimate advantages, usually an entropy bonus, and often a KL term.

GRPO: let the group be the baseline

Training a value network for a large language model is expensive and hard to get right. Group Relative Policy Optimization avoids it. For each prompt it samples a group of answers, scores each one, and uses the group's own statistics as the baseline:

Ai=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG)+ϵA_i = \frac{r_i - \operatorname{mean}(r_1, \dots, r_G)}{\operatorname{std}(r_1, \dots, r_G) + \epsilon}

An answer is good if it beats its siblings on the same prompt. That advantage then drives a PPO-style clipped update, with a KL penalty toward a reference policy. A caution I keep attached to this formula: group size, reward scaling, clipping and the exact token-level objective differ between papers and codebases, so it describes the idea, not every variant that carries the name.

Why verifiable rewards matter

Reinforcement learning is only as good as its reward. A learned reward model can be flattered: the policy finds outputs that score well without being good. Tasks with a checkable outcome avoid that problem. A maths answer either matches or does not; code either passes its tests or does not.

DeepSeek-R1 is the best-known demonstration. The paper reports that large-scale RL with rule-based rewards on such tasks was enough for long chains of reasoning to emerge in the model's outputs, and that the released model combined this with supervised stages to improve readability and general usefulness. The broader point is that the bottleneck moves from collecting demonstrations to building environments where correctness can be checked.

Reasoning: prompted versus trained

Chain-of-thought prompting asks a model to write intermediate steps before the answer, and often improves accuracy on multi-step problems with no change to the weights. A reasoning-trained model goes further: producing the working is part of what it was optimized to do. In both cases the cost is the same kind, more tokens per answer, so more latency and compute. That is test-time scaling: spending inference compute, instead of parameters, to buy accuracy.

The stages at a glance

Stage Signal Teaches Main limit
Pretraining Next token on raw text Language and world knowledge No notion of task or preference
SFT Curated prompt and response pairs Format, instruction following Capped by demonstration quality
DPO Preferred vs. rejected answers Which answer is better Needs comparison data
PPO / GRPO Scalar reward on sampled answers Behaviour beyond the demonstrations Only as good as the reward

References

  1. Schulman et al. (2017), Proximal Policy Optimization Algorithms
  2. Rafailov et al. (2023), Direct Preference Optimization: Your Language Model is Secretly a Reward Model
  3. Shao et al. (2024), DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models
  4. DeepSeek-AI (2025), DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning
  5. Wei et al. (2022), Chain-of-Thought Prompting Elicits Reasoning in Large Language Models

06. Diffusion in latent space: From adding noise to Stable Diffusion

Diffusion models generate images by learning to undo noise. The idea is simple enough to state in a sentence, yet the path from that sentence to a system that turns a text prompt into a high-resolution picture goes through several distinct design decisions. These notes take them in order.

Destroying an image on purpose

The forward process adds a little Gaussian noise at each of many steps until nothing of the image is left. Conveniently, the result after tt steps has a closed form, so any noise level can be sampled directly from the clean image x0x_0:

xt=αˉt  x0+1−αˉt  ϵ,ϵ∼N(0,I)x_t = \sqrt{\bar\alpha_t}\; x_0 + \sqrt{1 - \bar\alpha_t}\; \epsilon, \qquad \epsilon \sim \mathcal{N}(0, I)

Here αˉt\bar\alpha_t is a schedule that falls from near 1 (almost clean) to near 0 (almost pure noise). Nothing is learned in this direction. Its only job is to manufacture training pairs: a noisy image, and the exact noise that was added to make it.

Learning to undo it

The network ϵθ\epsilon_\theta sees a noisy image and the step index, and predicts the noise:

L=Ex0, ϵ, t[∥ϵ−ϵθ(xt,t)∥2]\mathcal{L} = \mathbb{E}_{x_0,\, \epsilon,\, t} \left[ \big\lVert \epsilon - \epsilon_\theta(x_t, t) \big\rVert^2 \right]

That is an ordinary regression loss, which is a large part of why diffusion models train so stably compared with adversarial ones: there is no second network to balance against. One model is trained across all noise levels at once, with the step index telling it how much noise to expect.

Sampling is where the cost is

Generation starts from pure noise and applies the network repeatedly, removing a little noise each time. If one evaluation of the denoiser costs CC and sampling takes SS steps, an image costs about S⋅CS \cdot C. Training looks at one random step per example, but sampling has to walk the whole chain. This is the central weakness of the approach, and much of the follow-up work, faster samplers and distillation into few-step models, is aimed at shrinking SS.

Moving to latent space

Running the denoiser on raw pixels is expensive. A 512×512512 \times 512 RGB image has 512⋅512⋅3=786,432512 \cdot 512 \cdot 3 = 786{,}432 values. Latent diffusion first trains an autoencoder that compresses the image by a factor of 8 along each side into a 4-channel latent of size 64×64×4=16,38464 \times 64 \times 4 = 16{,}384 values. That is 48 times fewer numbers for every one of the SS denoising steps.

The pipeline then has three parts with clearly separated jobs:

  • The autoencoder handles perceptual detail: textures and sharp edges are reconstructed by its decoder.
  • The denoiser works only in the compact latent space and handles composition and semantics.
  • The decoder is applied once, at the very end, to turn the final latent back into pixels.

The price is that image quality is now bounded by the autoencoder. Fine structures it cannot reconstruct, small text being the classic example, cannot be recovered by the denoiser however well it is trained.

Telling it what to draw

Text conditioning enters through cross-attention. A text encoder turns the prompt into a sequence of embeddings, and at several resolutions inside the denoiser the image features attend to them, with image features as queries and text embeddings as keys and values. It is the same mechanism as in a translation model, pointed at a different pair of modalities.

Following the prompt closely takes one more step. Classifier-free guidance trains the same network both with and without the prompt, by dropping the text some of the time, and at sampling extrapolates from the unconditional prediction toward the conditional one:

ϵ^=ϵθ(xt,∅)+s (ϵθ(xt,c)−ϵθ(xt,∅))\hat\epsilon = \epsilon_\theta(x_t, \varnothing) + s \,\big(\epsilon_\theta(x_t, c) - \epsilon_\theta(x_t, \varnothing)\big)

With s=1s = 1 this is plain conditional sampling. Larger values follow the prompt more strictly at the cost of diversity, and eventually of image quality. It also doubles the work per step, since each step needs two predictions.

What SDXL changed

Stable Diffusion XL keeps the latent-diffusion recipe and scales its parts: a considerably larger denoiser, two text encoders used together for a richer reading of the prompt, conditioning on image size and crop so that training on mixed resolutions does not leak into the outputs, and an optional refiner model for the last denoising steps. None of this alters the principle. It moves the balance between quality and cost.

Where the time goes

Lever Effect on cost Effect on output
Sampling steps SS Linear Fewer steps lose detail unless the sampler is designed for it
Latent instead of pixel space Large reduction per step Bounded by autoencoder quality
Guidance scale ss Two predictions per step Prompt adherence against diversity
Resolution Grows with the number of latent positions, faster where attention is used More detail, more memory

References

  1. Ho, Jain & Abbeel (2020), Denoising Diffusion Probabilistic Models
  2. Kingma & Welling (2013), Auto-Encoding Variational Bayes
  3. Rombach et al. (2022), High-Resolution Image Synthesis with Latent Diffusion Models
  4. Ho & Salimans (2022), Classifier-Free Diffusion Guidance
  5. Podell et al. (2023), SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis