MLflow 클라이언트 호환성
Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
MLflow는 머신 러닝 실험 추적을 위한 인기 있는 오픈 소스 도구입니다. 로컬 환경에서 MLflow 클라이언트 호환성을 사용하려면: 코드를 실행하는 호스트에서 추적 URI 및 토큰 환경 변수를 설정합니다. 학습 코드에 mlflow.set_tracking_uri() 호출이 포함된 경우 제거합니다.
MLflow는 머신 러닝 실험 추적을 위한 인기 있는 오픈 소스 도구입니다. GitLab 모델 실험 추적과 GitLab 모델 레지스트리는 MLflow 클라이언트와 호환됩니다. 설정에는 기존 코드에 대한 최소한의 변경이 필요합니다.
MLflow 클라이언트 통합 활성화#
사전 요구 사항:
- GitLab 호환 Python 클라이언트:
- 권장: GitLab MLOps Python 클라이언트.
- 다른 옵션으로는 MLflow 클라이언트 버전이 있습니다. MLflow 클라이언트는 GitLab과 호환됩니다.
- Developer, Maintainer 또는 Owner 권한과
api범위가 있는 개인, 프로젝트 또는 그룹 액세스 토큰. - 프로젝트 ID. 프로젝트 ID를 찾으려면:
- 상단 표시줄에서 Search or go to를 선택하고 프로젝트를 찾습니다.
- Settings > General을 선택합니다.
로컬 환경에서 MLflow 클라이언트 호환성을 사용하려면:
-
코드를 실행하는 호스트에서 추적 URI 및 토큰 환경 변수를 설정합니다. 로컬 환경, CI 파이프라인 또는 원격 호스트가 될 수 있습니다. 예를 들어:
export MLFLOW_TRACKING_URI="<your gitlab endpoint>/api/v4/projects/<your project id>/ml/mlflow" export MLFLOW_TRACKING_TOKEN="<your_access_token>" -
학습 코드에
mlflow.set_tracking_uri()호출이 포함된 경우 제거합니다.
모델 레지스트리에서는 오른쪽 상단의 오버플로 메뉴에서 세로 줄임표(⋮)를 선택하여 추적 URI를 복사할 수 있습니다.
모델 실험#
학습 코드를 실행할 때 MLflow 클라이언트를 사용하여 GitLab에서 실험, 실행, 모델, 모델 버전, 로그 파라미터, 메트릭, 메타데이터 및 아티팩트를 생성할 수 있습니다.
실험이 로그되면 /<your project>/-/ml/experiments 아래에 나열됩니다.
실행은 등록되며 실험, 모델 또는 모델 버전을 선택하여 탐색할 수 있습니다.
실험 만들기#
import mlflow
# Create a new experiment
experiment_id = mlflow.create_experiment(name="<your_experiment>")
# Setting the active experiment also creates a new experiment if it doesn't exist.
mlflow.set_experiment(experiment_name="<your_experiment>")
실행 만들기#
import mlflow
# Creating a run requires an experiment ID or an active experiment
mlflow.set_experiment(experiment_name="<your_experiment>")
# Runs can be created with or without a context manager
with mlflow.start_run() as run:
print(run.info.run_id)
# Your training code
with mlflow.start_run():
# Your training code
파라미터 및 메트릭 로깅#
import mlflow
mlflow.set_experiment(experiment_name="<your_experiment>")
with mlflow.start_run():
# Parameter keys need to be unique in the scope of the run
mlflow.log_param(key="param_1", value=1)
# Metrics can be updated throughout the run
mlflow.log_metric(key="metrics_1", value=1)
mlflow.log_metric(key="metrics_1", value=2)
아티팩트 로깅#
import mlflow
mlflow.set_experiment(experiment_name="<your_experiment>")
with mlflow.start_run():
# Plaintext text files can be logged as artifacts using `log_text`
mlflow.log_text('Hello, World!', artifact_file='hello.txt')
mlflow.log_artifact(
local_path='<local/path/to/file.txt>',
artifact_path='<optional relative path to log the artifact at>'
)
모델 로깅#
지원되는 MLflow 모델 플레이버 중 하나를 사용하여 모델을 로깅할 수 있습니다. 모델 플레이버로 로깅하면 메타데이터가 기록되어 다양한 도구 및 환경에서 모델을 더 쉽게 관리, 로드 및 배포할 수 있습니다.
import mlflow
from sklearn.ensemble import RandomForestClassifier
mlflow.set_experiment(experiment_name="<your_experiment>")
with mlflow.start_run():
# Create and train a simple model
model = RandomForestClassifier(n_estimators=10, random_state=42)
model.fit(X_train, y_train)
# Log the model using MLflow sklearn mode flavour
mlflow.sklearn.log_model(model, artifact_path="")
실행 로드#
히스토리
- GitLab 17.9에서 도입되었습니다.
예를 들어 예측을 위해 GitLab 모델 레지스트리에서 실행을 로드할 수 있습니다.
import mlflow
import mlflow.pyfunc
run_id = "<your_run_id>"
download_path = "models" # Local folder to download to
mlflow.pyfunc.load_model(f"runs:/{run_id}/", dst_path=download_path)
sample_input = [[1,0,3,4],[2,0,1,2]]
model.predict(data=sample_input)
실행을 CI/CD 작업에 연결#
학습 코드가 CI/CD 작업에서 실행되는 경우 GitLab은 해당 정보를 사용하여 실행 메타데이터를 향상시킬 수 있습니다. 실행을 CI/CD 작업에 연결하려면:
-
프로젝트 CI 변수에 다음 변수를 포함합니다:
MLFLOW_TRACKING_URI:"<your gitlab endpoint>/api/v4/projects/<your project id>/ml/mlflow"MLFLOW_TRACKING_TOKEN:<your_access_token>
-
실행 실행 컨텍스트 내의 학습 코드에 다음 코드 스니펫을 추가합니다:
import os import mlflow with mlflow.start_run(run_name=f"Run {index}"): # Your training code # Start of snippet to be included if os.getenv('GITLAB_CI'): mlflow.set_tag('gitlab.CI_JOB_ID', os.getenv('CI_JOB_ID')) # End of snippet to be included
모델 레지스트리#
MLflow 클라이언트를 사용하여 모델 및 모델 버전을 관리할 수도 있습니다. 모델은 /<your project>/-/ml/models 아래에 등록됩니다.
모델#
모델 만들기#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
description = 'Model description'
model = client.create_registered_model(model_name, description=description)
참고
create_registered_model인수tags는 무시됩니다.name은 프로젝트 내에서 고유해야 합니다.name은 기존 실험의 이름이 될 수 없습니다.
모델 가져오기#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
model = client.get_registered_model(model_name)
모델 업데이트#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
description = 'New description'
client.update_registered_model(model_name, description=description)
모델 삭제#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
client.delete_registered_model(model_name)
모델에 실행 로깅#
모든 모델에는 [model] 접두사가 붙은 동일한 이름의 관련 실험이 있습니다.
모델에 실행을 로깅하려면 올바른 이름을 전달하는 실험을 사용합니다:
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
exp = client.get_experiment_by_name(f"[model]{model_name}")
run = client.create_run(exp.experiment_id)
모델 버전#
모델 버전 만들기#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
description = 'Model version description'
model_version = client.create_model_version(model_name, source="", description=description)
버전 파라미터가 전달되지 않으면 최신 업로드된 버전에서 자동 증가됩니다. 모델 버전 생성 중 태그를 전달하여 버전을 설정할 수 있습니다. 버전은 SemVer 형식을 따라야 합니다.
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
tags = { "gitlab.version": version }
client.create_model_version(model_name, version, description=description, tags=tags)
참고
- 인수
run_id는 무시됩니다. 모든 모델 버전은 실행처럼 동작합니다. 실행에서 모드 버전을 만드는 것은 아직 지원되지 않습니다. - 인수
source는 무시됩니다. GitLab이 모델 버전 파일에 대한 패키지 위치를 만듭니다. - 인수
run_link는 무시됩니다. - 인수
await_creation_for는 무시됩니다.
모델 업데이트#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
description = 'New description'
client.update_model_version(model_name, version, description=description)
모델 버전 가져오기#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
client.get_model_version(model_name, version)
모델의 최신 버전 가져오기#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
client.get_latest_versions(model_name)
참고
- 인수
stages는 무시됩니다. - 버전은 가장 높은 시맨틱 버전 순으로 정렬됩니다.
모델 버전 로드#
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version' # for example: '1.0.0'
# Alternatively search the version
version = mlflow.search_registered_models(filter_string="name='{model_name}'")[0].latest_versions[0].version
model = mlflow.pyfunc.load_model(f"models:/{model_name}/{latest_version}")
# Or load the latest version
model = mlflow.pyfunc.load_model(f"models:/{model_name}/latest")
모델 버전에 메트릭 및 파라미터 로깅#
모든 모델 버전은 실행이기도 하며, 사용자가 파라미터와 메트릭을 로깅할 수 있습니다. 실행 ID는 GitLab의 모델 버전 페이지에서 찾거나 MLflow 클라이언트를 사용하여 찾을 수 있습니다:
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
model_version = client.get_model_version(model_name, version)
run_id = model_version.run_id
# Your training code
client.log_metric(run_id, '<metric_name>', '<metric_value>')
client.log_param(run_id, '<param_name>', '<param_value>')
client.log_batch(run_id, metric_list, param_list, tag_list)
각 파일의 크기 제한이 5GB이므로 더 큰 모델은 분할해야 합니다.
모델 버전에 아티팩트 로깅#
GitLab은 MLflow 클라이언트가 파일을 업로드하는 데 사용할 수 있는 패키지를 만듭니다.
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
model_version = client.get_model_version(model_name, version)
run_id = model_version.run_id
# Your training code
client.log_artifact(run_id, '<local/path/to/file.txt>', artifact_path="")
client.log_figure(run_id, figure, artifact_file="my_plot.png")
client.log_dict(run_id, my_dict, artifact_file="my_dict.json")
client.log_image(run_id, image, artifact_file="image.png")
아티팩트는 https/<your project>/-/ml/models/<model_id>/versions/<version_id>에서 사용할 수 있습니다.
모델 버전을 CI/CD 작업에 연결#
실행과 유사하게 모델 버전을 CI/CD 작업에 연결하는 것도 가능합니다:
import os
from mlflow import MlflowClient
client = MlflowClient()
model_name = '<your_model_name>'
version = '<your_version>'
model_version = client.get_model_version(model_name, version)
run_id = model_version.run_id
# Your training code
if os.getenv('GITLAB_CI'):
client.set_tag(model_version.run_id, 'gitlab.CI_JOB_ID', os.getenv('CI_JOB_ID'))
지원되는 MLflow 클라이언트 메서드 및 주의 사항#
GitLab은 MLflow 클라이언트에서 다음 메서드를 지원합니다. 자세한 내용은 MLflow 문서에서 찾을 수 있습니다. 아래 메서드의 MlflowClient 대응 메서드도 동일한 주의 사항으로 지원됩니다.
| 메서드 | 지원 여부 | 추가된 버전 | 비고 |
|---|---|---|---|
create_experiment |
Yes | 15.11 | |
get_experiment |
Yes | 15.11 | |
get_experiment_by_name |
Yes | 15.11 | |
delete_experiment |
Yes | 17.5 | |
set_experiment |
Yes | 15.11 | |
get_run |
Yes | 15.11 | |
delete_run |
Yes | 17.5 | |
start_run |
Yes | 15.11 | (16.3) 이름이 제공되지 않으면 실행에 임의의 별명이 부여됩니다. |
search_runs |
Yes | 15.11 | (16.4) experiment_ids는 열 또는 메트릭 순서를 가진 단일 실험 ID만 지원합니다. |
log_artifact |
Yes with caveat | 15.11 | (15.11) artifact_path는 비어 있어야 합니다. 디렉토리를 지원하지 않습니다. |
log_artifacts |
Yes with caveat | 15.11 | (15.11) artifact_path는 비어 있어야 합니다. 디렉토리를 지원하지 않습니다. |
log_batch |
Yes | 15.11 | |
log_metric |
Yes | 15.11 | |
log_metrics |
Yes | 15.11 | |
log_param |
Yes | 15.11 | |
log_params |
Yes | 15.11 | |
log_figure |
Yes | 15.11 | |
log_image |
Yes | 15.11 | |
log_text |
Yes with caveat | 15.11 | (15.11) 디렉토리를 지원하지 않습니다. |
log_dict |
Yes with caveat | 15.11 | (15.11) 디렉토리를 지원하지 않습니다. |
set_tag |
Yes | 15.11 | |
set_tags |
Yes | 15.11 | |
set_terminated |
Yes | 15.11 | |
end_run |
Yes | 15.11 | |
update_run |
Yes | 15.11 | |
log_model |
Partial | 15.11 | (15.11) 아티팩트를 저장하지만 모델 데이터는 저장하지 않습니다. artifact_path는 비어 있어야 합니다. |
load_model |
Yes | 17.5 | |
download_artifacts |
Yes | 17.9 | |
list_artifacts |
Yes | 17.9 |
기타 MLflowClient 메서드:
| 메서드 | 지원 여부 | 추가된 버전 | 비고 |
|---|---|---|---|
create_registered_model |
Yes with caveats | 16.8 | 참고 사항을 확인하세요 |
get_registered_model |
Yes | 16.8 | |
delete_registered_model |
Yes | 16.8 | |
update_registered_model |
Yes | 16.8 | |
create_model_version |
Yes with caveats | 16.8 | 참고 사항을 확인하세요 |
get_model_version |
Yes | 16.8 | |
get_latest_versions |
Yes with caveats | 16.8 | 참고 사항을 확인하세요 |
update_model_version |
Yes | 16.8 | |
create_registered_model |
Yes | 16.8 | |
create_registered_model |
Yes | 16.8 |
알려진 이슈#
- 지원되는 메서드에 나열되지 않은 MLflow 클라이언트 메서드는 여전히 작동할 수 있지만 테스트되지 않았습니다.
- 실험 및 실행 생성 중 ExperimentTags는 표시되지 않더라도 저장됩니다.
