Доступ/загрузка артефактов из MLflow, работающего в DockerPython

Программы на Python
Ответить
Anonymous
 Доступ/загрузка артефактов из MLflow, работающего в Docker

Сообщение Anonymous »

В настоящее время я работаю над созданием тестовых контейнеров, например тестированием с использованием сервера MLflow, работающего в Docker. Я использую довольно простой образ Docker для настройки сервера MLflow и запускаю небольшой обучающий скрипт, который записывает полученную модель в качестве артефакта в MLflow:

Код: Выделить всё

# Dockerfile.mlflow-test
FROM ghcr.io/mlflow/mlflow:latest

# Install additional dependencies
RUN pip install scikit-learn pandas numpy

# Set up working directory
WORKDIR /mlflow

# Create MLflow directories
RUN mkdir -p /mlflow/mlruns && \
chmod -R 777 /mlflow

# Copy and modify training script
COPY train_model.py .

# Train and register model during build
ENV MLFLOW_TRACKING_URI=sqlite:///mlflow.db
ENV MLFLOW_ARTIFACT_ROOT=file:///mlflow/mlruns
RUN python train_model.py

# Expose MLflow UI port
EXPOSE 5000

# Start MLflow server
CMD ["mlflow", "server", \
"--host", "0.0.0.0", \
"--port", "5000", \
"--backend-store-uri", "sqlite:///mlflow.db", \
"--default-artifact-root", "file:///mlflow/mlruns"]
При запуске правильно отображается пользовательский интерфейс MLflow, и я также вижу артефакты, соответствующие запущенной модели (на http://127.0.0.1:5000/# /experiments/0/runs/3894c76664d24c43a537de715a25d664/artifacts).
Однако, когда Затем я запускаю следующий код Python для локальной загрузки артефактов:

Код: Выделить всё

import mlflow
from mlflow import MlflowClient
from mlflow.artifacts import download_artifacts, list_artifacts

mlflow.set_tracking_uri("http://127.0.0.1:5000")

ARTIFACT_DESTINATION_DIR = "./test-artifacts"
MODEL_NAME = "test_model"
ALIAS = "Test"

client = MlflowClient(mlflow.get_tracking_uri())

def get_latest_version(model_name, mlflow_client=client):
return mlflow_client.get_registered_model(model_name).latest_versions[0].version

def get_latest_version_for_alias(
model_name: str, alias: str, mlflow_client=client
) -> int:
return mlflow_client.get_model_version_by_alias(model_name, alias).version

def get_run_id_for_model_version(
model_name: str, version: str, mlflow_client=client
) ->  str:
model_version = mlflow_client.get_model_version(model_name, version)
return model_version.run_id

def download_latest_artifacts_for_model_alias(
model_name: str = MODEL_NAME,
alias: str = ALIAS,
destination_dir: str = ARTIFACT_DESTINATION_DIR,
mlflow_client=client,
):
# First, get latest model version for the given alias
version = get_latest_version_for_alias(
model_name=model_name, alias=alias, mlflow_client=mlflow_client
)
print(f"VERSION: {version}")

# Get the run ID for this version
run_id = get_run_id_for_model_version(
model_name=model_name, version=version, mlflow_client=mlflow_client
)
print(f"RUN ID: {run_id}")

# Construct the artifact URI using runs:/ scheme
artifact_uri = f"runs:/{run_id}/model"
print(f"ARTIFACT URI: {artifact_uri}")

# Define the proper local dir
full_destination_dir = f"{destination_dir}/{model_name}/{alias}/{version}"

# Download all of the artifacts
download_artifacts(artifact_uri=artifact_uri, dst_path=full_destination_dir)

# Test the functions
print("Registered models:", mlflow.search_registered_models())
print("Latest version:", get_latest_version(MODEL_NAME, client))
print("Latest version for alias:", get_latest_version_for_alias(MODEL_NAME, ALIAS, client))
print("Downloading artifacts...")
download_latest_artifacts_for_model_alias(
MODEL_NAME,
ALIAS,
destination_dir=ARTIFACT_DESTINATION_DIR,
mlflow_client=client
)
Я получаю следующий результат:

Код: Выделить всё

Registered models: []
Latest version: 1
Latest version for alias: 1
Downloading artifacts...
VERSION: 1
RUN ID: 3894c76664d24c43a537de715a25d664
ARTIFACT URI: runs:/3894c76664d24c43a537de715a25d664/model
Traceback (most recent call last):
File "/home/user/Projects/my-api/tests/integration/test_container.py", line 154, in 
download_latest_artifacts_for_model_alias(
File "/home/user/Projects/my-api/tests/integration/test_container.py", line 147, in download_latest_artifacts_for_model_alias
download_artifacts(artifact_uri=artifact_uri, dst_path=full_destination_dir)
File "/home/user/Projects/venvs/.my-api/lib/python3.10/site-packages/mlflow/artifacts/__init__.py", line 64, in download_artifacts
return _download_artifact_from_uri(artifact_uri, output_path=dst_path)
File "/home/user/Projects/venvs/.my-api/lib/python3.10/site-packages/mlflow/tracking/artifact_utils.py", line 116, in _download_artifact_from_uri
return repo.download_artifacts(artifact_path=artifact_path, dst_path=output_path)
File "/home/user/Projects/venvs/.my-api/lib/python3.10/site-packages/mlflow/store/artifact/runs_artifact_repo.py", line 131, in download_artifacts
return self.repo.download_artifacts(artifact_path, dst_path)
File "/home/user/Projects/venvs/.my-api/lib/python3.10/site-packages/mlflow/store/artifact/local_artifact_repo.py", line 85, in download_artifacts
return super().download_artifacts(artifact_path, dst_path)
File "/homeuser/Projects/venvs/.my-api/lib/python3.10/site-packages/mlflow/store/artifact/artifact_repo.py", line 284, in download_artifacts
raise MlflowException(
mlflow.exceptions.MlflowException: The following failures occurred while downloading one or more artifacts from /mlflow/mlruns/0/3894c76664d24c43a537de715a25d664/artifacts:
##### File model #####
[Errno 2] No such file or directory: '/mlflow/mlruns/0/3894c76664d24c43a537de715a25d664/artifacts/model'
Я просто не понимаю, почему он может получить все метаданные, версию, идентификатор запуска и т. д., но не может позволить мне загрузить артефакты? Я понимаю, что это как-то связано с тем, как артефакты «монтируются» внутри файловой системы контейнера Docker, но затем я задаюсь вопросом: как правильно правильно загружать артефакты с помощью такой локальной настройки Docker?
Также стоит упомянуть, что я могу «просто» свернуть артефакты напрямую, используя прямую ссылку, и запустить id, например http://localhost:5000/get-artifact?path ... efcad67167, чтобы он был доступен.
Заранее спасибо!

Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-docker
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»