在传统的 AI 开发流程中,从数据采集、清洗、模型训练到最终部署,往往涉及多个手动环节。这种‘人工干预’不仅效率低下,且容易因环境不一致导致线上线下表现脱节。本文将介绍如何结合 DVC(Data Version Control)与 GitHub Actions 构建一套零干预的 MLOps 流水线。
核心逻辑
- 数据驱动:利用 DVC 追踪数据变化,当数据仓库(如 S3)有新数据迁入时,提交 .dvc 指纹文件。
- 触发流水线:GitHub Actions 监测到代码或数据指纹变更,自动拉起训练算力。
- 自动化训练与评估:通过 CML (Continuous Machine Learning) 生成实验报告并推送到 Pull Request。
- 自动部署:审核通过后,模型自动打包并推送到推理服务(如 Hugging Face 或 AWS SageMaker)。
步骤一:配置 DVC 数据追踪
首先,我们需要将庞大的数据集托管在外部存储,而在 Git 中仅保留元数据。
# 初始化 DVC
dvc init
# 添加远程存储(以 S3 为例)
dvc remote add -d myremote s3://my-bucket/data
# 追踪数据目录
dvc add data/raw_images
# 提交指纹文件到 Git
git add data/raw_images.dvc .gitignore
git commit -m "Update raw data reference"
步骤二:编写自动化训练脚本
确保训练脚本 train.py 能够接受参数并输出模型权重及评估指标(metrics.json)。
import json
import torch
# 模拟训练过程
def train():
model = torch.nn.Linear(10, 1)
loss = 0.05
# 保存模型
torch.save(model.state_dict(), "model.pt")
# 保存指标
with open("metrics.json", "w") as f:
json.dump({"accuracy": 0.95, "loss": loss}, f)
if __name__ == "__main__":
train()
步骤三:配置 GitHub Actions 工作流
在 .github/workflows/pipeline.yaml 中定义自动化逻辑。这是实现‘无人工干预’的关键。
name: MLOps-Pipeline
on: [push]
jobs:
run-training:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: iterative/setup-dvc@v1
- name: Pull data from DVC
run: dvc pull
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_KEY }}
- name: Train Model
run: |
pip install -r requirements.txt
python train.py
- name: Create CML Report
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo "## 训练结果报告" > report.md
cat metrics.json >> report.md
cml comment create report.md
- name: Deploy to Production
if: github.ref == 'refs/heads/main'
run: |
# 假设使用 Docker 部署
docker build -t my-model-service:latest .
docker push my-registry/my-model-service:latest
总结
通过这套方案,算法工程师只需关注数据标注和模型代码编写。一旦执行 git push,整个基础设施会自动完成数据拉取、分布式训练、结果反馈和线上更新。这种高度自动化的流程极大减少了运维成本,确保了模型交付的可靠性。
汤不热吧