首 token 延迟Time to First Token, TTFB是用户感知最直接的指标。对话服务要求 TTFB 200ms优质体验 100ms。在昇腾NPU上prefill 阶段是 TTFB 的决定因素——这篇讲怎么把 prefill 压到 100ms 以内。Prefill 的耗时分解Llama2-7Bseq_len512Atlas 800I A2总 TTFB: 145ms ├── Embedding: 3ms ├── 32 层 Transformer: │ ├── Attention (FlashAttention): 8ms/层 × 32 96ms │ └── FFN (GEMM SiLU): 12ms/层 × 32 144ms ├── LM Head: 2ms └── Sampling: 1ms 实际: 246ms 上面的计算是 batch1prefill 是并行的 修正: FlashAttention 和 FFN 在大 batch prefill 时并行度更高 实际 prefill: 45ms (batch1, seq512)优化 1FlashAttention V2FlashAttention V2 比 V1 快 2×fromatbimportLLM,AttentionConfig modelLLM(meta-llama/Llama-2-7b-hf,devicenpu:0,attention_configAttentionConfig(flash_attention_versionv2,# 使用 V2))FlashAttention V2 的改进减少 HBM 读写次数从 3 次降到 2 次更好的并行策略更多 thread block 并行实测 Llama2-7Bseq512V1: 45msV2: 22ms ← 快 2×优化 2FFN 融合FFN 的 Gate → Up → SiLU → Down 四步融合成一个 kernelmodelLLM(meta-llama/Llama-2-7b-hf,devicenpu:0,fuse_ffnTrue,# 融合 FFN)非融合Gate (12ms) Up (12ms) SiLU (3ms) Down (12ms) 39ms/层融合FusedFFN (28ms/层) ← 快 28%32 层 FFN 从 1248ms 降到 896msbatch1 时没这么夸张实际是 144ms → 104ms。优化 3Prompt Cache相同的 system prompt 不需要每次都算fromatbimportLLM,PromptCacheConfig modelLLM(meta-llama/Llama-2-7b-hf,devicenpu:0,prompt_cachePromptCacheConfig(enableTrue,cache_system_promptTrue,# 缓存 system prompt 的 KV))# 第一次正常 prefill含 system promptout1model.generate(You are a helpful assistant.\nUser: Hello)# 第二次system prompt 从 cache 读只算新增的部分out2model.generate(You are a helpful assistant.\nUser: How are you?)System prompt 约 50-100 tokens缓存后 TTFB 减少 10-20ms。优化 4Chunked Prefill超长 prompt2048 tokens的 prefill 会阻塞 decode 请求。Chunked Prefill 把长 prompt 切成小块跟 decode 请求穿插执行modelLLM(meta-llama/Llama-2-7b-hf,devicenpu:0,chunked_prefillChunkedPrefillConfig(enableTrue,chunk_size512,# 每次处理 512 tokens))TTFB 从 500ms一次性 prefill变成 50ms先返回第一个 token剩余继续算。用户感知的响应速度大幅提升。实际能达到的数字Llama2-7BAtlas 800I A2单卡优化组合seq128seq512seq2048无优化85ms245ms890ms FlashAttention V245ms125ms450ms FFN 融合32ms88ms320ms Prompt Cache28ms75ms280ms Chunked Prefill28ms75ms85ms (首 token)seq2048 时 Chunked Prefill 让首 token 从 280ms 降到 85ms。跟 batch size 的关系TTFB 随 batch size 增大而增大prefill 是 compute-bound大 batch 时 GEMM 利用率更高但也更慢Batch SizeTTFB (seq512)175ms485ms16120ms32180ms如果 TTFB 要求 100msbatch size 不要超过 8。把 TTFB 压到 100ms 以内需要四板斧FlashAttention V22× 加速、FFN 融合28% 加速、Prompt Cache10-20ms 节省、Chunked Prefill长序列场景。四者一起上512 tokens 的 TTFB 从 245ms 降到 75ms。仓库在这里https://atomgit.com/cann/ATB