

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

# 開啟步驟快取
<a name="pipelines-caching-enabling"></a>

若要開啟步驟快取，您必須將 `CacheConfig` 屬性新增至步驟定義。`CacheConfig` 屬性會在管道定義檔案中使用以下格式：

```
{
    "CacheConfig": {
        "Enabled": false,
        "ExpireAfter": "<time>"
    }
}
```

`Enabled` 欄位會指出是否針對特定步驟開啟了快取。您可以將欄位設定為 `true`，這會告訴 SageMaker AI 嘗試尋找先前執行且具有相同屬性的步驟。或者，您可以將欄位設定為 `false`，這會告訴 SageMaker AI 在每次管道執行時執行步驟。`ExpireAfter` 是 [ISO 8601 持續時間](https://en.wikipedia.org/wiki/ISO_8601#Durations)格式中定義逾時期間的字串。`ExpireAfter` 持續時間可以是年、月、週、日、小時或分鐘值。每個值由一個數字組成，後跟一個表示持續時間單位的字母。例如：
+ “30d” = 30 天
+ “5y” = 5 年
+ “T16m” = 16 分鐘
+ “30dT5h” = 30 天 5 小時。

以下討論說明使用 Amazon SageMaker Python SDK 為新管道或既有管道開啟快取的程序。

**為新管道開啟快取**

對於新管道，請使用 `enable_caching=True` 初始化 `CacheConfig` 執行個體，並將其作為管道步驟輸入提供。下列範例會為訓練步驟開啟逾時時間為 1 小時的快取：

```
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.workflow.steps import CacheConfig
      
cache_config = CacheConfig(enable_caching=True, expire_after="PT1H")
estimator = Estimator(..., sagemaker_session=PipelineSession())

step_train = TrainingStep(
    name="TrainAbaloneModel",
    step_args=estimator.fit(inputs=inputs),
    cache_config=cache_config
)
```

**為既有的管道開啟快取**

若要為既有、已定義之管道開啟快取，請開啟步驟的 `enable_caching` 屬性，並將 `expire_after` 設定為逾時值。最後，使用 `pipeline.upsert()` 或 `pipeline.update()` 更新管道。再次執行後，下列程式碼範例會為訓練步驟開啟逾時時間為 1 小時的快取：

```
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.workflow.steps import CacheConfig
from sagemaker.workflow.pipeline import Pipeline

cache_config = CacheConfig(enable_caching=True, expire_after="PT1H")
estimator = Estimator(..., sagemaker_session=PipelineSession())

step_train = TrainingStep(
    name="TrainAbaloneModel",
    step_args=estimator.fit(inputs=inputs),
    cache_config=cache_config
)

# define pipeline
pipeline = Pipeline(
    steps=[step_train]
)

# additional step for existing pipelines
pipeline.update()
# or, call upsert() to update the pipeline
# pipeline.upsert()
```

或者，在定義 (既有) 管道之後更新快取組態，允許一次持續的程式碼執行。下列程式碼範例會示範此方法：

```
# turn on caching with timeout period of one hour
pipeline.steps[0].cache_config.enable_caching = True 
pipeline.steps[0].cache_config.expire_after = "PT1H" 

# additional step for existing pipelines
pipeline.update()
# or, call upsert() to update the pipeline
# pipeline.upsert()
```

如需有關 Python SDK 參數如何影響快取的詳細程式碼範例和討論，請參閱 Amazon SageMaker Python SDK 文件中的 [Caching Configuration](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#caching-configuration)。