AI Infra 与性能优化
这个主题讨论 AI 应用为什么贵、为什么慢,以及如何做系统级优化。
当 AI 功能从 Demo 进入真实业务,性能问题会同时出现在模型、网络、检索、工具、队列和前端体验里。这个阶段会把“调一个更快模型”扩展为“从请求链路、缓存、路由、降级和成本观测一起优化”。
学习目标
完成这个主题后,你应该能够:
- 拆解一次 AI 请求的成本结构和延迟结构。
- 使用 TTFT、tokens per second、total latency、error rate 和 cost per request 评估系统。
- 设计 prompt cache、response cache、embedding cache、retrieval cache 和 tool result cache。
- 实现模型路由、fallback、限流、队列和降级模式。
- 理解本地模型、边缘推理和浏览器端 AI 的适用边界。
关键概念
TTFT 是 Time To First Token,决定用户什么时候看到第一个输出。Streaming 能显著改善感知速度,但不一定减少总耗时。
Generation Time 通常与输出 token 数量和模型吞吐有关。输出越长,越需要控制 max tokens、格式约束和分段生成。
Model Routing 根据任务类型、成本预算、延迟要求和能力需求选择模型。不是所有请求都应该走最强模型。
Cache 不是一个缓存层就够了。Prompt、embedding、检索结果、工具结果和完整响应都有不同命中条件与失效策略。
Fallback 是 AI 系统的可靠性设计。模型失败、供应商限流、检索超时或工具不可用时,系统应该有可解释的降级路径。
AI Infra 延迟结构
这张图把一次请求拆成网关、排队、缓存、检索、模型首 token、流式生成和后处理。优化时要先定位瓶颈,再决定是缓存、路由、限流还是换模型。
核心主题
- AI 成本结构:input token、output token、model price、tool cost、vector database cost、storage cost。
- AI 延迟结构:network latency、queue time、first token time、generation time、tool latency、retrieval latency。
- 性能指标:TTFT、tokens per second、total latency、throughput、error rate、cost per request。
- Cache:prompt cache、response cache、embedding cache、retrieval cache、tool result cache。
- Queue:request queue、background job、long-running task、retry queue。
- Rate Limit:user limit、tenant limit、provider limit、model limit。
- Model Routing:fast model、smart model、cheap model、coding model、vision model。
- Model Fallback:provider fallback、model fallback、degraded mode。
- Local Model:Ollama、LM Studio、vLLM、llama.cpp、GGUF。
- Browser AI:WebGPU、WebNN、local inference、privacy advantage。
- Edge AI:edge inference、edge routing、Cloudflare Workers AI。
- 概念级推理优化:batching、KV Cache、quantization、speculative decoding。
阶段实践拆解
- 增加请求日志:记录 model、input tokens、output tokens、latency、TTFT、status 和 estimated cost。
- 实现模型路由:按任务类型选择 fast、smart、cheap、vision 或 coding model。
- 实现 fallback:主模型失败或限流时切换备用模型,并标记 degraded mode。
- 接入响应缓存:对稳定 prompt、低风险问答或工具结果做缓存,设计 cache key 和失效策略。
- 接入队列和限流:对长任务异步执行,对用户、租户和模型供应商分别限制频率。
- 构建成本 Dashboard:按用户、功能、模型、日期统计请求量、成本、错误和延迟。
- 本地部署小模型:用 Ollama 或 llama.cpp 运行一个本地模型,对比隐私、成本、延迟和质量。
阶段实践
- 实现模型路由。
- 实现响应缓存。
- 实现成本统计 Dashboard。
- 本地部署一个小模型。
计划文章
- 为什么 AI 应用很贵
- AI 应用如何做成本优化
- 小模型、本地模型和大模型 API 如何取舍