

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

# 微調 Nova 1.0
<a name="nova-fine-tune-1"></a>

**注意**  
您可以使用受監督微調 (SFT) 和直接偏好設定最佳化來微調 Amazon Nova 1.0 系列模型。如需微調 Nova 2.0 模型，請參閱[微調 Nova 2.0。](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-fine-tune-2.html)

## 先決條件
<a name="nova-model-training-jobs-prerequisites"></a>

開始訓練任務之前，請注意以下事項：
+ Amazon S3 儲存貯體，用於存放訓練任務的輸入資料和輸出。您可以為兩種類型的資料使用一個儲存貯體，也可以為每一種類型的資料使用個別的儲存貯體。請確定您的儲存貯體位於您建立所有其他資源以進行訓練 AWS 區域 的相同位置。如需詳細資訊，請參閱[建立一般用儲存貯體](https://docs.aws.amazon.com//AmazonS3/latest/userguide/create-bucket-overview.html)。
+ 具有執行訓練任務許可的 IAM 角色。請務必使用 `AmazonSageMakerFullAccess` 連接 IAM 政策。如需詳細資訊，請參閱[如何使用 SageMaker AI 執行角色](https://docs.aws.amazon.com//sagemaker/latest/dg/sagemaker-roles.html)。
+ 基本 Amazon Nova 配方，請參閱[取得 Amazon Nova 配方](nova-model-recipes.md#nova-model-get-recipes)。

## 資料準備
<a name="nova-model-training-prepare-data"></a>

準備高品質且格式正確的資料，是大型語言模型微調程序的重要第一步。無論您是將監督式微調 (SFT) 或直接偏好最佳化 (DPO) 搭配全秩或低秩適應 (LoRA) 方法使用，您的資料都必須遵守特定格式需求，以確保模型訓練成功。本節概述所需的資料格式、驗證方法和最佳實務，協助您有效地準備資料集，以微調 Amazon Nova 模型。

### 資料格式要求
<a name="nova-model-training-prepare-data-format"></a>

**SFT**

SFT 資料格式需求 - 對於完整排名 SFT 和 LoRA SFT，資料應遵循如下所示的格式。如需此格式的範例和限制條件，請參閱[準備資料以微調理解模型](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-prepare-data-understanding.html)。

SFT 資料驗證 - 若要在提交之前驗證資料集格式，建議您使用 [Amazon Bedrock 範例儲存庫](https://github.com/aws-samples/amazon-bedrock-samples/blob/main/custom-models/bedrock-fine-tuning/nova/understanding/dataset_validation/nova_ft_dataset_validator.py)中的以下驗證指令碼。此驗證工具有助於確保您的 `jsonl` 檔案符合所需的格式規格，並在提交微調任務之前找出任何潛在問題。

**DPO**

DPO 資料格式需求 - 對於完整排名的 DPO 和具有 LoRA 的 DPO，資料應遵循如下所示的格式。資料集也必須採用與 SFT 類似的格式，但最後一回合需要有偏好設定對。

DPO 資料集其他限制條件 - 資料集的其他限制條件與 SFT 的相同。如需詳細資訊，請參閱[資料集限制條件](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-prepare-data-understanding.html)。預計要有一個 JSONL 檔案用於訓練，並有一個 JSONL 檔案用於驗證。驗證集是選用的。

DPO 資料集建議 - 需要至少 1,000 個偏好設定對，才能得到有效的訓練。高品質偏好設定資料將產生更有效率的結果。

### 範例
<a name="nova-model-training-prepare-data-example"></a>

**範例 DPO 資料格式**

```
// N-1 turns same as SFT format
{
    "role": "assistant",
    "candidates": [
        {
            "content": [
                {
                    "text": "..."
                } // content list can contain multiple 'text' objects
            ],
            "preferenceLabel": "preferred"
        },
        {
            "content": [
                {
                    "text": "..."
                } // content list can contain multiple 'text' objects
            ],
            "preferenceLabel": "non-preferred"
        }
    ]
}
```

**範例 DPO 資料格式 (多回合)**

```
{
    "system": [
        {
            "text": "..."
        }
    ],
    "messages":[
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "assistant",
            "candidates": [
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "preferred"
                },
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "non-preferred"
                }
            ]
        }
    ],
}
```

**範例 DPO 資料格式 (含影像)**

```
{
    "system": [
        {
            "text": "..."
        }
    ],
    "messages":[
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                },
                {
                    "text": "..."
                },
                {
                    "image": {
                        "format": "jpeg",
                        "source": {
                            "s3Location": {
                                "uri": "s3://your-bucket/your-path/your-image.jpg",
                                "bucketOwner": "your-aws-account-id"
                            }
                        }
                    }
                } // "content" can have multiple "text" and "image" objects.
                 // max image count is 10
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                },
                {
                    "text": "..."
                },
                {
                    "image": {
                        "format": "jpeg",
                        "source": {
                            "s3Location": {
                                "uri": "s3://your-bucket/your-path/your-image.jpg",
                                "bucketOwner": "your-aws-account-id"
                            }
                        }
                    }
                } // "content" can have multiple "text" and "image" objects.
                 // max image count is 10
            ]
        },
        {
            "role": "assistant",
            "candidates": [
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "preferred"
                },
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "non-preferred"
                }
            ]
        }
    ],
}
```

### 資料集限制
<a name="nova-model-training-prepare-data-limits"></a>

訓練任務預設為 1 天的時間限制，但為了說明，下表中的預估值假設訓練持續時間為 5 天。最佳實務是，建議您將訓練時間限制延長為上限 28 天，以因應較長的訓練工作負載。若要請求增加限制，請參閱[請求增加配額](https://docs.aws.amazon.com//servicequotas/latest/userguide/request-quota-increase.html)。

**SFT 資料集限制**

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/nova/latest/userguide/nova-fine-tune-1.html)

DPO 資料集限制

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/nova/latest/userguide/nova-fine-tune-1.html)

透過減少 epoch 的數量或記錄的內容長度，您可以提供更多記錄。

## 全秩 SFT 和 LoRA PEFT 組態
<a name="nova-model-training-jobs-recipe-config"></a>

本節涵蓋全秩監督式微調 (SFT) 和低秩適應參數效率微調 (LoRA PEFT) 方法的配方組態指導方針。這些配方檔案可做為模型自訂任務的藍圖，讓您指定訓練參數、超參數和其他關鍵設定，以決定模型如何從資料中學習。若要調整超參數，請依照[選取超參數](https://docs.aws.amazon.com//nova/latest/userguide/customize-fine-tune-hyperparameters.html)中的指導方針。

### 微調組態 (全秩 SFT 和 LoRA PEFT)
<a name="nova-model-training-jobs-recipe-config-1"></a>

就配方而論，全秩 SFT 和 LoRA PEFT 的唯一差別是 LoRA PEFT 組態，如果是全秩則設為 'null'，如果使用 LoRA PEFT 型微調則設為適當的值。範例配方可在[配方](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes) GitHub 儲存庫中使用。下表顯示您可能會覺得有用的詳細組態。

關於**「執行」組態**。


|  | 金錀 | 定義 | 微型 | Lite | pro | 
| --- | --- | --- | --- | --- | --- | 
| 執行組態 | model\$1type |  指定要使用的 Nova 模型變體。請勿修改此欄位。  |  "amazon.nova-micro-v1:0:128k"  |  "amazon.nova-lite-v1:0:300k"  |  "amazon.nova-pro-v1:0:300k"  | 
|  | model\$1name\$1or\$1path |  基本模型的路徑。  |  "nova-micro/prod"  |  "nova-lite/prod"  |  "nova-pro/prod"  | 
|  | 複本 |  分散式訓練中要使用的運算執行個體數目。  |  2。4 或 8  |  4、8 或 16  |  6、12 或 24  | 

關於 **“training\$1config” 組態**。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/nova/latest/userguide/nova-fine-tune-1.html)

### 微調特定組態 (DPO)
<a name="nova-model-training-jobs-recipe-config-2"></a>

與 LoRA PEFT 和 FullRank SFT 相比，直接偏好最佳化 (DPO) 的唯一差別在於 dpo\$1cfg 組態與允許的值。請參閱下表以了解特別針對 DPO 允許的範例。範例配方可在[配方](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes) GitHub 儲存庫中使用。下表提供您可能會覺得有幫助的詳細組態。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/nova/latest/userguide/nova-fine-tune-1.html)

## 在 SageMaker 訓練任務上執行自訂的 Nova 模型
<a name="nova-model-training-jobs-notebook"></a>

本節示範如何透過 Jupyter 筆記本環境在 SageMaker 訓練任務上執行自訂的 Nova 模型。您可以找到完整的範例，其中逐步說明設定和啟動訓練任務的程序，並提供參考表以用於選取適當容器映像 URI 和執行個體組態。此方法可讓您以程式設計方式控制微調工作流程，同時利用 SageMaker AI 的受管基礎設施進行模型自訂。如需詳細資訊，請參閱[使用 SageMaker AI 估算器執行訓練任務](https://docs.aws.amazon.com//sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry-estimator.html)。

### 參考表
<a name="nova-model-training-jobs-reference-table"></a>

在執行範例筆記本之前，請參閱下表以選取適當的容器映像 URI 和執行個體組態。

**選取映像 URI**


| Recipe | 映像 URI | 
| --- | --- | 
|  SFT 映像 URI  | 708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-SFT-latest | 
|  DPO 映像 URI  | 708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-DPO-latest | 

**選取執行個體類型和計數**


| 模型 | 微調任務類型 | 技術類型 | 執行個體類型 | 建議的執行個體計數 | 允許的執行個體計數 | 
| --- | --- | --- | --- | --- | --- | 
| Amazon Nova Micro | SFT | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1完整排名 | g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  |  | p4d.24xlarge | 2 | 2、4、8 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 1 | 1、2、4、8 | 
|  | DPO | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1完整排名 | p4d.24xlarge, p5.48xlarge, p5en.48xlarge | 2 | 2、4、8 | 
| Amazon Nova Lite | SFT | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 1 | 1、4、8、16 | 
|  |  | LoRA\$1完整排名 | p4d.24xlarge | 4 | 4、8、16 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 2 | 2、4、8、16 | 
|  | DPO | LoRA | g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1完整排名 | p4d.24xlarge, p5.48xlarge, p5en.48xlarge | 4 | 4、8、16 | 
| Amazon Nova Pro | SFT | LoRA | p4d.24xlarge | 6 | 6、12、24 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 3 | 3、6、12、24 | 
|  |  | LoRA\$1完整排名 | p5.48xlarge, p5en.48xlarge | 6 | 6、12、24 | 
|  | DPO | LoRA | p4d.24xlarge | 6 | 6、12、24 | 
|  |  | LoRA\$1完整排名 | p4d.24xlarge | 12 | 12、24 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 4 | 4、8、16 | 

### 範例筆記本
<a name="nova-model-training-jobs-notebook"></a>

下列範例筆記本示範如何執行訓練任務。如需如何使用 SageMaker 訓練任務自訂 Nova 模型的其他入門筆記本，請參閱[使用 SageMaker AI 估算器來執行訓練任務](https://docs.aws.amazon.com//sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry-estimator.html)。

```
# 1. Install dependencies

!pip install sagemaker==2.254.1

# 2. Import dependencies and initialize sagemaker session

import sagemaker,boto3

sm = boto3.client('sagemaker', region_name='us-east-1')
sagemaker_session = sagemaker.session.Session(boto_session=boto3.session.Session(), sagemaker_client=sm)

# 3. Configure your job
# Define the core configuration for launching a SageMaker Training Job. This includes input/output S3 URIs, container image, hardware setup, and other runtime parameters. Update the placeholders below before submitting the job.

job_name = "<Your Job Name>"

input_s3_uri = "<S3 path to input data>"
validation_s3_uri = "<S3 path to validation data>" # optional, leave blank if no validation data

output_s3_uri = "<S3 path to output location>"

image_uri = "<Image URI from documentation>" # you can choose the image for SFT/DPO
instance_type = "ml.p5.48xlarge" # do not change
instance_count = <Integer number of hosts> # change hosts as needed. Refer to documentation for allowed values based on model type.
role_arn = "<IAM Role you want to use to run the job>"
recipe_path = "<Local path to the recipe file>"
output_kms_key = "<KMS key arn to encrypt trained model in Amazon-owned S3 bucket>" # optional, leave blank for Amazon managed encryption

# 4. Launch SageMaker Training Job
# This block sets up and runs the SageMaker training job using the PyTorch estimator. It configures the training image, hardware, input channels, and TensorBoard integration. Validation data is included if provided.

from sagemaker.debugger import TensorBoardOutputConfig
from sagemaker.pytorch import PyTorch
from sagemaker.inputs import TrainingInput

tensorboard_output_config = TensorBoardOutputConfig(
    s3_output_path=output_s3_uri,
)

estimator = PyTorch(
    output_path=output_s3_uri,
    base_job_name=job_name,
    role=role_arn,
    instance_count=instance_count,
    instance_type=instance_type,
    training_recipe=recipe_path,
    sagemaker_session=sagemaker_session,
    image_uri=image_uri,
    tensorboard_output_config=tensorboard_output_config, # Add the setting for using TensorBoard.
    disable_profiler=True,
    debugger_hook_config=False,
    output_kms_key=output_kms_key
)

trainingInput = TrainingInput(
    s3_data=input_s3_uri,
    distribution='FullyReplicated',
    s3_data_type='Converse'
)

if (validation_s3_uri):
    validationInput = TrainingInput(
        s3_data=validation_s3_uri,
        distribution='FullyReplicated',
        s3_data_type='Converse'
    )

    estimator.fit(inputs={"train": trainingInput, "validation": validationInput}) # inputs must be called "train" and "validation", do not change
else:
    estimator.fit(inputs={"train": trainingInput})
```

## 超參數最佳化指導方針
<a name="nova-model-hyperparameter"></a>

要有效地微調 Nova LLM 模型，需要仔細選擇超參數。雖然本節說明了基本的配方結構和元件，但針對特定使用案例最佳化超參數通常需要額外的指導方針。如需選取超參數、最佳實務和最佳化策略的完整建議，請參閱[選取超參數](https://docs.aws.amazon.com//nova/latest/userguide/customize-fine-tune-hyperparameters.html)。此資源提供詳細的指導方針，可供根據您的資料集特性和訓練目標，選擇適當的學習率、批次大小、訓練 epoch 和其他關鍵參數。建議您在微調配方組態時參閱本指南，以獲得最佳模型效能。

如需 epoch、學習率和學習暖機步驟的最小值、最大值和預設值等詳細資訊，請參閱[理解模型的超參數](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-hyperparameters-understanding-models.html)。

**常見的配方修改**

以下是一些根據特定使用案例常見的配方調整：
+ **對於較小的資料集 (< 1,000 個範例)**

  ```
  training_config:
      max_epochs: 2  # More passes through a smaller dataset
  model:
      hidden_dropout: 0.1  # Increase regularization
      weight_decay: 0.01   # Increase regularization
  ```
+ **對於以有限的運算提高效率**

  ```
  peft:
      peft_scheme: "lora"
      lora_tuning:
  ```
+ **對於複雜的指令調整**

  ```
  optim:
      lr: 5e-6  # Lower learning rate for more stable learning
      sched:
          warmup_steps: 100  # Longer warmup for stability
  ```