> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/lfm2-24b.md).

# LFM2-24B-A2B

在 Clore.ai 上部署 Liquid AI 的 LFM2-24B-A2B——混合 SSM+Attention 架构，总参数 24B / 活跃参数 2B

> LFM2-24B-A2B 通过 Liquid AI 的混合式架构，在高效语言建模方面实现了突破 **状态空间模型 + 注意力** 架构。它拥有 24B 总参数，但每个 token 仅有 2B 激活参数，在仅需约 6GB VRAM 进行 FP16 推理的情况下仍能提供令人印象深刻的性能。该模型在 RTX 4090 上可达到约 350 tok/s，使其成为目前速度最快的大型语言模型之一。

## 一览

* **模型大小**: 24B 总参数 / 2B 激活参数（混合式 SSM+Attention）
* **许可证**: Liquid AI 开源许可证（非商业免费，提供商业许可证）
* **上下文**: 32K tokens
* **性能**: 性能可与 7B-13B 稠密模型相媲美
* **显存**: \~6GB FP16，\~3GB INT8
* **速度**: 在 RTX 4090 上约 \~350 tok/s，在 RTX 3090 上约 \~200 tok/s

## 为什么选择 LFM2-24B-A2B？

**革命性的架构**: LFM2-24B-A2B 将状态空间模型（SSM）与选择性注意力机制相结合。SSM 高效处理序列，而注意力层专注于复杂推理。这种混合方法以小模型的效率实现了大模型的质量。

**卓越速度**: 2B 激活参数的设计使推理速度极快。不同于传统模型会激活全部参数，LFM2 只选择性地启用必要组件，从而在消费级硬件上实现 350+ tokens/秒。

**内存高效**: FP16 仅需 6GB VRAM，LFM2-24B-A2B 可轻松运行在中端 GPU 上。这使其非常适合边缘部署、开发环境以及成本敏感的生产环境。

**Liquid AI 创新**: 由 Liquid AI（由 MIT 研究人员创立）开发，LFM2 代表了神经网络架构的前沿研究。混合 SSM+Attention 设计或许就是高效语言建模的未来。

**许可说明**: Liquid AI 开源许可证允许免费非商业使用。商业部署需要从 Liquid AI 另行获取许可证。这是 **不** MIT — 在生产使用前请核实许可条款。

## GPU 推荐

| GPU             | 显存   | 性能             | 每日成本\*  |
| --------------- | ---- | -------------- | ------- |
| RTX 3060 12GB   | 12GB | 约180 tok/s     | \~$0.80 |
| RTX 3070        | 8GB  | 约220 tok/s     | \~$0.90 |
| **RTX 4060 Ti** | 16GB | 约300 tok/s     | \~$1.20 |
| **RTX 4090**    | 24GB | **约350 tok/s** | \~$2.10 |
| RTX 3090        | 24GB | 约200 tok/s     | \~$1.10 |
| A100 40GB       | 40GB | 约400 tok/s     | \~$3.50 |

**最佳性价比**: RTX 4060 Ti 16GB 具备出色的性价比。 **最高速度**: RTX 4090 释放了 LFM2 的全部潜力。

\*Clore.ai 市场预估价格

## 使用 vLLM 部署

### 安装 vLLM

```bash
pip install vllm>=0.6.0
# 或最新版本
pip install git+https://github.com/vllm-project/vllm.git
```

### 单 GPU 设置

```bash
vllm serve liquid-ai/LFM2-24B-A2B \\
  --model liquid-ai/LFM2-24B-A2B \\
  --tensor-parallel-size 1 \\
  --dtype float16 \\
  --max-model-len 32768 \\
  --served-model-name lfm2-24b \\
  --trust-remote-code \\
  --disable-log-stats
```

### 查询服务器

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1", 
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="lfm2-24b",
    messages=[
        {"role": "system", "content": "你是一位专注于技术解释的有帮助的 AI 助手。"},
        {"role": "user", "content": "解释状态空间模型与传统 Transformer 的区别"}
    ],
    max_tokens=1024,
    temperature=0.7
)

