

# 直接偏好优化（DPO）
<a name="nova-dpo-smtj"></a>

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

直接偏好优化（DPO）是一种对齐技术，利用成对对比数据对基础模型进行微调，使模型输出与人类偏好保持一致。与强化学习方法不同，DPO 直接基于人类反馈（即哪些响应更优）来优化模型行为，是一种更稳定、更具可扩展性的方案。

**为何选择 DPO**

基础模型生成的输出虽然在事实层面可能是正确的，但往往无法与特定用户需求、组织价值观或安全要求相符合。DPO 可通过以下功能解决该问题：
+ 根据预期行为模式微调模型
+ 减少不良或有害输出
+ 使模型响应与品牌声音和沟通指南保持一致
+ 根据领域专家的反馈改善响应质量
+ 通过偏好的响应模式实施安全护栏

**DPO 的工作原理**

DPO 使用配对的示例，由人类评估者指出在两种可能的响应中偏好哪一种响应。该模型通过学习来最大化生成偏好响应的可能性，同时最大程度减少非预期的响应。

**DPO 的适用场景**

将 DPO 用于以下方案：
+ 针对需要符合特定人类偏好的主观输出进行优化
+ 调整模型的语气、风格或内容特征
+ 根据用户反馈和错误分析进行针对性改进
+ 在不同使用案例中保持一致的输出质量
+ 仅使用偏好数据进行无奖励强化学习训练

## 支持的模型与技术
<a name="nova-dpo-smtj-models"></a>

DPO 同时支持全参数微调和 LoRA（低秩适配）：


| 模型 | 支持的输入 | 实例类型 | 推荐的实例计数 | 支持的实例计数 | 
| --- | --- | --- | --- | --- | 
| Amazon Nova Micro | 文本 | ml.p5.48xlarge | 2 | 2、4、8 | 
| Amazon Nova Lite | 文本、图像 | ml.p5.48xlarge | 4 | 2、4、8、16 | 
| Amazon Nova Pro | 文本、图像 | ml.p5.48xlarge | 6 | 6、12、24 | 

**训练方法**
+ **全秩 DPO**：更新所有模型参数。可能实现更优的对齐效果，但需消耗更多计算资源，且生成的模型体积更大。
+ **LoRA DPO**：使用轻量化适配器，实现参数高效微调。在保持良好对齐质量的同时，以更小的模型体积实现更高效的训练与部署。

对于大多数使用案例，LoRA 方案具备足够的适配能力，且效率显著提升。

## 数据格式
<a name="nova-dpo-smtj-data"></a>

DPO 训练数据格式与 SFT 一致，区别仅在于最后一轮助手响应必须包含带有 `preferred` 和 `non-preferred` 标签的偏好对。

### 基本结构
<a name="nova-dpo-smtj-data-structure"></a>

最终轮次的助手响应使用 `candidates` 数组而非 `content` 字段：

```
{
  "role": "assistant",
  "candidates": [
    {
      "content": [
        {
          "text": "This is the preferred response."
        }
      ],
      "preferenceLabel": "preferred"
    },
    {
      "content": [
        {
          "text": "This is the non-preferred response."
        }
      ],
      "preferenceLabel": "non-preferred"
    }
  ]
}
```

### 完整文本示例
<a name="nova-dpo-smtj-data-text-example"></a>

```
{
  "schemaVersion": "bedrock-conversation-2024",
  "system": [
    {
      "text": "You are a helpful assistant."
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "What is the capital of France?"
        }
      ]
    },
    {
      "role": "assistant",
      "content": [
        {
          "text": "The capital of France is Paris."
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "text": "Tell me more about it."
        }
      ]
    },
    {
      "role": "assistant",
      "candidates": [
        {
          "content": [
            {
              "text": "Paris is the capital and largest city of France, known for the Eiffel Tower, world-class museums like the Louvre, and its rich cultural heritage."
            }
          ],
          "preferenceLabel": "preferred"
        },
        {
          "content": [
            {
              "text": "Paris is a city in France."
            }
          ],
          "preferenceLabel": "non-preferred"
        }
      ]
    }
  ]
}
```

