mlx 是一个灵活高效的阵列框架,适用于 apple 芯片上的数字计算和机器学习。我们将探索统一内存、懒性计算和函数转换等基本功能。我们还将了解一些有关使用 swift 和 python api 来构建和加速支持不同 apple 平台的机器学习模型的更高级技巧。

视频封面
视频地址

此文章由AI生成,可能存在错误,如有问题,请联系djs66256@163.com

开始使用适用于 Apple 芯片的 MLX

MLX 是苹果公司专为 Apple 芯片设计的开源数组框架,旨在为数值计算和机器学习任务提供高效灵活的工具。本文将详细介绍 MLX 的核心功能、安装使用方法以及如何利用其特性加速机器学习工作负载。

MLX 简介

MLX 是一个专门针对 Apple 芯片优化的数组框架,支持从基础数值运算到大规模机器学习模型的各类任务。该框架的特点包括:

  • 支持 CPU 和 GPU 加速
  • 提供 Python 和 Swift API
  • 适用于 Mac、iPhone、iPad 和 Vision Pro 等苹果设备
  • 采用 MIT 开源许可证

MLX 的核心 API 设计与 NumPy 高度相似,同时提供与 PyTorch 和 JAX 类似的高阶机器学习工具,使得熟悉这些框架的用户可以快速上手。

安装与基础使用

安装 MLX Python 版非常简单,只需运行以下命令:

pip3 install mlx

基础数组操作示例展示了 MLX 的使用方式:

import mlx.core as mx

a = mx.array([1, 2, 3])
b = mx.array([4, 5, 6])
c = a + b

print(f"结果 c: {c}")
print(f"形状: {c.shape}")
print(f"数据类型: {c.dtype}")

MLX 核心特性

统一内存架构

MLX 充分利用了 Apple 芯片的统一内存架构,CPU 和 GPU 共享相同物理内存:

a = mx.array([1, 2, 3])
b = mx.array([4, 5, 6])

c = mx.add(a, b, stream=mx.gpu)
d = mx.multiply(a, b, stream=mx.cpu)

惰性计算

MLX 采用惰性执行引擎,优化大型计算的性能:

a = mx.array([1, 2, 3])
b = mx.array([4, 5, 6])
c = a + b

# 显式触发计算
mx.eval(c)

函数变换

MLX 提供自动微分等函数变换功能:

def sin(x):
    return mx.sin(x)

dfdx = mx.grad(sin)
d2fdx2 = mx.grad(mx.grad(mx.sin))

神经网络构建

MLX 提供 mlx.nnmlx.optimizers 两个高阶包用于构建和训练神经网络:

class MLP(nn.Module):
    """简单的多层感知机"""
    
    def __init__(self, dim, h_dim):
        super().__init__()
        self.linear1 = nn.Linear(dim, h_dim)
        self.linear2 = nn.Linear(h_dim, dim)
    
    def __call__(self, x):
        x = self.linear1(x)
        x = nn.relu(x)
        x = self.linear2(x)
        return x

性能优化技巧

MLX 提供多种性能优化方法:

函数编译

@mx.compile
def compiled_gelu(x):
    return x * (1 + mx.erf(x / math.sqrt(2))) / 2

使用优化实现

mx.fast.rms_norm(x, weight, eps=1e-5)

添加自定义 Metal 内核

source = """
    uint elem = thread_position_in_grid.x;
    out[elem] = metal::exp(inp[elem]);
"""
kernel = mx.fast.metal_kernel(
    name="myexp",
    input_names=["inp"],
    output_names=["out"],
    source=source,
)

模型量化

quantized_weight, scales, biases = mx.quantize(
    weight, bits=4, group_size=32,
)

MLX Swift

Swift 版本的 MLX 同样功能强大,使用方式与 Python 类似:

import MLX

let a = MLXArray([1, 2, 3])
let b = MLXArray([1, 2, 3])
let c = a + b

学习资源

开发者可以通过以下资源进一步学习 MLX:

相关视频:
借助 MLX 在 Apple 芯片上探索大语言模型

文档:
MLX
MLX LM - Python API
MLX Explore - Python API
MLX Framework
MLX Llama Inference
MLX Swift

MLX 为 Apple 芯片上的机器学习开发提供了强大而灵活的工具,开发者可以利用其特性构建高效的机器学习应用。