

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 亚马逊 SageMaker ML Lineage 追踪
<a name="lineage-tracking"></a>

**重要**  
截至 2023 年 11 月 30 日，之前的亚马逊 SageMaker Studio 体验现在被命名为 Amazon St SageMaker udio Classic。以下部分专门介绍如何使用 Studio Classic 应用程序。有关使用更新的 Studio 体验的信息，请参阅 [亚马逊 SageMaker Studio](studio-updated.md)。  
Studio Classic 仍针对现有工作负载进行维护，但不再可供入门使用。您只能停止或删除现有的 Studio Classic 应用程序，不能创建新的应用程序。我们建议您将[工作负载迁移到全新 Studio 体验](studio-updated-migrate.md)。

Amazon SageMaker ML Lineage Tracking 创建并存储有关机器学习 (ML) 工作流程从数据准备到模型部署的步骤的信息。利用跟踪信息，您可以重现工作流步骤，跟踪模型和数据集世系，并建立模型治理和审计标准。

SageMaker AI 的 Lineage Tracking 功能在后端运行，用于跟踪与模型训练和部署工作流程相关的所有元数据。其中包括您的训练作业、使用的数据集、管道、端点和实际模型。您可以随时查询世系服务，以找到用于训练模型的确切构件。使用这些构件，只要您可以访问所使用的确切数据集，就可以重新创建相同的机器学习工作流来重现模型。一个试验组件会跟踪训练作业。此试验组件包含用作训练作业一部分的所有参数。如果不需要重新运行整个工作流，可以重现训练作业以派生出相同的模型。

借助 SageMaker AI Lineage Tracking，数据科学家和模型构建者可以执行以下操作：
+ 保存模型发现实验的运行历史记录。
+ 通过跟踪用于审计和合规性验证的模型世系构件，建立模型治理。

下图显示了 Amazon A SageMaker I 在 end-to-end模型训练和部署 ML 工作流程中自动创建的谱系图示例。

