

# Amazon Nova 模型训练
<a name="smtj-training"></a>

通过 SageMaker 训练作业对 Amazon Nova 模型进行训练，支持监督式微调（SFT）与强化微调（RFT）。每种技术适用于不同的自定义需求，并可应用于不同版本的 Amazon Nova 模型。

**Topics**
+ [微调 Nova 2.0](nova-fine-tune-2.md)
+ [使用 Amazon Nova 模型进行强化微调（RFT）](nova-reinforcement-fine-tuning.md)

# 微调 Nova 2.0
<a name="nova-fine-tune-2"></a>

## 先决条件
<a name="nova-model-training-jobs-prerequisites2"></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)。

## 什么是 SFT？
<a name="nova-2-what-is-sft"></a>

监督式微调（SFT）使用带标注的输入-输出对训练语言模型。模型从包含提示和响应的示范示例中学习，优化能力以适配特定任务、指令或预期行为。

## 数据准备
<a name="nova-2-data-preparation"></a>

### 概述
<a name="nova-2-data-overview"></a>

Nova 2.0 SFT 数据采用与 Nova 1.0 相同的 Converse API 格式，并新增了可选的推理内容字段。如需完整格式规范，请参阅：
+ 推理内容：[ReasoningContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ReasoningContentBlock.html)
+ Converse API 架构：[Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference-call.html)
+ 数据集约束：[数据集约束](https://docs.aws.amazon.com/nova/latest/userguide/fine-tune-prepare-data-understanding.html)

### 支持的功能
<a name="nova-2-supported-features"></a>
+ **输入类型**：用户内容块中的文本、图像或视频
+ **助手内容**：纯文本响应和推理内容
+ **数据集构成**：必须为同构数据。选择如下选项之一：
  + 纯文本轮次
  + 文本 \$1 图像轮次
  + 文本 \$1 视频轮次（支持文档理解）

**重要**  
不得在同一数据集中或不同对话轮次间混合使用图像和视频。

### 目前的局限性
<a name="nova-2-current-limitations"></a>
+ **多模态推理内容**：虽然 Converse 格式支持基于图像的推理内容，但 Nova 2.0 SFT 仅支持 reasoningText 字段中基于文本的推理内容。
+ **验证集**：Nova 2.0 的 SFT 训练不支持提供验证数据集。若传入验证数据集，训练过程中将被忽略。该限制同时适用于基于 UI 提交和程序化提交的训练作业。

### 支持的媒体格式
<a name="nova-2-supported-media"></a>
+ **图像**：PNG、JPEG、GIF
+ **视频**：MOV、MKV、MP4

### 数据格式示例
<a name="nova-2-data-examples"></a>

------
#### [ Text-only (Nova 1.0 compatible) ]

```
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "system": [  
    {  
      "text": "You are a digital assistant with a friendly personality"  
    }  
  ],  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "text": "What country is right next to Australia?"  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "text": "The closest country is New Zealand"  
        }  
      ]  
    }  
  ]  
}
```

------
#### [ Text with reasoning (Nova 2.0) ]

```
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "system": [  
    {  
      "text": "You are a digital assistant with a friendly personality"  
    }  
  ],  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "text": "What country is right next to Australia?"  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "reasoningContent": {  
            "reasoningText": {  
              "text": "I need to use my world knowledge of geography to answer this question"  
            }  
          }  
        },  
        {  
          "text": "The closest country to Australia is New Zealand, located to the southeast across the Tasman Sea."  
        }  
      ]  
    }  
  ]  
}
```

------
#### [ Image \$1 text input ]

```
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "system": [  
    {  
      "text": "You are a helpful assistant."  
    }  
  ],  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "image": {  
            "format": "jpeg",  
            "source": {  
              "s3Location": {  
                "uri": "s3://your-bucket/your-path/your-image.jpg",  
                "bucketOwner": "your-aws-account-id"  
              }  
            }  
          }  
        },  
        {  
          "text": "Which country is highlighted in the image?"  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "reasoningContent": {  
            "reasoningText": {  
              "text": "I will determine the highlighted country by examining its location on the map and using my geographical knowledge"  
            }  
          }  
        },  
        {  
          "text": "The highlighted country is New Zealand"  
        }  
      ]  
    }  
  ]  
}
```

------
#### [ Video \$1 text input ]

```
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "system": [  
    {  
      "text": "You are a helpful assistant."  
    }  
  ],  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "video": {  
            "format": "mp4",  
            "source": {  
              "s3Location": {  
                "uri": "s3://your-bucket/your-path/your-video.mp4",  
                "bucketOwner": "your-aws-account-id"  
              }  
            }  
          }  
        },  
        {  
          "text": "What is shown in this video?"  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "reasoningContent": {  
            "reasoningText": {  
              "text": "I will analyze the video content to identify key elements"  
            }  
          }  
        },  
        {  
          "text": "The video shows a map with New Zealand highlighted"  
        }  
      ]  
    }  
  ]  
}
```

------

## 工具调用
<a name="nova-2-tool-calling"></a>

Nova 2.0 SFT 支持基于工具调用模式进行模型训练，使模型能够学习何时以及如何调用外部工具或函数。

### 工具调用的数据格式
<a name="nova-2-tool-calling-format"></a>

工具调用训练数据包含用于定义可用工具的 `toolConfig` 部分，以及展示工具使用模式的对话轮次内容。

**示例输入**

```
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "system": [  
    {  
      "text": "You are an expert in composing function calls."  
    }  
  ],  
  "toolConfig": {  
    "tools": [  
      {  
        "toolSpec": {  
          "name": "getItemCost",  
          "description": "Retrieve the cost of an item from the catalog",  
          "inputSchema": {  
            "json": {  
              "type": "object",  
              "properties": {  
                "item_name": {  
                  "type": "string",  
                  "description": "The name of the item to retrieve cost for"  
                },  
                "item_id": {  
                  "type": "string",  
                  "description": "The ASIN of item to retrieve cost for"  
                }  
              },  
              "required": [  
                "item_id"  
              ]  
            }  
          }  
        }  
      },  
      {  
        "toolSpec": {  
          "name": "getItemAvailability",  
          "description": "Retrieve whether an item is available in a given location",  
          "inputSchema": {  
            "json": {  
              "type": "object",  
              "properties": {  
                "zipcode": {  
                  "type": "string",  
                  "description": "The zipcode of the location to check in"  
                },  
                "quantity": {  
                  "type": "integer",  
                  "description": "The number of items to check availability for"  
                },  
                "item_id": {  
                  "type": "string",  
                  "description": "The ASIN of item to check availability for"  
                }  
              },  
              "required": [  
                "item_id", "zipcode"  
              ]  
            }  
          }  
        }  
      }  
    ]  
  },  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "text": "I need to check whether there are twenty pieces of the following item available. Here is the item ASIN on Amazon: id-123. Please check for the zipcode 94086"  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "reasoningContent": {  
            "reasoningText": {  
              "text": "The user wants to check how many pieces of the item with ASIN id-123 are available in the zipcode 94086"  
            }  
          }  
        },  
        {  
          "toolUse": {  
            "toolUseId": "getItemAvailability_0",  
            "name": "getItemAvailability",  
            "input": {  
              "zipcode": "94086",  
              "quantity": 20,  
              "item_id": "id-123"  
            }  
          }  
        }  
      ]  
    },  
    {  
      "role": "user",  
      "content": [  
        {  
          "toolResult": {  
            "toolUseId": "getItemAvailability_0",  
            "content": [  
              {  
                "text": "[{\"name\": \"getItemAvailability\", \"results\": {\"availability\": true}}]"  
              }  
            ]  
          }  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {  
          "text": "Yes, there are twenty pieces of item id-123 available at 94086. Would you like to place an order or know the total cost?"  
        }  
      ]  
    }  
  ]  
}
```

### 工具调用要求
<a name="nova-2-tool-calling-requirements"></a>

创建工具调用训练数据时，请遵循以下要求：


| 要求 | 说明 | 
| --- | --- | 
| ToolUse 放置 | ToolUse 只能出现在助手轮次中 | 
| ToolResult 放置 | ToolResult 只能出现在用户轮次中 | 
| ToolResult 格式 | ToolResult 只能为文本或 JSON。Nova 模型不支持其他模态 | 
| inputSchema 格式 | toolSpec 中的 inputSchema 必须是有效的 JSON 架构对象 | 
| toolUseId 匹配 | 每个 ToolResult 必须引用前序助手轮次 ToolUse 中的有效 toolUseId，且每个 toolUseId 在单次对话中仅可使用一次 | 

### 重要提示
<a name="nova-2-tool-calling-notes"></a>
+ 确保工具定义在所有训练样本中保持一致
+ 模型将从所提供的示例中学习工具调用模式
+ 包含各类场景示例，明确各工具的适用与不适用情况

## 文档理解
<a name="nova-2-document-understanding"></a>

Nova 2.0 SFT 支持基于文档任务的训练，使模型能够学习如何分析并回答与 PDF 文档相关的问题。

### 文档理解数据格式
<a name="nova-2-document-format"></a>

文档理解训练数据在用户内容块中包含文档引用，模型将学习对文档内容进行提取与推理。

**示例输入**

```
{  
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "text": "What are the ways in which a customer can experience issues during checkout on Amazon?"  
        },  
        {  
          "document": {  
            "format": "pdf",  
            "source": {  
              "s3Location": {  
                "uri": "s3://my-bucket-name/path/to/documents/customer_service_debugging.pdf",  
                "bucketOwner": "123456789012"  
              }  
            }  
          }  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {
          "reasoningContent": {  
            "reasoningText": {  
              "text": "I need to find the relevant section in the document to answer the question."  
            }  
          }
        },
        {  
          "text": "Customers can experience issues with 1. Data entry, 2. Payment methods, 3. Connectivity while placing the order. Which one would you like to dive into?"  
        }   
      ]
    }  
  ]  
}
}
```

### 文档理解限制
<a name="nova-2-document-limitations"></a>


| 限制 | Details | 
| --- | --- | 
| 支持的格式 | 仅支持 PDF 文件 | 
| 最大文档大小 | 10 MB | 
| 模态混合 | 单个样本可包含文档与文本，但不可将文档与其他模态（图像、视频）混用 | 

### 文档理解最佳实践
<a name="nova-2-document-best-practices"></a>
+ 确保文档格式清晰，文本可正常提取
+ 提供覆盖不同文档类型与问题格式的多样化样本
+ 包含推理内容，帮助模型学习文档分析模式

## 视频理解
<a name="nova-2-video-understanding"></a>

Nova 2.0 SFT 支持基于视频任务的训练，使模型能够学习如何分析并回答与视频内容相关的问题。

### 视频理解数据格式
<a name="nova-2-video-format"></a>

视频理解训练数据在用户内容块中包含视频引用，模型将学习从视频内容中提取信息并进行推理。

**示例输入**

```
  
{  
  "schemaVersion": "bedrock-conversation-2024",  
  "messages": [  
    {  
      "role": "user",  
      "content": [  
        {  
          "text": "What are the ways in which a customer can experience issues during checkout on Amazon?"  
        },  
        {  
          "video": {  
            "format": "mp4",  
            "source": {  
              "s3Location": {  
                "uri": "s3://my-bucket-name/path/to/videos/customer_service_debugging.mp4",  
                "bucketOwner": "123456789012"  
              }  
            }  
          }  
        }  
      ]  
    },  
    {  
      "role": "assistant",  
      "content": [  
        {
          "reasoningContent": {  
            "reasoningText": {  
              "text": "I need to find the relevant section in the video to answer the question."  
            }  
          }
        },
        {  
          "text": "Customers can experience issues with 1. Data entry, 2. Payment methods, 3. Connectivity while placing the order. Which one would you like to dive into?"  
        }   
      ]  
    }  
  ]  
}
```

### 视频理解限制
<a name="nova-2-video-limitations"></a>


| 限制 | Details | 
| --- | --- | 
| 最大视频大小 | 50 MB | 
| 视频最长时长 | 15 分钟 | 
| 单个样本视频数量 | 每个样本仅允许包含一个视频，不支持在同一样本中使用多个视频 | 
| 模态混合 | 单个样本可包含视频与文本，但不可将视频与其他模态（图像、文档）混用 | 

### 支持的视频格式
<a name="nova-2-video-formats"></a>
+ MOV
+ MKV
+ MP4

### 视频理解最佳实践
<a name="nova-2-video-best-practices"></a>
+ 保持视频简洁明了，聚焦与任务相关的内容
+ 确保视频画质清晰，便于模型提取有效信息
+ 提出的问题应明确指向视频中的特定内容
+ 提供覆盖不同视频类型与问题格式的多样化样本

## 推理模式与非推理模式
<a name="nova-2-reasoning-modes"></a>

### 理解推理内容
<a name="nova-2-understanding-reasoning"></a>

推理内容（亦称思维链）会记录模型在生成最终答案前的中间思考步骤。在 `assistant` 轮次中，可通过 `reasoningContent` 字段加入这些推理轨迹。

**损失计算方式**
+ **包含推理内容**：训练损失同时计入推理词元和最终输出词元
+ **不含推理内容**：训练损失仅基于最终输出词元计算

您可在多轮对话的多个助手轮次中添加 `reasoningContent`。

**格式规范**
+ 推理内容使用纯文本
+ 除非任务明确要求，否则避免使用 `<thinking>` 和 `</thinking>` 等标记标签
+ 确保推理内容清晰，并与问题求解过程相关

### 何时启用推理模式
<a name="nova-2-when-enable-reasoning"></a>

在以下场景中，在训练配置里设置 `reasoning_enabled: true`：
+ 训练数据包含推理词元
+ 希望模型在生成最终输出前先产生思考词元
+ 需要在复杂推理任务上获得更优性能

允许在 `reasoning_enabled = true` 的情况下，使用非推理数据集训练 Nova。但是，这样做可能会导致模型丧失推理能力，因为 Nova 主要学习数据中呈现的应答方式，而非执行推理过程。如果希望使用非推理数据集训练，同时在推理阶段保留推理能力，则可在训练时关闭推理 (`reasoning_enabled = false`)，并在推理时启用。这种方式虽能在推理时使用推理，但无法保证效果优于不启用推理的推理方式。一般建议：使用推理数据集时，训练与推理均启用推理；使用非推理数据集时，两者均关闭推理。

在以下场景中，设置 `reasoning_enabled: false`：
+ 训练数据不包含推理词元
+ 训练任务较为简单，无需显式推理步骤
+ 希望优化速度并减少词元使用量

### 生成推理数据
<a name="nova-2-generating-reasoning"></a>

如果数据集缺失推理轨迹，可借助 Nova Premier 等具备推理能力的模型来生成。将输入-输出对提供给模型，记录其推理过程，从而构建包含推理内容的增强型数据集。

### 使用推理词元进行训练
<a name="nova-2-using-reasoning-training"></a>

启用推理模式进行训练时，模型会学习将内部推理过程与最终答案分离开。训练过程：
+ 将数据组织为三元组结构：输入、推理和答案
+ 基于推理词元和答案词元的标准下一词元预测损失进行优化
+ 引导模型在生成回复前先进行内部逻辑推理

### 优质推理内容的要素
<a name="nova-2-effective-reasoning"></a>

高质量的推理内容应包含以下要素：
+ 中间思考与分析
+ 逻辑推导与推理步骤
+ 分步解决问题的方法
+ 推理步骤与结论之间的明确关联

这些要素有助于模型掌握“先思考，后作答”的能力。

## 数据集准备指南
<a name="nova-2-dataset-preparation"></a>

### 规模与质量
<a name="nova-2-size-quality"></a>
+ **推荐样本量**：2000 – 10000 个样本
+ **最小样本量**：200
+ **优先级**：质量胜于数量。确保样本准确、标注规范
+ **应用贴合度**：数据集应尽可能贴近实际使用案例

### 多样性
<a name="nova-2-diversity"></a>

样本需具备多样性，满足以下要求：
+ 覆盖所有预期输入类型
+ 包含不同难度级别的样本
+ 纳入边界情况与各类变体
+ 避免模型过拟合于单一模式

### 输出格式
<a name="nova-2-output-formatting"></a>

在助手响应中明确指定所需输出格式：
+ JSON 结构
+ 表
+ CSV 格式
+ 应用程序专属的自定义格式

### 多回合对话
<a name="nova-2-multi-turn"></a>

使用多轮对话数据集时请注意：
+ 损失仅基于助手轮次计算，而非用户轮次
+ 每个助手响应都应格式正确
+ 保持各轮对话风格与格式一致

### 质量检查清单
<a name="nova-2-quality-checklist"></a>
+ 数据集规模充足（2000 – 10000 个样本）
+ 涵盖所有使用案例的多样化样本
+ 输出格式清晰统一
+ 标签与标注准确无误
+ 贴合实际生产场景
+ 无矛盾或歧义内容

### 上传数据
<a name="nova-2-uploading-data"></a>

数据集需上传到 SageMaker 训练作业可访问的存储桶。有关设置相应权限的信息，请参阅[先决条件](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model-general-prerequisites.html)。

## 启动训练作业
<a name="nova-2-starting-training"></a>

### 选择超参数并更新配方
<a name="nova-2-selecting-hyperparameters"></a>

Nova 2.0 的设置方式与 Nova 1.0 基本一致。将输入数据上传到 S3 后，使用 [SageMaker HyperPod Recipes](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes/fine-tuning/nova) 中 fine-tuning 文件夹下的配方。对于 Nova 2.0，以下是一些可以根据使用案例更新的关键超参数。以下是 Nova 2.0 SFT PEFT 配方的样本。对于容器映像 URI，请使用 `708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-SFT-V2-latest` 来运行 SFT 微调作业。

请使用 v2.254.1 版本的 SageMaker AI PySDK，确保与 Nova 训练严格兼容。将 SDK 升级到 v3.0 版本会导致破坏性变更。对 SageMaker AI PySDK v3 的支持即将推出。

**示例输入**

```
!pip install sagemaker==2.254.1
```

```
run:  
  name: {peft_recipe_job_name}  
  model_type: amazon.nova-2-lite-v1:0:256k  
  model_name_or_path: {peft_model_name_or_path}  
  data_s3_path: {train_dataset_s3_path} # SageMaker HyperPod (SMHP) only and not compatible with SageMaker Training jobs. Note replace my-bucket-name with your real bucket name for SMHP job  
  replicas: 4                      # Number of compute instances for training, allowed values are 4, 8, 16, 32  
  output_s3_path: ""               # Output artifact path (Hyperpod job-specific; not compatible with standard SageMaker Training jobs). Note replace my-bucket-name with your real bucket name for SMHP job  
  
training_config:  
  max_steps: 10                   # Maximum training steps. Minimal is 4.  
  save_steps: 10                      # How many training steps the checkpoint will be saved. Should be less than or equal to max_steps  
  save_top_k: 1                    # Keep top K best checkpoints. Note supported only for SageMaker HyperPod jobs. Minimal is 1.  
  max_length: 32768                # Sequence length (options: 8192, 16384, 32768 [default], 65536)  
  global_batch_size: 32            # Global batch size (options: 32, 64, 128)  
  reasoning_enabled: true          # If data has reasoningContent, set to true; otherwise False  
  
  lr_scheduler:  
    warmup_steps: 15               # Learning rate warmup steps. Recommend 15% of max_steps  
    min_lr: 1e-6                   # Minimum learning rate, must be between 0.0 and 1.0  
  
  optim_config:                    # Optimizer settings  
    lr: 1e-5                       # Learning rate, must be between 0.0 and 1.0  
    weight_decay: 0.0              # L2 regularization strength, must be between 0.0 and 1.0  
    adam_beta1: 0.9                # Exponential decay rate for first-moment estimates, must be between 0.0 and 1.0  
    adam_beta2: 0.95               # Exponential decay rate for second-moment estimates, must be between 0.0 and 1.0  
  
  peft:                            # Parameter-efficient fine-tuning (LoRA)  
    peft_scheme: "lora"            # Enable LoRA for PEFT  
    lora_tuning:  
      alpha: 64                    # Scaling factor for LoRA weights ( options: 32, 64, 96, 128, 160, 192),  
      lora_plus_lr_ratio: 64.0
```

该配方包含的超参数与 Nova 1.0 基本一致。核心超参数如下：
+ `max_steps`：希望作业运行的步数。通常，1 轮 epoch（遍历完整数据集一次）的计算方式为：步数 = 数据样本数/全局批次大小。步数越大、全局批次越小，任务运行耗时越长。
+ `reasoning_enabled`：控制数据集的推理模式。选项：
  + `true`：启用推理模式（相当于高强度推理）
  + `false`：禁用推理模式

  注意：在 SFT 中，无法精细控制推理强度。设置 `reasoning_enabled: true` 即启用完整推理能力。
+ `peft.peft_scheme`：设置为“lora”即启用基于 PEFT 的微调。设置为 null（不带引号）即启用全秩微调。

### 启动训练作业
<a name="nova-2-start-job"></a>

```
from sagemaker.pytorch import PyTorch  
  
# define OutputDataConfig path  
if default_prefix:  
    output_path = f"s3://{bucket_name}/{default_prefix}/{sm_training_job_name}"  
else:  
    output_path = f"s3://{bucket_name}/{sm_training_job_name}"  

output_kms_key = "<KMS key arn to encrypt trained model in Amazon-owned S3 bucket>" # optional, leave blank for Amazon managed encryption
  
recipe_overrides = {  
    "run": {  
        "replicas": instance_count,  # Required  
        "output_s3_path": output_path  
    },  
}  
  
estimator = PyTorch(  
    output_path=output_path,  
    base_job_name=sm_training_job_name,  
    role=role,  
    disable_profiler=True,  
    debugger_hook_config=False,  
    instance_count=instance_count,  
    instance_type=instance_type,  
    training_recipe=training_recipe,  
    recipe_overrides=recipe_overrides,  
    max_run=432000,  
    sagemaker_session=sagemaker_session,  
    image_uri=image_uri,
    output_kms_key=output_kms_key,
    tags=[  
        {'Key': 'model_name_or_path', 'Value': model_name_or_path},  
    ]  
)  
  
print(f"\nsm_training_job_name:\n{sm_training_job_name}\n")  
print(f"output_path:\n{output_path}")
```

```
from sagemaker.inputs import TrainingInput  
  
train_input = TrainingInput(  
    s3_data=train_dataset_s3_path,  
    distribution="FullyReplicated",  
    s3_data_type="Converse",  
)  
  
estimator.fit(inputs={"validation": val_input}, wait=False)
```

**注意**  
Nova 2.0 的监督式微调不支持传递验证数据集。

要启动作业，请执行以下操作：
+ 更新配方中的数据集路径与超参数
+ 运行笔记本中指定的代码单元，提交训练作业

笔记本将自动处理作业提交，并提供状态跟踪功能。

# 使用 Amazon Nova 模型进行强化微调（RFT）
<a name="nova-reinforcement-fine-tuning"></a>

## 概述
<a name="nova-rft-overview"></a>

**什么是 RFT？**

强化微调（RFT）通过基于反馈信号（即指示模型表现优劣的可衡量分数或奖励）的训练来提升模型性能，而不是基于精确的正确答案。与从输入-输出对中学习的监督式微调不同，RFT 使用奖励函数来评测模型响应，并迭代优化模型以获得最高奖励。这种方法适用于难以定义精确输出但能可靠衡量响应质量的任务。

**何时使用 RFT**

当您能够定义清晰、可衡量的成功标准，但难以提供精确的正确输出用于训练时，便可使用 RFT。该方法适用于：
+ 质量具有主观性或多维度的任务，如创意写作、代码优化或复杂推理
+ 存在多种可行方案，但部分方案明显更优的场景
+ 需要迭代改进、个性化或遵循复杂业务规则的应用
+ 收集高质量标注样本成本过高或不切实际的情况

**最佳使用案例**

在输出质量可客观衡量、但最优应答难以预先定义的领域，RFT 表现优异：
+ 数学问题求解和代码生成
+ 科学推理与结构化数据分析
+ 需要逐步推理或多轮问题求解的任务
+ 兼顾多个目标（准确率、效率、风格）的应用
+ 可通过执行结果或性能指标以编程方式验证成功与否的场景

**支持的模型**

Nova Lite 2.0

## 数据格式概述
<a name="nova-rft-data-format"></a>

RFT 训练数据必须遵循 OpenAI 强化微调[格式](https://platform.openai.com/docs/api-reference/fine-tuning/reinforcement-input)。每个训练样本都是一个 JSON 对象，其中包含：
+ 包含 `system` 和 `user` 角色对话轮次的 `messages` 数组
+ 包含用于奖励计算的期望输出或评测标准的 `reference_answer` 字段

**目前的局限性**
+ 仅文本

### 数据格式示例
<a name="nova-rft-data-examples"></a>

每个样本需单独占一行，JSONL 文件中每行对应一个 JSON 对象。

------
#### [ Chemistry problem ]

```
{
  "id": "chem-01",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful chemistry assistant"
    },
    {
      "role": "user",
      "content": "Calculate the molecular weight of caffeine (C8H10N4O2)"
    }
  ],
  "reference_answer": {
    "molecular_weight": 194.19,
    "unit": "g/mol",
    "calculation": "8(12.01) + 10(1.008) + 4(14.01) + 2(16.00) = 194.19"
  }
}
```

------
#### [ Math problem ]

```
{
  "id": "sample-001",  // Optional
  "messages": [
    {
      "role": "system",
      "content": "You are a math tutor"
    },
    {
      "role": "user",
      "content": "Solve: 2x + 5 = 13"
    }
  ],
  "reference_answer": {
    "solution": "x = 4",
    "steps": ["2x = 13 - 5", "2x = 8", "x = 4"]
  }
}
```

------
#### [ Code problem ]

```
{
  "id": "code-002",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful programming assistant"
    },
    {
      "role": "user",
      "content": "Write a Python function that reverses a string without using built-in reverse methods"
    }
  ],
  "reference_answer": {
    "code": "def reverse_string(s):  \n    result = ''  \n    for i in range(len(s) - 1, -1, -1):  \n        result += s[i]  \n    return result",
    "test_cases": [
      {
        "input": "hello",
        "expected_output": "olleh"
      },
      {
        "input": "",
        "expected_output": ""
      },
      {
        "input": "a",
        "expected_output": "a"
      },
      {
        "input": "Python123",
        "expected_output": "321nohtyP"
      }
    ],
    "all_tests_pass": true
  }
}
```

------

`reference_answer` 字段包含期望输出或评测标准，供奖励函数对模型响应进行评分。其不限于结构化输出，可采用任何有助于奖励函数评测质量的格式。

## 数据集规模建议
<a name="nova-rft-dataset-size"></a>

**起步要求**
+ 至少 100 个训练样本
+ 至少 100 个评测样本

**评测优先的方法**

在投入大规模 RFT 训练之前，请先评测模型的基线性能：
+ **性能优异（奖励大于 95%）**：无需进行 RFT，模型表现足够好
+ **性能极差（奖励为 0%）**：先切换到 SFT，建立基本能力
+ **性能中等**：适合采用 RFT 训练

从小规模数据集开始，可实现以下效果：
+ 验证奖励函数无错误
+ 确认 RFT 适合于使用案例
+ 尽早发现并修复问题
+ 在扩展规模前测试工作流

验证通过后，即可扩展到更大规模的数据集，进一步提升模型性能。

## 有效训练数据的特征
<a name="nova-rft-effective-data"></a>

**清晰性与一致性**

优质的 RFT 样本需要清晰、无歧义的输入数据，以便能够针对不同的模型输出进行准确的奖励计算。数据中应避免以下干扰：
+ 格式不一致
+ 标签或指令相互矛盾
+ 提示词含义模糊
+ 参考答案互相冲突

任何歧义都会误导训练过程，导致模型学习到非预期的行为。

**多样性**

数据集应覆盖生产环境中的各类使用案例，确保模型在真实环境中表现稳健。包含：
+ 不同的输入格式和边界情况
+ 从日志和用户分析中映射实际的生产使用模式
+ 跨用户类型、地理区域和季节性变化的采样
+ 包含从简单到复杂的问题难度级别

**奖励函数注意事项**

设计奖励函数，实现高效训练：
+ 在几秒钟内执行完毕（而非几分钟）
+ 使用 Lambda 实现高效并行
+ 返回一致且可靠的分数
+ 妥善处理不同类型的模型输出

快速且可扩展的奖励函数可支持快速迭代，并在实验中实现高成本效益。

## 其它属性
<a name="nova-rft-additional-properties"></a>

RFT 数据格式支持核心架构要求（`messages` 和 `reference_answer`）之外的自定义字段。这种灵活性支持您添加奖励函数完成有效评测所需的任意附加数据。

**注意**  
无需在配方中进行配置，该数据格式原生支持附加字段。只需将其包含在训练数据的 JSON 中，即可通过 `metadata` 字段传递给奖励函数。

**常见附加属性**

元数据字段示例：
+ `task_id`：用于跟踪的唯一标识符
+ `difficulty_level`：问题复杂度指示符
+ `domain`：主题领域或类别
+ `expected_reasoning_steps`：解题过程中的步骤数

**包含其他属性的示例**

```
{
  "messages": [
    {
      "role": "system",
      "content": "You are a math tutor"
    },
    {
      "role": "user",
      "content": "Solve: 2x + 5 = 13"
    }
  ],
  "reference_answer": {
    "solution": "x = 4",
    "steps": ["2x = 13 - 5", "2x = 8", "x = 4"]
  },
  "task_id": "algebra_001",
  "difficulty_level": "easy",
  "domain": "algebra",
  "expected_reasoning_steps": 3
}
```

这些附加字段将在评测期间传递给奖励函数，从而实现针对特定使用案例量身定制的复杂评分逻辑。

## 训练配置
<a name="nova-rft-training-config"></a>

**配方示例**

```
# Note:
# This recipe can run on p5.48xlarge and p5en.48xlarge instance types.
run:
  name: "my-rft-run"                           # Unique run name (appears in logs/artifacts).
  model_type: amazon.nova-2-lite-v1:0:256k
  model_name_or_path: nova-lite-2/prod
  data_s3_path: s3://<bucket>/<data file>      # Training dataset in JSONL;
  replicas: 4
  reward_lambda_arn: arn:aws:lambda:<region>:<account-id>:function:<function-name>

  ## MLFlow configs
  mlflow_tracking_uri: "" # Required for MLFlow
  mlflow_experiment_name: "my-rft-experiment" # Optional for MLFlow. Note: leave this field non-empty
  mlflow_run_name: "my-rft-run" # Optional for MLFlow. Note: leave this field non-empty

## SMTJ GRPO Training specific configs
training_config:
  max_length: 8192                              # Context window (tokens) for inputs+prompt;
  global_batch_size: 16                         # Total samples per optimizer step across all replicas (16/32/64/128/256).
  reasoning_effort: high                        # Enables reasoning mode high / low / or null for non-reasoning

  rollout:                                      # How responses are generated for GRPO/advantage calc.
    advantage_strategy:
      number_generation: 2                      # N samples per prompt to estimate advantages (variance vs cost).
    generator:
      max_new_tokens: 6000                      # Cap on tokens generated per sample
      set_random_seed: true                     # Seed generation for reproducibility across runs.
      temperature: 1                            # Softmax temperature;
      top_k: 1                                  # Sample only from top-K logits
    rewards:
      preset_reward_function: null              # Usage of preset reward functions [exact_match]
      api_endpoint:
        lambda_arn: arn:aws:lambda:<region>:<account-id>:function:<function-name>
        lambda_concurrency_limit: 12             # Max concurrent Lambda invocations (throughput vs. throttling).

  trainer:
    max_steps: 2                                 # Steps to train for. One Step = global_batch_size
    save_steps: 5
    test_steps: 1

    # RL parameters
    ent_coeff: 0.0                              # A bonus added to the policy loss that rewards higher-output entropy.
    kl_loss_coef: 0.001                         # Weight on the KL penalty between the actor (trainable policy) and a frozen reference model

    optim_config:                    # Optimizer settings
        lr: 5e-5                       # Learning rate
        weight_decay: 0.0              # L2 regularization strength (0.0–1.0)
        adam_beta1: 0.9
        adam_beta2: 0.95

    peft:                            # Parameter-efficient fine-tuning (LoRA)
        peft_scheme: "lora"            # Enable LoRA for PEFT
        lora_tuning:
            alpha: 32
            lora_plus_lr_ratio: 64.0     # LoRA+ learning rate scaling factor (0.0–100.0)
```

## 使用 LLM-as-a-judge 的 RFT 训练
<a name="nova-rft-llm-judge"></a>

### 概述
<a name="nova-rft-llm-judge-overview"></a>

大语言模型（LLM）越来越多地被用作强化微调（RFT）工作流中的评判工具，提供自动化的奖励信号来指导模型优化。在这种方法中，LLM 会根据指定标准对模型输出进行评测（包括正确性、质量、风格一致性或语义等效性等），并分配用于驱动强化学习过程的奖励值。

对于传统奖励函数难以通过编程定义的任务，该方法尤为实用。例如判断不同表达形式（如“1/3”“0.333”和“三分之一”）是否语义等效，或评测连贯性、相关性等细微特征。通过将基于 LLM 的评判机制作为奖励函数，可将 RFT 扩展到复杂领域，无需大量人工标注，进而在传统对齐问题之外的各类场景中，实现模型的快速迭代与持续优化。

### 推理模式选择
<a name="nova-rft-reasoning-mode"></a>

**可用模式**
+ none：无推理（省略 reasoning\$1effort 字段）
+ low：最小推理开销
+ high：最大推理能力（指定了 reasoning\$1effort 时，此为默认值）

**注意**  
RFT 无中等选项。如果配置中不含 reasoning\$1effort 字段，则禁用推理。启用推理时，建议将 `max_new_tokens` 设置为 32768，以容纳更长的推理输出内容。

**何时使用各个模式**

在以下场景使用高强度推理：
+ 复杂分析任务
+ 数学问题求解
+ 多步逻辑推导
+ 逐步思考能带来价值的任务

在以下场景使用无推理（省略 reasoning\$1effort）或低强度推理：
+ 简单事实查询
+ 直接分类
+ 速度与成本优化
+ 直接问答

**成本与性能权衡**

较高强度推理模式会导致：
+ 训练时间和成本增加
+ 推理延迟和成本增加
+ 模型在复杂推理任务上的能力提升

### 验证 LLM 评判工具
<a name="nova-rft-validating-judge"></a>

在生产中部署 LLM-as-a-judge 之前，请验证评判工具模型的评测是否与人类判断一致。这涉及：
+ 测量 LLM 评判工具与人工评测员在任务代表性样本上的一致率
+ 确保 LLM 与人类评测的一致率达到或超过人类之间的一致率
+ 识别评判工具模型中可能存在的偏差
+ 建立信心，确保奖励信号能按预期方向引导模型

此验证步骤有助于确保自动化评测过程能够产生符合生产质量标准的模型。

### LLM 评判工具的 Lambda 配置
<a name="nova-rft-lambda-config"></a>

采用 LLM-as-a-judge，是对使用 Lambda 函数实现可验证奖励强化学习（RLVR）的扩展。在 Lambda 函数内部，需调用 Amazon Bedrock 中托管的任一模型。

**重要配置要求：**


| 配置 | 要求 | Details | 
| --- | --- | --- | 
| Amazon Bedrock 吞吐量 | 充足的配额 | 确保所使用的 Amazon Bedrock 模型吞吐量配额足以满足训练工作负载 | 
| Lambda 超时 | 延长超时 | 将 Lambda 函数超时配置为最多 15 分钟。默认设置为 3 秒，不足以满足 Amazon Bedrock 模型的响应需求 | 
| Lambda 并发 | 提高并发 | Lambda 在训练期间会被并行调用。提高并发以提供最大程度的可用吞吐量 | 
| 配方配置 | 匹配 Lambda 设置 | 并发限制必须在配方中进行配置 | 

## 创建与运行作业
<a name="nova-rft-creating-jobs"></a>

**启动训练作业**

使用 SageMaker 训练作业笔记本模板：[https://docs.aws.amazon.com/sagemaker/latest/dg/nova-fine-tuning-training-job.html#nova-model-training-jobs-notebook](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-fine-tuning-training-job.html#nova-model-training-jobs-notebook)

**实例要求**

容器同时支持全秩和 LoRA 训练：
+ **LoRA 训练**：2/4/6/8 个 p5.48xlarge 或 p5en.48xlarge 实例
+ **全秩训练**：2/4/6/8 个 p5.48xlarge 实例（必需）

## 监控训练
<a name="nova-rft-monitoring"></a>

训练日志包含每一步的全面指标。主要指标类别：

**奖励指标**
+ `critic/rewards/mean`、`critic/rewards/max`、`critic/rewards/min`：奖励分布
+ `val-score/rewards/mean@1`：验证奖励

**模型行为**
+ `actor/entropy`：策略多样性（值越高表示探索性越强）

**训练健康度**
+ `actor/pg_loss`：策略梯度损失
+ `actor/pg_clipfrac`：裁剪更新频率
+ `actor/grad_norm`：梯度范数

**响应特征**
+ `prompt_length/mean`、`prompt_length/max`、`prompt_length/min`：输入词元统计
+ `response_length/mean`、`response_length/max`、`response_length/min`：输出词元统计
+ `response/aborted_ratio`：不完整生成率（0 表示全部完成）

**性能**
+ `perf/throughput`：训练吞吐量
+ `perf/time_per_step`：每步训练时间
+ `timing_per_token_ms/*`：每个词元的处理时间

**资源使用**
+ `perf/max_memory_allocated_gb`、`perf/max_memory_reserved_gb`：GPU 内存
+ `perf/cpu_memory_used_gb`：CPU 内存

## 使用经过微调的模型
<a name="nova-rft-using-models"></a>

训练完成后，最终模型检查点将保存到指定的输出位置。检查点路径可在以下位置获取：
+ 训练日志
+ 输出 Amazon S3 位置（由笔记本中的 `output_s3_uri` 定义）中的 `manifest.json` 文件

## 限制与最佳实践
<a name="nova-rft-limitations"></a>

**限制**
+ **Lambda 超时**：奖励函数须在 15 分钟内执行完毕（防止进程失控并控制成本）
+ **仅支持单轮对话**：不支持多轮对话
+ **数据要求**：需具备充足的多样性；在稀疏奖励场景下（正例占比 ＜5%）训练难度较高
+ **计算成本**：比监督式微调更昂贵
+ **无多模态数据**：仅支持文本数据类型

**最佳实践**

**从小规模起步**
+ 从 100 – 200 个样本开始
+ 验证奖励函数正确性
+ 根据结果逐步扩展

**训练前评测**
+ 在 RFT 之前测试基线模型性能
+ 如果奖励始终为 0%，建议先通过 SFT 训练构建基础能力
+ 若奖励占比 ＞95%，则可能无需进行 RFT

**监控训练**
+ 跟踪平均奖励分数和分布
+ 注意过拟合（练奖励上升，而验证奖励下降）
+ 留意异常模式：
  + 奖励在 0.15 以下趋于平稳
  + 奖励方差随时间逐步增大
  + 验证性能下降

**优化奖励函数**
+ 在几秒钟内执行完毕（而非几分钟）
+ 尽量减少外部 API 调用
+ 使用高效算法
+ 实现完善的错误处理机制
+ 充分利用 Lambda 的并行扩展能力

**迭代策略**

如果奖励没有提升：
+ 调整奖励函数设计
+ 提升数据集多样性
+ 添加更多代表性样本
+ 确保奖励信号清晰一致

## 高级能力：Nova Forge
<a name="nova-rft-advanced"></a>

对于需要突破标准 RFT 限制的高级能力的用户，Nova Forge 作为付费订阅服务提供，包括：
+ 多轮对话支持
+ 执行时间超过 15 分钟的奖励函数
+ 额外的算法和调优选项
+ 自定义训练配方修改
+ 最先进的人工智能技术

Nova Forge 在 SageMaker HyperPod 上运行，旨在支持企业客户构建自己的前沿模型。

## 实用命令与技巧
<a name="nova-rft-useful-commands"></a>

您可使用一系列[可观测性脚本](https://github.com/aws-samples/amazon-nova-samples/tree/main/customization/SageMakerUilts/SageMakerJobsMonitoring)，帮助监控训练作业的状态和进度。

可用脚本包括：
+ 为训练作业状态更新启用电子邮件通知
+ 根据作业配置获取训练时间估算
+ 获取进行中作业的预期训练时间近似值

**安装**

**注意**  
在使用以下任何脚本之前，请务必刷新 AWS 凭证。

```
pip install boto3
git clone https://github.com/aws-samples/amazon-nova-samples.git
cd amazon-nova-samples/customization/SageMakerUilts/SageMakerJobsMonitoring/
```

**基本用法**

```
# Enabling email notifications for training job status updates
python enable_sagemaker_job_notifs.py --email test@amazon.com test2@gmail.com --region us-east-1 --platform SMTJ

Creating resources........
Please check your email for a subscription confirmation email, and click 'Confirm subscription' to start receiving job status email notifications!
You'll receive the confirmation email within a few minutes.
```

```
# Obtaining training time estimates based on job configurations
python get_training_time_estimate.py
```

```
# Obtaining approximations for how long training is expected to take for in-progress jobs
python get-training-job-progress.py --region us-east-1 --job-name my-training-job --num-dataset-samples 1000
```

有关更多详细信息和示例，请参阅[此处](https://github.com/aws-samples/amazon-nova-samples/blob/main/customization/SageMakerUilts/SageMakerJobsMonitoring/README.md)。