> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# LLM 推理引擎解读
- URL: https://www.hubwiz.com/blog/llm-inference-engine-explained/
- Published: 2026-09-04T13:12:00.000Z
- Updated: 2026-09-04T13:12:00.000Z
- Description: LLM推理引擎详解：llama.cpp、HFT、vLLM、SGLang、CPU、GPU及厂商专用技术栈。
- Author: admin
- Tags: AI INFRA, #Import 2026-10-14 14:41

大语言模型（LLM）本质上是一组学习到的权重，而非能独立回答提示的自包含应用。这些权重是模型在训练过程中学到的数值，决定了模型如何响应输入。因此，下载的模型包含了模型的学习状态，但它并不包含能接受提示并直接返回文本的完整应用。仍然需要某些东西将这些权重加载到内存中，将输入传递给模型，然后计算输出。

## 1、什么是 LLM 推理引擎？

大型语言模型 (LLM) 主要由一组已学习的权重组成，而不是一个能够独立回答提示的独立应用程序。这些权重是模型在训练过程中学习到的数值，它们决定了模型如何响应输入。因此，下载的模型包含模型的学习状态，但并不包含一个能够接收提示并自动返回文本的完整应用程序。仍然需要其他程序将这些权重加载到内存中，将输入传递给模型，并计算输出。

```
提示
↓
LLM 推理引擎
↓
模型权重
↓
生成的词元
↓
文本响应
```

由于这些权重本身无法执行，因此需要一个推理引擎来加载它们，运行模型架构，并生成响应中的下一个词元。权重包含模型在训练过程中学习到的模式，正是这些模式使得不同的模型在编码、数学、推理或其他任务上表现更佳。

推理引擎本身并不添加这些知识。它的任务是将模型学习到的权重应用于提示词，并计算下一个可能词元的概率，然后在生成响应时重复此过程。因此，不同的引擎应该保留同一模型的底层功能，尽管量化、数值精度和词元采样等选择可能会导致输出结果有所不同。

```
提示词元
↓
模型应用学习到的权重
↓
对可能的下一个词元进行评分
↓
“infer” 0.61
“the” 0.08
“because” 0.05
“27” 0.03
... ...
↓
选择下一个词元
↓
“infer”
```

每个引擎支持不同的模型格式，并在硬件、内存使用和性能方面做出不同的权衡。一个引擎可能旨在高效地在笔记本电脑 CPU 上运行量化模型，而另一个引擎可能旨在跨强大的 GPU 处理大量请求。一些引擎还要求特定的模型格式，或者在同一底层模型的特定表示形式下效果最佳。

该模型包含学习到的能力，包括训练期间编码的模式、关系和任务行为，而推理引擎决定如何将这些学习到的权重加载到内存中，如何在可用硬件上执行模型计算，如何生成标记，以及整个过程的运行效率如何。

## 2、从LLM模型文件到可运行代码

在下面的代码示例中，每个引擎将运行相同的底层模型 `Qwen/Qwen2.5-1.5B-Instruct`，并回答相同的提示：

```
A server handles 240 requests per second. Traffic increases by 35%.
How many requests per second must it handle? Show the calculation.
```

### 2.1 llama.cpp

