Inference engineering推理工程
Serve models on fixed hardware and know what each second costs.在固定硬件上部署模型,并弄清每一秒花在哪里。
What it is and why it exists它是什么,为什么需要它
What是什么
Inference engineering turns model weights into a dependable endpoint. You decide which models run, how they share memory, how long they stay loaded, how many requests run at once, and how much context each request may use.推理工程把模型权重变成一个可靠的服务端点。你要决定运行哪些模型、它们如何共享内存、空闲多久后卸载、同时处理多少请求,以及每个请求可以使用多少上下文。
Why为什么
Every other layer calls this one. Retrieval calls it to embed. The harness calls it to plan and to answer. The evaluator calls it to judge. If one call takes 70 seconds because a model was evicted, no prompt change above it will fix that.其他每一层都要调用这一层。检索用它做向量化,Harness 用它做规划和回答,评估用它做裁判。如果因为模型被换出内存,一次调用要 70 秒,上层怎么改提示词都没用。
How it works工作原理
- A serving engine loads weights into memory and exposes an HTTP API. The reference build uses Ollama, plus a second runtime (MLX) for one small fast model.推理引擎把权重加载进内存,并提供 HTTP API。参考系统使用 Ollama,另有一个运行时(MLX)专门服务一个小而快的模型。
- Memory is the binding constraint. The reference machine has about 78 GB usable for models. Two mid-size models fit together. The largest fits only alone.内存是硬约束。参考机器可用于模型的内存约 78 GB。两个中等模型可以同时驻留,最大的模型只能单独运行。
- A model stays resident for a keep-alive window. A request for a model that is not resident pays a cold load, and loading it may evict another.模型在 keep-alive 时间窗内保持驻留。请求一个未驻留的模型要付出冷加载的代价,而且加载它可能会把另一个模型挤出内存。
- After load, latency is close to output tokens divided by tokens per second. On the reference build the median was 26 seconds at 72 tokens per second, which matches a median answer of about 1,700 tokens.加载完成后,延迟约等于输出 token 数除以每秒 token 数。参考系统的中位延迟是 26 秒,速率 72 token/秒,正好对应约 1,700 token 的中位回答长度。
Where it sits in the build order它在搭建顺序中的位置
Needs first前置模块
Nothing. You can start here.没有。可以从这里开始。
Unlocks解锁
- API and gatewayAPI 与网关A gateway forwards to an engine. Its timeouts and limits are set from measured load times and generation rates.网关要把请求转发给引擎。它的超时和限额根据测得的加载时间和生成速率来设定。
- RAG and knowledge graphRAG 与知识图谱Search needs an embedding call at index time and at query time. The vector width is fixed by that model, so the model choice comes first.索引和查询时都需要调用 embedding。向量维度由该模型决定,所以要先选定模型。
- Harness engineeringHarness 工程The planner is a model call. Round budgets and output caps are set from measured rates.规划节点就是一次模型调用。轮次预算和输出上限根据测得的速率设定。
- Operations and deployment运维与部署The engine is the first service to supervise, and its memory limits decide what may run at the same time.引擎是第一个需要守护的服务,它的内存上限决定了哪些东西可以同时运行。
In the reference build在参考系统中
| Path路径 | Role作用 |
|---|---|
| ollama-env.sh | Serving settings: loaded-model cap, keep-alive, parallelism, context length.服务参数:驻留模型上限、keep-alive、并发数、上下文长度。 |
| apps/agent-server/model_router.py | Picks a model per request. Two mechanisms: tag swap and base-URL swap.为每个请求选模型。两种机制:换 tag 和换 base URL。 |
| apps/agent-server/model_catalog.json | The lineup: which model serves default, fast, and vision work.模型阵容:哪个模型负责默认、快速、视觉任务。 |
| apps/agent-server/bench_latency.py | Measures time to first token and tokens per second from real requests.从真实请求测量首 token 时间和每秒 token 数。 |
Process map流程图
What happens to one request at the engine一个请求在引擎里经历了什么
- 1Request arrives请求到达OpenAI-style JSON with a model name, messages, and max tokens.OpenAI 格式的 JSON,包含模型名、消息和最大 token 数。
- 2Is the model resident?模型在内存里吗?If yes, go to prompt evaluation. If no, the engine must load it and may evict another.在,就直接处理提示词。不在,引擎必须先加载,可能要换出别的模型。
- 3Cold load冷加载Tens of seconds for a 20 to 60 GB model. The largest avoidable cost.20 到 60 GB 的模型需要几十秒。这是最大的可避免开销。
- 4Prompt evaluation处理提示词Cost grows with prompt size. Tool schemas and system prompts count on every turn.开销随提示词长度增长。工具 schema 和系统提示词每一轮都要计入。
- 5Generation生成Output tokens at a steady rate. Time is tokens divided by rate.以稳定速率输出 token。时间等于 token 数除以速率。
- 6Stream out流式输出Tokens leave as they are produced, so the first one arrives early.token 一边生成一边发出,所以第一个 token 很早就到。
Build steps搭建步骤
Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。
- 1Write the memory budget before you choose models先写内存预算,再选模型
- 2Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上
- 3Set the serving parameters on purpose有意识地设定服务参数
- 4Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
- 5Write one client function and use it everywhere写一个客户端函数,全系统共用
- 6Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
- 7Add a second runtime only where it earns its place只在值得的地方增加第二个运行时
- 8Route by task type, and fail safe按任务类型路由,并且失败时不出错
- 9Cut latency where it is actually spent在真正耗时的地方降低延迟
- 10Keep the engine private让引擎保持私有
01Write the memory budget before you choose models先写内存预算,再选模型
Do this操作
- Find usable model memory: unified memory minus the OS and your services on Apple silicon, or VRAM per card on a GPU server.算出可用于模型的内存:Apple 芯片是统一内存减去系统和服务占用;GPU 服务器是每张卡的显存。
- For each candidate, write its resident size: weights at your quantization plus headroom for context.为每个候选模型写下驻留大小:所选量化精度下的权重,加上上下文的余量。
- Run the lab with your own numbers. Read which pairs fit and what each cold load costs.把你自己的数字填进 lab 运行。看哪些组合能同时驻留,以及每个模型冷加载要多久。
- Decide which models must be warm together. That pair is your default path.决定哪些模型必须同时保持热状态。这一对就是你的默认路径。
def plan(usable_gb: float, models: dict, load_gb_per_s: float = 1.5) -> dict:
"""models maps name -> resident size in GB (weights plus context headroom)."""
fits_alone = {m: size <= usable_gb for m, size in models.items()}
pairs = {}
for a, b in combinations(models, 2):
total = models[a] + models[b]
pairs[(a, b)] = {"total_gb": round(total, 1), "fits": total <= usable_gb}
cold_load_s = {m: round(size / load_gb_per_s) for m, size in models.items()}
return {"fits_alone": fits_alone, "pairs": pairs, "cold_load_s": cold_load_s}python3 -m labs.m01_inference.budgetusable 77.8 GB
workhorse-35b + vision-27b = 51.3 GB fits
workhorse-35b + reasoner-120b = 83.2 GB DOES NOT FIT
workhorse-35b + embedder = 22.6 GB fits
vision-27b + reasoner-120b = 89.9 GB DOES NOT FIT
vision-27b + embedder = 29.3 GB fits
reasoner-120b + embedder = 61.2 GB fits
cold load estimate (s): {'workhorse-35b': 15, 'vision-27b': 19, 'reasoner-120b': 41, 'embedder': 0}- Inference engineering推理工程 2: Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上 (which models to pull要拉取哪些模型)
- Inference engineering推理工程 3: Set the serving parameters on purpose有意识地设定服务参数 (how many models may be resident允许同时驻留几个模型)
- Inference engineering推理工程 7: Add a second runtime only where it earns its place只在值得的地方增加第二个运行时 (memory left for a small model留给小模型的内存)
02Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上Not executed in the labslab 中未执行
- which models to pull要拉取哪些模型 ← Inference engineering推理工程 1: Write the memory budget before you choose models先写内存预算,再选模型
Do this操作
- Install the engine with your package manager.用包管理器安装引擎。
- Set the model directory to the data volume before the first pull.第一次拉取模型之前,把模型目录指向数据卷。
- Pull the workhorse model and the embedding model from your budget.按预算拉取主力模型和 embedding 模型。
brew install ollama # Linux: curl -fsSL https://ollama.com/install.sh | sh
export AI_DATA=/Volumes/DATA # your data volume
export OLLAMA_MODELS="$AI_DATA/models/ollama"
ollama serve &
ollama pull <workhorse-model>
ollama pull nomic-embed-text
ollama listThis step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write- Inference engineering推理工程 3: Set the serving parameters on purpose有意识地设定服务参数 (the engine to configure要配置的引擎)
- Inference engineering推理工程 4: Call the endpoint the way every later layer will用后续各层都会用的方式调用端点 (a running engine运行中的引擎)
- Operations and deployment运维与部署 1: List every service, its port, and its interpreter列出每个服务、它的端口和解释器 (the engine process引擎进程)
03Set the serving parameters on purpose有意识地设定服务参数Not executed in the labslab 中未执行
- how many models may be resident允许同时驻留几个模型 ← Inference engineering推理工程 1: Write the memory budget before you choose models先写内存预算,再选模型
- the engine to configure要配置的引擎 ← Inference engineering推理工程 2: Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上
Do this操作
- Cap loaded models at what the budget allows.把驻留模型上限设为预算允许的数量。
- Set keep-alive longer than the normal gap between requests.把 keep-alive 设得比请求之间的正常间隔更长。
- Set parallel slots to the concurrency you expect. Each slot reserves context memory.按预期并发设定并行槽位。每个槽位都会预留上下文内存。
- Set context length explicitly, send one request, and read the engine log to confirm the real prompt size.明确设定上下文长度,发一个请求,然后读引擎日志确认真实的提示词大小。
export OLLAMA_MAX_LOADED_MODELS=2 # at most 2 models resident
export OLLAMA_KEEP_ALIVE=30m # unload after 30 idle minutes
export OLLAMA_NUM_PARALLEL=4 # concurrent requests per model
export OLLAMA_CONTEXT_LENGTH=49152 # tokens of context per slot
export OLLAMA_FLASH_ATTENTION=1 # less memory for long contextsThis step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write04Call the endpoint the way every later layer will用后续各层都会用的方式调用端点Not executed in the labslab 中未执行
- a running engine运行中的引擎 ← Inference engineering推理工程 2: Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上
Do this操作
- Call the endpoint with curl before adding any library.在引入任何库之前,先用 curl 调用端点。
- Confirm the response has `choices` and a `usage` block.确认响应里有 `choices` 和 `usage` 字段。
- Export `LAB_BASE_URL` and `LAB_MODEL`. Every lab from here on uses your real model when these are set.导出 `LAB_BASE_URL` 和 `LAB_MODEL`。设置之后,后面所有 lab 都会使用你的真实模型。
curl -s http://127.0.0.1:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "<workhorse-model>",
"messages": [{"role": "user", "content": "Reply with the word ready."}],
"max_tokens": 16}' | python3 -m json.tool
export LAB_BASE_URL=http://127.0.0.1:11434/v1
export LAB_MODEL=<workhorse-model>This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write- Inference engineering推理工程 5: Write one client function and use it everywhere写一个客户端函数,全系统共用 (the request and response shape请求和响应的格式)
- Inference engineering推理工程 6: Measure time to first token and tokens per second测量首 token 时间和每秒 token 数 (the endpoint to measure要测量的端点)
- Inference engineering推理工程 10: Keep the engine private让引擎保持私有 (the port to protect要保护的端口)
- API and gatewayAPI 与网关 1: Decide the public surface确定对外接口 (the request and response format to preserve需要保持不变的请求和响应格式)
05Write one client function and use it everywhere写一个客户端函数,全系统共用
- the request and response shape请求和响应的格式 ← Inference engineering推理工程 4: Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
Do this操作
- Read the function below. It returns the same response shape from a real endpoint or from the fake model.阅读下面的函数。无论调用真实端点还是假模型,它返回的响应结构都相同。
- Note what the fake model is: a deterministic test double. It proves plumbing and nothing about quality.注意假模型是什么:一个确定性的测试替身。它只能证明管道通了,证明不了质量。
def chat(messages: list, tools: Optional[list] = None, model: Optional[str] = None,
max_tokens: int = 512, policy: Optional[Policy] = None) -> dict:
"""Send messages, get an OpenAI-shaped completion back."""
base = os.environ.get("LAB_BASE_URL", "").rstrip("/")
if not base:
message = (policy or default_policy)(messages, tools)
return _wrap(message, messages)
body = {"model": model or os.environ.get("LAB_MODEL", ""), "messages": messages,
"max_tokens": max_tokens, "stream": False}
if tools:
body["tools"] = tools
req = urllib.request.Request(
base + "/chat/completions", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json",
"Authorization": "Bearer " + os.environ.get("LAB_API_KEY", "none")})
with urllib.request.urlopen(req, timeout=float(os.environ.get("LAB_TIMEOUT", "180"))) as r:
return json.loads(r.read())- API and gatewayAPI 与网关 3: Write the gateway handler编写网关处理函数 (chat() as the upstream作为上游的 chat())
- RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库 (embed()embed())
- Harness engineeringHarness 工程 1: Build the flat loop and bound it搭建扁平循环并设上限 (chat()chat())
- Skills技能(Skills) 4: Match a request to at most one skill把请求匹配到至多一个技能 (embed()embed())
- Memory记忆 4: Add recall over past turns加入对历史对话的回忆 (embed()embed())
- Multi-agent patterns多智能体模式 5: Build two independent judges搭建两个相互独立的裁判 (embed(), and chat() when a judge is a modelembed();裁判是模型时还需要 chat())
06Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
- the endpoint to measure要测量的端点 ← Inference engineering推理工程 4: Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
Do this操作
- Run the bench twice in a row against your endpoint.对你的端点连续运行两次基准测试。
- Compare the first call with the second. A large gap in time to first token is a cold load.对比第一次和第二次。首 token 时间差距大,就是冷加载。
- Check that total time is close to first-token time plus tokens divided by rate.检查总时间是否接近 首 token 时间 + token 数 ÷ 速率。
def bench_stream(base_url: str, model: str, prompt: str, max_tokens: int = 200) -> dict:
"""Stream one completion and time it. Works against any OpenAI-compatible server."""
body = json.dumps({"model": model, "stream": True, "max_tokens": max_tokens,
"messages": [{"role": "user", "content": prompt}]}).encode()
req = urllib.request.Request(base_url.rstrip("/") + "/chat/completions", data=body,
headers={"Content-Type": "application/json",
"Authorization": "Bearer " + os.environ.get("LAB_API_KEY", "none")})
t0 = time.time()
first = None
pieces = 0
with urllib.request.urlopen(req, timeout=600) as resp:
for raw in resp:
line = raw.decode().strip()
if not line.startswith("data:") or line.endswith("[DONE]"):
continue
delta = json.loads(line[5:])["choices"][0].get("delta", {})
if delta.get("content"):
first = first or time.time()
pieces += 1 # one streamed piece is roughly one token
end = time.time()
gen = max(end - (first or end), 1e-6)
return {"ttft_s": round((first or end) - t0, 2), "total_s": round(end - t0, 2),
"tokens": pieces, "tok_per_s": round(pieces / gen, 1)}python3 -m labs.m01_inference.benchno LAB_BASE_URL set, showing a worked example with fixed numbers
cold : first token after 41.2 s, 200 tokens at 72.0 tok/s, total 43.98 s. Predicted total = ttft + tokens / rate = 43.98 s
warm : first token after 0.6 s, 200 tokens at 72.0 tok/s, total 3.38 s. Predicted total = ttft + tokens / rate = 3.38 s
same model, same rate. The 40 s difference is the cold load.- Inference engineering推理工程 7: Add a second runtime only where it earns its place只在值得的地方增加第二个运行时 (proof the workhorse is too slow for cheap jobs主力模型做便宜任务太慢的证据)
- Inference engineering推理工程 8: Route by task type, and fail safe按任务类型路由,并且失败时不出错 (which model is fast enough for which task哪个模型对哪类任务足够快)
- Inference engineering推理工程 9: Cut latency where it is actually spent在真正耗时的地方降低延迟 (the baseline to beat要超越的基线)
07Add a second runtime only where it earns its place只在值得的地方增加第二个运行时Not executed in the labslab 中未执行
- memory left for a small model留给小模型的内存 ← Inference engineering推理工程 1: Write the memory budget before you choose models先写内存预算,再选模型
- proof the workhorse is too slow for cheap jobs主力模型做便宜任务太慢的证据 ← Inference engineering推理工程 6: Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
Do this操作
- Start the small model in its own process on its own port.在独立进程、独立端口上启动小模型。
- Note the difference: this runtime serves one model per process, so you select it by URL and not by model name.注意区别:这个运行时一个进程只服务一个模型,所以靠 URL 来选它,而不是靠模型名。
# Apple silicon. One process, one model, its own port.
mlx_lm.server --model mlx-community/<small-model>-4bit --port 8082
# NVIDIA: vllm serve <model> --port 8082This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write- Inference engineering推理工程 8: Route by task type, and fail safe按任务类型路由,并且失败时不出错 (the base URL of the fast model快速模型的 base URL)
08Route by task type, and fail safe按任务类型路由,并且失败时不出错
- which model is fast enough for which task哪个模型对哪类任务足够快 ← Inference engineering推理工程 6: Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
- the base URL of the fast model快速模型的 base URL ← Inference engineering推理工程 7: Add a second runtime only where it earns its place只在值得的地方增加第二个运行时
Do this操作
- Classify each request: default, fast, or vision.给每个请求分类:默认、快速、视觉。
- Map the class to a catalog entry. An entry has either a model tag or a base URL.把类别映射到目录条目。条目要么是模型 tag,要么是 base URL。
- On anything unknown, missing, or failing, return nothing so the request runs as it would have.遇到未知、缺失或出错的情况,返回空值,让请求按原样执行。
def resolve_for_request(payload: dict, catalog: Optional[dict] = None) -> Optional[dict]:
"""Return {'model': tag} or {'base_url': url}, or None to leave the request untouched."""
try:
if payload.get("model"): # the caller chose: do nothing
return None
entry = (CATALOG if catalog is None else catalog).get(detect_task(payload))
if not entry:
return None # unknown task: do nothing
if entry.get("base_url"):
return {"base_url": entry["base_url"]}
if entry.get("tag"):
return {"model": entry["tag"]}
return None # incomplete entry: do nothing
except Exception:
return None # any error: do nothingpython3 -m labs.m01_inference.routertext -> {'model': 'workhorse-35b'}
image -> {'model': 'vision-27b'}
short -> {'base_url': 'http://127.0.0.1:8082/v1'}
explicit-> None
no catalog -> None- API and gatewayAPI 与网关 6: Apply the model router in the gateway在网关里应用模型路由 (resolve_for_request()resolve_for_request())
09Cut latency where it is actually spent在真正耗时的地方降低延迟Not executed in the labslab 中未执行
- the baseline to beat要超越的基线 ← Inference engineering推理工程 6: Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
Do this操作
- Set a default max-tokens value and ask for shorter answers in the system prompt. Output volume dominates.设一个默认的 max_tokens,并在系统提示词里要求简短回答。输出量是主要因素。
- Stream responses and reuse one pooled HTTP client.使用流式响应,并复用一个 HTTP 连接池。
- Keep prompts small. Tool schemas, the system prompt, and memory are charged on every turn.保持提示词精简。工具 schema、系统提示词和记忆每一轮都要计费。
- List every model your request path can load, including the embedder. Remove avoidable loads.列出请求路径上可能加载的所有模型,包括 embedding 模型。去掉可以避免的加载。
This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write10Keep the engine private让引擎保持私有Not executed in the labslab 中未执行
- the port to protect要保护的端口 ← Inference engineering推理工程 4: Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
Do this操作
- Bind the engine to localhost or a private network interface.把引擎绑定到 localhost 或私有网络接口。
- From another device on a different network, confirm the engine port does not answer.从另一个网络的设备上确认引擎端口没有响应。
This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write- API and gatewayAPI 与网关 7: Open one public door只开一个对外入口 (an engine that is not reachable directly一个无法被直接访问的引擎)
How it works with the other parts它如何与其他部分协作
- API and gatewayAPI 与网关The gateway is the only thing allowed to forward outside traffic to the engine.只有网关可以把外部流量转发给引擎。
- RAG and knowledge graphRAG 与知识图谱Retrieval uses the embedding model. Loading it can evict a chat model, so retrieval design affects inference cost.检索使用 embedding 模型。加载它可能挤掉聊天模型,所以检索设计会影响推理成本。
- Harness engineeringHarness 工程Each tool round is another model call. Round budgets and prompt size are inference decisions made in the harness.每一轮工具调用都是一次模型调用。轮次预算和提示词大小是在 Harness 里做出的推理决策。
- Evaluation评估Judges and question writers are model calls. A small second runtime lets evals run without evicting the serving model.裁判和出题也是模型调用。小的第二运行时让评估运行时不会挤掉服务模型。
What went wrong in the real build真实搭建中踩过的坑
A context setting that was present but not in effect配置写了,但没有生效
- What happened发生了什么
- A context cap was configured for a coding client. Requests still sent far larger prompts and timed out after 15 minutes.给编程客户端配置了上下文上限,但请求仍然发送大得多的提示词,15 分钟后超时。
- Fix修复
- Read the engine log for the real prompt size on each request before touching anything else.先读引擎日志里每个请求的真实提示词大小,再动别的。
- Lesson教训
- A configured value is a claim. The log line is the evidence.配置值只是声明,日志才是证据。
The embedder evicted the chat modelembedding 模型挤掉了聊天模型
- What happened发生了什么
- With a cap of two resident models, a knowledge search loaded the embedding model and pushed the chat model out. The next answer paid a 35 to 70 second reload.驻留上限为两个模型时,一次知识检索加载了 embedding 模型,把聊天模型挤了出去。下一次回答要等 35 到 70 秒重新加载。
- Fix修复
- Route definition questions to a full-text lookup that loads no model.把定义类问题路由到不加载任何模型的全文检索。
- Lesson教训
- Count every model your request path can load, including the small ones.把请求路径上可能加载的每个模型都算进去,小模型也算。
Latency blamed on model speed把延迟归咎于模型速度
- What happened发生了什么
- Median latency was 26 seconds and p90 was 89 seconds. The generation rate was a healthy 72 tokens per second.中位延迟 26 秒,p90 为 89 秒。而生成速率是正常的 72 token/秒。
- Fix修复
- Cap default output tokens, stream, and extend keep-alive.限制默认输出 token 数,使用流式,延长 keep-alive。
- Lesson教训
- Latency is tokens divided by rate. Check the numerator first.延迟等于 token 数除以速率。先检查分子。
The same idea on other platforms同样的思路在其他平台上
| Platform平台 | How this module maps本模块如何对应 |
|---|---|
| Databricks | Hosted model endpoints replace the engine, and Unity Gateway (formerly AI Gateway) gives one API across models. Your memory budget becomes a throughput and cost budget. The endpoint is OpenAI-compatible, so the contract step carries over.托管的模型端点取代引擎,Unity Gateway(原 AI Gateway)用一套 API 访问各种模型。内存预算变成吞吐量和成本预算。端点兼容 OpenAI,所以契约那一步原样适用。 |
| IBM watsonx | watsonx.ai hosts foundation models behind an inference API, with on-demand deployments for dedicated capacity. Model choice is a catalog decision. You still measure rate and first-token time per model.watsonx.ai 通过推理 API 托管基础模型,并可按需部署专用容量。选模型变成在目录里做选择。你仍然要逐个模型测量速率和首 token 时间。 |
| Codex | Codex is a client of an inference endpoint. It uses hosted models by default and can be pointed at another provider in its config, including a local OpenAI-compatible server.Codex 是推理端点的客户端。默认使用托管模型,也可以在配置里指向其他供应商,包括本地的 OpenAI 兼容服务。 |
| Cursor | Cursor consumes inference. It can override the OpenAI base URL to reach your own endpoint for some features. Serving decisions are made wherever that endpoint runs.Cursor 是推理的使用方。部分功能可以覆盖 OpenAI base URL 来访问你自己的端点。服务层面的决策在端点所在的地方做。 |
| Claude Code / Agent SDK | Claude Code and the Agent SDK call a hosted model, or a compatible gateway you configure. Context budgets still apply and are charged on every turn.Claude Code 和 Agent SDK 调用托管模型,或你配置的兼容网关。上下文预算依然存在,而且每一轮都计费。 |
| Another machine | On an NVIDIA machine use vLLM or llama.cpp in place of the Mac runtimes. The budget is VRAM per card. Use systemd in place of launchd. Every step from the contract onward is identical.在 NVIDIA 机器上用 vLLM 或 llama.cpp 代替 Mac 上的运行时。预算是每张卡的显存。用 systemd 代替 launchd。从契约那一步开始,其余完全相同。 |
Step-by-step guides per platform各平台的分步指南
Explain it back讲给自己听
Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。
Why does the memory budget come before model selection?为什么内存预算要排在选模型之前?
A request is slow. What do you look at first, and why?一个请求很慢。你先看什么?为什么?
Why are there two routing mechanisms?为什么有两种路由机制?
You want to build retrieval before this module. What do you stub?你想在这个模块之前先做检索。需要用什么替代?
Terms术语
| Resident驻留 | Loaded in memory and ready to generate without a load delay.已加载在内存中,无需等待加载即可生成。 |
| Keep-aliveKeep-alive | How long an idle model stays resident before the engine unloads it.空闲模型在被引擎卸载前保持驻留的时长。 |
| TTFTTTFT(首 token 时间) | Time to first token. What the user feels as responsiveness.从请求到第一个 token 的时间。用户感受到的响应速度。 |
| Quantization量化 | Storing weights at lower precision to cut memory, with some quality cost.用更低精度存储权重以节省内存,会损失一些质量。 |
From the live build来自实时构建
Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Reranker: cap and release the MLX buffer cache (process had grown to 71 GB)
- Finish the Update Today — remaining steps
- AI Local Server → Vercel Integration Guide
- Whole-System Audit and Revised Update Plan
- AI Stack Update Runbook — 2026-08-20
- 01 — System Architecture
- 02 — The Build Process, Step by Step
- Standalone reranker server for build-host agent-server's rerank_route.py. Added 2026-08-03.
- Double-click button: stops and restarts the NEW agent-server harness (apps/agent-server/main.py, FastAPI + agent_loop.py, port 8788).
- REWRITTEN by Install-Autostart.command. The services this script used to nohup are now launchd jobs, so starting them means LOADING them, not spawning a second copy.
- what is every local model doing RIGHT NOW. python3 llm_activity.py one snapshot, in the terminal python3 llm_activity.py --watch refresh every 5s until Ctrl-C python3 llm_activity.py --html also write $AI_DATA/llm-activity.html python3 llm_activity.py --html --watch keep ...
- Measure what parallel mining actually buys — 2026-09-10. The claim being tested is narrow and worth testing rather than assuming: mlx_lm.server answers one request at a time, so N servers should give close to N times the throughput UNTIL memory bandwidth saturates.
- copy-truncate rotation for AI_DATA logs. WHY COPY-TRUNCATE AND NOT MOVE: Ollama, agent-server and the MLX backends hold their log files open with O_APPEND.
- document -> verified audiobook (English + Chinese) $AI_DATA/apps/agent-server/venv/bin/python3 make_audiobook.py FILE All synthesis, normalization and quality checking lives in tts_engine.py.
- production text-to-speech for long documents (EN + ZH) ===================================================================== Replaces the naive "post a big chunk, hope it comes back" approach with the loop commercial audiobook pipelines actually use: normalize -> small units -> ...