学习

AI 究竟 是如何工作的

一份通俗易懂的指南,讲清每个模型页面上都会出现的术语——Token、上下文窗口、缓存命中、智能体、MCP、混合专家——每章都有动手演示,并配有我们追踪的 274 个模型的真实例子。

20 章 · 约 16 分钟 · 语音讲解

互动演示和技术说明为英文。

01 · 什么是 AI?

什么是 AI?

人工智能是一种从例子中学习规律的软件,而不是照着人手写的规则执行。一个见过数百万封邮件的垃圾邮件过滤器,会自己学会垃圾邮件长什么样;没有人去逐条编写规则。

编程工具里的 AI 是大语言模型(LLM)。它通过阅读海量的文本和代码——书籍、网站、文档、开源仓库——并不断调整数十亿个内部数值(称为参数)来训练,直到它非常擅长一件事:猜出接下来会出现什么文字。

这听起来很简单,但要准确猜出程序的下一行,模型必须掌握语法、事实、编程语言的规则,以及解决问题的实际思路。它所做的一切——回答问题、写代码、修复 bug——都建立在这一项能力之上。

深入了解Transformers, layers and parameters · 英文技术说明

Today's language models are transformers. Text becomes a sequence of token IDs; each ID is looked up in an embedding table to get a vector of a few thousand numbers (the model's width, d_model). That sequence of vectors then flows through a stack of identical blocks — 30 to 120 of them — and each block does two things:

  • Self-attention: every position looks back at earlier positions and pulls in the information it needs (which noun does “it” refer to, which variable was declared above).
  • A feed-forward network (MLP): a wide two-layer network applied to each position separately, where much of the model's stored knowledge lives.

Residual connections add each block's output back onto its input, and normalisation keeps the numbers in range. At the end, an unembedding matrix turns the final vector into one score (a logit) per vocabulary entry. Parameters are just the entries of all these matrices. For a dense model, a good estimate is:

params ≈ 12 × layers × d_model²   (+ vocab × d_model for embeddings)
# e.g. 32 layers, d_model 4096  →  12 × 32 × 4096² ≈ 6.4B  (+0.5B embeddings) ≈ "7B"

Nothing in that list is a rule about language. All of the behaviour comes from the values the parameters take during training.

02 · 模型如何作答

模型如何 作答

构建模型分为两个阶段。训练是最昂贵的部分:成千上万块芯片连续运行数周,让模型阅读数据并调整参数。之后模型就被固定下来。推理则是你使用它时发生的过程:输入你的文字,模型一小块一小块地生成回答。

每一步,模型都会查看到目前为止的全部内容,并为每个可能的下一块内容打出一个概率。选出一个,加到文本末尾,然后不断重复,直到回答结束。这就是为什么回答会一个词一个词地出现在屏幕上。

一个叫温度的设置控制这种选择有多大胆。低温度几乎总是选概率最高的那个,适合写代码;高温度会让不太可能的词也被选中,适合头脑风暴。

Try itNext-token sampler