print(response.choices[0].message.content)
```

## 使用 Ollama 部署

Ollama 提供了最简单的部署路径：

```bash
# 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh

# 拉取 LFM2 模型
ollama pull liquid-ai/lfm2:24b

# 交互式运行
ollama run liquid-ai/lfm2:24b

# API 模式
ollama serve
```

### Ollama API 用法

```python
import requests

# 简单补全
response = requests.post('http://localhost:11434/api/generate',
    json={
        'model': 'liquid-ai/lfm2:24b',
        'prompt': '使用记忆化实现一个计算斐波那契数的 Python 函数',
        'stream': False
    }
)

print(response.json()['response'])

# 聊天格式
chat_response = requests.post('http://localhost:11434/api/chat',
    json={
        'model': 'liquid-ai/lfm2:24b',
        'messages': [
            {'role': 'user', 'content': '用简单的话解释量子纠缠'}
        ],
        'stream': False
    }
)

print(chat_response.json()['message']['content'])
```

## Docker 模板

```dockerfile
FROM nvidia/cuda:12.8.1-devel-ubuntu22.04

# 安装 Python 3.10
RUN apt-get update && apt-get install -y \
    python3.10 python3-pip curl && \\
    rm -rf /var/lib/apt/lists/*

# 安装 vLLM
RUN pip install vllm>=0.6.0 transformers

# 设置环境
ENV PYTHONUNBUFFERED=1

# 预下载模型（可选）
# RUN python3 -c "from transformers import AutoModel; AutoModel.from_pretrained('liquid-ai/LFM2-24B-A2B', trust_remote_code=True)"

EXPOSE 8000

CMD ["vllm", "serve", "liquid-ai/LFM2-24B-A2B", \\
     "--host", "0.0.0.0", \\
     "--port", "8000", \\
     "--dtype", "float16", \\
     "--max-model-len", "16384", \\
     "--trust-remote-code"]
```

构建并运行：

```bash
docker build -t lfm2-24b .
docker run --gpus all -p 8000:8000 lfm2-24b
```

## 速度基准测试

测试 LFM2 的卓越推理速度：

```python
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

def speed_test():
    prompts = [
        "解释机器学习的一段话",
        "编写一个快速的 Python 排序算法",
        "描述可再生能源的好处",
        "法国的首都是什么，以及它为什么重要？",
        "创建一个简单的 HTML 页面结构"
    ]
    
    total_tokens = 0
    total_time = 0
    
    for prompt in prompts:
        start_time = time.time()
        
        response = client.chat.completions.create(
            model="lfm2-24b",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=200,
            temperature=0.1
        )
        
        end_time = time.time()
        
        tokens = len(response.choices[0].message.content.split())
        duration = end_time - start_time
        
        total_tokens += tokens
        total_time += duration
        
        print(f"Prompt: {prompt[:30]}...")
        print(f"Tokens: {tokens}, Time: {duration:.2f}s, Speed: {tokens/duration:.1f} tok/s\n")
    
    avg_speed = total_tokens / total_time
    print(f"Average speed: {avg_speed:.1f} tokens/second")
    return avg_speed

# 运行速度测试
speed_test()
```

## 降低 VRAM 的量化

对于 VRAM 有限的 GPU，请使用量化版本：

### GPTQ 量化

```bash
# 安装 auto-gptq
pip install auto-gptq

# 使用量化模型（降至约 3GB VRAM）
vllm serve liquid-ai/LFM2-24B-A2B-GPTQ \\
  --model liquid-ai/LFM2-24B-A2B-GPTQ \\
  --quantization gptq \\
  --dtype float16 \\
  --max-model-len 16384
```

### AWQ 量化

```bash
# 安装 autoawq
pip install autoawq

# 使用 AWQ 量化模型
vllm serve liquid-ai/LFM2-24B-A2B-AWQ \\
  --model liquid-ai/LFM2-24B-A2B-AWQ \\
  --quantization awq \
  --dtype float16
```

## 高级配置

### 内存优化设置

适用于 8GB GPU：

```bash
vllm serve liquid-ai/LFM2-24B-A2B \\
  --model liquid-ai/LFM2-24B-A2B \\
  --dtype float16 \\
  --max-model-len 8192 \
  --gpu-memory-utilization 0.85 \\
  --swap-space 4 \\
  --trust-remote-code
```

### 高吞吐量设置

适用于生产工作负载：

```bash
vllm serve liquid-ai/LFM2-24B-A2B \\
  --model liquid-ai/LFM2-24B-A2B \\
  --tensor-parallel-size 1 \\
  --max-num-seqs 32 \\
  --max-num-batched-tokens 8192 \\
  --dtype float16 \\
  --trust-remote-code
```

## SSM 架构优势

LFM2 的混合 SSM+Attention 提供了独特优势：

**线性扩展**: SSM 随序列长度线性扩展，而传统 Transformer 呈二次方扩展。这使得长上下文处理更高效。

**选择性注意力**: 只有关键 token 会触发完整注意力机制，从而降低计算开销。

**内存效率**: 2B 激活参数的设计意味着 24B 参数中的大多数在推理过程中保持休眠状态，大幅降低内存带宽需求。

**快速序列处理**: SSM 在文本生成等序列任务上表现出色，相比纯注意力机制具有更高吞吐量。

## 给 Clore.ai 用户的建议

* **单 GPU 重点优化**: LFM2-24B-A2B 已针对单 GPU 部署进行了优化。多 GPU 设置不会带来显著收益。
* **上下文长度**: 为获得最高速度，请使用较短上下文（8K-16K）。更长的上下文会削弱 SSM 的效率优势。
* **温度设置**: 更低的温度（0.1-0.3）可通过减少不确定性来最大化推理速度。
* **批量大小**: 对于多个并发请求，增加批量大小比使用多 GPU 更有效。
* **许可合规**: 在生产部署前，请与 Liquid AI 核实商业许可要求。

## 故障排查

| 问题                                 | 解决方案                                                                              |
| ---------------------------------- | --------------------------------------------------------------------------------- |
| `ImportError: liquid_transformers` | 安装： `pip install git+https://github.com/LiquidAI-project/liquid-transformers.git` |
| 启动缓慢                               | 预下载： `huggingface-cli download liquid-ai/LFM2-24B-A2B`                            |
| `OutOfMemoryError`                 | 使用量化版本或减少 `max-model-len`                                                         |
| 响应质量差                              | 检查许可限制——某些模型版本的功能受限                                                               |
| SSM 层错误                            | 更新 transformers： `pip install transformers>=4.45.0`                               |

## 性能对比

| 模型               | 激活参数   | 显存（FP16）  | 速度（RTX 4090）   |
| ---------------- | ------ | --------- | -------------- |
| Llama 3.2 3B     | 3B     | \~6GB     | 约280 tok/s     |
| Qwen2.5 7B       | 7B     | 约 14GB    | 约180 tok/s     |
| **LFM2-24B-A2B** | **2B** | **\~6GB** | **约350 tok/s** |
| Mistral 7B       | 7B     | 约 14GB    | 约200 tok/s     |
| Phi-3.5 3.8B     | 38亿    | 约 8GB     | 约250 tok/s     |

LFM2-24B-A2B 在同类模型中实现了最佳的速度/VRAM 比例。

## 资源

* [Hugging Face 上的 LFM2-24B-A2B](https://huggingface.co/liquid-ai/LFM2-24B-A2B)
* [Liquid AI 公司](https://liquid.ai/)
* [SSM 架构论文](https://arxiv.org/abs/2312.00752)
* [Liquid AI 许可](https://liquid.ai/licensing)
* [vLLM 对 SSM 的支持](https://docs.vllm.ai/en/latest/models/supported_models.html#liquid-ai)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/lfm2-24b.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
