

# 微调 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 角色。请务必为 IAM 策略附加 `AmazonSageMakerFullAccess`。有关更多信息，请参阅[如何使用 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 数据集建议：有至少 1000 个偏好对，便于实现高效训练。高质量的偏好数据将带来更有效的结果。

### 示例
<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 天，以适应更久的训练工作负载。要请求增加限额，请参阅 [Requesting a quota increase](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_cn/nova/latest/userguide/nova-fine-tune-1.html)

DPO 数据集限制

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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 存储库中获取。下表列出了您可能会觉得有用的详细配置。

关于**“run”配置**。


|  | 键 | 定义 | Micro | 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"  | 
|  | replicas |  要在分布式训练中使用的计算实例数。  |  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_cn/nova/latest/userguide/nova-fine-tune-1.html)

### 微调特定配置（DPO）
<a name="nova-model-training-jobs-recipe-config-2"></a>

与 LoRA PEFT 和全秩 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_cn/nova/latest/userguide/nova-fine-tune-1.html)

## 在 SageMaker 训练作业中运行自定义 Nova 模型
<a name="nova-model-training-jobs-notebook"></a>

本节演示如何通过 Jupyter Notebook 环境，在 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**


| 指南 | 映像 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)。

**常见配方修改**

下面是一些基于特定使用案例的常见配方调整：
+ **对于较小的数据集（小于 1000 个示例）**

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