### 带图像示例
<a name="nova-dpo-smtj-data-image-example"></a>

```
{
  "schemaVersion": "bedrock-conversation-2024",
  "system": [
    {
      "text": "You are a helpful assistant."
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "Describe this image."
        },
        {
          "image": {
            "format": "jpeg",
            "source": {
              "s3Location": {
                "uri": "s3://your-bucket/your-path/image.jpg",
                "bucketOwner": "your-aws-account-id"
              }
            }
          }
        }
      ]
    },
    {
      "role": "assistant",
      "candidates": [
        {
          "content": [
            {
              "text": "The image shows a detailed description with relevant context and observations."
            }
          ],
          "preferenceLabel": "preferred"
        },
        {
          "content": [
            {
              "text": "This is a picture."
            }
          ],
          "preferenceLabel": "non-preferred"
        }
      ]
    }
  ]
}
```

### 数据集要求
<a name="nova-dpo-smtj-data-requirements"></a>
+ **格式**：单个 JSONL 文件用于训练，单个 JSONL 文件用于验证（可选）
+ **最小规模**：建议至少 1000 个偏好对以保证训练效果
+ **质量**：高质量的偏好数据可带来更优效果
+ **其他约束**：与 SFT 相同。有关更多信息，请参阅数据集限制。

**上传数据**

```
aws s3 cp /path/to/training-data/ s3://your-bucket/train/ --recursive
aws s3 cp /path/to/validation-data/ s3://your-bucket/val/ --recursive
```

## 配方配置
<a name="nova-dpo-smtj-recipe"></a>

### 常规运行配置
<a name="nova-dpo-smtj-recipe-run"></a>

```
run:
  name: "my-dpo-run"
  model_type: "amazon.nova-lite-v1:0:300k"
  model_name_or_path: "nova-lite/prod"
  replicas: 4
```


| 参数 | 说明 | 
| --- | --- | 
| name | 训练作业的描述性名称 | 
| model\$1type | Nova 模型变体（切勿修改） | 
| model\$1name\$1or\$1path | 基础模型路径（切勿修改） | 
| replicas | 分布式训练所用计算实例数量 | 

### 训练配置
<a name="nova-dpo-smtj-recipe-training"></a>

```
training_config:
  max_length: 16384
  global_batch_size: 32

  trainer:
    max_epochs: 3

  model:
    hidden_dropout: 0.0
    attention_dropout: 0.0
    ffn_dropout: 0.0
```


| 参数 | 说明 | Range | 
| --- | --- | --- | 
| max\$1length | 以词元为单位的最大序列长度 | 1024–32768 | 
| global\$1batch\$1size | 每个优化器步骤处理的样本数 | Micro/Lite/Pro：16、32、64、128。Micro/Lite：256 | 
| max\$1epochs | 数据集训练轮次 | 最小值：1 | 
| hidden\$1dropout | 隐藏层状态的丢弃率 | 0.0–1.0 | 
| attention\$1dropout | 注意力权重的丢弃率 | 0.0–1.0 | 
| ffn\$1dropout | 前馈层的丢弃率 | 0.0–1.0 | 

### 优化器配置
<a name="nova-dpo-smtj-recipe-optimizer"></a>

```
model:
  optim:
    lr: 1e-5
    name: distributed_fused_adam
    adam_w_mode: true
    eps: 1e-08
    weight_decay: 0.0
    betas:
      - 0.9
      - 0.999
    sched:
      warmup_steps: 10
      constant_steps: 0
      min_lr: 1e-6
```


| 参数 | 说明 | Range | 
| --- | --- | --- | 
| lr | 学习率 | 0–1（通常为 1e-6 到 1e-4） | 
| weight\$1decay | L2 正则化强度 | 0.0–1.0 | 
| warmup\$1steps | 学习率逐步提升的步数 | 0–20 | 
| min\$1lr | 衰减结束时的最小学习率 | 0–1（必须小于 lr） | 

