

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

# Amazon Nova 模型的訓練
培訓

在 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
監督式微調 (SFT)

## 先決條件
先決條件

開始訓練任務之前，請注意以下事項：
+ 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)。

## 什麼是 SFT？


監督式微調 (SFT) 會使用標記的輸入輸出對來訓練語言模型。此模型會從包含提示和回應的示範範例中學習，改善其功能以符合特定任務、指示或所需行為。

## 資料準備


### 概觀


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)

### 支援的功能

+ **輸入類型** – 使用者內容區塊中的文字、影像或影片
+ **助理內容** – 純文字回應和推理內容
+ **資料集合成** – 必須是同質的。選擇以下一項：
  + 純文字轉彎
  + 文字 \$1 影像轉彎
  + 文字 \$1 影片轉場 （支援文件理解）

**重要**  
您無法在相同資料集內或在不同回合之間混合影像和影片。

### 目前限制

+ **多模態推理內容** – 雖然 Converse 格式支援以影像為基礎的推理內容，但 Nova 2.0 SFT 在 reasoningText 欄位中僅支援以文字為基礎的推理內容。
+ **驗證集** – 您無法為具有 Nova 2.0 的 SFT 提供驗證資料集。如果您提供驗證資料集，則會在訓練期間忽略該資料集。此限制適用於 UI 型和程式設計任務提交。

### 支援的媒體格式

+ **影像** – PNG、JPEG、GIF
+ **影片** – MOV、MKV、MP4

### 資料格式範例


------
#### [ 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"  
        }  
      ]  
    }  
  ]  
}
```

------

## 工具呼叫


Nova 2.0 SFT 支援工具呼叫模式的訓練模型，讓您的模型了解呼叫外部工具或函數的時間和方式。

### 工具呼叫的資料格式


工具呼叫訓練資料包含定義可用工具的`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?"  
        }  
      ]  
    }  
  ]  
}
```

### 工具呼叫需求


建立工具呼叫訓練資料時，請遵循下列要求：


| 需求 | Description | 
| --- | --- | 
| ToolUse 置放 | ToolUse 必須僅以助理輪換顯示 | 
| ToolResult 置放 | ToolResult 必須僅顯示在使用者轉彎中 | 
| ToolResult 格式 | ToolResult 只能是文字或 JSON。Nova 模型不支援其他模態 | 
| inputSchema 格式 | toolSpec 中的 inputSchema 必須是有效的 JSON 結構描述物件 | 
| toolUseId 比對 | 每個 ToolResult 必須參考先前助理 ToolUse 中的有效 ToolUse toolUseId，每個toolUseId 在每次對話中只使用一次 | 

### 重要說明

+ 確保您的工具定義在所有訓練範例之間保持一致
+ 此模型會從您提供的示範中學習工具叫用模式
+ 包含何時使用每個工具以及何時不使用工具的各種範例

## 理解文件


Nova 2.0 SFT 支援訓練以文件為基礎的任務，讓您的模型了解如何分析和回應有關 PDF 文件的問題。

### 文件理解的資料格式


文件了解訓練資料包含使用者內容區塊中的文件參考，模型學習會擷取文件內容並說明原因。

**範例輸入**

```
{  
{  
  "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?"  
        }   
      ]
    }  
  ]  
}
}
```

### 文件理解限制



| 限制 | 詳細資訊 | 
| --- | --- | 
| 支援的格式 | 僅限 PDF 檔案 | 
| 文件大小上限 | 10 MB | 
| 模態混合 | 範例可以有文件和文字，但不能將文件與其他形式 （影像、影片） 混合 | 

### 文件理解的最佳實務

+ 確保文件格式清晰且可擷取文字
+ 提供涵蓋不同文件類型和問題格式的多樣化範例
+ 包含推理內容以協助模型學習文件分析模式

## 影片理解


Nova 2.0 SFT 支援視訊型任務的訓練，讓您的模型了解如何分析和回應有關視訊內容的問題。

### 影片理解的資料格式


影片理解訓練資料包含使用者內容區塊中的影片參考，模型學習會擷取影片內容的資訊和原因。

**範例輸入**

```
  
