# LFM2-24B-A2B

> LFM2-24B-A2B 通过 Liquid AI 的混合方法在高效语言建模方面实现了突破， **状态空间模型 + 注意力** 架构。总参数为 240 亿，但每个标记仅激活 20 亿参数，在提供出色性能的同时，FP16 推理仅需约 \~6GB 显存。该模型在 RTX 4090 上实现约 350 tok/s，使其成为可用的最快大型语言模型之一。

## 一目了然

* **模型规模**: 总计 240 亿 / 每次 20 亿 激活参数（混合 SSM+注意力）
* **许可**: Liquid AI 开放许可（非商业用途免费，商业许可可用）
* **上下文**: 32K 标记
* **性能**: 与 7B-13B 密集模型竞争
* **显存（VRAM）**: 约 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+ 标记/秒。

**内存高效**: 仅需 6GB FP16 显存，LFM2-24B-A2B 可在中端 GPU 上舒适运行。这使其非常适合边缘部署、开发环境和注重成本的生产设置。

**Liquid AI 创新**: 由 Liquid AI（由麻省理工学院研究人员创立）开发，LFM2 代表了神经架构领域的前沿研究。混合的 SSM+注意力 设计可能是高效语言建模的未来。

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

## GPU 建议

| GPU             | 显存（VRAM） | 性能              | 每日费用\*  |
| --------------- | -------- | --------------- | ------- |
| 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.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()
```

## 为降低显存的量化

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

### GPTQ 量化

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

# 使用量化模型（显存降至约 ~3GB）
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+注意力 提供独特优势：

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

**选择性注意力**: 只有关键标记触发完整的注意力机制，从而减少计算开销。

**内存效率**: 2B 激活参数的设计意味着在推理期间 240 亿参数中的大部分处于静止状态，大幅降低内存带宽需求。

**快速的序列处理**: 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     | 3.8B   | \~8GB     | \~250 tok/s     |

LFM2-24B-A2B 在其类别中实现了最佳的速度/显存比。

## 资源

* [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: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
