DVC 管線

Machine Learning 的 CI/CD

Ravi Bhadauria

Machine Learning Engineer

為何需要資料管線

  • 單獨做資料版控用處不大
  • 追蹤資料血緣很重要
    • 篩選、清理、轉換
    • 模型訓練
  • 只執行需要的步驟
  • 有向無環圖(DAG)中的步驟

DAG 示意圖,說明前處理、訓練與產物之間的關係

Machine Learning 的 CI/CD

DVC 管線

  • 定義 ML 工作流程與相依性的階段序列

  • 定義於 dvc.yaml

    • 輸入資料與指令碼(deps
    • 階段執行指令(cmd
    • 輸出產物(outs
      • 特殊資料,如 metricsplots
  • 類似 GitHub Actions 的 workflow

    • 著重 ML 任務而非 CI/CD
    • 可在 GHA 中抽象成一步
Machine Learning 的 CI/CD

定義管線階段

  • 使用 dvc stage add 建立階段
dvc stage add \
-n preprocess \
-d raw_data.csv -d preprocess.py \
-o processed_data.csv \
python preprocess.py
  • dvc.yaml 內容
    stages:
    preprocess:
      cmd: python preprocess.py
      deps:
      - preprocess.py
      - raw_data.csv
      outs:
      - processed_data.csv
    
Machine Learning 的 CI/CD

相依圖

  • 以前一步的輸出新增訓練步驟
    dvc stage add \
    -n train \
    -d train.py -d processed_data.csv \
    -o plots.png -o metrics.txt \
    python train.py
    
stages:
  preprocess:
    cmd: python preprocess.py
    deps:
    - preprocess.py
    - raw_data.csv
    outs:
    - processed_data.csv

train: cmd: python train.py deps: - processed_data.csv - train.py outs: - plots.png
Machine Learning 的 CI/CD

重製管線

  • dvc repro 重製管線
-> dvc repro
Running stage 'preprocess':                                      
> python preprocess.py

Running stage 'train': > python train.py Updating lock file 'dvc.lock'
  • 會產生狀態檔 dvc.lock
    • 類似 .dvc 檔,記錄 MD5 雜湊
    • 立刻提交到 Git 以記錄狀態 git add dvc.lock && git commit -m "first pipeline repro"`
Machine Learning 的 CI/CD

使用快取結果

  • 利用快取結果加速反覆試驗
-> dvc repro
Stage 'preprocess' didn't change, skipping
Running stage 'train' with command: ...
Machine Learning 的 CI/CD

視覺化 DVC 管線

-> dvc dag
+------------+ 
| preprocess | 
+------------+ 
       *       
       *       
       *       
  +-------+    
  | train |    
  +-------+
1 https://dvc.org/doc/command-reference/dag
Machine Learning 的 CI/CD

重點整理

  • DVC 管線的用途
    • 依靠快取快速迭代
    • 透過 dvc.yamldvc.lock 確保可重現性
    • 支援 CI/CD
  • dvc stage add 產生管線
  • dvc repro 重製/執行
  • dvc dag 視覺化
Machine Learning 的 CI/CD

一起來練習吧!

Machine Learning 的 CI/CD

Preparing Video For Download...