

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

# Trainium SageMaker 訓練任務預先訓練教學課程
<a name="sagemaker-hyperpod-trainium-sagemaker-training-jobs-pretrain-tutorial"></a>

本教學課程會引導您使用 SageMaker 訓練任務搭配 AWS Trainium 執行個體來設定和執行訓練前任務。
+ 設定您的環境
+ 啟動訓練任務

在開始前，請確定您具有以下先決條件。

**先決條件**  
開始設定環境之前，請確定您具有下列先決條件：  
Amazon FSx 檔案系統或 S3 儲存貯體，您可以在其中載入資料並輸出訓練成品。
在 Amazon SageMaker AI 上請求 `ml.trn1.32xlarge` 執行個體的服務配額。若要請求增加服務配額，請執行下列動作：  
導覽至 AWS Service Quotas 主控台。
選擇 AWS 服務。
選取 JupyterLab。
為 `ml.trn1.32xlarge` 指定一個執行個體。
使用 `AmazonSageMakerFullAccess`和 `AmazonEC2FullAccess`受管政策建立 AWS Identity and Access Management (IAM) 角色。這些政策為 Amazon SageMaker AI 提供執行範例的許可。
採用下列其中一種格式的資料：  
JSON
JSONGZ (壓縮 JSON)
ARROW
(選用) 如果您需要來自 HuggingFace 的預先訓練權重，或者如果您要訓練 Llama 3.2 模型，則您必須在開始訓練之前取得 HuggingFace 權杖。如需取得權杖的詳細資訊，請參閱[使用者存取權杖](https://huggingface.co/docs/hub/en/security-tokens)。

## 為 Trainium SageMaker 訓練任務設定您的環境
<a name="sagemaker-hyperpod-trainium-sagemaker-training-jobs-environment-setup"></a>

執行 SageMaker 訓練任務之前，請使用 `aws configure`命令來設定您的 AWS 登入資料和偏好的區域 。或者，您也可以透過 `AWS_ACCESS_KEY_ID`、`AWS_SECRET_ACCESS_KEY` 和 `AWS_SESSION_TOKEN` 等環境變數提供憑證。如需詳細資訊，請參閱 [SageMaker AI Python SDK](https://github.com/aws/sagemaker-python-sdk)。

我們強烈建議在 SageMaker AI JupyterLab 中使用 SageMaker AI Jupyter 筆記本，來啟動 SageMaker 訓練任務。如需詳細資訊，請參閱[SageMaker JupyterLab](studio-updated-jl.md)。
+ (選用) 如果您在 Amazon SageMaker Studio 中使用 Jupyter 筆記本，則可以略過執行下列命令。請務必使用版本 >= python 3.9

  ```
  # set up a virtual environment
  python3 -m venv ${PWD}/venv
  source venv/bin/activate
  # install dependencies after git clone.
  
  git clone --recursive git@github.com:aws/sagemaker-hyperpod-recipes.git
  cd sagemaker-hyperpod-recipes
  pip3 install -r requirements.txt
  ```
+ 安裝 SageMaker AI Python SDK

  ```
  pip3 install --upgrade sagemaker
  ```
+ 
  + 如果您要執行 llama 3.2 多模態訓練任務，則 `transformers` 版本必須為 `4.45.2` 或更新版本。
    + 只有在您使用 SageMaker AI Python SDK 時，才會在 source\$1dir 中將 `transformers==4.45.2` 附加至 `requirements.txt`。
    + 如果您使用要使用 `sm_jobs` 做為叢集類型來啟動的 HyperPod 配方，則不需要指定轉換器版本。
  + `Container`：SageMaker AI Python SDK 會自動設定 Neuron 容器。

## 使用 Jupyter 筆記本啟動訓練任務
<a name="sagemaker-hyperpod-trainium-sagemaker-training-jobs-launch-training-job-notebook"></a>

您可以使用下列 Python 程式碼，以使用您的配方執行 SageMaker 訓練任務。它利用來自 [SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/) 的 PyTorch 估算器來提交配方。下列範例會將 llama3-8b 配方啟動為 SageMaker AI 訓練任務。
+ `compiler_cache_url`：用來儲存編譯成品的快取，例如 Amazon S3 成品。

```
import os
import sagemaker,boto3
from sagemaker.debugger import TensorBoardOutputConfig

from sagemaker.pytorch import PyTorch

sagemaker_session = sagemaker.Session()
role = sagemaker.get_execution_role()

recipe_overrides = {
    "run": {
        "results_dir": "/opt/ml/model",
    },
    "exp_manager": {
        "explicit_log_dir": "/opt/ml/output/tensorboard",
    },
    "data": {
        "train_dir": "/opt/ml/input/data/train",
    },
    "model": {
        "model_config": "/opt/ml/input/data/train/config.json",
    },
    "compiler_cache_url": "<compiler_cache_url>"
} 

tensorboard_output_config = TensorBoardOutputConfig(
    s3_output_path=os.path.join(output, 'tensorboard'),
    container_local_output_path=overrides["exp_manager"]["explicit_log_dir"]
)

estimator = PyTorch(
    output_path=output_path,
    base_job_name=f"llama-trn",
    role=role,
    instance_type="ml.trn1.32xlarge",
    sagemaker_session=sagemaker_session,
    training_recipe="training/llama/hf_llama3_70b_seq8k_trn1x16_pretrain",
    recipe_overrides=recipe_overrides,
)

estimator.fit(inputs={"train": "your-inputs"}, wait=True)
```

上述程式碼會使用訓練配方建立 PyTorch 估算器物件，然後使用 `fit()` 方法符合模型。使用 `training_recipe` 參數來指定您要用於訓練的配方。

## 使用配方啟動器啟動訓練任務
<a name="sagemaker-hyperpod-trainium-sagemaker-training-jobs-launch-training-job-recipes"></a>
+ 更新 `./recipes_collection/cluster/sm_jobs.yaml`
  + compiler\$1cache\$1url：用來儲存成品的 URL。它可以是 Amazon S3 URL。

  ```
  sm_jobs_config:
    output_path: <s3_output_path>
    wait: True
    tensorboard_config:
      output_path: <s3_output_path>
      container_logs_path: /opt/ml/output/tensorboard  # Path to logs on the container
    wait: True  # Whether to wait for training job to finish
    inputs:  # Inputs to call fit with. Set either s3 or file_system, not both.
      s3:  # Dictionary of channel names and s3 URIs. For GPUs, use channels for train and validation.
        train: <s3_train_data_path>
        val: null
    additional_estimator_kwargs:  # All other additional args to pass to estimator. Must be int, float or string.
      max_run: 180000
      image_uri: <your_image_uri>
      enable_remote_debug: True
      py_version: py39
    recipe_overrides:
      model:
        exp_manager:
          exp_dir: <exp_dir>
        data:
          train_dir: /opt/ml/input/data/train
          val_dir: /opt/ml/input/data/val
  ```
+ 更新 `./recipes_collection/config.yaml`

  ```
  defaults:
    - _self_
    - cluster: sm_jobs
    - recipes: training/llama/hf_llama3_8b_seq8k_trn1x4_pretrain
  cluster_type: sm_jobs # bcm, bcp, k8s or sm_jobs. If bcm, k8s or sm_jobs, it must match - cluster above.
  
  instance_type: ml.trn1.32xlarge
  base_results_dir: ~/sm_job/hf_llama3_8B # Location to store the results, checkpoints and logs.
  ```
+ 使用 `main.py` 啟動任務

  ```
  python3 main.py --config-path recipes_collection --config-name config
  ```

如需設定 SageMaker 訓練任務的詳細資訊，請參閱[SageMaker 訓練任務預先訓練教學課程 (GPU)](sagemaker-hyperpod-gpu-sagemaker-training-jobs-pretrain-tutorial.md)。