{  
  "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?"  
        }   
      ]  
    }  
  ]  
}
```

### 影片理解限制



| 限制 | 詳細資訊 | 
| --- | --- | 
| 影片大小上限 | 50 MB | 
| 最大視訊持續時間 | 15 分鐘 | 
| 每個範例的影片數 | 每個範例只允許一個影片。不支援相同範例中的多個影片 | 
| 模態混合 | 範例可以有影片和文字，但不能將影片與其他形式 （影像、文件） 結合 | 

### 支援的影片格式

+ MOV
+ MKV
+ MP4

### 影片理解的最佳實務

+ 保持影片簡潔並專注於與您的任務相關的內容
+ 確保影片品質足以讓模型擷取有意義的資訊
+ 提供明確的問題，以參考影片內容的特定層面
+ 包含涵蓋不同影片類型和問題格式的多樣化範例

## 原因與非原因模式


### 了解推理內容


合理的內容 （也稱為chain-of-thought) 會在產生最終答案之前擷取模型的中繼思考步驟。`assistant` 然後，使用 `reasoningContent` 欄位來包含這些推理追蹤。

**如何計算損失**
+ **使用推理內容** – 訓練損失包括推理權杖和最終輸出權杖
+ **沒有推理內容** – 僅根據最終輸出權杖計算訓練損失

您可以在多迴轉對話中`reasoningContent`跨多個助理迴轉包含 。

**格式化準則**
+ 使用純文字來推理內容
+ 避免標記標籤，例如 `<thinking>`和 ，`</thinking>`除非您的任務特別要求
+ 確保推理內容清晰且與問題解決程序相關

### 何時啟用推理模式


在下列情況下，在您的訓練組態`reasoning_enabled: true`中設定 ：
+ 您的訓練資料具有推理權杖
+ 您希望模型在產生最終輸出之前產生思維權杖
+ 您需要改善複雜推理任務的效能

`reasoning_enabled = true` 允許使用 在非合理資料集上訓練 Nova。不過，這樣做可能會導致模型失去其推理功能，因為 Nova 主要學習在不套用推理的情況下產生資料中呈現的回應。如果您想要在非合理資料集上訓練 Nova，但仍預期推論期間的推理，您可以在訓練期間停用推理 (`reasoning_enabled = false`)，但啟用它以進行推論。雖然此方法允許在推論時間使用推理，但與推論相比，它並不保證改善效能，無需推理。一般而言，在使用推理資料集時啟用訓練推理和推論，並在使用非合理的資料集時停用兩者推理。

設定`reasoning_enabled: false`時機：
+ 您的訓練資料沒有推理權杖
+ 您正在針對無法從明確推理步驟中受益的直接任務進行訓練
+ 您想要最佳化速度並減少字符用量

### 產生推理資料


如果您的資料集缺少推理追蹤，您可以使用 Nova Premier 之類的推理能力模型來建立它們。將您的輸入輸出對提供給模型，並擷取其推理程序，以建置推理擴增的資料集。

### 使用推理字符進行訓練


啟用推理模式的訓練時，模型會學習將內部推理與最終答案分開。訓練程序：
+ 將資料組織為三元組：輸入、推理和回答
+ 使用推理和回答權杖的標準下一個權杖預測損失進行最佳化
+ 鼓勵模型在產生回應之前進行內部推理

### 有效的推理內容


高品質推理內容應包括：
+ 中繼想法和分析
+ 邏輯扣除和推論步驟
+ Step-by-step解決問題的方法
+ 步驟和結論之間的明確連線

這有助於模型開發「在回答之前思考」的能力。

## 資料集準備準則


### 大小和品質

+ **建議大小** – 2，000-10，000 個範例
+ **最低範例** – 200
+ **優先順序** – 數量的品質。確保範例準確且標註正確
+ **應用程式一致性** – 資料集應緊密反映您的生產使用案例

### 多樣性


包含下列各種範例：
+ 涵蓋預期輸入的完整範圍
+ 代表不同的難度等級
+ 包含邊緣案例和變化
+ 防止過度擬合至窄模式

### 輸出格式


在助理回應中明確指定所需的輸出格式：
+ JSON 結構
+ 表格
+ CSV format (CSV 格式)
+ 您應用程式特有的自訂格式

### 多回合對話


對於多迴轉資料集，請記住：
+ 只有在助理輪換時才會計算損失，而非使用者輪換時
+ 每個助理回應都應正確格式化
+ 在對話回合之間保持一致性

### 品質檢查清單

+ 足夠的資料集大小 (2K-10K 範例）
+ 涵蓋所有使用案例的多樣化範例
+ 清晰、一致的輸出格式
+ 準確的標籤和註釋
+ 生產案例的代表
+ 沒有矛盾或模棱兩可之處

### 上傳資料


資料集應上傳至 SageMaker 訓練任務可存取的儲存貯體。如需設定正確許可的資訊，請參閱[先決條件](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model-general-prerequisites.html)。

## 啟動訓練任務


### 選取超參數並更新配方


Nova 2.0 的設定大致上與 Nova 1.0 相同。輸入資料上傳到 S3 後，請在微調資料夾下使用 [SageMaker HyperPod ](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes/fine-tuning/nova)配方中的配方。對於 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 微調任務。

請使用 SageMaker AI PySDK 的 v2.254.1，以嚴格相容於 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` – 您要執行任務的步驟數目。一般而言，對於一個 epoch （一個執行整個資料集），步驟數目 = 資料樣本數目/全域批次大小。步驟數目越大，全域批次大小越小，任務執行的時間就越長。
+ `reasoning_enabled` – 控制資料集的推理模式。選項：
  + `true`：啟用推理模式 （相當於高推理）
  + `false`：停用推理模式

  注意：對於 SFT，無法精細控制推理工作量。設定 `reasoning_enabled: true` 可啟用完整推理功能。
