

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

# 準備訓練任務以收集 TensorBoard 輸出資料
<a name="debugger-htb-prepare-training-job"></a>

SageMaker AI 中，機器學習的典型訓練任務包含兩個主要步驟：準備訓練指令碼和設定 SageMaker AI Python SDK 的 SageMaker AI 估算器物件。在本節中，您將了解所需的變更，以便從 SageMaker 訓練任務中收集與 TensorBoard 相容的資料。

## 先決條件
<a name="debugger-htb-prerequisites"></a>

下列清單顯示開始使用 SageMaker AI 與 TensorBoard 的先決條件。
+  AWS 帳戶中使用 Amazon VPC 設定的 SageMaker AI 網域。

  如需有關設定網域的指示，請參閱[使用快速設定佈設到 Amazon SageMaker AI 網域](https://docs.aws.amazon.com/sagemaker/latest/dg/onboard-quick-start.html)。您還需要為個別使用者新增網域使用者設定檔，才能在 SageMaker AI 上存取 TensorBoard。如需詳細資訊，請參閱[新增使用者設定檔](domain-user-profile-add.md)。
+ 下列清單是在 SageMaker AI 上使用 TensorBoard 時所需的最低許可組合。
  + `sagemaker:CreateApp`
  + `sagemaker:DeleteApp`
  + `sagemaker:DescribeTrainingJob`
  + `sagemaker:Search`
  + `s3:GetObject`
  + `s3:ListBucket`

## 步驟 1：使用開放原始碼 TensorBoard 協助程式工具修改訓練指令碼
<a name="debugger-htb-prepare-training-job-1"></a>

請確定您決定要收集哪些輸出張量和純量，並使用下列任一工具修改訓練指令碼中的程式碼：TensorBoardX、TensorFlow 摘要寫入器、PyTorch 摘要寫入器或 SageMaker Debugger。

此外，請務必將 TensorBoard 資料輸出路徑，指定為訓練容器中回調的日誌目錄 (`log_dir`)。

如需每個架構回調的更多相關資訊，請參閱下列資源。
+ PyTorch 的話，請使用[torch.utils.tensorboard.SummaryWriter](https://pytorch.org/docs/stable/tensorboard.html#module-torch.utils.tensorboard)。另請參閱*PyTorch 教學課程*內的[在 PyTorch 中使用 TensorBoard](https://pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html#using-tensorboard-in-pytorch) 和[日誌純量](https://pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html#log-scalars)章節。或者，您也可以使用 [TensorBoardX 摘要寫入器](https://tensorboardx.readthedocs.io/en/latest/tutorial.html)。

  ```
  LOG_DIR="/opt/ml/output/tensorboard"
  tensorboard_callback=torch.utils.tensorboard.writer.SummaryWriter(log_dir=LOG_DIR)
  ```
+ 針對 TensorFlow，請使用 TensorBoard 的原生回調，[tf.keras.callbacks.TensorBoard](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/TensorBoard)。

  ```
  LOG_DIR="/opt/ml/output/tensorboard"
  tensorboard_callback=tf.keras.callbacks.TensorBoard(
      log_dir=LOG_DIR, histogram_freq=1)
  ```
+ 如為 PyTorch 轉換器，您可以使用[transformers.integrations.TensorBoardCallback](https://huggingface.co/docs/transformers/main/en/main_classes/callback#transformers.integrations.TensorBoardCallback)。

  對於 TensorFlow 的轉換器，請使用`tf.keras.tensorboard.callback`，並將其傳遞給轉換器中的 keras 回調。
**提示**  
您也可以使用不同的容器本機輸出路徑。不過在 [步驟 2：使用 TensorBoard 輸出組態建立 SageMaker 訓練估算器物件](#debugger-htb-prepare-training-job-2)，您必須正確對應路徑，SageMaker AI 才能成功搜尋本機路徑，並將 TensorBoard 資料儲存至 S3 輸出儲存貯體。
+ 如需使用 SageMaker Debugger Python 程式庫修改訓練指令碼的指引，請參閱[調整您的訓練指令碼以註冊勾點](debugger-modify-script.md)。

## 步驟 2：使用 TensorBoard 輸出組態建立 SageMaker 訓練估算器物件
<a name="debugger-htb-prepare-training-job-2"></a>

在設定 SageMaker AI 架構估算器時使用 `sagemaker.debugger.TensorBoardOutputConfig`。此組態 API 會將您指定用來儲存 TensorBoard 資料的 S3 儲存貯體，與訓練容器 (`/opt/ml/output/tensorboard`) 中的本機路徑對應。將模組的物件傳遞給估算器類別的`tensorboard_output_config`參數。下列程式碼片段為一則範例，顯示使用 TensorBoard 輸出組態參數準備 TensorFlow 估算器。

**注意**  
此範例假設您使用 SageMaker Python SDK。如果您使用低階 SageMaker API，則應在 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) API 的請求語法中包含以下內容。  

```
"TensorBoardOutputConfig": { 
  "LocalPath": "/opt/ml/output/tensorboard",
  "S3OutputPath": "{{s3_output_bucket}}"
}
```

```
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import TensorBoardOutputConfig

# Set variables for training job information, 
# such as s3_out_bucket and other unique tags.
... 

LOG_DIR="/opt/ml/output/tensorboard"

output_path = os.path.join(
    "{{s3_output_bucket}}", "{{sagemaker-output}}", "{{date_str}}", "{{your-training_job_name}}"
)

tensorboard_output_config = TensorBoardOutputConfig(
    s3_output_path=os.path.join(output_path, '{{tensorboard}}'),
    container_local_output_path=LOG_DIR
)

estimator = TensorFlow(
    entry_point="{{train.py}}",
    source_dir="{{src}}",
    role={{role}},
    image_uri={{image_uri}},
    instance_count={{1}},
    instance_type="{{ml.c5.xlarge}}",
    base_job_name="{{your-training_job_name}}",
    tensorboard_output_config=tensorboard_output_config,
    hyperparameters=hyperparameters
)
```

**注意**  
TensorBoard 應用程式不提供立即可用的 SageMaker AI 超參數調校任務支援，因為 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateHyperParameterTuningJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateHyperParameterTuningJob.html) API 未與映射的 TensorBoard 輸出組態整合。若要將 TensorBoard 應用程式用於超參數調校任務，您需要在訓練指令碼中撰寫將指標上傳至 Amazon S3 的程式碼。將指標上傳至 Amazon S3 儲存貯體後，您就可以將儲存貯體載入 SageMaker AI 上的 TensorBoard 應用程式。