

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon SageMaker 機器學習 (ML) 歷程追蹤
<a name="lineage-tracking"></a>

**重要**  
自 2023 年 11 月 30 日起，先前的 Amazon SageMaker Studio 體驗現在命名為 Amazon SageMaker Studio Classic。下節專門介紹如何使用 Studio Classic 應用程式。如需使用已更新 Studio 體驗的資訊，請參閱 [Amazon SageMaker Studio](studio-updated.md)。  
Studio Classic 仍會針對現有工作負載進行維護，但無法再用於加入。您只能停止或刪除現有的 Studio Classic 應用程式，而且無法建立新的應用程式。建議您[將工作負載遷移至新的 Studio 體驗](studio-updated-migrate.md)。

Amazon SageMaker 機器學習 (ML) 歷程追蹤會從資料準備到模型部署，建立並儲存與 ML 工作流程所有步驟相關的資訊。透過追蹤這些資訊，您可以重現工作流程步驟、追蹤模型和資料集歷程，以及建立模型控管和稽核標準。

SageMaker AI 的歷程追蹤特徵可在後端運作，以追蹤與模型訓練和部署工作流程相關聯的所有中繼資料。這包括您的訓練工作、使用的資料集、管道、端點和實際模型。您可以隨時查詢歷程服務，尋找用於訓練模型的確切成品。使用這些成品，您可以重新建立相同的機器學習 (ML) 工作流程以重製模型，只要您有權存取所使用的確切資料集。試驗元件會追蹤訓練工作。此試驗元件具有做為訓練工作一部分使用的所有參數。如果您不需要重新執行整個工作流程，您可以重製訓練工作以衍生相同的模型。

使用 SageMaker AI 歷程追蹤，資料科學家和模型建置器可以執行下列動作：
+ 保留模型發現實驗的執行歷史記錄。
+ 透過追蹤模型歷程成品來建立模型控管，以進行稽核和合規性驗證。

下圖顯示 Amazon SageMaker AI 在端對端模型訓練和部署 ML 工作流程中自動建立的範例歷程圖。