+ `peft.peft_scheme` – 將此設定為「lora」可啟用以 PEFT 為基礎的微調。將其設定為 null （無引號） 可啟用全執行微調。

### 開始訓練任務


```
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)
強化微調 (RFT)

## 概觀


**什麼是 RFT？**

強化微調 (RFT) 透過訓練意見回饋訊號來改善模型效能，這些訊號是可測量的分數或獎勵，指出模型的效能，而不是確切的正確答案。與從輸入輸出對中學習的監督式微調不同，RFT 使用獎勵函數來評估模型回應，並反覆最佳化模型以最大化這些獎勵。此方法在定義確切的正確輸出具有挑戰性時表現卓越，但您可以可靠地測量回應品質。

**何時使用 RFT**

當您可以定義明確、可衡量的成功條件，但難以為訓練提供確切正確的輸出時，請使用 RFT。它非常適合：
+ 品質是主觀或多面向的任務 （創造性寫入、程式碼最佳化、複雜推理）
+ 具有多個有效解決方案的案例，其中有些解決方案明顯優於其他解決方案
+ 需要反覆改進、個人化或遵守複雜業務規則的應用程式
+ 收集高品質標籤範例昂貴或不切實際的案例

**最佳使用案例**

RFT 在可以客觀測量輸出品質，但難以預先定義最佳回應的網域中表現卓越：
+ 數學問題解決和程式碼產生
+ 科學推理和結構化資料分析
+ 需要step-by-step推理或多迴轉問題解決的任務
+ 應用程式平衡多個目標 （準確性、效率、風格）
+ 可透過執行結果或效能指標以程式設計方式驗證成功的案例

**支援的模型**

Nova Lite 2.0

## 資料格式概觀


RFT 訓練資料必須遵循 OpenAI 強化微調[格式](https://platform.openai.com/docs/api-reference/fine-tuning/reinforcement-input)。每個訓練範例都是 JSON 物件，其中包含：
+ 使用 `system`和 `user`角色進行對話輪換的`messages`陣列
+ `reference_answer` 包含預期輸出或評估條件的欄位，以進行獎勵計算

**目前限制**
+ 僅文字

### 資料格式範例


每個範例應該位於 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` 欄位包含預期輸出或評估條件，您的獎勵函數會用來對模型的回應進行評分。它不限於結構化輸出，它可以包含任何格式，協助您的獎勵函數評估品質。

## 資料集大小建議


**起點**
+ 最少 100 個訓練範例
+ 最少 100 個評估範例