The best language for a quick script is

    Illustrative odds. At temperature 0 the top choice always wins; turn it up and the long tail starts getting picked.
    深入了解Logits, softmax, temperature and sampling · 英文技术说明

    The model outputs a logit zᵢ for every token in its vocabulary. Softmax turns logits into probabilities, and temperature T divides them first:

    p(i) = exp(zᵢ / T) / Σⱼ exp(zⱼ / T)
    T → 0   : all probability on the top token (greedy decoding)
    T = 1   : the model's own distribution
    T > 1   : flatter — rare tokens get picked more often

    Samplers then trim the tail before picking: top-k keeps the k most likely tokens, top-p (nucleus) keeps the smallest set whose probabilities sum to p, and min-p drops tokens below a fraction of the top token's probability. Repetition and frequency penalties lower the logits of tokens already used. A fixed seed makes sampling repeatable on the same hardware and software.

    The generation loop

    tokens = tokenize(prompt)
    kv = prefill(tokens)                 # one parallel pass over the whole prompt
    while True:
        logits = forward(last_token, kv)  # one step, reusing the cached keys/values
        next = sample(logits, T, top_p)
        if next == END: break
        tokens.append(next); stream(next)

    Prefill is a big parallel matrix multiply and is limited by compute; each decode step is tiny and is limited by how fast weights can be read from memory. That split explains most of what you'll see about speed later in this guide.

    03 · Token

    什么是 Token?

    模型读的不是字母,也不是完整的单词,而是 Token:一小段文本,通常是一个词、词的一部分或一个符号。常见的英文单词只占一个 Token,罕见的词会被拆成两三块。英文里一个 Token 大约是四个字符;中文通常一个汉字约占一个 Token 左右,因此同样的内容往往需要更多 Token。代码因为符号和缩进多,每行用的 Token 也更多。

    Token 之所以重要,是因为模型按 Token 计量和计费。价格按每百万 Token 计算,你发送的内容(输入)和模型写回的内容(输出)分别计价,输出通常贵好几倍。

    Try itToken counter

    An approximation — every model family has its own tokenizer, so exact counts differ a little.
    深入了解Byte-pair encoding and vocabularies · 英文技术说明

    Most tokenizers use byte-pair encoding (BPE) or a close relative. Training starts from raw bytes and repeatedly merges the most frequent adjacent pair into a new token, until the vocabulary reaches its target size. Frequent strings (“ the”, “function”, four spaces of indentation) end up as single tokens; rare strings fall back to smaller pieces, and ultimately to individual bytes, so any text can be encoded.

    • Vocabulary sizes range from about 32,000 (older Llama, Mistral) to 150,000–260,000 (Qwen, Gemma, GPT-4o-era tokenizers). Bigger vocabularies mean fewer tokens per text but a bigger embedding table.
    • Languages are not treated equally. English averages about 4 characters per token; many other languages and scripts need noticeably more tokens for the same meaning, so they cost more and fill the context faster. Newer multilingual tokenizers have narrowed the gap.
    • Special tokens mark structure the user never types: start and end of a message, role markers such as <|im_start|>assistant, tool-call delimiters, image placeholders.
    • Numbers are tokenized oddly (“1234” might be “12” + “34”), which is one reason models used to struggle with arithmetic; many tokenizers now split digits individually.

    04 · 上下文窗口

    上下文 窗口

    上下文窗口是模型一次能看到的文本量:你的指令、到目前为止的对话、编程智能体打开的文件,以及它正在写的回答。它是模型的工作记忆,窗口之外的内容对模型来说根本不存在。

    上下文以 Token 计量。一百万 Token 的窗口大约能同时容纳 75 万个英文单词,相当于十本小说或一个中等规模的代码库。模型本身不会记住你以前的聊天;工具通过把以前的文字重新放回窗口来给它“记忆”。窗口满了以后,最早的内容会被丢弃或总结。

    Try itFill the window

    • System prompt
    • Files
    • Chat
    • Logs
    • Repo
    When something new does not fit, the oldest items fall out of the window (the system prompt always stays).
    深入了解Attention cost, positions and the KV cache · 英文技术说明

    In attention, every token computes a query, a key and a value. Each query is compared with every earlier key, and the resulting weights mix the values:

    Attention(Q, K, V) = softmax(Q·Kᵀ / √d) · V
    cost of prefill  ∝ n²   (every token vs. every earlier token)
    memory per token = 2 × layers × kv_heads × head_dim × bytes   ← the KV cache

    During generation the keys and values of past tokens are kept in the KV cache, so each new token only computes its own. That cache grows linearly with context and is often what limits long contexts — far more than the weights. Designs that shrink it: grouped-query attention (many query heads share a few KV heads), multi-head latent attention (DeepSeek; stores a compressed latent instead of full keys and values), sliding-window layers that only look back a few thousand tokens, and hybrids that mix in linear-attention or state-space layers with constant-size memory.

    Positions are encoded with RoPE (rotary embeddings), which rotate queries and keys by an angle that depends on position. Context windows are extended after training by stretching those angles (position interpolation, NTK scaling, YaRN) and fine-tuning briefly on long documents. Advertised and effective context differ: models retrieve facts from the start and end of a long prompt more reliably than from the middle, so put the most important material at the edges.

    05 · 系统提示词

    提示词与 系统提示词

    你输入的一切都是提示词。但在你的消息到达之前,你所用的应用已经先给模型发送了它自己的隐藏指令:系统提示词。它规定模型是谁、能用哪些工具、用什么风格写作、绝不能做什么。编程智能体的系统提示词很长,会说明如何编辑文件、何时运行测试、何时请求许可。

    所以同一个模型在两个工具里可能感觉完全不同:同一个大脑,不同的任务说明。好的提示词要具体:说清你想要什么,提供模型猜不到的背景,给出输出示例,并说明怎样才算“完成”。

    Try itSame question, different system prompt
    System

    You

    How do I reverse a list in Python?

    Model

    深入了解Chat templates and structured output · 英文技术说明

    A conversation is serialised into one token sequence by the model's chat template. The system prompt is simply the first message, wrapped in role markers:

    <|im_start|>system
    You are a careful coding assistant. Tools: read_file, run_tests …<|im_end|>
    <|im_start|>user
    How do I reverse a list in Python?<|im_end|>
    <|im_start|>assistant
    

    Models are trained to give the system role more authority than user or tool messages (an instruction hierarchy), but it's still just text in the same window. That's the root of prompt injection: instructions hidden in a web page, file or tool result can try to override the real ones. Agents defend with permissions, sandboxes and by treating tool output as data.

    Structured output goes further than asking nicely for JSON. With constrained decoding, the runtime compiles a JSON Schema or grammar into a state machine and masks the logits of any token that would break it, so the output is guaranteed to parse. llama.cpp calls these GBNF grammars; hosted APIs expose them as “structured outputs” or “JSON mode”.

    06 · 缓存命中

    什么是 缓存命中?

    编程智能体会一遍又一遍地把同一大段文本发给模型:系统指令、项目文件和到目前为止的对话。每一轮只有最后几行在变。每次都从头处理这些内容,既慢又贵。

    提示词缓存解决了这个问题。服务商会保存它对请求开头部分已经完成的计算。下一次请求如果以完全相同的文本开头,就直接复用这些计算。这种复用就是缓存命中,被缓存的 Token 会大幅打折计费。只要开头附近有一个字符改变,后面的部分就全部是缓存未命中,按原价计费。

    缓存的有效期很短,常常只有几分钟,所以在密集的会话中最有用。同样的工作,便宜得多,也更快;这就是为什么工具会尽力让每次请求的开头保持完全一致。

    Try itSession cost · Claude Sonnet 5.5 on Anthropic
    Without cache$5.36
    With cache hits$0.91

    83% cheaper with caching

    Each turn repeats the prefix, adds 2,000 new tokens and gets 1,000 back. Fresh input $2.00, cache hit $0.10 per million tokens (95% off).
    深入了解How prefix caching works · 英文技术说明

    What's cached is the KV cache of a prompt prefix — the keys and values computed during prefill. Serving engines split the cache into fixed blocks (vLLM's PagedAttention uses 16-token pages), hash each block together with everything before it, and reuse any block whose hash matches a new request. A change at position k changes the hash of every block after k, which is why one edited character near the start invalidates the rest.

    cost = cached_tokens × cache_read_price
         + new_tokens    × input_price
         + written_tokens × cache_write_price   (some providers)
         + output_tokens × output_price

    Some APIs cache automatically; others ask you to mark a breakpoint after the stable part (system prompt, tool definitions, documents). Practical rules: keep the stable material first and byte-identical (no timestamps in the system prompt), append rather than edit conversation history, and keep tool definitions in a fixed order. Entries are evicted after minutes of inactivity, or held longer for a fee. Running locally, llama.cpp and Ollama keep the last prompt's KV cache in memory, which is why a follow-up question starts answering almost instantly.

    07 · 推理 Token

    推理 Token

    有些模型可以先思考再回答。它们不会立刻作答,而是先写出一段私下的推理过程:拆解问题、尝试一种方法、检查结果、纠正错误,最后才写出最终答案。

    这让它们在难题上表现好得多,比如棘手的 bug、数学题和规划大型改动。代价是思考本身也由 Token 构成。推理 Token 按输出计费,即使你根本看不到它们。很多工具允许你选择推理强度,从低到高。

    Try itReasoning effort · priced on Claude Opus 5.5

    Question: “Why does this test fail only on Mondays?” Token counts are typical, not exact.
    深入了解Test-time compute and reinforcement learning · 英文技术说明

    Reasoning models are trained with reinforcement learning on verifiable tasks: maths with checkable answers, code with unit tests, puzzles with known solutions. The model generates long chains of thought; chains that end in a correct answer are rewarded. Over training, behaviours that help — breaking problems down, checking work, backtracking — become more frequent, and the chains get longer.

    This adds a second scaling axis: besides a bigger model, you can spend more test-time compute. Accuracy on hard problems rises roughly with the logarithm of the thinking budget, up to a point. Effort settings (low/medium/high) or explicit budget tokens cap that spend.

    • Thinking tokens are output tokens: billed as output and generated at decode speed, so they add latency as well as cost.
    • Many APIs return a summary or an encrypted copy of the reasoning instead of the raw chain; agents pass it back on the next turn so the model keeps its train of thought between tool calls (interleaved thinking).
    • More thinking isn't always better: simple lookups get slower and occasionally worse when a model over-thinks.

    08 · 工具与智能体

    工具调用与 智能体

    模型本身只能写文字。工具调用改变了这一点。应用会告诉模型有哪些工具——读取文件、运行命令、搜索网络——当模型需要某个工具时,它会写出一个结构化的请求,而不是普通回复。应用真正去执行这个工具,再把结果交还给模型。模型读完结果后决定下一步做什么。

    把这个过程放进循环,就得到了智能体:读取失败的测试、打开文件、修改代码、重新运行测试,一直重复到测试通过。本站上的每一个编程智能体,本质上都是这个循环。

    Try itStep through an agent loop
    深入了解Tool definitions and the agent loop · 英文技术说明

    A tool is described to the model as a name, a description and a JSON Schema for its arguments. The model replies with a structured call instead of text; the client executes it and sends the result back as a tool message.

    {"name": "run_tests",
     "description": "Run the project's test suite and return failures",
     "input_schema": {"type": "object",
       "properties": {"path": {"type": "string"}}, "required": []}}
    
    messages = [system, user]
    while True:
        reply = model(messages, tools)
        if not reply.tool_calls: return reply.text
        for call in reply.tool_calls:            # may run several in parallel
            result = execute(call)               # sandbox + permission checks here
            messages += [reply, tool_result(call.id, result)]

    What separates good agents from bad ones is mostly around this loop: precise tool descriptions, small and composable tools, truncating huge outputs, asking permission for risky actions, and context management — summarising or dropping old tool results so long sessions don't overflow the window. tool_choice can force a specific tool or forbid tools; constrained decoding keeps the arguments valid JSON.

    09 · MCP

    MCP: 模型上下文协议

    模型使用的每一个工具都得有人接入。在 MCP 出现之前,每个应用都用自己的方式接入每个服务。模型上下文协议(Model Context Protocol)是这种接入的共同标准——可以把它想象成 AI 工具的 USB-C 接口。

    MCP 服务器把一个服务——GitHub、数据库、浏览器、你的设计文件——包装起来,并描述它提供的工具。任何支持 MCP 的应用都能接入它,模型马上就能使用这些工具。服务器写一次就能到处用,这就是它们迅速大量涌现的原因。

    Try itPlug in a server
    MCP clientYour coding agent0 tools available
    Click servers to plug them in. Each one adds its tools to what the model can do — no changes to the model or the app.
    深入了解Inside the protocol · 英文技术说明

    MCP is JSON-RPC 2.0 between a client (inside the agent or IDE) and a server. Local servers run as a subprocess and talk over stdio; remote ones use Streamable HTTP, with OAuth 2.1 for login. The session starts with an initialize handshake in which both sides declare their capabilities.

    → {"jsonrpc":"2.0","id":1,"method":"tools/list"}
    ← {"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"create_issue",
         "description":"Open a GitHub issue","inputSchema":{…}}]}}
    → {"jsonrpc":"2.0","id":2,"method":"tools/call",
       "params":{"name":"create_issue","arguments":{"title":"Fix login"}}}

    Servers offer three primitives: tools (actions the model can call), resources (data the app can read into context, addressed by URI) and prompts (reusable templates the user can invoke). Clients can offer sampling (the server asks the host's model to generate text) and elicitation (the server asks the user a question). Every tool's schema is sent to the model, so dozens of servers can eat thousands of tokens of context — one reason agents now load tool definitions lazily.

    10 · UTCP

    UTCP: 通用工具调用协议

    MCP 在模型和服务之间放了一个服务器。通用工具调用协议(UTCP)从另一个问题出发:如果一个服务已经有 API,为什么还要再包一层服务器?UTCP 是一个开放标准,让智能体直接调用工具。

    每个工具发布一份手册:一个 JSON 文件,列出每个工具做什么、需要哪些输入、怎样调用。智能体读一次手册,之后就用服务自己的协议(例如 HTTP 或命令行)和服务自己的登录方式直接与它通信。

    代价是工作只是换了地方,并没有消失。智能体的客户端必须支持每一种协议,自己处理登录、重试和错误,而每个工具要负责自己的安全。MCP 的服务器数量和厂商支持也要多得多。

    你不必永远二选一:UTCP 有一个插件,可以调用现有的 MCP 服务器。

    Try itFollow one tool call
    Your agent MCP server Weather API
    The agent sends
    Someone maintains
    Login handled by
    {
      "manual_version": "1.0.0",
      "utcp_version": "1.0.1",
      "tools": [{
        "name": "get_weather",
        "description": "Get current weather for a location",
        "inputs": {
          "type": "object",
          "properties": { "location": { "type": "string" } },
          "required": ["location"]
        },
        "tool_call_template": {
          "call_template_type": "http",
          "url": "https://api.example.com/weather",
          "http_method": "GET"
        }
      }]
    }
    Switch protocols to compare the same weather lookup. The API is a made-up example.
    深入了解Manuals and call templates · 英文技术说明

    A UTCP manual lists tools, each with JSON Schema inputs and outputs and a tool_call_template saying how to reach it. Templates exist for HTTP, server-sent events, streamable HTTP, the command line, text files and MCP itself. The client substitutes the arguments into the template and calls the service directly, with the service's own authentication (API key, OAuth or basic auth, declared in the template and filled from local variables).

    agent ──reads manual once──▶  /utcp  (JSON)
    agent ──GET /weather?location=Oslo──▶  api.example.com   # no proxy in between

    The trade-off versus MCP: no extra server process and no extra hop, and existing APIs work as they are; but the client must implement every transport, and features MCP standardises — resources, prompts, sampling, server-initiated notifications — are out of scope.

    11 · 向量嵌入与 RAG

    向量嵌入与 RAG

    计算机无法直接比较含义,所以模型会把文本变成一串数字,称为向量嵌入(embedding)。每个嵌入都是数百维空间中的一个点,含义相近的文本会落在附近——“修复登录 bug”会靠近“身份验证错误”,即使两者没有一个相同的词。

    这样就能按含义搜索:每个文档嵌入一次,再把每个问题嵌入,取出最近的文档。检索增强生成(RAG)会在模型回答之前把这些文档放进上下文窗口。这就是模型无需在你的代码库上训练,也能回答关于它的问题的原因。

    Try itSearch by meaning
      A 2-D sketch of a space that really has hundreds of dimensions. The three closest documents are what RAG would hand to the model.
      深入了解Vectors, similarity and retrieval pipelines · 英文技术说明

      An embedding model maps text to a vector, typically 384 to 4,096 dimensions. Similarity is usually cosine similarity:

      cos(a, b) = (a · b) / (‖a‖ ‖b‖)      # 1 = same direction, 0 = unrelated

      Search over millions of vectors uses approximate nearest-neighbour indexes such as HNSW graphs or IVF clusters, in a vector database or a library like FAISS. A production RAG pipeline usually adds:

      • Chunking: split documents into passages of a few hundred tokens, ideally along headings or function boundaries, with some overlap.
      • Hybrid search: combine vectors with keyword search (BM25), which catches exact names, error codes and identifiers that embeddings blur.
      • Reranking: a cross-encoder scores the top 50–100 candidates against the question and keeps the best handful.
      • Grounded prompting: put the passages in the context with their sources and ask the model to cite them.

      Coding agents often skip vectors entirely and search with grep-style tools in a loop — exact, always up to date, and good enough when the model can iterate.

      12 · 幻觉

      模型为什么会 产生幻觉

      模型的任务是生成可能的文本,而不是真实的文本。大多数时候两者一致;不一致时,它可能会非常自信地说出错误的内容。这就是幻觉。

      在代码里,幻觉表现为一个不存在的函数、一个从未加入的配置项,或一个听起来恰到好处的软件包名。它们在冷门库、最近的改动和精确细节上最常见。防御方法:给模型真实的资料(文档、文件、搜索),让它运行代码和测试,并核实所有重要的内容。

      Try itSpot the made-up answer

      Each question has two real answers and one a model might plausibly invent.
      深入了解Why it happens and how it is measured · 英文技术说明

      Pre-training rewards predicting plausible text, not saying “I don't know”; benchmarks that grade only right or wrong reward guessing over abstaining. So a model that hasn't stored a fact still produces the most fact-shaped continuation. Rare facts — seen a handful of times in training — are the most at risk, which is why niche libraries and recent APIs suffer most.

      • Calibration measures whether stated confidence matches accuracy. Some evaluations now score abstentions separately and penalise confident errors.
      • Grounding (RAG, search, reading the actual source file) moves the answer from memory to the context, where models are much more reliable.
      • Verification loops — run the code, run the tests, type-check, call the real API — catch invented functions immediately.
      • Package hallucinations are a security problem: attackers register package names that models tend to invent (“slopsquatting”). Check that a dependency exists and is the one you meant before installing it.

      13 · 模型如何训练

      模型是如何 训练的

      模型分阶段构建。首先是预训练:它阅读数万亿个 Token,学习预测下一个 Token。它的知识就来自这里,这也是迄今最昂贵的一步——但这时的结果还不是一个好用的助手。

      接着,用优质对话示例进行微调,教它遵循指令。最后是强化学习:它尝试完成任务,回答由人、其他模型或自动检查(比如代码能否通过测试)打分,好的回答得到奖励。最后这一步正是编程模型进步如此之快的重要原因。

      Try itSame prompt, three stages
      Prompt

      Write a function that checks whether a word is a palindrome.

      Model after pre-training

      深入了解Loss, compute and post-training · 英文技术说明

      Pre-training minimises cross-entropy loss: the negative log-probability the model gave to each actual next token, averaged over trillions of tokens. Gradients from that loss nudge every parameter, batch after batch.

      loss = − (1/N) Σ log p(tokenₜ | tokens<ₜ)
      training compute ≈ 6 × parameters × training tokens   (FLOPs)
      # 70B params × 15T tokens ≈ 6.3 × 10²⁴ FLOPs

      Scaling laws describe how loss falls predictably with more parameters, data and compute; modern models are trained on far more tokens per parameter than the old “compute-optimal” ratio of about 20, because a smaller model that's been trained longer is cheaper to serve.

      Post-training turns the predictor into an assistant: supervised fine-tuning on curated conversations; preference optimisation (RLHF with a reward model, or DPO directly on pairs of better/worse answers); and RL with verifiable rewards for maths, code and agent tasks, run in sandboxes with real tools. Distillation trains a smaller model on a larger one's outputs, which is how many fast “mini” and “flash” models are made.

      14 · 混合专家

      混合 专家

      普通的稠密模型在处理每个 Token 时都会用上全部参数。混合专家(MoE)模型则被拆分成许多更小的子网络,称为专家。对每个 Token,一个小小的路由器只挑选少数几个专家来工作,其余的保持空闲。

      结果是:模型拥有巨大网络的知识,而每个 Token 的成本却只相当于一个小模型。这就是为什么总参数和激活参数要分开列出。总规模决定部署模型需要多少内存;激活规模决定每个 Token 有多快、多便宜。

      Try itRoute tokens through experts

      token router expert 1expert 2expert 3expert 4expert 5expert 6expert 7expert 8
      Different tokens wake different experts. Over a sentence, most experts get used — but only 2 of 8 at a time.
      深入了解Routers, top-k gating and load balancing · 英文技术说明

      In an MoE layer the feed-forward network is replaced by E experts and a router. For each token the router computes a score per expert, keeps the top k and mixes their outputs by those scores:

      g = softmax(W_router · x)          # one weight per expert
      y = Σ_{i ∈ topk(g)} gᵢ · Expertᵢ(x)
      active params ≈ shared (attention, embeddings, shared experts) + k/E × expert params

      Modern MoEs use many small experts (128–384) with 4–10 active, often plus one always-on shared expert. Training adds a load-balancing term (or a bias adjustment) so tokens spread evenly; otherwise a few experts take all the work. Serving at scale uses expert parallelism — experts spread over many GPUs, tokens routed between them. At home the useful fact is the asymmetry: memory scales with total parameters, speed with active ones, and the rarely-used experts can sit in system RAM while attention runs on the GPU.

      15 · 量化

      量化 (fp8、fp4)

      每个参数都是一个数字,而数字可以用更高或更低的精度存储。量化用更少的比特来存储它们——例如 8 比特(fp8)或 4 比特(fp4),而不是 16 比特。模型变得更小,部署起来更快,通常也更便宜,代价是质量略有下降,有时能察觉到。

      这就是同一个开放模型在不同服务商那里价格不同的原因:它们可能在不同硬件上运行不同的精度。

      Try itShrink a model

      The orange line is a smooth signal stored with the chosen precision: fewer bits, fewer levels, more rounding.
      深入了解Scales, blocks and quantization formats · 英文技术说明

      Quantization maps each weight to a small integer and stores a scale (and sometimes an offset) per block of weights:

      q = round(w / scale)           # e.g. a 4-bit integer in [-8, 7]
      w ≈ q × scale                  # what the GPU reconstructs on the fly
      bits per weight = bits + (scale bits / block size)
      # Q4_K: blocks of 32 inside super-blocks of 256, 6-bit scales → ~4.5 bpw;
      # Q4_K_M keeps some tensors at Q6_K → ~4.85 bpw on average
      • Post-training quantization methods (GPTQ, AWQ, llama.cpp's importance matrix) use a little calibration text to decide where precision matters most and round to minimise output error, not weight error.
      • Hardware formats: FP8 (E4M3) is native on recent NVIDIA, AMD and Intel accelerators; MXFP4 and NVFP4 are 4-bit floats with shared block scales supported by the newest GPUs, so 4-bit can run at full speed instead of being unpacked.
      • Quantization-aware training (QAT) simulates low precision during training, so the released 4-bit model loses almost nothing.
      • Quality loss is measured with perplexity or, better, the KL divergence between the quantized and full-precision output distributions, plus task benchmarks.

      16 · 开放与封闭权重

      开放与封闭 权重

      模型的权重就是它学到的参数——这个文件就是模型本身。封闭模型不公开权重:你只能通过实验室自己的应用或 API 使用它们。开放权重模型会公开权重,任何人都可以下载、运行、微调,或转售访问服务。

      封闭模型在原始能力上往往领先。开放模型则给你选择:众多服务商在价格和速度上竞争,数据留在你自己的机器上,而且即使开发者转向别处,模型依然可以继续使用。

      Try itThe models we track
      Price is per million input tokens.
      深入了解Licences, formats and fine-tuning · 英文技术说明

      “Open weights” isn't automatically “open source”. Licences range from permissive (Apache 2.0, MIT) to custom ones with usage policies, attribution rules or limits for very large companies. The Open Source Initiative's definition of open-source AI also asks for enough information about the training data to reproduce the model, which few releases provide.

      Weights are distributed as safetensors files (a simple, memory-mappable format that can't execute code, unlike old pickle checkpoints) with a config.json describing the architecture and a tokenizer. Community conversions add GGUF (llama.cpp) and MLX (Apple).

      Open weights can be fine-tuned. LoRA freezes the model and trains a low-rank update for selected matrices — W' = W + B·A, with A and B thin — so only a fraction of a percent of the parameters train; QLoRA does this on a 4-bit base model, which puts fine-tuning a 30B model within reach of a single 24 GB GPU.

      17 · 在家运行 AI

      在家运行 AI

      开放权重模型可以在你自己的电脑上运行。一个叫运行时的程序——Ollama、LM Studio 或 llama.cpp——会把模型权重加载到内存中,最好是显卡的显存(VRAM),然后像云服务商一样生成文字。数据不会离开你的电脑,不按 Token 收费,而且可以离线使用。

      两个数字决定你能运行什么。内存决定哪些模型装得下:大约是参数量 × 每个权重的比特数 ÷ 8,再加上上下文所需的空间。一个 80 亿参数的模型在 4 比特下大约需要 5 GB;700 亿参数的模型需要 40 GB 以上。内存带宽决定速度,因为每生成一个新 Token 都要把所有激活权重重新读一遍——所以激活参数很少的混合专家模型在家用场景中特别受欢迎。

      打开计算器:它会检测你的硬件,告诉你哪些模型能运行、速度多快、哪些设置或升级有帮助,以及安装它们的具体命令。

      Try itWill it run?

      Check your own computer →

      Simplified: weights plus a 16K-token context. The full calculator uses each model’s real size and attention shape.

      看看你的电脑能运行哪些模型 →

      深入了解The memory and speed formulas · 英文技术说明
      memory  ≈ params × bpw / 8 + KV cache + ~0.8 GB
      KV      = 2 × layers × kv_heads × head_dim × 2 bytes × context
      tok/s   ≈ 0.65 × bandwidth / (active_params × bpw / 8)
      
      RTX 4090 (1008 GB/s), 32B dense @ Q4_K_M (19.4 GB):  ≈ 34 tok/s
      Apple M4 Max (546 GB/s), 30B-A3B MoE @ Q4 (1.8 GB/token): ≈ 100+ tok/s
      Dual-channel DDR5 (~80 GB/s), 8B @ Q4 (4.9 GB): ≈ 10 tok/s

      Offloading splits the bytes read per token between fast VRAM and slow system RAM; the slow part dominates. Mixture-of-experts models offload best: keep attention, embeddings and shared experts on the GPU (they're read every token), and put routed experts in RAM (each is read only when chosen). The Run AI at home page applies these formulas to every open model with its real attention shape.

      18 · 多模态

      多模态 模型

      早期的语言模型只能处理文字。多模态模型还能接收图片、PDF、音频甚至视频。这对编程出奇地有用:粘贴一张布局出错的截图或设计稿,让模型把它做出来;或者让智能体截取正在开发的应用画面,检查自己的成果。

      在内部,图片也会变成 Token。它被切成许多小块,每一块大约变成一个 Token——所以一张大图占用的上下文可能和一页文字一样多。

      Try itHow many tokens is an image?

      Uses one common rule of thumb — about one token per 750 pixels. Each provider resizes and counts a little differently.
      深入了解Vision encoders and image tokens · 英文技术说明

      Most multimodal LLMs bolt a vision encoder (a Vision Transformer) onto the language model. The image is resized, cut into patches (often 14×14 or 16×16 pixels), each patch becomes a vector, and a small projector maps those vectors into the language model's embedding space, where they sit in the sequence like word tokens. Many models merge neighbouring patches 2×2 to save tokens:

      image tokens ≈ (width / 28) × (height / 28)    # 14-px patches, 2×2 merge
      1024 × 768  →  ~37 × 27 ≈ 1,000 tokens

      Providers cap the resolution or tile large images, so counts differ by API. Audio is handled the same way — a speech encoder turns audio frames into embeddings — and video as a sequence of sampled frames. “Natively multimodal” models are pre-trained on mixed text and images from the start rather than having vision added later. Generating images is usually a separate system (diffusion, or autoregressive image tokens).

      19 · 速度

      速度:延迟与 吞吐量

      有两个数字决定模型用起来有多快。延迟,即首个 Token 的等待时间,是你等多久才看到第一个字。吞吐量,即每秒 Token 数,是文字开始出现后流出的速度。问一个简单问题时延迟最重要;让智能体写一个大文件时,吞吐量更重要。

      速度取决于模型大小、服务的繁忙程度,以及提供服务一方的硬件和软件。推理模型在可见回答开始之前,还要花时间思考。

      Try itFeel the difference
      
          
      0.0 s
      深入了解The roofline: compute vs memory bandwidth · 英文技术说明

      A chip is limited either by arithmetic (FLOPs per second) or by how fast it can move data (bytes per second). The ratio of work to data — arithmetic intensity — decides which:

      decode, batch 1 : ~2 FLOPs per weight byte read  → memory-bound
      prefill, 2k tok : ~4,000 FLOPs per weight byte    → compute-bound
      time to first token ≈ queueing + prefill(prompt) + network

      That's why serving providers batch many users together: reading the weights once and applying them to 64 requests makes decode far more efficient, at a small latency cost per user. Speculative decoding exploits the same slack for one user: a cheap draft (a small model, or extra prediction heads) proposes several tokens, the big model verifies them all in one parallel pass and keeps the prefix it agrees with — identical output, often 2–3× faster when drafts are accepted. Specialised chips (Cerebras, Groq, SambaNova) keep weights in on-chip SRAM with enormous bandwidth, which is how they reach thousands of tokens per second.

      20 · 基准测试

      如何看懂 基准测试

      基准测试是一种标准测试——给每个模型同样的任务,以便比较分数。有些用考试式的难题测试知识和推理;编程基准则把真实项目中的真实 bug 交给模型,检查它的修复能否让测试通过。

      看分数要谨慎。模型可能在训练中见过这些题目,从而抬高分数;实验室会挑选展示哪些结果;而在某类任务上得分高,对另一类任务说明不了太多。最好的基准测试是你自己的工作——在你真正要做的任务上试几个模型。

      Try itTop tracked models

      Real GitHub issues fixed in Python repos.

      Scores from Epoch AI. Compare many more on the leaderboard.
      深入了解Contamination, pass@k and arena ratings · 英文技术说明
      • Contamination: if test questions leaked into training data, scores measure memory. Defences include held-out private test sets, fresh problems dated after a model's cutoff (LiveCodeBench-style) and checking whether a model can complete a question it shouldn't know.
      • pass@k for code is the probability that at least one of k samples passes the tests, estimated without bias from n ≥ k samples with c correct: pass@k = 1 − C(n−c, k) / C(n, k). Agentic benchmarks such as SWE-bench Verified give the model a real repository and issue, then run the project's hidden tests on its patch.
      • Arena ratings come from people comparing two anonymous answers; a Bradley–Terry model turns millions of votes into Elo-like scores. They measure preference — including style and length — not correctness.
      • Watch the error bars: on a 500-question test, ±2 points is often noise. And benchmarks saturate — once top models score above 90%, differences stop meaning much and a harder test replaces it.

      示例根据公开的模型与服务商目录计算。语音由 Magnific 生成。