cas*_*sen 3 azure azure-machine-learning-service azureml-python-sdk
使用 v2 Azure ML Python SDK (azure-ai-ml) 如何获取当前正在运行的作业的实例?
在 v1 (azureml-core) 中我会这样做:
from azureml.core import Run
run = Run.get_context()
if isinstance(run, Run):
print("Running on compute...")
Run Code Online (Sandbox Code Playgroud)
v2 SDK 上的等效项是什么?
v2 中的内容比 v1 中涉及的内容更多一些。原因是 v2 明确区分了控制平面(启动/停止作业、部署计算等)和数据平面(运行数据科学代码、从存储加载数据等)。
作业可以执行控制平面操作,但它们需要使用用户明确分配给作业的正确身份来执行此操作。
首先让我向您展示如何执行此操作的代码。此脚本创建一个 MLClient,然后使用该客户端连接到服务,以检索作业的元数据,并从中提取提交作业的用户的名称:
# control_plane.py
from azure.ai.ml import MLClient
from azure.ai.ml.identity import AzureMLOnBehalfOfCredential
import os
def get_ml_client():
uri = os.environ["MLFLOW_TRACKING_URI"]
uri_segments = uri.split("/")
subscription_id = uri_segments[uri_segments.index("subscriptions") + 1]
resource_group_name = uri_segments[uri_segments.index("resourceGroups") + 1]
workspace_name = uri_segments[uri_segments.index("workspaces") + 1]
credential = AzureMLOnBehalfOfCredential()
client = MLClient(
credential=credential,
subscription_id=subscription_id,
resource_group_name=resource_group_name,
workspace_name=workspace_name,
)
return client
ml_client = get_ml_client()
this_job = ml_client.jobs.get(os.environ["MLFLOW_RUN_ID"])
print("This job was created by:", this_job.creation_context.created_by)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,代码使用特殊的方法AzureMLOnBehalfOfCredential来创建 MLClient。AzureCliCredential您在本地(或)使用的选项InteractiveBrowserCredential不适用于远程作业,因为您未通过az login该远程运行上的浏览器提示进行身份验证。为了使您的凭据在远程作业上可用,您需要使用 来运行该作业user_identity。并且您需要使用该类从环境中检索相应的凭证AzureMLOnBehalfOfCredential。
那么,如何使用 来运行工作呢user_identity?下面是实现它的 yaml:
$schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json
type: command
command: |
pip install azure-ai-ml
python control_plane.py
code: code
environment:
image: library/python:latest
compute: azureml:cpu-cluster
identity:
type: user_identity
Run Code Online (Sandbox Code Playgroud)
请注意identity底部的部分。另请注意,我很懒,安装 azureml-ai-ml sdk 作为工作的一部分。在实际设置中,我当然会创建一个安装了该软件包的环境。
这些是身份类型的有效设置:
aml_token:这是默认设置,不允许您访问控制平面managed或managed_identity:这意味着作业将在给定的托管身份(也称为计算身份)下运行。这将在您的工作中通过 访问azure.identity.ManagedIdentityCredential。当然,您需要为所选的计算身份提供访问工作区的权限,以便能够读取作业信息。user_identity:这将以提交用户的身份运行作业。azure.ai.ml.identity.AzureMLOnBehalfOfCredential它将与如上所示的凭据一起使用。因此,对于您的用例,您有 2 个选择:
user_identity使用该类AzureMLOnBehalfOfCredential来创建 MLClientmanaged_identity使用该类ManagedIdentityCredential创建 MLClient| 归档时间: |
|
| 查看次数: |
2483 次 |
| 最近记录: |