**評估優先方法**

在投資大規模 RFT 訓練之前，請評估模型的基準效能：
+ **高效能 (>95% 獎勵）** – RFT 可能不必要，您的模型已表現良好
+ **非常差的效能 (0% 獎勵）** – 首先切換到 SFT 以建立基本功能
+ **中等效能** – RFT 可能是適當的

從小型資料集開始，您可以：
+ 驗證您的獎勵函數沒有錯誤
+ 確認 RFT 是適合您使用案例的正確方法
+ 及早識別和修正問題
+ 在向上擴展之前測試工作流程

驗證後，您可以擴展到更大的資料集，以進一步改善效能。

## 有效訓練資料的特性


**清晰度和一致性**

良好的 RFT 範例需要清晰、不明確的輸入資料，以便在不同的模型輸出間進行準確的獎勵計算。避免資料中的雜訊，包括：
+ 不一致的格式
+ 矛盾的標籤或指示
+ 模棱兩可的提示
+ 衝突的參考答案

任何模棱兩可的情況都會誤導訓練程序，並導致模型學習非預期的行為。

**多樣性**

您的資料集應擷取生產使用案例的完整多樣性，以確保強大的實際效能。包括：
+ 不同的輸入格式和邊緣案例
+ 從日誌和使用者分析映射實際的生產使用模式
+ 使用者類型、地理區域和季節性變化的範例
+ 包含從簡單到複雜問題的難度等級

**獎勵函數考量事項**

設計您的獎勵函數以進行高效訓練：
+ 在幾秒鐘內執行 （非分鐘）
+ 使用 Lambda 有效平行化
+ 傳回一致、可靠的分數
+ 正常處理不同類型的模型輸出

快速、可擴展的獎勵函數可實現快速迭代和經濟實惠的實驗。

## 其他屬性


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

這些額外的欄位會在評估期間傳遞給您的獎勵函數，以根據您的特定使用案例量身打造複雜的評分邏輯。

## 訓練組態


**範例配方**

```
# 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 做為判斷的 RFT 訓練


### 概觀


大型語言模型 LLMs) 在強化微調 (RFT) 工作流程中逐漸被用作判斷，提供引導模型最佳化的自動獎勵訊號。在此方法中，LLM 會根據指定的條件評估模型輸出，無論是評估正確性、品質、風格遵循或語意相等性，並指派推動強化學習程序的獎勵。

這對於傳統獎勵函數難以以程式設計方式定義的任務特別有用，例如判斷不同的表示法 （例如 "1/3"、"0.333" 和 "1/3") 是否在語義上相等，或評估一致性和相關性等細微品質。透過使用以 LLM 為基礎的判斷做為獎勵函數，您可以將 RFT 擴展到複雜的網域，而不需要大量的人工註釋，因此除了傳統對齊問題之外，可在各種使用案例中快速迭代和持續改善模型。

### 合理模式選擇


**可用模式**
+ none – 無推理 （省略 reasoning\$1effort 欄位）
+ 低 - 最低推理開銷
+ 高 – 最大推理功能 （指定 reasoning\$1effort 時預設為預設值）

**注意**  
RFT 沒有媒體選項。如果組態中沒有 reasoning\$1effort 欄位，則會停用推理。啟用推理時，您應該將 `max_new_tokens`設定為 32768，以容納延伸推理輸出。

**何時使用每個模式**

使用高推理：
+ 複雜的分析任務
+ 數學問題解決
+ 多步驟邏輯扣除
+ step-by-step思考可增加價值的任務

不使用 （省略 reasoning\$1effort) 或低推理：
+ 簡單事實查詢
+ 直接分類
+ 速度和成本最佳化
+ 直接的問答

**成本和效能權衡**

較高的推理模式會增加：
+ 訓練時間和成本
+ 推論延遲和成本
+ 複雜推理任務的模型功能

### 驗證您的 LLM 判斷


在生產環境中部署 LLM-as-a-judge 之前，請驗證判斷模型的評估是否符合人類判斷。這包括：
+ 針對您任務的代表性範例，測量 LLM 判斷者與人工評估者之間的協議率
+ 確保 LLM 與人類的協議符合或超過人類之間的協議費率
+ 識別判斷模型中的潛在偏差
+ 建立對獎勵訊號引導模型朝預期方向的信心

此驗證步驟有助於確保自動化評估程序會產生符合您生產品質標準的模型。

### LLM 判斷的 Lambda 組態


使用 LLM 做為判斷，是使用 Lambda 函數進行強化學習與可驗證獎勵 (RLVR) 的延伸。在 Lambda 函數中，您可以呼叫 Amazon Bedrock 中託管的其中一個模型。

**重要的組態需求：**


| Configuration | 需求 | 詳細資訊 | 
| --- | --- | --- | 
| Amazon Bedrock 輸送量 | 足夠的配額 | 確保所使用的 Amazon Bedrock 模型的輸送量配額足以滿足您的訓練工作負載 | 
| Lambda 逾時 | 延長逾時 | 將 Lambda 函數逾時設定為最長 15 分鐘。預設設定為 3 秒，這不足以回應 Amazon Bedrock 模型 | 
| Lambda 並行 | 並行增加 | Lambda 會在訓練期間平行叫用。增加並行以最大化可用輸送量 | 
| 配方組態 | 比對 Lambda 設定 | 必須在配方中設定並行限制 | 

## 建立和執行任務


**啟動訓練任務**

使用 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)

**執行個體需求**

容器同時支援 Full-Rank 和 LoRA 訓練：
+ **LoRA 訓練** – 2/4/6/8 × p5.48xlarge 或 p5en.48xlarge 執行個體
+ **全執行訓練** – 2/4/6/8 × p5.48xlarge 執行個體 （必要）

## 監控訓練


訓練日誌包含每個步驟的全方位指標。金鑰指標類別：

**獎勵指標**
+ `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 記憶體

## 使用微調的模型


訓練完成後，最終模型檢查點會儲存到您指定的輸出位置。檢查點路徑可用於：
+ 訓練日誌
+ `manifest.json` 輸出 Amazon S3 位置中的 檔案 （由 在您的筆記本`output_s3_uri`中定義）

## 限制和最佳實務


**限制**
+ **Lambda 逾時** – 獎勵函數必須在 15 分鐘內完成 （防止失控程序和管理成本）
+ **僅限單轉** – 不支援多轉對話
+ **資料需求** – 需要足夠的多樣性；難以獲得稀疏獎勵 (<5% 的正面範例）
+ **運算成本** – 比監督式微調更昂貴
+ **無多模態資料** – 僅支援文字資料類型

**最佳實務**

**從小開始**
+ 從 100-200 個範例開始
+ 驗證獎勵函數正確性
+ 根據結果逐步擴展

**訓練前評估**
+ 在 RFT 之前測試基準模型效能
+ 如果獎勵持續為 0%，請先使用 SFT 建立基本功能
+ 如果獎勵 >95%，RFT 可能不必要

**監控訓練**
+ 追蹤平均獎勵分數和分佈
+ 注意過度擬合 （訓練獎勵增加，同時驗證獎勵減少）
+ 尋找相關的模式：
  + 獎勵穩定低於 0.15
  + 隨時間增加獎勵差異
  + 降低驗證效能

**最佳化獎勵函數**
+ 在幾秒鐘內執行 （非分鐘）
+ 將外部 API 呼叫降至最低
+ 使用高效演算法
+ 實作適當的錯誤處理
+ 利用 Lambda 的平行擴展

**反覆運算策略**

如果獎勵未改善：
+ 調整獎勵函數設計
+ 增加資料集多樣性
+ 新增更多代表性範例
+ 驗證獎勵訊號是否清晰且一致

## 進階功能：Nova Forge


對於需要超出標準 RFT 限制之進階功能的使用者，Nova Forge 可作為付費訂閱服務方案使用：
+ 多迴轉對話支援
+ 以 >15 分鐘的執行時間獎勵函數
+ 其他演算法和調校選項
+ 自訂訓練配方修改
+ State-of-the-art技術

Nova Forge 在 SageMaker HyperPod 上執行，旨在支援企業客戶建置自己的前沿模型。

## 有用的命令和秘訣


提供[可觀測性指令碼](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)。