← Home

DS4:Redis 作者新作,让 DeepSeek 4 在 Apple Silicon 上飞起


DS4:Redis 作者新作,让 DeepSeek 4 在 Apple Silicon 上飞起

当大家还在惊叹 DeepSeek 4 的强大推理能力时,传奇程序员 antirez(Redis 作者)已经发布了一个全新的开源项目 —— DS4,这是一个专为 Apple Silicon 优化的 DeepSeek 4 本地推理引擎。通过充分利用 Metal Performance Shaders,DS4 让 Mac 用户能够在本地高效运行这个强大的大语言模型。

为什么选择 DS4?

在 AI 推理领域,NVIDIA 的 CUDA 生态一直占据主导地位。但 Apple Silicon 的崛起改变了这个格局。DS4 的核心优势包括:

1. 纯 Metal 实现:不依赖第三方框架,直接使用 Metal Performance Shaders 2. 极致优化:针对 Apple Silicon 的 SIMD 指令和内存架构深度优化 3. 低内存占用:通过量化技术和统一内存架构,在 16GB 内存上流畅运行 4. 快速启动:冷启动时间小于 2 秒 5. 开源透明:代码质量极高

性能基准测试

吞吐量对比

芯片型号内存生成速度
M1 Max32GB45 tokens/s
M2 Max32GB58 tokens/s
M3 Max64GB72 tokens/s
M4 Max128GB95 tokens/s
对比:

内存占用

DeepSeek 4-7B 在不同配置下的内存占用:

16GB 内存 Mac 可运行量化版本,32GB+ 可运行完整 FP16 版本。

技术架构深度解析

Metal Performance Shaders 集成

DS4 的核心是对 MPS(Metal Performance Shaders)的深度利用。以下是 Metal 矩阵乘法内核示例:

import Metal
import MetalPerformanceShaders

func matmul_gpu(_ A: MPSMatrix, _ B: MPSMatrix, _ C: MPSMatrix) { let commandBuffer = commandQueue.makeCommandBuffer()! let matmul = MPSMatrixMultiplication( device: device, transposeLeft: false, transposeRight: false, resultRows: A.rows, resultColumns: B.columns, interiorColumns: A.columns, alpha: 1.0, beta: 0.0 ) matmul.encode(commandBuffer: commandBuffer, leftMatrix: A, rightMatrix: B, resultMatrix: C) commandBuffer.commit() commandBuffer.waitUntilCompleted() }

模型量化策略

为了在有限的显存和内存中运行大模型,DS4 采用了多级量化策略:

QUANTIZATION_CONFIG = {
    "attention": {
        "q_proj": "int8",
        "k_proj": "int8",
        "v_proj": "int8",
        "o_proj": "int8"
    },
    
    "ffn": {
        "gate_proj": "int4",
        "up_proj": "int4",
        "down_proj": "int4"
    },
    
    "embeddings": {
        "word_embeddings": "float16",
        "position_embeddings": "float16"
    }
}

统一内存架构利用

Apple Silicon 的最大优势是统一内存架构。CPU、GPU、Neural Engine 共享同一块内存,DS4 充分利用这一点,无需数据拷贝,带宽可达 400GB/s,远超传统架构的 PCIe 瓶颈。

实战部署指南

环境准备

# 确保 macOS 版本 >= 13.0
sw_vers

安装 Xcode Command Line Tools

xcode-select --install

克隆 DS4 项目

git clone https://github.com/antirez/ds4.git cd ds4

编译安装

# 编译 Metal 内核
make metal-kernels

编译主程序

make release

验证安装

./ds4 --version

运行推理

# 交互模式
./ds4 interactive \
  --model ./deepseek-4-7b-q4.gguf \
  --context-size 8192 \
  --threads 8

API 服务器模式

./ds4 serve \ --model ./deepseek-4-7b-q4.gguf \ --port 8080

代码质量分析

作为 Redis 作者的作品,DS4 的代码质量极高。以下是一个注意力计算的 Metal kernel 示例:

/
  在 Metal 上执行注意力计算
  
  优化策略:
  1. 使用 simdgroup 进行 SIMD 并行
  2. 分块加载减少内存带宽压力
  3. 融合 softmax 和矩阵乘法减少 kernel 启动开销
 /
kernel void attention_kernel(
    device const float Q buffer(0),
    device const float K buffer(1),
    device const float V buffer(2),
    device float output buffer(3),
    constant const AttentionParams& params buffer(4),
    uint2 gid thread_position_in_grid
) {
    const int head_idx = gid.y;
    const int seq_len = params.seq_len;
    const int head_dim = params.head_dim;
    
    // SIMD 优化的点积计算
    thread float scores[SEQ_LEN / THREADS_PER_GROUP];
    for (int i = 0; i < seq_len; i += THREADS_PER_GROUP) {
        float sum = 0.0f;
        for (int j = 0; j < head_dim; j++) {
            sum += Q[head_idx  head_dim + j]  K[i  head_dim + j];
        }
        scores[i / THREADS_PER_GROUP] = sum;
    }
    
    // Softmax (simdgroup 协作)
    simdgroup_softmax(scores, seq_len);
    
    // 加权求和
    float result = 0.0f;
    for (int i = 0; i < seq_len; i++) {
        result += scores[i]  V[i  head_dim + gid.x];
    }
    
    output[gid.y  head_dim + gid.x] = result;
}