### DPO 专属配置
<a name="nova-dpo-smtj-recipe-dpo"></a>

```
model:
  dpo_cfg:
    beta: 0.1
```


| 参数 | 说明 | Range | 
| --- | --- | --- | 
| beta | 拟合训练数据与贴近原模型的平衡系数 | 0.001–0.5 | 
+ **较高的 beta 值（如 0.1）**：更多保留基准模型的行为，但偏好学习速度可能较慢
+ **较低的 beta 值（如 0.01–0.05）**：偏好学习更激进，但存在与基准模型偏离的风险

**建议**：初始设置 `beta: 0.1`；若发现偏好学习效果不足，再向下调整。

### LoRA PEFT 配置
<a name="nova-dpo-smtj-recipe-lora"></a>

```
model:
  peft:
    peft_scheme: "lora"
    lora_tuning:
      loraplus_lr_ratio: 64.0
      alpha: 32
      adapter_dropout: 0.01
```


| 参数 | 说明 | 允许值 | 
| --- | --- | --- | 
| peft\$1scheme | 微调方法 | "lora" 或 null（全秩） | 
| alpha | LoRA 权重的缩放系数 | 32、64、96、128、160、192 | 
| loraplus\$1lr\$1ratio | LoRA\$1 学习率缩放系数 | 0.0–100.0 | 
| adapter\$1dropout | LoRA 参数的正则化 | 0.0–1.0 | 

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

**容器映像**

```
708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-DPO-latest
```

**示例代码**

```
from sagemaker.pytorch import PyTorch
from sagemaker.inputs import TrainingInput

instance_type = "ml.p5.48xlarge"
instance_count = 4

image_uri = "708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-DPO-latest"

recipe_overrides = {
    "training_config": {
        "trainer": {"max_epochs": 2},
        "model": {
            "dpo_cfg": {"beta": 0.1},
            "peft": {
                "peft_scheme": "lora",
                "lora_tuning": {
                    "loraplus_lr_ratio": 64.0,
                    "alpha": 32,
                    "adapter_dropout": 0.01,
                },
            },
        },
    },
}

estimator = PyTorch(
    output_path=f"s3://{bucket_name}/{job_name}",
    base_job_name=job_name,
    role=role,
    instance_count=instance_count,
    instance_type=instance_type,
    training_recipe="fine-tuning/nova/nova_lite_p5_gpu_lora_dpo",
    recipe_overrides=recipe_overrides,
    max_run=18000,
    sagemaker_session=sagemaker_session,
    image_uri=image_uri,
    disable_profiler=True,
    debugger_hook_config=False,
)

train_input = TrainingInput(
    s3_data=train_dataset_s3_path,
    distribution="FullyReplicated",
    s3_data_type="Converse",
)

val_input = TrainingInput(
    s3_data=val_dataset_s3_path,
    distribution="FullyReplicated",
    s3_data_type="Converse",
)

estimator.fit(inputs={"train": train_input, "validation": val_input}, wait=True)
```

## 部署模型
<a name="nova-dpo-smtj-deploy"></a>

训练完成后，可通过自定义模型导入功能，将自定义模型部署到 Amazon Bedrock。该模型同时支持预置吞吐量与按需推理。经 LoRA 训练的模型仅支持按需推理。

有关部署说明，请参阅[部署自定义模型](deploy-custom-model.md)。

## 限制
<a name="nova-dpo-smtj-limitations"></a>
+ **输入模态**：DPO 仅支持文本与图像。不支持视频输入。
+ **输出模态**：纯文本
+ **偏好对**：最终助手轮次必须恰好包含 2 个候选结果，并标注 `preferred` 与 `non-preferred` 标签
+ **图像限制**：每个内容块最多支持 10 张图像
+ **混合模态**：同一训练作业中不可同时混合文本、图像与视频