![\[\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/pipelines/PipelineLineageWorkflow.png)


**Topics**
+ [世系跟踪实体](lineage-tracking-entities.md)
+ [Amazon SageMaker AI 创建的追踪实体](lineage-tracking-auto-creation.md)
+ [手动创建跟踪实体](lineage-tracking-manual-creation.md)
+ [查询世系实体](querying-lineage-entities.md)
+ [跟踪跨账户脉络](xaccount-lineage-tracking.md)

# 世系跟踪实体
<a name="lineage-tracking-entities"></a>

跟踪实体保留了 end-to-end机器学习工作流程中所有元素的表示形式。您可以使用此表示形式来建立模型治理，重现工作流和维护工作历史记录。

当您创建 SageMaker AI 任务（例如处理作业、训练作业和批量转换作业）时，Amazon SageMaker AI 会自动为试验组件及其关联的试验和实验创建跟踪实体。除了自动跟踪之外，您还可以[手动创建跟踪实体](lineage-tracking-manual-creation.md)，对工作流中的自定义步骤进行建模。有关更多信息，请参阅 [Studio 经典版中的亚马逊 SageMaker 实验](experiments.md)。

SageMaker AI 还会自动为工作流程中的其他步骤创建跟踪实体，因此您可以从头到尾跟踪工作流程。有关更多信息，请参阅 [Amazon SageMaker AI 创建的追踪实体](lineage-tracking-auto-creation.md)。

您可以创建其他实体来补充 SageMaker AI 创建的实体。有关更多信息，请参阅 [手动创建跟踪实体](lineage-tracking-manual-creation.md)。

SageMaker AI 会重复使用任何现有实体，而不是创建新实体。例如，只能有一个具有唯一 `SourceUri` 的构件。

**用于查询世系的关键概念**
+ **世系** - 跟踪机器学习工作流中各实体之间关系的元数据。
+ **QueryLineage**— 检查你的血统并发现实体之间关系的行动。
+ **世系实体** - 构成您的世系的元数据元素。
+ **跨账户世系** - 您的机器学习工作流可能跨多个账户。使用跨账户世系，您可以配置多个账户，以便在共享实体资源之间自动创建世系关联。 QueryLineage 然后甚至可以从这些共享账户中返回实体。

定义了以下跟踪实体：

**实验实体**
+ [试验组件](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrialComponent.html) - 机器学习试验的一个阶段。包括处理作业、训练作业和批量转换作业。
+ [试验](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrial.html) - 试验组件组合，通常会生成一个模型。
+ [实验](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateExperiment.html) - 试验分组，通常侧重于解决特定使用案例。

**世系实体**
+ [试验组件](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrialComponent.html) - 表示世系中的处理、训练和转换作业。也是实验管理的一部分。
+ [上下文](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateContext.html) - 提供其他跟踪或实验实体的逻辑分组。从概念上讲，实验和试验都是上下文。示例包括端点和模型包。
+ [操作](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateAction.html) - 表示操作或活动。通常，一项操作至少涉及一个输入构件或输出构件。示例包括工作流步骤和模型部署。
+ [构件](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateArtifact.html) - 表示 URI 可寻址的对象或数据。构件通常是试验组件或操作的输入或输出。示例包括数据集（S3 存储桶 URI）或映像（Amazon ECR 注册表路径）。
+ [关联](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AddAssociation.html) - 链接其他跟踪或实验实体，如训练数据位置与训练作业之间的关联。

  关联具有可选 `AssociationType` 属性。以下值以及每种类型的建议用法可供选择。 SageMaker AI 对其使用没有任何限制：
  + `ContributedTo` - 源对目标做出了贡献或参与促成了目标。例如，训练数据为训练作业做出了贡献。
  + `AssociatedWith` - 源已连接到目标。例如，批准工作流与模型部署相关联。
  + `DerivedFrom` - 目标是对源的修改。例如，处理作业的通道输入的摘要输出派生自原始输入。
  + `Produced` - 源生成了目标。例如，训练作业生成了一个模型构件。
  + `SameAs` - 当在不同账户中使用相同的世系实体时。

**常用属性**
+ **类型属性**

  操作、构件和上下文实体的*类型* 属性分别为 `ActionType`、`ArtifactType` 和 `ContextType`。此属性是一个自定义字符串，可以将有意义的信息与实体相关联，并可用作列表中的筛选器 APIs。
+ **源属性**

  操作、构件和上下文实体都有一个 `Source` 属性。此属性提供了实体所代表的底层 URI。部分示例包括：
  + `UpdateEndpoint` 操作，其中源为 `EndpointArn`。
  + 用于处理作业的映像构件，其中源为 `ImageUri`。
  + 上下文 `Endpoint`，其中源为 `EndpointArn`。
+ **元数据属性**

  操作和构件实体具有可选 `Metadata` 属性，可以提供以下信息：
  + `ProjectId`— 例如，模型所属 SageMaker 的人工智能 MLOps 项目的 ID。
  + `GeneratedBy`— 例如，注册模型包版本的 SageMaker AI 管道执行。
  + `Repository` - 例如，包含算法的存储库。
  + `CommitId` - 例如，算法版本的提交 ID。

# Amazon SageMaker AI 创建的追踪实体
<a name="lineage-tracking-auto-creation"></a>

如果有数据， SageMaker Amazon SageMaker AI 会自动为 AI 任务、模型、模型包和终端节点创建跟踪实体。 SageMaker AI 创建的血统实体的数量没有限制。

有关如何手动创建跟踪实体的信息，请参阅[手动创建跟踪实体](lineage-tracking-manual-creation.md)。

**Topics**
+ [为 SageMaker AI 作业跟踪实体](#lineage-tracking-auto-creation-jobs)
+ [模型包的跟踪实体](#lineage-tracking-auto-creation-model-package)
+ [端点的跟踪实体](#lineage-tracking-auto-creation-endpoint)

## 为 SageMaker AI 作业跟踪实体
<a name="lineage-tracking-auto-creation-jobs"></a>

SageMaker AI 会为每个 A SageMaker I 作业创建一个试用组件并与之关联。 SageMaker AI 会创建工件来跟踪任务元数据以及每个工件与作业之间的关联。

项目是为以下任务属性创建的，并与 A SageMaker I 任务的 Amazon 资源名称 (ARN) 相关联。构件 `SourceUri` 列在括号中。

**训练作业**
+ 包含训练算法的映像 (`TrainingImage`)。
+ 每个输入通道的数据源 (`S3Uri`)。
+ 模型的位置 (`S3OutputPath)`)。
+ 托管 Spot 检查点数据的位置 (`S3Uri`)。

**处理作业**
+ 处理作业要运行的容器 (`ImageUri`)。
+ 每个处理输入和处理输出的数据位置 (`S3Uri`)。

**转换作业**
+ 要转换的输入数据源 (`S3Uri`)。
+ 转换的结果 (`S3OutputPath`)。

**注意**  
[CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)例如，亚马逊简单存储服务 (Amazon S3) Simple Service 项目是根据提供给创建 API 的 Amazon S3 URI 值进行跟踪的，而不是根据每个文件的 Amazon S3 密钥和哈希值或 etag 值进行跟踪。

## 模型包的跟踪实体
<a name="lineage-tracking-auto-creation-model-package"></a>

创建了以下实体：

**模型包**
+ 每个模型包组的上下文。
+ 每个模型包的构件。
+ 每个模型包构件与该包所属的每个模型包组上下文之间的关联。
+ 用于创建模型包版本的操作。
+ 模型包构件和创建操作之间的关联。
+ 模型包构件与包所属的每个模型包组上下文之间的关联。
+ 推理容器
  + 模型包中定义的每个容器中使用的映像的构件。
  + 每个容器中使用的模型的构件。
  + 每个构件和模型包构件之间的关联。
+ 算法
  + 模型包中定义的每个算法的构件。
  + 每个算法创建的模型的工件。
  + 每个构件和模型包构件之间的关联。

## 端点的跟踪实体
<a name="lineage-tracking-auto-creation-endpoint"></a>

以下实体由 Amazon A SageMaker I 创建：

**端点**
+ 每个端点的上下文
+ 创建每个端点的模型部署的操作
+ 部署到端点的每个模型的构件
+ 模型中使用的映像的构件
+ 模型的模型包的构件
+ 部署到端点的每个映像的构件
+ 每个构件与模型部署操作之间的关联

# 手动创建跟踪实体
<a name="lineage-tracking-manual-creation"></a>

您可以为任何属性手动创建跟踪实体，以建立模型管理、重现工作流程并保存工作历史记录。有关 Amazon A SageMaker I 自动创建的跟踪实体的信息，请参阅[Amazon SageMaker AI 创建的追踪实体](lineage-tracking-auto-creation.md)。以下教程演示了在 SageMaker 训练作业和端点之间手动创建和关联工件，然后跟踪工作流程所需的步骤。

您可以为除关联之外的所有实体添加标签。标签是提供自定义信息的任意键值对。您可以按标签对列表或搜索查询进行筛选或排序。有关更多信息，请参阅中的为[AWS 资源添加标签](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)。*AWS 一般参考*

有关演示如何创建世系实体的示例笔记本，请参阅亚马逊[ SageMaker 示例 GitHub ](https://github.com/awslabs/amazon-sagemaker-examples)存储库中的 [Amazon SageMaker AI Lineag](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-lineage) e 笔记本。

**Topics**
+ [手动创建实体](#lineage-tracking-manual-create)
+ [手动跟踪工作流](#lineage-tracking-manual-track)
+ [限制](#lineage-tracking-manual-track-limits)

## 手动创建实体
<a name="lineage-tracking-manual-create"></a>

以下过程向您展示如何在 SageMaker AI 训练作业和终端节点之间创建和关联工件。请执行下列步骤：

**导入跟踪实体和关联**

1. 导入世系跟踪实体。

   ```
   import sys
   !{sys.executable} -m pip install -q sagemaker
   
   from sagemaker import get_execution_role
   from sagemaker.session import Session
   from sagemaker.lineage import context, artifact, association, action
   
   import boto3
   boto_session = boto3.Session(region_name=region)
   sagemaker_client = boto_session.client("sagemaker")
   ```

1. 创建输入和输出构件。

   ```
   code_location_arn = artifact.Artifact.create(
       artifact_name='source-code-location',
       source_uri='s3://...',
       artifact_type='code-location'
   ).artifact_arn
   
   # Similar constructs for train_data_location_arn and test_data_location_arn
   
   model_location_arn = artifact.Artifact.create(
       artifact_name='model-location',
       source_uri='s3://...',
       artifact_type='model-location'
   ).artifact_arn
   ```

1. 训练模型并获取代表训练作业的 `trial_component_arn`。

1. 将输入构件和输出构件与训练作业（试验组件）进行关联。

   ```
   input_artifacts = [code_location_arn, train_data_location_arn, test_data_location_arn]
   for artifact_arn in input_artifacts:
       try:
           association.Association.create(
               source_arn=artifact_arn,
               destination_arn=trial_component_arn,
               association_type='ContributedTo'
           )
       except:
           logging.info('association between {} and {} already exists', artifact_arn, trial_component_arn)
   
   output_artifacts = [model_location_arn]
   for artifact_arn in output_artifacts:
       try:
            association.Association.create(
               source_arn=trial_component_arn,
               destination_arn=artifact_arn,
               association_type='Produced'
           )
       except:
           logging.info('association between {} and {} already exists', artifact_arn, trial_component_arn)
   ```

1. 创建推理端点。

   ```
   predictor = mnist_estimator.deploy(initial_instance_count=1,
                                        instance_type='ml.m4.xlarge')
   ```

1. 创建端点上下文。

   ```
   from sagemaker.lineage import context
   
   endpoint = sagemaker_client.describe_endpoint(EndpointName=predictor.endpoint_name)
   endpoint_arn = endpoint['EndpointArn']
   
   endpoint_context_arn = context.Context.create(
       context_name=predictor.endpoint_name,
       context_type='Endpoint',
       source_uri=endpoint_arn
   ).context_arn
   ```

1. 将训练作业（试验组件）与端点上下文进行关联。

   ```
   association.Association.create(
       source_arn=trial_component_arn,
       destination_arn=endpoint_context_arn
   )
   ```

## 手动跟踪工作流
<a name="lineage-tracking-manual-track"></a>

您可以手动跟踪在上一节中创建的工作流。

根据上一个示例中的端点 Amazon 资源名称 (ARN)，以下过程将向您展示如何跟踪工作流，返回到用于训练部署到端点的模型的数据集。请执行下列步骤：

**跟踪从端点到训练数据源的工作流**

1. 导入跟踪实体。

   ```
   import sys
   !{sys.executable} -m pip install -q sagemaker
   
   from sagemaker import get_execution_role
   from sagemaker.session import Session
   from sagemaker.lineage import context, artifact, association, action
   
   import boto3
   boto_session = boto3.Session(region_name=region)
   sagemaker_client = boto_session.client("sagemaker")
   ```

1. 从端点 ARN 获取端点上下文。

   ```
   endpoint_context_arn = sagemaker_client.list_contexts(
       SourceUri=endpoint_arn)['ContextSummaries'][0]['ContextArn']
   ```

1. 从试验组件和端点上下文之间的关联中获取试验组件。

   ```
   trial_component_arn = sagemaker_client.list_associations(
       DestinationArn=endpoint_context_arn)['AssociationSummaries'][0]['SourceArn']
   ```

1. 从试验组件和端点上下文之间的关联中获取训练数据位置构件。

   ```
   train_data_location_artifact_arn = sagemaker_client.list_associations(
       DestinationArn=trial_component_arn, SourceType='Model')['AssociationSummaries'][0]['SourceArn']
   ```

1. 从训练数据位置构件获取训练数据位置。

   ```
   train_data_location = sagemaker_client.describe_artifact(
       ArtifactArn=train_data_location_artifact_arn)['Source']['SourceUri']
       print(train_data_location)
   ```

   响应：

   ```
   s3://sagemaker-sample-data-us-east-2/mxnet/mnist/train
   ```

## 限制
<a name="lineage-tracking-manual-track-limits"></a>

您可以在任何实体、实验和世系之间创建关联，但以下情况除外：
+ 您无法在两个实验实体之间创建关联。实验实体由实验、试验和试验组件组成。
+ 您可以创建与其他关联的关联。

如果您尝试创建已存在的实体，则会出现错误。

**手动创建的世系实体的最大数量**
+ 操作数：3000
+ 构件数：6000
+ 关联数：6000
+ 上下文数：500

Amazon A SageMaker I 自动创建的世系实体的数量没有限制。

# 查询世系实体
<a name="querying-lineage-entities"></a>

Amazon SageMaker AI 会在您使用世系实体时自动生成图表。您可以查询这些数据来回答各种问题。下面将说明如何在 SDK for Python 中查询这些数据。

有关如何在 Amazon SageMaker Studio 中查看注册模特血统的信息，请参阅[在 Studio 中查看模型任务流水线详情](model-registry-lineage-view-studio.md)。

您可以查询世系实体以执行以下操作：
+ 检索创建模型时使用的所有数据集。
+ 检索创建端点时使用的所有作业。
+ 检索所有使用数据集的模型。
+ 检索所有使用模型的端点。
+ 检索哪些端点派生自特定数据集。
+ 检索创建了训练作业的管道执行。
+ 检索实体之间的关系，以便进行调查、治理和再现。
+ 检索所有使用该构件的下游试验。
+ 检索所有使用该构件的上游试验。
+ 检索使用所提供的 S3 URI 的构件列表。
+ 检索使用该数据集构件的上游构件。
+ 检索使用该数据集构件的下游构件。
+ 检索使用该映像构件的数据集。
+ 检索使用该上下文的操作。
+ 检索使用该端点的处理作业。
+ 检索使用该端点的转换作业。
+ 检索使用该端点的试验组件。
+ 检索与模型包组关联的管道执行的 ARN。
+ 检索所有使用该操作的构件。
+ 检索所有使用该模型包批准操作的上游数据集。
+ 从模型包批准操作中检索模型包。
+ 检索使用该端点的下游端点上下文。
+ 检索与试验组件关联的管道执行的 ARN。
+ 检索使用该试验组件的数据集。
+ 检索使用该试验组件的模型。
+ 探索您的世系以实现可视化。

**限制**
+ 以下区域不提供世系查询功能：
  + 非洲（开普敦）- af-south
  + 亚太地区（雅加达）– ap-southeast-3
  + 亚太地区（大阪）– ap-northeast-3
  + 欧洲地区（米兰）- eu-south-1
  + 欧洲（西班牙）- eu-south-2
  + 以色列（特拉维夫）– il-central-1
+ 要发现的关系的最大深度目前限制为 10。
+ 筛选仅限于以下属性：上次修改日期、创建日期、类型和世系实体类型。

**Topics**
+ [查询世系实体入门](#querying-lineage-entities-getting-started)

## 查询世系实体入门
<a name="querying-lineage-entities-getting-started"></a>

最简单的入门方式是通过：
+ 适用于 [Python 的亚马逊 SageMaker AI 软件开发工具包](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/lineage/artifact.py#L397)定义了许多常见用例。
+ [有关演示如何使用 SageMaker AI Lineage 在谱系 APIs 图中查询关系的笔记本，请参阅 sagemaker-lineage-multihop-queries .ipynb。](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/sagemaker-lineage-multihop-queries.ipynb)

以下示例说明如何使用`LineageQuery`和构造查询`LineageFilter` APIs 来回答有关 Lineage Graph 的问题，并针对一些用例提取实体关系。

**Example 使用 `LineageQuery` API 查找实体关联**  

```
from sagemaker.lineage.context import Context, EndpointContext
from sagemaker.lineage.action import Action
from sagemaker.lineage.association import Association
from sagemaker.lineage.artifact import Artifact, ModelArtifact, DatasetArtifact

from sagemaker.lineage.query import (
    LineageQuery,
    LineageFilter,
    LineageSourceEnum,
    LineageEntityEnum,
    LineageQueryDirectionEnum,
)
# Find the endpoint context and model artifact that should be used for the lineage queries.

contexts = Context.list(source_uri=endpoint_arn)
context_name = list(contexts)[0].context_name
endpoint_context = EndpointContext.load(context_name=context_name)
```

**Example 查找与端点关联的所有数据集**  

```
# Define the LineageFilter to look for entities of type `ARTIFACT` and the source of type `DATASET`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT], sources=[LineageSourceEnum.DATASET]
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the lineage objects corresponding to the datasets
dataset_artifacts = []
for vertex in query_result.vertices:
    dataset_artifacts.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(dataset_artifacts)
```

**Example 查找与端点关联的模型**  

```
# Define the LineageFilter to look for entities of type `ARTIFACT` and the source of type `MODEL`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT], sources=[LineageSourceEnum.MODEL]
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the lineage objects corresponding to the model
model_artifacts = []
for vertex in query_result.vertices:
    model_artifacts.append(vertex.to_lineage_object().source.source_uri)

# The results of the `LineageQuery` API call return the ARN of the model deployed to the endpoint along with
# the S3 URI to the model.tar.gz file associated with the model
pp.pprint(model_artifacts)
```

**Example 查找与端点关联的试验组件**  

```
# Define the LineageFilter to look for entities of type `TRIAL_COMPONENT` and the source of type `TRAINING_JOB`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.TRIAL_COMPONENT],
    sources=[LineageSourceEnum.TRAINING_JOB],
)

# Providing this `LineageFilter` to the `LineageQuery` constructs a query that traverses through the given context `endpoint_context`
# and find all datasets.

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[endpoint_context.context_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

# Parse through the query results to get the ARNs of the training jobs associated with this Endpoint
trial_components = []
for vertex in query_result.vertices:
    trial_components.append(vertex.arn)

pp.pprint(trial_components)
```

**Example 更改世系的焦点**  
可以修改 `LineageQuery`，使其具有不同的 `start_arns`，这将更改世系的焦点。此外，`LineageFilter` 可以采用多个来源和实体来扩大查询范围。  
在下文中，我们使用模型作为世系焦点，并查找与之关联的端点和数据集。  

```
# Get the ModelArtifact

model_artifact_summary = list(Artifact.list(source_uri=model_package_arn))[0]
model_artifact = ModelArtifact.load(artifact_arn=model_artifact_summary.artifact_arn)
query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[LineageSourceEnum.ENDPOINT, LineageSourceEnum.DATASET],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # Find all the entities that descend from the model, i.e. the endpoint
    direction=LineageQueryDirectionEnum.DESCENDANTS,
    include_edges=False,
)

associations = []
for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # Find all the entities that ascend from the model, i.e. the datasets
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(associations)
```

**Example 使用 `LineageQueryDirectionEnum.BOTH` 查找前代和后代关系**  
当方向设置为 `BOTH` 时，查询将遍历图表以查找前代和后代关系。这种遍历不仅从起始节点开始，而且从访问的每个节点开始。如果一个训练作业运行了两次，并且该训练作业生成的两个模型都部署到端点，则方向设置为 `BOTH` 的查询结果会显示这两个端点。这是因为训练和部署模型时使用的是同一映像。由于该映像对模型是通用的，因此 `start_arn` 和两个端点都会显示在查询结果中。  

```
query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[LineageSourceEnum.ENDPOINT, LineageSourceEnum.DATASET],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],  # Model is the starting artifact
    query_filter=query_filter,
    # This specifies that the query should look for associations both ascending and descending for the start
    direction=LineageQueryDirectionEnum.BOTH,
    include_edges=False,
)

associations = []
for vertex in query_result.vertices:
    associations.append(vertex.to_lineage_object().source.source_uri)

pp.pprint(associations)
```

**Example `LineageQuery` 中的方向 - `ASCENDANTS` 与 `DESCENDANTS`**  
要了解世系图表中的方向，请使用以下实体关系图表 - 数据集 -> 训练作业 -> 模型 -> 端点  
端点是模型的后代，而模型是数据集的后代。同样，模型是端点的前代。`direction` 参数可用于指定查询应返回 `start_arns` 中实体的后代实体还是前代实体。如果 `start_arns` 包含模型且方向为 `DESCENDANTS`，则查询将返回端点。如果方向为 `ASCENDANTS`，则查询将返回数据集。  

```
# In this example, we'll look at the impact of specifying the direction as ASCENDANT or DESCENDANT in a `LineageQuery`.

query_filter = LineageFilter(
    entities=[LineageEntityEnum.ARTIFACT],
    sources=[
        LineageSourceEnum.ENDPOINT,
        LineageSourceEnum.MODEL,
        LineageSourceEnum.DATASET,
        LineageSourceEnum.TRAINING_JOB,
    ],
)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.ASCENDANTS,
    include_edges=False,
)

ascendant_artifacts = []

# The lineage entity returned for the Training Job is a TrialComponent which can't be converted to a
# lineage object using the method `to_lineage_object()` so we extract the TrialComponent ARN.
for vertex in query_result.vertices:
    try:
        ascendant_artifacts.append(vertex.to_lineage_object().source.source_uri)
    except:
        ascendant_artifacts.append(vertex.arn)

print("Ascendant artifacts : ")
pp.pprint(ascendant_artifacts)

query_result = LineageQuery(sagemaker_session).query(
    start_arns=[model_artifact.artifact_arn],
    query_filter=query_filter,
    direction=LineageQueryDirectionEnum.DESCENDANTS,
    include_edges=False,
)

descendant_artifacts = []
for vertex in query_result.vertices:
    try:
        descendant_artifacts.append(vertex.to_lineage_object().source.source_uri)
    except:
        # Handling TrialComponents.
        descendant_artifacts.append(vertex.arn)

print("Descendant artifacts : ")
pp.pprint(descendant_artifacts)
```

**Example 可简化世系查询的 SDK 帮助程序函数**  
类 `EndpointContext`、`ModelArtifact` 和 `DatasetArtifact` 都有一些帮助程序函数，它们是 `LineageQuery` API 的包装器，可以让某些世系查询更容易利用。以下示例演示如何使用这些帮助程序函数。  

```
# Find all the datasets associated with this endpoint

datasets = []
dataset_artifacts = endpoint_context.dataset_artifacts()
for dataset in dataset_artifacts:
    datasets.append(dataset.source.source_uri)
print("Datasets : ", datasets)

# Find the training jobs associated with the endpoint
training_job_artifacts = endpoint_context.training_job_arns()
training_jobs = []
for training_job in training_job_artifacts:
    training_jobs.append(training_job)
print("Training Jobs : ", training_jobs)

# Get the ARN for the pipeline execution associated with this endpoint (if any)
pipeline_executions = endpoint_context.pipeline_execution_arn()
if pipeline_executions:
    for pipeline in pipelines_executions:
        print(pipeline)

# Here we use the `ModelArtifact` class to find all the datasets and endpoints associated with the model

dataset_artifacts = model_artifact.dataset_artifacts()
endpoint_contexts = model_artifact.endpoint_contexts()

datasets = [dataset.source.source_uri for dataset in dataset_artifacts]
endpoints = [endpoint.source.source_uri for endpoint in endpoint_contexts]

print("Datasets associated with this model : ")
pp.pprint(datasets)

print("Endpoints associated with this model : ")
pp.pprint(endpoints)

# Here we use the `DatasetArtifact` class to find all the endpoints hosting models that were trained with a particular dataset
# Find the artifact associated with the dataset

dataset_artifact_arn = list(Artifact.list(source_uri=training_data))[0].artifact_arn
dataset_artifact = DatasetArtifact.load(artifact_arn=dataset_artifact_arn)

# Find the endpoints that used this training dataset
endpoint_contexts = dataset_artifact.endpoint_contexts()
endpoints = [endpoint.source.source_uri for endpoint in endpoint_contexts]

print("Endpoints associated with the training dataset {}".format(training_data))
pp.pprint(endpoints)
```

**Example 获取世系图表可视化**  
示例笔记本 [visualizer.py](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/visualizer.py) 中提供了一个帮助程序类 `Visualizer` 来帮助绘制世系图表。呈现查询响应时，将显示一个包含 `StartArns` 世系关系的图表。从 `StartArns` 开始，可视化显示了与 `query_lineage` API 操作中返回的其他世系实体之间的关系。  

```
# Graph APIs
# Here we use the boto3 `query_lineage` API to generate the query response to plot.

from visualizer import Visualizer

query_response = sm_client.query_lineage(
    StartArns=[endpoint_context.context_arn], Direction="Ascendants", IncludeEdges=True
)

viz = Visualizer()
viz.render(query_response, "Endpoint")
        
        query_response = sm_client.query_lineage(
    StartArns=[model_artifact.artifact_arn], Direction="Ascendants", IncludeEdges=True
)
viz.render(query_response, "Model")
```

# 跟踪跨账户脉络
<a name="xaccount-lineage-tracking"></a>

Amazon SageMaker AI 支持跟踪来自不同 AWS 账户的血统实体。其他 AWS 账户可以与你共享他们的血统实体，你可以通过直接的 API 调用或 SageMaker AI 血统查询来访问这些血统实体。

SageMaker AI [AWS Resource Access Manager](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html)用来帮助您安全地共享血统资源。您可以通过 [AWS RAM 控制台](https://console.aws.amazon.com/ram/home)共享资源。



## 设置跨账户世系跟踪
<a name="setup-xaccount-lineage-tracking"></a>

您可以[世系跟踪实体](lineage-tracking-entities.md)通过 Amazon A SageMaker I 中的血统群组对自己的血统进行分组和共享。 SageMaker AI 仅支持每个账户一个默认血统组。 SageMaker 每当在您的账户中创建血统实体时，AI 都会创建默认血统组。您的账户拥有的每个世系实体都将分配给此默认世系组。要与其他账户共享世系实体，您需要与该账户共享此默认世系组。

**注意**  
您可以共享世系组中的所有世系跟踪实体，也可以不共享任何世系跟踪实体。

使用 AWS Resource Access Manager 控制台为您的世系实体创建资源共享。有关更多信息，请参阅《AWS Resource Access Manager 用户指南》**中的[共享您的 AWS 资源](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html)。

**注意**  
创建资源共享后，可能需要花几分钟时间，才能完成资源和主体关联。设置关联后，共享账户将收到加入资源共享的邀请。共享账户必须接受邀请才能访问共享资源。有关接受资源共享邀请的更多信息 AWS RAM，请参阅 [Resource Acc *ess Manager 用户指南*中的使用共享 AWS 资源](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-shared.html)。AWS 

### 您的跨账户世系跟踪资源策略
<a name="setup-xaccount-lineage-tracking-resource-policy"></a>

Amazon SageMaker AI 仅支持一种类型的资源策略。A SageMaker I 资源策略必须允许以下所有操作：

```
"sagemaker:DescribeAction"
"sagemaker:DescribeArtifact"
"sagemaker:DescribeContext"
"sagemaker:DescribeTrialComponent"
"sagemaker:AddAssociation"
"sagemaker:DeleteAssociation"
"sagemaker:QueryLineage"
```

**Example 以下是使用创建的 SageMaker AI 资源策略， AWS Resource Access Manager 用于为账户世系组创建资源共享。**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "FullLineageAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": "111122223333"
      },
      "Action": [
        "sagemaker:DescribeAction",
        "sagemaker:DescribeArtifact",
        "sagemaker:DescribeContext",
        "sagemaker:DescribeTrialComponent",
        "sagemaker:AddAssociation",
        "sagemaker:DeleteAssociation",
        "sagemaker:QueryLineage"
      ],
      "Resource": "arn:aws:sagemaker:us-west-2:111111111111:lineage-group/sagemaker-default-lineage-group"
    }
  ]
}
```

## 跟踪跨账户世系实体
<a name="tracking-lineage-xaccount"></a>

通过跨账户世系跟踪，您可以使用相同的 `AddAssociation` API 操作关联不同账户中的世系实体。当你关联两个世系实体时， SageMaker AI 会验证你是否有权对两个世系实体执行 `AddAssociation` API 操作。 SageMaker 然后，人工智能建立了该协会。如果您没有权限， SageMaker AI *不会*创建关联。建立跨账户关联后，您可以通过 `QueryLineage` API 操作从其他账户访问任一世系实体。有关更多信息，请参阅 [查询世系实体](querying-lineage-entities.md)。

除了 SageMaker AI 自动创建世系实体外，如果您拥有跨账户访问权限， SageMaker AI 还会连接引用相同对象或数据的工件。如果不同账户使用来自一个账户的数据进行血统跟踪， SageMaker AI 会在每个账户中创建一个工件来跟踪该数据。在跨账户血统中，每当 SageMaker AI 创建新工件时， SageMaker AI 都会检查是否还有其他针对相同数据创建的工件也与您共享。 SageMaker 然后，AI 在新创建的工件和与你共享的每个工件之间建立关联，`AssociationType`设置为`SameAs`。然后，您可以使用 `[QueryLineage](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_QueryLineage.html)` API 操作遍历您自己账户中的世系实体，找到与您共享但由其他 AWS 账户拥有的世系实体。有关更多信息，请参阅 [查询世系实体](querying-lineage-entities.md)。

**Topics**
+ [访问不同账户中的世系资源](#tracking-lineage-xaccount-accessing-resources)
+ [查询跨账户世系实体的授权](#tracking-lineage-xaccount-authorization)

### 访问不同账户中的世系资源
<a name="tracking-lineage-xaccount-accessing-resources"></a>

设置共享血统的跨账户访问权限后，您可以直接使用 ARN 调用以下 SageMaker API 操作来描述来自其他账户的共享血统实体：
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAction.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAction.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeArtifact.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeArtifact.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeContext.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeContext.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrialComponent.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrialComponent.html)

您还可以使用以下 SageMaker API 操作管理与您共享的不同账户所拥有的世系实体的[关联](https://docs.aws.amazon.com/sagemaker/latest/dg/lineage-tracking-entities.html)：
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AddAssociation.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AddAssociation.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DeleteAssociation.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DeleteAssociation.html)

[有关演示如何使用 SageMaker AI Lineage 跨账户查询血统的笔记本。 APIs ，请参阅 sagemaker-lineage-cross-account-with-ram.ipynb。](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/sagemaker-lineage-cross-account-with-ram.ipynb)

### 查询跨账户世系实体的授权
<a name="tracking-lineage-xaccount-authorization"></a>

Amazon SageMaker AI 必须验证您是否有权在上执行 `QueryLineage` API 操作`StartArns`。这是通过附加到 `LineageGroup` 的资源策略强制执行的。此操作的结果包括您有权访问的所有世系实体，无论这些实体归您的账户所有还是由其他账户共享。有关更多信息，请参阅 [查询世系实体](querying-lineage-entities.md)。