反覆測試時不斷變更參數,很難記住哪些設定產生了特定結果。MLflow 是實驗追蹤工具,會記錄每次執行的參數、指標和產出檔案,讓這些資料能在同一處比較。我安裝了 MLflow,並測試它能否在網路中斷的情況下記錄及比較執行結果。
MLflow 會記錄每次執行的參數、指標和標籤,並可在同一個畫面比較多次執行。此專案依 Apache 2.0 License 發布原始碼 (*1)。
1. 安裝 MLflow
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'mlflow==3.14.0'
WORKDIR /work
podman build -t mlflow-sandbox .
2. 遇到的障礙:檔案儲存已棄用
MLflow 可以將實驗記錄儲存在本機檔案中,無須伺服器。我使用了傳統的檔案儲存 URI(file:///work/mlruns),執行卻因以下錯誤而停止。
mlflow.exceptions.MlflowException: The filesystem tracking backend (e.g., './mlruns') is
in maintenance mode and will not receive further updates. Please migrate to a database
backend (e.g., 'sqlite:///mlflow.db') ...
在目前的 MLflow 版本中,檔案儲存以維護模式運作。新的使用需要明確授權。我依照錯誤訊息的指示,切換至 SQLite 後端。
3. 使用 SQLite 後端記錄執行結果
import mlflow
mlflow.set_tracking_uri("sqlite:///work/mlflow.db")
mlflow.set_experiment("rootless-container-benchmark")
with mlflow.start_run(run_name="baseline") as run:
mlflow.log_param("memory_limit_mb", 2048)
mlflow.log_param("cpu_limit", 2)
mlflow.log_metric("startup_seconds", 1.42)
mlflow.log_metric("throughput_rps", 340.5)
with mlflow.start_run(run_name="tuned") as run:
mlflow.log_param("memory_limit_mb", 4096)
mlflow.log_param("cpu_limit", 2)
mlflow.log_metric("startup_seconds", 1.18)
mlflow.log_metric("throughput_rps", 512.3)
runs = mlflow.search_runs(experiment_names=["rootless-container-benchmark"])
print(runs[["tags.mlflow.runName", "params.memory_limit_mb", "metrics.throughput_rps"]].to_string(index=False))
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 --userns=keep-id \
-v "$(pwd)":/work -w /work mlflow-sandbox \
python tracking_demo.py
-v 選項讓容器內部可以讀寫指定目錄。請在專為實驗保留的空目錄中執行此指令。由於 sqlite:///work/mlflow.db 會在掛載點下建立資料庫檔案,請避免在含有重要既存資料的位置執行。
執行期間,MLflow 印出數行警告,表示找不到 git 指令。MLflow 原本嘗試記錄啟動該次執行的環境中的 Git commit 資訊,因此這次失敗並未影響實驗記錄。指令印出以下表格:
tags.mlflow.runName params.memory_limit_mb metrics.throughput_rps
tuned 4096 512.3
baseline 2048 340.5
MLflow 記錄了兩次參數值不同的執行,search_runs 則在同一個畫面中比較了它們。實驗記錄與搜尋只使用一個本機 SQLite 檔案便完成,無須伺服器。
無須記住先前執行的設定
反覆測試時若變更參數卻不保留記錄,就無法重現各種設定下發生的情況。在本機執行 MLflow 這類工具,便能將實驗追蹤納入工作流程,無須操作伺服器。您可以用記錄而非記憶作為實驗歷程的基礎。
來源
*1 MLflow (GitHub), https://github.com/mlflow/mlflow, Apache 2.0 License