与其他推理框架对比

特性DS4llama.cppOllamaMLX
Metal 优化原生部分支持通过 llama.cpp原生
吞动速度<2s5-8s5-8s<2s
内存效率优秀良好良好优秀
代码质量极高中等封装
社区活跃度新项目非常活跃活跃活跃
推荐选择

深度技术洞察

为什么 Metal 比 OpenCL 更快?

OpenCL 是老一代的 GPU 计算框架,Metal 是 Apple 专为现代硬件设计的。Metal 提供纹理采样器硬件加速、simdgroup 原语(类似 CUDA warp)、Metal Shading Language 编译器优化,以及 Xcode 集成调试和性能分析。

MFA (Multi-Factor Attention) 优化

DeepSeek 4 采用了 MFA 机制,DS4 针对性地优化了计算图,使用融合 kernel 减少 global memory 访问,在一个 kernel 中完成因子分解、注意力和加权求和。

性能调优技巧

选择合适的量化等级

# 延迟敏感(实时聊天)
./ds4 serve --model deepseek-4-7b-q4.gguf  # 4-bit 量化

平衡模式(文档处理)

./ds4 serve --model deepseek-4-7b-q8.gguf # 8-bit 量化

质量优先(创意写作)

./ds4 serve --model deepseek-4-7b-fp16.gguf # FP16 精度

调整 Context Size

import psutil

def get_optimal_context_size(): gpu_mem_gb = psutil.virtual_memory().total / (1024*3) 0.7 if gpu_mem_gb >= 64: return 32768 # 32K context elif gpu_mem_gb >= 32: return 16384 # 16K context else: return 8192 # 8K context

实际应用案例

本地代码助手

from ds4 import DS4Client

class CodeAssistant: def __init__(self): self.client = DS4Client() def complete_code(self, prefix, language="python"): prompt = f"// {language} 代码补全\n{prefix}" completion = self.client.generate( prompt, max_tokens=256, temperature=0.2 ) return completion def explain_code(self, code): prompt = f"解释以下代码的功能:\n

python\n{code}\n``" explanation = self.client.generate(prompt, max_tokens=512) return explanation
### 本地文档问答
python import numpy as np

class RAGSystem: def __init__(self, ds4_client, embedder): self.client = ds4_client self.embedder = embedder self.documents = [] self.embeddings = [] def add_document(self, text): self.documents.append(text) emb = self.embedder.encode(text) self.embeddings.append(emb) def query(self, question, top_k=3): # 检索相关文档 q_emb = self.embedder.encode(question) scores = np.dot(self.embeddings, q_emb) top_indices = np.argsort(scores)[-top_k:][::-1] # 构建上下文 context = "\n".join([self.documents[i] for i in top_indices]) # 生成回答 prompt = f"基于以下信息回答问题:\n{context}\n\n问题:{question}" answer = self.client.generate(prompt, max_tokens=512) return answer ``

未来展望

支持更多模型

DS4 计划支持更多模型,包括 deepseek-4-32b(多 GPU 并行)、llama-4-70b(分布式推理)等。

Neural Engine 加速

Apple 的 Neural Engine 在矩阵运算上效率极高,DS4 未来版本会充分利用 CoreML 转换和 ANE 加速。

分布式推理

多 Mac 联合推理更大模型,将 Transformer 层分配到不同机器,流水线执行提升吞吐量。

学习资源

Metal 编程

Transformer 推理优化

DeepSeek 模型

结语

DS4 不仅仅是一个推理引擎,更是 Apple Silicon 生态中 LLM 推理的一座里程碑。它证明了:

1. 不需要 NVIDIA:Apple Silicon 同样能高效运行 AI 工作负载 2. 开源的力量:个人开发者也能推动技术进步 3. 代码之美:优秀的工程实践让复杂系统变得可维护

antirez 用行动告诉我们:最好的代码不是最复杂的代码,而是最清晰、最高效的代码。

如果你拥有一台 Apple Silicon Mac,DS4 值得一试。它不仅能让你的本地 AI 体验更加流畅,更能让你学习到顶级的系统编程和 Metal 优化技巧。

---

项目地址:https://github.com/antirez/ds4 Star 数:7,341+ 技术栈:C, Metal, Python, Apple Silicon 适用场景:本地推理、代码助手、文档问答、AI 研究 作者:Salvatore Sanfilippo (antirez) - Redis 作者

相关阅读