[llama.cpp](https://github.com/ggml-org/llama.cpp?ref=hubwiz.com) 是一个用C/C++编写的推理引擎，旨在跨CPU和GPU高效运行LLM。其主要模型格式是GGUF，包括量化文件。

```
!git clone https://github.com/ggml-org/llama.cpp
%cd llama.cpp

!cmake -B build -DCMAKE_BUILD_TYPE=Release
!cmake --build build -j2
!./build/bin/llama-cli \
  -hf Qwen/Qwen2.5-1.5B-Instruct-GGUF:Q4_K_M \
  -p "A server handles 240 requests per second. Traffic increases by 35%. How many requests per second must it handle? Show the calculation." \
  -n 80 \
  --temp 0
```

### 2.2 Hugging Face Transformers (HFT)

[Hugging Face Transformers (HFT)](https://huggingface.co/docs/transformers/index?ref=hubwiz.com) 是一个Python框架，通常加载以Hugging Face检查点形式分发的模型。

```
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-1.5B-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_name)

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)

prompt = """
A server handles 240 requests per second. Traffic increases by 35%.
How many requests per second must it handle? Show the calculation.
"""

messages = [
    {
        "role": "user",
        "content": prompt
    }
]

inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

outputs = model.generate(
    **inputs,
    max_new_tokens=80,
    do_sample=False
)

response = tokenizer.decode(
    outputs[0][inputs["input_ids"].shape[-1]:],
    skip_special_tokens=True
)

print(response)
```

### 2.3 vLLM

[vLLM](https://docs.vllm.ai/?ref=hubwiz.com) 是一个专注于GPU的推理和服务引擎，专为高吞吐量而设计。vLLM有两种主要使用方式：i) 离线Python推理，或 ii) HTTP服务。

```
from vllm import LLM, SamplingParams

model_name = "Qwen/Qwen2.5-1.5B-Instruct"
llm = LLM(model=model_name)

messages = [
    {
        "role": "user",
        "content": (
            "A server handles 240 requests per second. "
            "Traffic increases by 35%. "
            "How many requests per second must it handle? "
            "Show the calculation."
        ),
    }
]

sampling_params = SamplingParams(
    temperature=0,
    max_tokens=80
)

outputs = llm.chat(
    messages,
    sampling_params=sampling_params
)

print(outputs[0].outputs[0].text)
```

### 2.4 SGLang

[SGLang](https://github.com/sgl-project/sglang?ref=hubwiz.com) 是另一个专注于GPU的推理和服务引擎，也支持无需先启动API服务器的直接离线推理。

```
import sglang as sgl

model_name = "Qwen/Qwen2.5-1.5B-Instruct"

llm = sgl.Engine(model_path=model_name)

prompt = """
A server handles 240 requests per second. Traffic increases by 35%.
How many requests per second must it handle? Show the calculation.
"""

output = await llm.async_generate(
    prompt,
    sampling_params={
        "temperature": 0,
        "max_new_tokens": 80,
    },
)

print(output["text"])

llm.shutdown()
```

## 3、硬件约束

### 3.1 CPU推理

CPU推理是最灵活的选项，因为它可以在没有专用加速器硬件的普通机器上运行，但通常较慢，并且从较小的模型文件中获益匪浅。

```
Model weights in system memory
           │
           ▼
      ┌─────────┐
      │   CPU   │
      │         │
      │ Core 1  │
      │ Core 2  │
      │ Core 3  │
      │ Core 4  │
      │  ...    │
      └─────────┘
           │
           ▼
    Generated tokens
  Fewer powerful cores
  + large system memory
  + smaller/quantized model
  = practical inference
```

### 3.2 GPU推理

GPU推理更快，因为GPU被构建为同时执行许多数学运算，这符合LLM所需的工作类型。主要限制是GPU内存（VRAM）。

```
  Model weights in VRAM
           │
           ▼
┌───────────────────────┐
│          GPU          │
│                       │
│  ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪  │
│  ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪  │
│  ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪  │
│  ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪ ▪  │
│    many operations    │
└───────────────────────┘
           │
           ▼
    Generated tokens
Many smaller compute units
+ high memory bandwidth
+ limited VRAM
= fast parallel inference
```

## 4、平台专用LLM推理技术栈

通用推理引擎只是问题的一部分，因为某些硬件平台拥有围绕其芯片内存和计算处理方式构建的专属软件栈。NVIDIA、AMD、Apple 和 Cerebras 各自采用不同的方法，从 GPU 专用的推理引擎和编排层，到专为完全不同的处理器架构设计的紧密集成软件，不一而足。

这种差异化的原因在于，随着推理超出简单的本地部署，硬件架构的重要性日益凸显。一旦推理部署到多个 GPU 或服务器上，问题就不再仅仅是加载模型和生成令牌。请求必须路由到正确的工作进程，硬件必须根据流量变化进行添加或移除，并且之前计算的模型状态可以重用，而无需重新计算。

### 4.1 NVIDIA Dynamo

NVIDIA拥有自己的推理栈，因为软件可以专门为NVIDIA GPU进行优化，而不是将它们视为通用硬件。在引擎层面，NVIDIA提供 [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM?ref=hubwiz.com)。[NVIDIA Dynamo](https://docs.nvidia.com/dynamo/dev?ref=hubwiz.com) 位于推理引擎之上。

```
                   NVIDIA Dynamo
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
        vLLM          SGLang      TensorRT-LLM
          │              │              │
          └──────────────┼──────────────┘
                         ▼
                    NVIDIA GPUs
```

### 4.2 AMD ATOMesh

AMD围绕ROCm和AMD Instinct GPU构建了自己的推理栈。在引擎层面，ATOM是AMD优化的LLM推理引擎。[ATOMesh](https://www.amd.com/en/developer/resources/technical-articles/2026/atomesh-unlocking-amd-hardware-for-scalable-llm-serving.html?ref=hubwiz.com) 处理跨集群的分布式推理。

```
                     AMD ATOMesh
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
        ATOM           vLLM          SGLang
          │              │              │
          └──────────────┼──────────────┘
                         ▼
                  AMD Instinct GPUs
                         │
                         ▼
                        ROCm
```

最终得到的架构与 NVIDIA 的架构非常相似，同时保持了推理引擎的可替换性：

```
NVIDIA Dynamo                   AMD ATOMesh
   │                               │
   ├── vLLM                        ├── ATOM
   ├── SGLang                      ├── vLLM
   └── TensorRT-LLM                └── SGLang
   │                               │
NVIDIA GPUs                     AMD Instinct GPUs
```

### 4.3 Apple Silicon与MLX-LM

Apple Silicon指的是为Mac和其他Apple设备设计的芯片。Apple Silicon改变了推理设置，因为CPU和GPU共享相同的统一内存，而不是将系统RAM和GPU内存分开。对于LLM，Apple提供 [MLX-LM](https://github.com/ml-explore/mlx-lm?ref=hubwiz.com)。

```
     Traditional PC
┌──────────────────────┐
|  CPU ── system RAM   |
| GPU ── separate VRAM |
└──────────────────────┘

     Apple Silicon

  Shared unified memory
   ┌───────────────┐
   │ model weights │
   │  other data   │
   └───────┬───────┘
       CPU + GPU
```

### 4.4 Cerebras晶圆级引擎（WSE）

Cerebras使用不同的推理栈，因为其 [晶圆级引擎（WSE）](https://www.cerebras.ai/chip?ref=hubwiz.com) 不是传统的CPU或GPU。WSE是横跨几乎整个硅晶圆构建的处理器。

```
    Open-source model
           │
           ▼
Cerebras compiler/runtime
           │
           ▼
  Wafer-Scale Engine
           │
           ▼
   Generated tokens
```

---

原文链接：[LLM inference engines explained](https://hammansamuel.medium.com/llm-inference-engines-explained-b5229723cfc8?ref=hubwiz.com) 

汇智网翻译整理，转载请标明出处