Azure Functions下MLX从安装到运行的全流程图解

云信安装大师
90
AI 质量分
10 5 月, 2025
2 分钟阅读
0 阅读

Azure Functions下MLX从安装到运行的全流程图解

引言

MLX(Machine Learning eXchange)是IBM开发的一个开源机器学习框架,而Azure Functions是微软的无服务器计算服务。本文将带你完成在Azure Functions环境中安装和运行MLX的全过程,让你能够轻松部署机器学习模型。

准备工作

在开始之前,请确保你具备以下条件:

  1. 有效的Azure账号
  2. Azure CLI已安装(安装指南
  3. Python 3.7或更高版本
  4. 基本的Python和命令行知识

第一步:创建Azure Function应用

1.1 登录Azure并创建资源组

代码片段
# 登录Azure
az login

# 创建资源组(替换<your-location>为你的区域,如eastus)
az group create --name MLXFunctionGroup --location <your-location>

注意:资源组名称必须唯一,建议使用有意义的命名。

1.2 创建存储账户

代码片段
# 创建存储账户(名称必须全局唯一)
az storage account create --name mlxstorage<随机数字> \
                          --location <your-location> \
                          --resource-group MLXFunctionGroup \
                          --sku Standard_LRS

1.3 创建Function应用

代码片段
# 创建Function应用(使用Python运行时)
az functionapp create --resource-group MLXFunctionGroup \
                      --consumption-plan-location <your-location> \
                      --runtime python \
                      --runtime-version 3.9 \
                      --functions-version 4 \
                      --name MLXFunctionApp \
                      --storage-account mlxstorage<你上面创建的编号>

第二步:设置本地开发环境

2.1 安装Azure Functions Core Tools

代码片段
# Windows
npm install -g azure-functions-core-tools@4

# Mac/Linux (可能需要sudo)
npm install -g azure-functions-core-tools@4 --unsafe-perm true

2.2 创建本地Function项目

代码片段
# 创建项目目录并初始化
mkdir MLXFunctionProject
cd MLXFunctionProject
func init --python

# 创建一个HTTP触发的函数
func new --name MLXProcessor --template "HTTP trigger" 

第三步:安装MLX及相关依赖

3.1 修改requirements.txt文件

在项目根目录下的requirements.txt文件中添加以下内容:

代码片段
mlx-api==0.1.0
numpy>=1.21.0
pandas>=1.3.0
scikit-learn>=0.24.0
flask>=2.0.0

3.2 安装依赖并测试本地运行

代码片段
# Windows (使用venv)
python -m venv .venv
.venv\Scripts\activate.bat
pip install -r requirements.txt

# Mac/Linux (使用venv)
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# 本地测试运行函数
func start

注意:如果遇到依赖冲突,可以尝试先升级pip:pip install --upgrade pip

第四步:编写MLX处理函数代码

编辑MLXProcessor/__init__.py文件:

代码片段
import logging
import json
import numpy as np
from mlx.api import ModelLoader, PredictorBase, DataTransformerBase

class SimpleTransformer(DataTransformerBase):
    """自定义数据转换器"""
    def transform(self, data):
        # JSON字符串转字典,然后提取特征数组
        data_dict = json.loads(data)
        features = np.array(data_dict['features'])
        return features.tolist()

class SimplePredictor(PredictorBase):
    """自定义预测器"""
    def predict(self, features):
        # Mock预测逻辑 -实际应用中替换为你的模型逻辑 
        return [sum(f) for f in features]

def main(req):
    """HTTP触发的主函数"""
    logging.info('Python HTTP trigger function processed a request.')

    try:
        req_body = req.get_json()

        # MLX模型加载和预测流程示例

        # Step1:初始化转换器(实际项目中应该预加载)
        transformer = SimpleTransformer()

        # Step2:初始化预测器(实际项目中应该预加载)
        predictor = SimplePredictor()

        # Step3:数据转换和预测(模拟流程)
        features = transformer.transform(json.dumps(req_body))
        predictions = predictor.predict(features)

        return json.dumps({
            "predictions": predictions,
            "status": "success"
        })

    except Exception as e:
        logging.error(f"Error processing request: {str(e)}")
        return json.dumps({
            "error": str(e),
            "status": "failed"
        }),500

    return func.HttpResponse(
             "Please pass a valid JSON payload in the request body",
             status_code=400)

第五步:部署到Azure Function并测试

5.1 Azure Function部署配置

确保host.json文件包含以下内容:

代码片段
{
    "version": "2.0",
    "extensionBundle": {
      "id": "Microsoft.Azure.Functions.ExtensionBundle",
      "version": "[4.*,5.*)"
    }
}

5.2 Azure Function部署命令

代码片段
func azure functionapp publish MLXFunctionApp 

注意:首次部署可能需要几分钟时间。

5.3 API测试调用示例

部署完成后,获取函数URL:

代码片段
func azure functionapp list-functions MLXFunctionApp 

然后使用curl或Postman测试:

代码片段
curl -X POST https://mlxfunctionapp.<region>.azurewebsites.net/api/MLXProcessor \
     -H "Content-Type: application/json" \ 
     -d '{"features": [[1,2,3], [4,5,6]]}'

预期响应:

代码片段
{
    "predictions": [6,15],
    "status":"success"
}

常见问题与解决方案

问题 解决方案
ModuleNotFoundError pip install -r requirements.txt后重新部署
HTTP Trigger返回404 function.json中确保authLevel设置为”anonymous”
Python版本不兼容 Azure Function仅支持特定Python版本(如3.x)
MLX API导入失败 pip install mlx-api==0.x.x指定正确版本

总结

本文详细介绍了如何在Azure Functions环境中从零开始安装和运行MLX框架的全过程:

1️⃣ 环境准备: Azure账号、CLI工具、Python环境
2️⃣ Function创建: CLI命令快速搭建无服务器环境
3️⃣ 本地开发: Core Tools+Python虚拟环境
4️⃣ MLX集成: API调用+自定义转换器和预测器
5️⃣ 部署上线: CLI一键发布+API测试

通过这种架构,你可以轻松扩展机器学习模型的推理能力,同时享受无服务器计算的弹性优势。

原创 高质量