![\[\]](http://docs.aws.amazon.com/zh_tw/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>

追蹤實體會保留端對端機器學習工作流程中所有元素的表現形式。您可以使用此表現形式來建立模型控管、重現工作流程，以及維護工作歷程記錄。

在您建立 SageMaker AI 任務 (例如處理任務、訓練任務和批次轉換任務) 時，Amazon SageMaker AI 會自動為試用元件及其相關聯的試用和實驗建立追蹤實體。除了自動追蹤之外，您還可以[手動建立追蹤實體](lineage-tracking-manual-creation.md)，為工作流程中的自訂步驟建立模型。如需詳細資訊，請參閱[Studio Classic 中的 Amazon SageMaker Experiments](experiments.md)。

SageMaker AI 還會自動為工作流程中的其他步驟建立追蹤實體，以便您可以實現端對端的工作流程追蹤。如需詳細資訊，請參閱[Amazon SageMaker AI 建立的追蹤實體](lineage-tracking-auto-creation.md)。

您可以建立其他實體來補充 SageMaker AI 建立的實體。如需詳細資訊，請參閱[手動建立追蹤實體](lineage-tracking-manual-creation.md)。

SageMaker AI 會重複使用任何現有實體，而不是建立新實體。例如，只能有一個成品具有唯一的 `SourceUri`。

**查詢歷程的重要概念**
+ **歷程** - 追蹤機器學習 (ML) 工作流程中各個實體之間關係的中繼資料。
+ **查詢歷程** - 檢查歷程並探索實體之間關係的動作。
+ **歷程實體** - 組成歷程所的中繼資料元素。
+ **跨帳戶歷程** - 您的機器學習 (ML) 工作流程可能跨越多個帳戶。透過跨帳戶歷程，您可以設定多個帳戶，在共用實體資源之間自動建立歷程關聯。然後，查詢歷程甚至可以從共用帳戶傳回實體。

已定義下列追蹤實體：

**實驗實體**
+ [試用元件](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`。此屬性是自訂字串，可以將有意義的資訊與實體相關聯，並用作清單 API 中的篩選器。
+ **來源屬性**

  動作、成品和內容實體具有 `Source` 屬性。此屬性提供實體所代表的基礎 URI。部分範例如下：
  + 來源為 `EndpointArn` 的 `UpdateEndpoint` 動作。
  + 來源為 `ImageUri` 之處理工作的映像成品。
  + 來源為 `EndpointArn` 的 `Endpoint` 內容。
+ **中繼資料屬性**

  動作和成品實體具有可選的 `Metadata` 屬性，可提供下列資訊：
  + `ProjectId` – 例如，模型所屬的 SageMaker AI MLOps 專案的 ID。
  + `GeneratedBy` - 例如，註冊模型套件版本的 SageMaker AI 管道執行。
  + `Repository` - 例如，包含演算法的儲存庫。
  + `CommitId` - 例如，演算法版本的遞交 ID。

# Amazon SageMaker AI 建立的追蹤實體
<a name="lineage-tracking-auto-creation"></a>

如果資料可用，Amazon SageMaker AI 會自動為 SageMaker 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 會為每個 SageMaker AI 任務建立試用元件，並與其相關聯。SageMaker AI 會建立成品來追蹤工作中繼資料以及每個成品與任務之間的關聯。

系統會為下列任務屬性建立成品，並與 SageMaker AI 任務的 Amazon Resource Name (ARN) 相關聯。成品 `SourceUri` 會在括號中列出。

**訓練工作**
+ 包含訓練演算法的映像 (`TrainingImage`)。
+ 每個輸入通道的資料來源 (`S3Uri`)。
+ 模型的位置 (`S3OutputPath)`)。
+ 受管點檢查點資料的位置 (`S3Uri`)。

**處理工作**
+ 要由處理工作執行的容器 (`ImageUri`)。
+ 每個處理輸入和處理輸出的資料位置 (`S3Uri`)。

**轉換工作**
+ 要轉換的輸入資料來源 (`S3Uri`)。
+ 轉換的結果 (`S3OutputPath`)。

**注意**  
Amazon Simple Storage Service (Amazon S3) 成品根據提供給建立 API 的 Amazon S3 URI 值進行追蹤 (例如 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html))，而不是根據 Amazon S3 金鑰和每個檔案的雜湊值或 etag 值進行追蹤。

## 模型套件追蹤實體
<a name="lineage-tracking-auto-creation-model-package"></a>

系統會建立下列實體：

**模型套件**
+ 每個模型套件群組的內容。
+ 每個模型套件的成品。
+ 每個模型套件成品與套件所屬之每個模型套件群組之間的內容關聯。
+ 用於建立模型套件版本的動作。
+ 模型套件成品與建立動作之間的關聯。
+ 模型套件成品與套件所屬的每個模型套件群組內容之間的關聯。
+ 推論容器
  + 在模型套件中定義之每個容器中使用的映像成品。
  + 每個容器中使用的模型成品。
  + 每個成品與模型套件成品之間的關聯。
+ 演算法
  + 模型套件中定義的每個演算法的成品。
  + 每個演算法所建立之模型的成品。
  + 每個成品與模型套件成品之間的關聯。

## 端點追蹤實體
<a name="lineage-tracking-auto-creation-endpoint"></a>

下列實體由 Amazon SageMaker AI 建立：

**端點**
+ 每個端點的內容
+ 建立每個端點之模型部署的動作
+ 部署到端點的每個模型的成品
+ 模型中使用的映像成品
+ 模型之模型套件的成品
+ 部署到端點之每個模型的成品
+ 每個成品與模型部署動作之間的關聯

# 手動建立追蹤實體
<a name="lineage-tracking-manual-creation"></a>

您可以為任何屬性手動建立追蹤實體，以建立模型治理、重現工作流程，以及維護工作歷程的記錄。如需 Amazon SageMaker AI 自動建立的追蹤實體的相關資訊，請參閱 [Amazon SageMaker AI 建立的追蹤實體](lineage-tracking-auto-creation.md)。以下教學課程展示在 SageMaker 訓練任務與端點之間手動建立和關聯成品，然後追蹤工作流程所需的步驟。

您可以將標籤新增至除了關聯以外的所有實體。標籤是提供自訂資訊的任意鍵值對。您能夠依標籤對清單執行篩選或排序，或執行搜尋查詢。如需詳細資訊，請參閱《》中的[標記 AWS 資源](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)*AWS 一般參考*。

如需示範如何建立歷程實體的範例筆記本，請參閱 [Amazon SageMaker 範例 GitHub 儲存庫](https://github.com/awslabs/amazon-sagemaker-examples)中的 [Amazon SageMaker AI 歷程](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-lineage)筆記本。

**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 Resource Name (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 SageMaker AI 自動建立的歷程實體數量沒有限制。

# 查詢歷程實體
<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>

開始查詢歷程實體的最簡單方式是：
+ [Amazon SageMaker AI SDK for Python](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/lineage/artifact.py#L397)，其中定義了許多常見使用案例。
+ 如需示範如何使用 SageMaker AI 歷程 API 查詢整個歷程圖中關係的筆記本，請參閱 [sagemaker-lineage-multihop-queries.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-lineage/sagemaker-lineage-multihop-queries.ipynb)。

下列範例展示如何使用 `LineageQuery` 和 `LineageFilter` API 建構查詢，以回答有關歷程圖的問題，並擷取一些使用案例中的實體關聯。

**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>

您可以透過 Amazon SageMaker AI 中的歷程群組來分組和共用 [歷程追蹤實體](lineage-tracking-entities.md)。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，請參閱*AWS 《Resource Access Manager 使用者指南*》中的[使用共用 AWS 資源](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-shared.html)。

### 跨帳戶歷程追蹤資源政策
<a name="setup-xaccount-lineage-tracking-resource-policy"></a>

Amazon SageMaker AI 僅支援一種類型的資源政策。SageMaker AI 資源政策必須允許執行下列所有操作：

```
"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 AI 會建立關聯。如果您沒有許可，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 歷程 API 跨帳戶查詢歷程的筆記本，請參閱 [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 必須驗證您是否具有在 `StartArns` 上執行 `QueryLineage` API 動作的許可。這是透過連接至 `LineageGroup` 的資源政策來強制執行的。此動作的結果包括您可以存取所有歷程實體，無論這些實體是由您的帳戶擁有還是由其他帳戶共用。如需詳細資訊，請參閱[查詢歷程實體](querying-lineage-entities.md)。