

# 评估经过训练的模型
评估

评估配方是一个定义如何执行 Amazon Nova 模型评测任务的 YAML 配置文件。使用此配方，您可以根据常用基准或自有的自定义数据集评估基础模型或训练模型的性能。性能指标可能存储在 Amazon S3 或 TensorBoard 中。评估提供定量指标来帮助您评估模型在各种任务中的性能，从而确定是否需要进一步自定义。

模型评测是一个离线过程，模型使用预定义的答案，按照固定的基准进行测试。模型不是实时评估的，也不是按照用户实时互动进行评估。对于实时评估，您可以在模型部署到 Amazon Bedrock 之后通过调用 Amazon Bedrock 运行时 API 进行评估。

**Topics**
+ [

# 可用的基准测试任务
](customize-fine-tune-evaluate-available-tasks.md)
+ [

# 了解配方参数
](customize-fine-tune-evaluate-understand-modify.md)
+ [

# 评估配方示例
](customize-fine-tune-evaluate-recipe-examples.md)
+ [

# 启动评估作业
](customize-fine-tune-evaluate-start-job.md)
+ [

# 访问和分析评估结果
](customize-fine-tune-evaluate-access-results.md)
+ [

# RFT 评测
](nova-hp-evaluate-rft.md)

# 可用的基准测试任务


一个可用的示例代码包，用于演示如何使用适用于 Amazon Nova 的 SageMaker AI 模型评测特征计算基准评测指标。要获取代码包，请参阅 [sample-Nova-lighteval-custom-task](https://github.com/aws-samples/sample-Nova-lighteval-custom-task/)。

以下是支持的可用行业标准基准测试列表。您可以在 `eval_task` 参数中指定以下基准测试：


| 基准 | 模式 | 说明 | 指标 | Strategy | 可用子任务 | 
| --- |--- |--- |--- |--- |--- |
| mmlu | 文本 | 多任务语言理解：考核 57 个科目的知识。 | 准确性 | zs\$1cot | 是 | 
| mmlu\$1pro | 文本 | MMLU（专业子集），专注于法律、医学、会计和工程等专业领域。 | 准确性 | zs\$1cot | 否 | 
| bbh | 文本 | 高级推理任务：一系列具有挑战性的问题，用于考核更高级别的认知和解决问题的能力。 | 准确性 | zs\$1cot | 是 | 
| gpqa | 文本 | 一般物理问题解答：评测对物理概念和相关问题解决能力的理解情况。 | 准确性 | zs\$1cot | 否 | 
| math | 文本 | 数学问题解决：衡量在代数、微积分及应用题等领域的数学推理能力。 | exact\$1match | zs\$1cot | 是 | 
| strong\$1reject | 文本 | 质量控制任务：测试模型检测和拒绝不当、有害或不正确内容的能力。 | deflection | zs | 是 | 
| IFEval | 文本 | 指令跟随评估：衡量模型遵循给定指令并按照规范完成任务的准确程度。 | 准确性 | zs | 否 | 
| gen\$1qa | 文本 | 自定义数据集评估：让您可以自带数据集进行基准测试，将模型输出与参考答案及 ROUGE 和 BLEU 等指标进行比较。 | 全部 | gen\$1qa | 否 | 
| llm\$1judge | 文本 | LLM-as-a-judge 偏好比较：使用 Amazon Nova Judge 模型来确定提示的成对响应之间的偏好（B 与 A 比较），计算 B 比 A 更受欢迎的概率。 | 全部 | judge | 否 | 
| humaneval | 文本 | HumanEval：一个基准测试数据集，旨在评估大型语言模型的代码生成能力 | pass@1 | zs | 否 | 
|  mm\$1llm\$1judge  |  多模态（图像）  |  该全新基准评测的运行方式与上述基于文本的 `llm_judge` 一致。唯一区别在于其支持图像推理。  |  全部  |  judge  |  否  | 
|  rubric\$1llm\$1judge  | Text |  Rubric Judge 是基于 Amazon Nova 2.0 Lite 构建的增强版 LLM-as-a-judge 评测模型。与仅提供偏好判定的[原始评判模型](https://aws.amazon.com/blogs/machine-learning/evaluating-generative-ai-models-with-amazon-nova-llm-as-a-judge-on-amazon-sagemaker-ai/)不同，Rubric Judge 可针对每个提示动态生成自定义评估准则，并在多个维度上给出细粒度评分。  |  全部  |  judge  |  否  | 
|  aime\$12024  | Text |  AIME 2024：2024 年美国数学邀请赛（American Invitational Mathematics Examination），用于考查高阶数学推理与问题求解能力  |  exact\$1match  |  zs\$1cot  | No | 
|  calendar\$1scheduling  | Text |  Natural Plan：日程规划任务，用于评估跨日期、跨人员的会议安排等规划能力  |  exact\$1match  |  fs  | No | 

以下 `mmlu` 子任务可用：

```
MMLU_SUBTASKS = [
    "abstract_algebra",
    "anatomy",
    "astronomy",
    "business_ethics",
    "clinical_knowledge",
    "college_biology",
    "college_chemistry",
    "college_computer_science",
    "college_mathematics",
    "college_medicine",
    "college_physics",
    "computer_security",
    "conceptual_physics",
    "econometrics",
    "electrical_engineering",
    "elementary_mathematics",
    "formal_logic",
    "global_facts",
    "high_school_biology",
    "high_school_chemistry",
    "high_school_computer_science",
    "high_school_european_history",
    "high_school_geography",
    "high_school_government_and_politics",
    "high_school_macroeconomics",
    "high_school_mathematics",
    "high_school_microeconomics",
    "high_school_physics",
    "high_school_psychology",
    "high_school_statistics",
    "high_school_us_history",
    "high_school_world_history",
    "human_aging",
    "human_sexuality",
    "international_law",
    "jurisprudence",
    "logical_fallacies",
    "machine_learning",
    "management",
    "marketing",
    "medical_genetics",
    "miscellaneous",
    "moral_disputes",
    "moral_scenarios",
    "nutrition",
    "philosophy",
    "prehistory",
    "professional_accounting",
    "professional_law",
    "professional_medicine",
    "professional_psychology",
    "public_relations",
    "security_studies",
    "sociology",
    "us_foreign_policy",
    "virology",
    "world_religions"
]
```

以下 `bbh` 子任务可用：

```
BBH_SUBTASKS = [
    "boolean_expressions",
    "causal_judgement",
    "date_understanding",
    "disambiguation_qa",
    "dyck_languages",
    "formal_fallacies",
    "geometric_shapes",
    "hyperbaton",
    "logical_deduction_five_objects",
    "logical_deduction_seven_objects",
    "logical_deduction_three_objects",
    "movie_recommendation",
    "multistep_arithmetic_two",
    "navigate",
    "object_counting",
    "penguins_in_a_table",
    "reasoning_about_colored_objects",
    "ruin_names",
    "salient_translation_error_detection",
    "snarks",
    "sports_understanding",
    "temporal_sequences",
    "tracking_shuffled_objects_five_objects",
    "tracking_shuffled_objects_seven_objects",
    "tracking_shuffled_objects_three_objects",
    "web_of_lies",
    "word_sorting"
]
```

以下 `math` 子任务可用：

```
MATH_SUBTASKS = [
    "algebra",
    "counting_and_probability",
    "geometry",
    "intermediate_algebra",
    "number_theory",
    "prealgebra",
    "precalculus",
]
```

# 了解配方参数


**运行配置**  
以下是常规运行配置和所涉及参数的说明。

```
run:
  name: eval_job_name
  model_type: amazon.nova-micro-v1:0:128k
  model_name_or_path: nova-micro/prod
  replicas: 1
  data_s3_path: ""
  output_s3_path: s3://output_path
  mlflow_tracking_uri: ""
  mlflow_experiment_name : ""
  mlflow_run_name : ""
```
+ `name`：（必填）评估作业的描述性名称。这有助于在 AWS 管理控制台中识别您的作业。
+ `model_type`：（必填）指定要使用的 Amazon Nova 模型变体。请勿手动修改此字段。选项包括：
  + `amazon.nova-micro-v1:0:128k`
  + `amazon.nova-lite-v1:0:300k`
  + `amazon.nova-pro-v1:0:300k`
  + `amazon.nova-2-lite-v1:0:256k`
+ `model_name_or_path`：（必填）基本模型的路径或训练后检查点的 S3 路径。选项包括：
  + `nova-micro/prod`
  + `nova-lite/prod`
  + `nova-pro/prod`
  + `nova-lite-2/prod`
  + （训练后检查点的 S3 路径）`s3://<escrow bucket>/<job id>/outputs/checkpoints`
+ `replicas`：（必填）要在分布式训练中使用的计算实例数。您必须将此值设置为 1，因为不支持多节点。
+ `data_s3_path`：（必填）输入数据集的 S3 路径。除非您使用*自带数据集*或 *LLM-as-a-Judge* 配方，否则请将此参数留空。
+ `output_s3_path`：（必填）存储输出评估构件的 S3 路径。请注意，输出 S3 存储桶必须由创建作业的账户创建。
+ `mlflow_tracking_uri`:（可选）用于跟踪 MLflow 运行/实验的 MLflow 跟踪服务器 ARN。确保您拥有通过 SageMaker AI 执行角色访问跟踪服务器的权限

**评估配置**  
以下是模型评测配置和所涉及参数的说明。

```
evaluation:
  task: mmlu
  strategy: zs_cot
  subtask: mathematics
  metric: accuracy
```
+ `task`：（必填）指定要使用的评估基准测试或任务。

  支持的任务列表：
  + mmlu
  + mmlu\$1pro
  + bbh
  + gpqa
  + math
  + strong\$1reject
  + gen\$1qa
  + ifeval
  + llm\$1judge
  + humaneval
  + mm\$1llm\$1judge
  + rubric\$1llm\$1judge
  + aime\$12024
  + calendar\$1scheduling
  + humaneval
+ `strategy`：（必填）定义评估方法：
  + zs\$1cot：零样本思维链，该提示方法激励大型语言模型逐步进行推理，而不提供明确的示例。
  + zs：零样本，该方法事先无需任何训练示例即可解决问题。
  + gen\$1qa：一种专门用于自带数据集配方的策略。
  + judge：一种专门用于 Amazon Nova LLM as judge 和 mm\$1llm\$1judge 的策略。
+ `subtask`：（可选且可移除）为某些评估任务指定具体的子任务。如果您的任务没有任何子任务，请将其从配方中移除。
+ `metric`：（必填）要使用的评估指标。
  + accuracy：正确答案的百分比
  + exact\$1match：（对于 `math` 基准测试），返回输入预测字符串与其引用完全匹配的速率。
  + deflection：（对于 `strong reject` 基准测试），返回基本模型的相对偏差和差异显著性指标。
  + pass@1：（对于 `humaneval` 基准测试），该指标用于衡量模型的最高置信度预测与正确答案相匹配的情况所占的百分比。
  + `all`：返回以下指标：
    + 对于 `gen_qa` 和自带数据集基准测试，返回以下指标：
      + `rouge1`：衡量生成的文本和参考文本之间的一元（单个词）重叠度。
      + `rouge2`：衡量生成的文本和参考文本之间的二元（两个连续的词）重叠度。
      + `rougeL`：衡量文本之间的最长公共子序列，匹配中可以存在间隙。
      + `exact_match`：二进制分数（0 或 1），用于指示生成的文本是否与参考文本逐个字符完全匹配。
      + `quasi_exact_match`：与精确匹配类似，但更加宽松，通常忽略大小写、标点符号和空格差异。
      + `f1_score`：精度和查全率之间的调和平均数，衡量预测答案和参考答案之间的词语重叠度。
      + `f1_score_quasi`：与 f1\$1score 类似，但匹配更为宽松，使用忽略细微差异的标准化文本比较。
      + `bleu`：衡量生成的文本和参考文本之间 n-gram 匹配的精确度，通常用于翻译评估。
    + 对于 `llm_judge` 和 `mm_llm_judge`，自定义数据集基准，需返回以下指标：
      + `a_scores`：前向和反向评估传递中 `response_A` 的获胜次数。
      + `a_scores_stderr`：成对判断中 `response_A scores` 的标准误差。
      + `b_scores`：前向和反向评估传递中 `response_B` 的获胜次数。
      + `b_scores_stderr`：成对判断中 `response_B scores` 的标准误差。
      + `ties`：`response_A` 和 `response_B` 被评估为相等的判断数量。
      + `ties_stderr`：成对判断中平局的标准误差。
      + `inference_error`：无法适当评估的判断数量。
      + `inference_error_stderr`：判断中推理错误的标准误差。
      + `score`：基于 `response_B` 在前向和反向传递中的获胜次数得出的总分。
      + `score_stderr`：成对判断中总分的标准误差。
      + `winrate`：使用 Bradley-Terry 概率模型计算的 response\$1B 比 response\$1A 更受欢迎的概率。
      + `lower_rate`：自动采样预估胜率的下限（第 2.5 百分位）。

**推理配置**  
以下是推理配置和所涉及参数的说明。所有参数都是可选的。

```
inference:
  max_new_tokens: 200
  top_k: -1
  top_p: 1.0
  temperature: 0
  top_logprobs: 10
  reasoning_effort: null  # options: low/high to enable reasoning or null to disable reasoning
```
+ `max_new_tokens`：要生成的最大词元数。必须是整数。
+ `top_k`：要考虑的最高概率词元的数量。必须是整数。
+ `top_p`：词元采样的累积概率阈值。此值必须是介于 0.0 到 1.0 之间的浮点数（含两端值）。
+ `temperature`：词元选择的随机性。值越大，随机性越大。使用 0 以使结果具有确定性。此值必须是最小值为 0 的浮点数。
+ `top_logprobs`：推理响应中需返回的最高对数概率数量。取值必须为 0 到 20 之间的整数。对数概率包含消息内容中返回的输出词元及其对应的对数概率值。
+ `reasoning_effort`：控制具备推理能力模型的推理行为。仅当 `model_type` 指定了具备推理能力的模型（当前为 `amazon.nova-2-lite-v1:0:256k`）时，才需设置 `reasoning_effort`。可用选项为 `null`（未设置时的默认值；表示禁用推理）、`low` 或 `high`。

请注意，对于 `humaneval`，建议使用以下推理配置：

```
inference:
  top_k: 1
  max_new_tokens: 1600
  temperature: 0.0
```

**MLflow 配置**  
以下是 MLflow 配置和所涉及参数的说明。所有参数都是可选的。

```
run:
  mlflow_tracking_uri: ""
  mlflow_experiment_name: ""
  mlflow_run_name: ""
```
+ `mlflow_tracking_uri`:（可选）MLflow 跟踪服务器地址（仅在 SMHP 下需要）
+ `mlflow_experiment_name`:（可选）实验名称，用于对相关的机器学习运行记录进行分组
+ `mlflow_run_name`:（可选）实验中某次特定训练运行的自定义名称

# 评估配方示例


Amazon Nova 提供了四种类型的评估配方，这些配方可在 SageMaker HyperPod 配方 GitHub 存储库中找到。

## 通用文本基准测试配方


这些配方让您能够通过一套全面的纯文本基准测试来评估 Amazon Nova 模型的基本功能。它们以 `xxx_general_text_benchmark_eval.yaml` 格式提供。

## 自带数据集基准测试配方


这些配方让您能够使用自己的数据集进行基准测试，并使用不同类型的指标将模型输出与参考答案进行对比。它们以 `xxx_bring_your_own_dataset_eval.yaml` 格式提供。

以下是自带数据集的要求：
+ 文件格式要求
  + 必须有一个包含评估示例的 `gen_qa.jsonl` 文件。
  + 您的数据集必须上传到 SageMaker 训练作业可以访问的 S3 位置。
  + 该文件必须遵循常规问答数据集所需的架构格式。
+ 架构格式要求：JSONL 文件中的每一行都必须是包含以下字段的 JSON 对象：
  + `query`：（必填）包含需要答案的问题或说明的字符串
  + `response`：（必填）包含预期模型输出的字符串
  + `system`：（可选）包含系统提示的字符串，用于在处理查询之前设置 AI 模型的行为、角色或个性
  + `metadata`：（可选）字符串类型，与本条记录关联的元数据，用于标签分类。

以下是自带数据集示例条目

```
{
   "system":"You are a english major with top marks in class who likes to give minimal word responses: ",
   "query":"What is the symbol that ends the sentence as a question",
   "response":"?"
}
{
   "system":"You are a pattern analysis specialist that provides succinct answers: ",
   "query":"What is the next number in this series? 1, 2, 4, 8, 16, ?",
   "response":"32"
}
{
   "system":"You have great attention to detail that follows instructions accurately: ",
   "query":"Repeat only the last two words of the following: I ate a hamburger today and it was kind of dry",
   "response":"of dry"
}
```

要使用您的自定义数据集，请按以下必填字段修改您的评估配方，且不要更改其中任何内容：

```
evaluation:
  task: gen_qa
  strategy: gen_qa
  metric: all
```

适用以下限制：
+ 每次评估只支持一个 JSONL 文件。
+ 该文件必须严格遵循定义的架构。
+ 上下文长度限制：对于数据集中的每个样本，上下文长度（包括系统 \$1 查询提示）应小于 3.5k。

## Nova LLM-as-a-Judge 基准测试配方


Amazon Nova LLM-as-a-Judge 是一项模型评测特征，让客户可以使用自定义数据集，将一个模型的响应质量与基准模型的响应质量进行比较。其接受包含提示、基线响应和挑战响应的数据集，然后使用 Amazon Nova Judge 模型基于 [Bradley-Terry 概率](https://en.wikipedia.org/wiki/Bradley%E2%80%93Terry_model)和成对比较提供胜率指标。

配方以 `xxx_llm_judge_eval.yaml` 格式提供。

以下是 LLM-as-a-Judge 的要求：
+ 文件格式要求
  + 有一个包含评估示例的 `llm_judge.jsonl` 文件。文件名称必须为 `llm_judge.jsonl`。
  + 您的数据集必须上传到 [SageMaker AI SageMaker HyperPod RIG](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-hp-cluster.html) 可以访问的 S3 位置。
  + 该文件必须遵循 `llm_judge.jsonl` 数据集所需的架构格式。
  + 输入数据集应确保所有记录的上下文长度小于 12k。
+ 架构格式要求：JSONL 文件中的每一行都必须是包含以下字段的 JSON 对象：
  + `prompt`：（必填）包含生成响应提示的字符串。
  + `response_A`：包含基准响应的字符串。
  + `response_B`：包含与基准响应进行比较的替代响应的字符串。

这是一个 LLM-as-a-Judge 示例条目

```
{
"prompt": "What is the most effective way to combat climate change?",
"response_A": "The most effective way to combat climate change is through a combination of transitioning to renewable energy sources and implementing strict carbon pricing policies. This creates economic incentives for businesses to reduce emissions while promoting clean energy adoption.",
"response_B": "We should focus on renewable energy. Solar and wind power are good. People should drive electric cars. Companies need to pollute less."
}
{
"prompt": "Explain how a computer's CPU works",
"response_A": "CPU is like brain of computer. It does math and makes computer work fast. Has lots of tiny parts inside.",
"response_B": "A CPU (Central Processing Unit) functions through a fetch-execute cycle, where instructions are retrieved from memory, decoded, and executed through its arithmetic logic unit (ALU). It coordinates with cache memory and registers to process data efficiently using binary operations."
}
{
"prompt": "How does photosynthesis work?",
"response_A": "Plants do photosynthesis to make food. They use sunlight and water. It happens in leaves.",
"response_B": "Photosynthesis is a complex biochemical process where plants convert light energy into chemical energy. They utilize chlorophyll to absorb sunlight, combining CO2 and water to produce glucose and oxygen through a series of chemical reactions in chloroplasts."
}
```

要使用您的自定义数据集，请按以下必填字段修改您的评估配方，且不要更改其中任何内容：

```
evaluation:
  task: llm_judge
  strategy: judge
  metric: all
```

适用以下限制：
+ 每次评估只支持一个 JSONL 文件。
+ 该文件必须严格遵循定义的架构。
+ Amazon Nova Judge 模型对于所有模型系列规格（即 Lite、Micro 和 Pro）都是一样的。
+ 目前不支持自定义评估模型。
+ 上下文长度限制：对于数据集中的每个样本，上下文长度（包括系统 \$1 查询提示）应小于 7k。

## 使用 Nova LLM-as-a-judge，完成多模态（图像）基准测试配方


Nova LLM Judge 多模态（图像）版（简称 Amazon Nova MM\$1LLM Judge）是一项模型评测功能，支持使用自定义数据集，将目标模型的响应质量与基线模型的响应进行对比评测。该功能接受包含提示、基线响应和挑战响应的数据集，以及 Base64 编码字符串图像，然后使用 Amazon Nova Judge 模型基于 [Bradley-Terry](https://en.wikipedia.org/wiki/Bradley%E2%80%93Terry_model) 概率模型通过成对比较提供胜率指标。配方格式：`xxx_mm_llm_judge _eval.yaml`。

**Nova LLM 数据集要求**

文件格式：
+ 包含评估示例的单个 `mm_llm_judge.jsonl` 文件。文件名称必须严格为 `llm_judge.jsonl`。
+ 您必须将数据集上传到 SageMaker 训练作业可以访问的 S3 位置。
+ 该文件必须遵循 `mm_llm_judge` 数据集所需的架构格式。
+ 输入数据集应确保：排除 image 属性后，所有记录的上下文长度均小于 12k。

架构格式：`.jsonl` 文件中的每一行都必须是包含以下字段的 JSON 对象。
+ 必填字段。

  `prompt`：包含生成响应提示的字符串。

  `images`：对象数组，每个对象包含 data 属性（值为 Base64 编码的图像字符串）。

  `response_A`：包含基准响应的字符串。

  `response_B`：包含与基准响应进行比较的替代响应的字符串。

示例条目

为便于阅读，以下示例包含换行与缩进，但在实际数据集中，每条记录必须单独占一行。

```
{
  "prompt": "what is in the image?",
  "images": [
    {
      "data": "data:image/jpeg;Base64,/9j/2wBDAAQDAwQDAwQEAwQFBAQFBgo..."
    }
  ],
  "response_A": "a dog.",
  "response_B": "a cat.",
}
{
  "prompt": "how many animals in echo of the images?",
  "images": [
    {
      "data": "data:image/jpeg;Base64,/9j/2wBDAAQDAwQDAwQEAwQFBAQFBgo..."
    },
    {
      "data": "data:image/jpeg;Base64,/DKEafe3gihn..."
    }
  ],
  "response_A": "The first image contains one cat and the second image contains one dog",
  "response_B": "The first image has one aminal and the second has one animal",
}
```

要使用您的自定义数据集，请按以下必填字段修改您的评估配方，且不要更改其中任何内容：

```
evaluation:
  task: mm_llm_judge
  strategy: judge
  metric: all
```

**限制**
+ 每次评估只支持一个 `.jsonl` 文件。
+ 该文件必须严格遵循定义的架构。
+ Nova MM Judge 模型仅支持图像参考。
+ Nova MM Judge 模型对于 Amazon Nova Lite 规格是一样的。
+ 目前不支持自定义评估模型。
+ 不支持 Amazon S3 图像 URI。
+ 输入数据集应确保：排除 image 属性后，所有记录的上下文长度均小于 12k。

## Rubric Judge


Rubric Judge 是基于 Amazon Nova 2.0 Lite 构建的增强版 LLM-as-a-judge 评测模型。与仅提供偏好判定（A 优于 B、B 优于 A 或平局）的[原始评判模型](https://aws.amazon.com/blogs/machine-learning/evaluating-generative-ai-models-with-amazon-nova-llm-as-a-judge-on-amazon-sagemaker-ai/)不同，Rubric Judge 可针对每个提示词动态生成自定义评估准则，并在多个维度上给出细粒度评分。

关键功能：
+ **动态评估维度生成**：根据输入提示自动生成相关的评估维度
+ **加权评分**：为各评估维度分配重要性权重，体现其相对优先级
+ **细粒度评测**：对每个维度以二分类（是/否）或量表（1–5 分）形式给出详细评分
+ **质量指标**：计算连续型质量得分（0–1 区间），量化不同响应之间的差异程度

模型生成的评估维度示例：

```
price_validation:
  description: "The response includes validation to ensure price is a positive value."
  type: "scale"
  weight: 0.3
```

模型会依据所有生成的评估维度对两组响应进行评估，再利用各维度得分得出最终偏好判定。

**Topics**
+ [

### 配方配置
](#nova-hp-evaluate-rubric-judge-recipe)
+ [

### 输入数据集格式
](#nova-hp-evaluate-rubric-judge-input)
+ [

### 评估输出
](#nova-hp-evaluate-rubric-judge-output)
+ [

### 推理模型支持
](#nova-hp-evaluate-rubric-judge-reasoning)

### 配方配置


**Rubric Judge 配方**  
在配方中通过设置 `task: rubric_llm_judge` 来启用 Rubric Judge：

```
run:
  name: nova-eval-job-name                              # [MODIFIABLE] Unique identifier for your evaluation job
  model_type: amazon.nova-2-lite-v1:0:256k              # [FIXED] Rubric Judge model type
  model_name_or_path: "nova-lite-2/prod"                # [FIXED] Path to model checkpoint or identifier
  replicas: 1                                           # [MODIFIABLE] Number of replicas for SageMaker Training job
  data_s3_path: ""                                      # [FIXED] Leave empty for SageMaker Training job
  output_s3_path: ""                                    # [FIXED] Leave empty for SageMaker Training job

evaluation:
  task: rubric_llm_judge                                # [FIXED] Evaluation task - enables Rubric Judge
  strategy: judge                                       # [FIXED] Evaluation strategy
  metric: all                                           # [FIXED] Metric calculation method

inference:
  max_new_tokens: 12000                                 # [MODIFIABLE] Maximum tokens to generate
  top_k: -1                                             # [MODIFIABLE] Top-k sampling parameter
  top_p: 1.0                                            # [MODIFIABLE] Nucleus sampling parameter
  temperature: 0                                        # [MODIFIABLE] Sampling temperature (0 = deterministic)
```

**原始 LLM-as-a-judge 配方（供比较）**  
原始评判模型使用 `task: llm_judge`：

```
run:
  name: eval-job-name                                   # [MODIFIABLE] Unique identifier for your evaluation job
  model_type: amazon.nova-micro-v1:0:128k               # [FIXED] Model type
  model_name_or_path: "nova-micro/prod"                 # [FIXED] Path to model checkpoint or identifier
  replicas: 1                                           # [MODIFIABLE] Number of replicas for SageMaker Training job
  data_s3_path: ""                                      # [FIXED] Leave empty for SageMaker Training job
  output_s3_path: ""                                    # [FIXED] Leave empty for SageMaker Training job

evaluation:
  task: llm_judge                                       # [FIXED] Original judge task
  strategy: judge                                       # [FIXED] Evaluation strategy
  metric: all                                           # [FIXED] Metric calculation method

inference:
  max_new_tokens: 12000                                 # [MODIFIABLE] Maximum tokens to generate
  top_k: -1                                             # [MODIFIABLE] Top-k sampling parameter
  top_p: 1.0                                            # [MODIFIABLE] Nucleus sampling parameter
  temperature: 0                                        # [MODIFIABLE] Sampling temperature (0 = deterministic)
```

### 输入数据集格式


输入数据集格式与[原始评判模型](https://aws.amazon.com/blogs/machine-learning/evaluating-generative-ai-models-with-amazon-nova-llm-as-a-judge-on-amazon-sagemaker-ai/)完全一致：

**必填字段：**
+ `prompt`：字符串类型，包含输入提示与指令
+ `response_A`：字符串类型，基准模型的输出
+ `response_B`：字符串类型，自定义模型的输出

**示例数据集（JSONL 格式）：**

```
{"prompt": "What is the most effective way to combat climate change?", "response_A": "The most effective way to combat climate change is through a combination of transitioning to renewable energy sources and implementing strict carbon pricing policies. This creates economic incentives for businesses to reduce emissions while promoting clean energy adoption.", "response_B": "We should focus on renewable energy. Solar and wind power are good. People should drive electric cars. Companies need to pollute less."}
{"prompt": "Explain how a computer's CPU works", "response_A": "CPU is like brain of computer. It does math and makes computer work fast. Has lots of tiny parts inside.", "response_B": "A CPU (Central Processing Unit) functions through a fetch-execute cycle, where instructions are retrieved from memory, decoded, and executed through its arithmetic logic unit (ALU). It coordinates with cache memory and registers to process data efficiently using binary operations."}
{"prompt": "How does photosynthesis work?", "response_A": "Plants do photosynthesis to make food. They use sunlight and water. It happens in leaves.", "response_B": "Photosynthesis is a complex biochemical process where plants convert light energy into chemical energy. They utilize chlorophyll to absorb sunlight, combining CO2 and water to produce glucose and oxygen through a series of chemical reactions in chloroplasts."}
```

**格式要求：**
+ 每条记录必须是单行 JSON 对象
+ 各行记录以换行符分隔
+ 严格遵循示例中所示的字段命名规则

### 评估输出


**输出结构**  
与原始评判模型相比，Rubric Judge 可生成更完善的评估指标：

```
{
  "config_general": {
    "lighteval_sha": "string",
    "num_fewshot_seeds": "int",
    "max_samples": "int | null",
    "job_id": "int",
    "start_time": "float",
    "end_time": "float",
    "total_evaluation_time_secondes": "string",
    "model_name": "string",
    "model_sha": "string",
    "model_dtype": "string | null",
    "model_size": "string"
  },
  "results": {
    "custom|rubric_llm_judge_judge|0": {
      "a_scores": "float",
      "a_scores_stderr": "float",
      "b_scores": "float",
      "b_scores_stderr": "float",
      "ties": "float",
      "ties_stderr": "float",
      "inference_error": "float",
      "inference_error_stderr": "float",
      "score": "float",
      "score_stderr": "float",
      "weighted_score_A": "float",
      "weighted_score_A_stderr": "float",
      "weighted_score_B": "float",
      "weighted_score_B_stderr": "float",
      "score_margin": "float",
      "score_margin_stderr": "float",
      "winrate": "float",
      "lower_rate": "float",
      "upper_rate": "float"
    }
  },
  "versions": {
    "custom|rubric_llm_judge_judge|0": "int"
  }
}
```

**Rubric Judge 新增指标**  
以下六项指标为 Rubric Judge 独有，可提供细粒度的质量评测：


| 指标 | 说明 | 
| --- |--- |
| weighted\$1score\$1A | 基于模型生成的所有评估维度，对 response\$1A 计算的归一化加权平均质量得分。得分按维度重要性加权，并归一化到 0–1 区间（分值越高，质量越好） | 
| weighted\$1score\$1A\$1stderr | weighted\$1score\$1A 的均值标准误，用于表示统计不确定性 | 
| weighted\$1score\$1B | 基于模型生成的所有评估维度，对 response\$1B 计算的归一化加权平均质量得分。得分按维度重要性加权，并归一化到 0–1 区间（分值越高，质量越好） | 
| weighted\$1score\$1B\$1stderr | weighted\$1score\$1B 的均值标准误，用于表示统计不确定性 | 
| score\$1margin | 加权分数差值（计算公式：weighted\$1score\$1A - weighted\$1score\$1B）。范围：-1.0 至 1.0。正值表示 response\$1A 更优；负值表示 response\$1B 更优；接近 0 表示两者质量相近 | 
| score\$1margin\$1stderr | score\$1margin 的均值标准误，用于表示质量差异测量结果的不确定性 | 

**加权分数指标说明**  
**用途**：加权分数提供连续型质量评估，作为二分类偏好判定的补充，便于更深入地分析模型性能。

**与原始评判模型的主要区别**：
+ **原始评判模型**：仅输出离散偏好结果（A 优于 B、B 优于 A、A 与 B 持平）
+ **Rubric Judge**：基于自定义评估维度，同时输出偏好结果与连续型质量得分（0–1 区间）

**score\$1margin 解读**：
+ `score_margin = -0.128`：表示 response\$1B 得分比 response\$1A 高 12.8 个百分点
+ `|score_margin| < 0.1`：质量差异极小（判定接近）
+ `|score_margin| > 0.2`：质量差异明显（判定置信度高）

**使用案例**：
+ **模型优化**：定位模型表现不足的具体方面
+ **质量量化**：不仅评估胜负关系，更衡量性能差距的大小
+ **置信度评测**：区分接近判定与明确的质量差异

**重要**  
最终判定仍以评判模型的显式偏好标签为准，以保留整体推理能力，并通过正向/反向评估有效缓解位置偏差。加权分数仅作为可观测性工具，不能替代主判定结果。

**计算方法**  
加权分数通过以下流程计算：
+ **提取评估维度数据**：解析评判模型的 YAML 输出，提取各维度得分与权重
+ **得分归一化**：
  + 量表型维度（1–5 分）：通过公式 `(score - 1) / 4` 归一化到 0–1 区间
  + 二分型维度（是/否）：转换为 1.0/0.0
+ **应用权重**：将每条归一化得分乘以对应维度的权重
+ **汇总得分**：对每条响应的所有加权分数求和
+ **计算差值**：计算 `score_margin = weighted_score_A - weighted_score_B`

**示例**：如果若 response\$1A 加权总分为 0.65，response\$1B 为 0.78，则 `score_margin` = -0.13，表示在所有加权维度下，response\$1B 的质量高出 13 个百分点。

### 推理模型支持


推理模型支持功能可借助具备推理能力的 Amazon Nova 模型开展评测，这类模型会在生成最终响应前执行显式的内部推理。该功能通过 `reasoning_effort` 参数实现 API 级别的控制，可动态启用/禁用推理功能，有助于提升复杂分析类任务的响应质量。

**支持的模型**：
+ amazon.nova-2-lite-v1:0:256k

**配方配置**  
在配方的 `inference` 模块中添加 `reasoning_effort` 参数，即可启用推理功能：

```
run:
  name: eval-job-name                                    # [MODIFIABLE] Unique identifier for your evaluation job
  model_type: amazon.nova-2-lite-v1:0:256k               # [FIXED] Must be a reasoning-supported model
  model_name_or_path: nova-lite-2/prod                   # [FIXED] Path to model checkpoint or identifier
  replicas: 1                                            # [MODIFIABLE] Number of replicas for SageMaker Training job
  data_s3_path: ""                                       # [MODIFIABLE] Leave empty for SageMaker Training job; optional for SageMaker  SageMaker HyperPod  job
  output_s3_path: ""                                     # [MODIFIABLE] Output path for SageMaker  SageMaker HyperPod  job (not compatible with SageMaker Training jobs)

evaluation:
  task: mmlu                                             # [MODIFIABLE] Evaluation task
  strategy: generate                                     # [MODIFIABLE] Evaluation strategy
  metric: all                                            # [MODIFIABLE] Metric calculation method

inference:
  reasoning_effort: high                                 # [MODIFIABLE] Enables reasoning mode; options: low/medium/high or null to disable
  max_new_tokens: 200                                    # [MODIFIABLE] Maximum tokens to generate
  top_k: 50                                              # [MODIFIABLE] Top-k sampling parameter
  top_p: 1.0                                             # [MODIFIABLE] Nucleus sampling parameter
  temperature: 0                                         # [MODIFIABLE] Sampling temperature (0 = deterministic)
```

**reasing\$1effort 参数使用说明**  
`reasoning_effort` 参数用于控制具备推理能力模型的推理行为。

**先决条件：**
+ **模型兼容性**：仅当 `model_type` 指定了具备推理能力的模型（当前为 `amazon.nova-2-lite-v1:0:256k`）时，才需设置 `reasoning_effort`
+ **错误处理**：对不受支持的模型使用 `reasoning_effort` 将会失败，并返回 `ConfigValidationError: "Reasoning mode is enabled but model '{model_type}' does not support reasoning. Please use a reasoning-capable model or disable reasoning mode."` 错误

**可用选项**：


| Option | 行为 | 词元限制 | 使用案例 | 
| --- |--- |--- |--- |
| null（默认） | 禁用推理模式 | 不适用 | 无需推理开销的标准评估 | 
| low | 启用推理并施加约束 | 内部推理占用 4000 词元 | 需要简洁推理的场景；兼顾速度与成本优化 | 
| high | 启用推理且无约束 | 内部推理无词元上限 | 需要深度分析与分步推理的复杂问题 | 

**何时启用推理**  
**满足以下场景时，建议使用推理模式（`low`、`medium` 或 `high`）**：
+ 复杂问题求解任务（数学、逻辑谜题、编程）
+ 需要中间推理过程的多步分析类问题
+ 详细推导或分步思考可提升准确率的任务
+ 优先保证响应质量而非速度的场景

**满足以下场景时，建议使用非推理模式（不设置该参数）**：
+ 简单问答或事实查询
+ 创意写作类任务
+ 对响应速度要求极高的场景
+ 需要排除推理开销的性能基准测试
+ 推理无法提升效果、需优化成本的场景

**问题排查**  
**错误：“Reasoning mode is enabled but model does not support reasoning”**

**原因**：`reasoning_effort` 参数被设为非空值，但指定的 `model_type` 支持推理。

**解决方法：**
+ 确认模型类型为 `amazon.nova-2-lite-v1:0:256k`
+ 若使用其他模型，或切换为具备推理能力的模型，或从配方中移除 `reasoning_effort` 参数

# 启动评估作业


下面提供了建议的评估实例类型和模型类型配置：

```
# Install Dependencies (Helm - https://helm.sh/docs/intro/install/)
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
chmod 700 get_helm.sh
./get_helm.sh
rm -f ./get_helm.sh

# Install the SageMaker HyperPod CLI
git clone --recurse-submodules https://github.com/aws/sagemaker-hyperpod-cli.git
git checkout -b release_v2
cd sagemaker-hyperpod-cli
pip install .

# Verify the installation
hyperpod --help

# Connect to a SageMaker HyperPod Cluster
hyperpod connect-cluster --cluster-name cluster-name


# Submit the Job using the recipe for eval
# Namespace by default should be kubeflow
hyperpod start-job [--namespace namespace] --recipe evaluation/nova/nova_micro_p5_48xl_general_text_benchmark_eval --override-parameters \
'{
    "instance_type":"p5d.48xlarge",
    "container": "708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-evaluation-repo:SM-HP-Eval-V2-latest",
    "recipes.run.name": custom-run-name,
    "recipes.run.model_type": model_type,
    "recipes.run.model_name_or_path" " model name or finetune checkpoint s3uri,
    "recipes.run.data_s3_path": s3 for input data only for genqa and llm_judge, must be full S3 path that include filename,
}'

# List jobs
hyperpod list-jobs [--namespace namespace] [--all-namespaces]

# Getting Job details
hyperpod get-job --job-name job-name [--namespace namespace] [--verbose]

# Listing Pods
hyperpod list-pods --job-name job-name --namespace namespace

# Cancel Job
hyperpod cancel-job --job-name job-name [--namespace namespace]
```

您还应该能够通过 Amazon EKS 集群控制台查看作业状态。

# 访问和分析评估结果


成功完成评估作业后，您可以参考本节中的信息访问并分析结果。根据配方中定义的 `output_s3_path`（例如 `s3://output_path/`），输出结构如下所示：

```
job_name/
├── eval-result/
│    └── results_[timestamp].json
│    └── inference_output.jsonl (only present for gen_qa)
│    └── details/
│        └── model/
│            └── execution-date-time/
│                └──details_task_name_#_datetime.parquet
└── tensorboard-results/
    └── eval/
        └── events.out.tfevents.[timestamp]
```

指标结果存储在指定的 S3 输出位置 `s3://output_path/job_name/eval-result/result-timestamp.json`。

Tensorboard 结果存储在 S3 路径 `s3://output_path/job_name/eval-tensorboard-result/eval/event.out.tfevents.epoch+ip` 中。

除 `llm_judge` 和 `strong_reject` 之外的所有推理输出都存储在 S3 路径中：`s3://output_path/job_name/eval-result/details/model/taskname.parquet`。

对于 `gen_qa`，`inference_output.jsonl` 文件针对每个 JSON 对象均包含以下字段：
+ prompt：提交给模型的最终提示
+ 推理：模型的原始推理输出
+ gold：来自输入数据集的目标响应
+ metadata：来自输入数据集的元数据字符串（如果提供）

要在 Tensorboard 中直观显示您的评估指标，请完成以下步骤：

1. 导航到 SageMaker AI Tensorboard。

1. 选择 **S3 文件夹**。

1. 添加您的 S3 文件夹路径，例如 `s3://output_path/job-name/eval-tensorboard-result/eval`。

1. 等待同步完成。

时间序列、标量和文本可视化均可用。

我们建议您遵循以下最佳实操：
+ 按模型和基准测试类型整理输出路径。
+ 保持一致的命名约定以便于跟踪。
+ 将解压缩的结果保存在安全的位置。
+ 监控 TensorBoard 同步状态以成功加载数据。

您可以在 CloudWatch 日志组 `/aws/sagemaker/Clusters/cluster-id` 中找到 SageMaker HyperPod 作业错误日志。

## 对数概率输出格式


在推理设置中配置 `top_logprobs` 后，评估输出会在 parquet 文件中包含词元级别的对数概率。每个词元位置都会以字典形式，返回排名靠前的候选词元及其对数概率，结构如下：

```
{
"Ġint": {"logprob_value": -17.8125, "decoded_value": " int"},
"Ġthe": {"logprob_value": -2.345, "decoded_value": " the"}
}
```

每个词元条目包含：
+ `logprob_value`：词元的对数概率值
+ `decoded_value`：词元经解码后人类可读的字符串形式

原始分词器词元作为字典键以确保唯一性，`decoded_value` 则提供可读形式。

# RFT 评测


**注意**  
仅当您为 Amazon Nova Forge 客户时，方可在自有 AWS 环境中通过远程奖励函数开展评测。

**重要**  
`rl_env` 配置字段仅用于评测，不用于训练。训练期间，需要使用 `reward_lambda_arn`（单轮）或带有 `rollout.delegate: true`（多轮）的 BYOO 基础设施来配置奖励函数。

**什么是 RFT 评测？**  
RFT 评测支持您在强化学习微调的训练前、训练中及训练后，通过自定义奖励函数评测模型性能。与采用预定义指标的标准评测不同，RFT 评测支持通过 Lambda 函数自定义成功标准，并依据您的具体需求对模型输出进行评分。

**为什么要使用 RFT 进行评测？**  
评测对于判断强化微调过程是否实现以下目标至关重要：
+ 提升模型与您特定使用案例及人类价值偏好的对齐程度
+ 维持或提升模型在核心任务上的能力
+ 避免产生非预期副作用，例如事实准确性下降、内容冗余度增加或其他任务性能退化
+ 满足由奖励函数定义的自定义成功标准

**何时使用 RFT 评测**  
在以下场景中使用 RFT 评测：
+ RFT 训练之前：在评测数据集上建立基线指标
+ RFT 训练期间：使用中间检查点监控训练进度
+ RFT 训练之后：验证最终模型是否符合您的要求
+ 模型对比：采用一致的奖励标准对多个模型版本进行评测

**注意**  
如需领域专属的自定义评估指标，请使用 RFT 评测。对于通用评测（准确率、困惑度、BLEU），请使用标准评测方法。

**Topics**
+ [

## 数据格式要求
](#nova-hp-evaluate-rft-data-format)
+ [

## 准备评测配方
](#nova-hp-evaluate-rft-recipe)
+ [

## 预设奖励函数
](#nova-hp-evaluate-rft-preset)
+ [

## 创建奖励函数
](#nova-hp-evaluate-rft-create-function)
+ [

## IAM 权限
](#nova-hp-evaluate-rft-iam)
+ [

## 执行评测作业
](#nova-hp-evaluate-rft-execution)
+ [

## 了解评测结果
](#nova-hp-evaluate-rft-results)

## 数据格式要求


**输入数据结构**  
RFT 评测输入数据必须遵循 OpenAI 强化微调格式。每个样本都是一个 JSON 对象，其中包含：
+ `messages`：包含 `system` 和 `user` 角色的对话轮次数组
+ 其他可选元数据，例如 reference\$1answer

**数据格式示例**  
以下示例显示了所需格式：

```
{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Solve for x. Return only JSON like {\"x\": <number>}. Equation: 2x + 5 = 13"
        }
      ]
    }
  ],
  "reference_answer": {
    "x": 4
  }
}
```

**目前的局限性**  
以下限制适用于 RFT 评测：
+ 纯文本模式：不支持多模态输入（图像、音频、视频）
+ 单轮对话：仅支持单条用户消息（不支持多轮对话）
+ JSON 格式：输入数据必须为 JSONL 格式（每行一个 JSON 对象）
+ 模型输出：根据指定模型生成的补全进行评测

## 准备评测配方


**示例配方配置**  
以下示例展示了一个完整的 RFT 评测配方：

```
run:
  name: nova-lite-rft-eval-job
  model_type: amazon.nova-lite-v1:0:300k
  model_name_or_path: s3://escrow_bucket/model_location    # [MODIFIABLE] S3 path to your model or model identifier
  replicas: 1                                             # [MODIFIABLE] For SageMaker Training jobs only; fixed for  SageMaker HyperPod  jobs
  data_s3_path: ""                                        # [REQUIRED FOR HYPERPOD] Leave empty for SageMaker Training jobs
  output_s3_path: ""                                      # [REQUIRED] Output artifact S3 path for evaluation results

evaluation:
  task: rft_eval                                          # [FIXED] Do not modify
  strategy: rft_eval                                      # [FIXED] Do not modify
  metric: all                                             # [FIXED] Do not modify

# Inference Configuration
inference:
  max_new_tokens: 8196                                    # [MODIFIABLE] Maximum tokens to generate
  top_k: -1                                               # [MODIFIABLE] Top-k sampling parameter
  top_p: 1.0                                              # [MODIFIABLE] Nucleus sampling parameter
  temperature: 0                                          # [MODIFIABLE] Sampling temperature (0 = deterministic)
  top_logprobs: 0

# Evaluation Environment Configuration (NOT used in training)
rl_env:
  reward_lambda_arn: arn:aws:lambda:<region>:<account_id>:function:<reward-function-name>
```

## 预设奖励函数


两个预设的奖励函数（`prime_code` 和 `prime_math`）可用作 Lambda 层，以便与 RFT Lambda 函数集成。

**概述**  
这些预设函数提供开箱即用的评测能力，适用于：
+ **prime\$1code**：代码生成和正确性评测
+ **prime\$1math**：数学推理和问题求解评测

**快速设置**  
要使用预设奖励函数，请执行以下操作：

1. 从 [nova-custom-eval-sdk 版本](https://github.com/aws/nova-custom-eval-sdk/releases)页面下载 Lambda 层

1. 使用 AWS CLI 发布 Lambda 层：

   ```
   aws lambda publish-layer-version \
       --layer-name preset-function-layer \
       --description "Preset reward function layer with dependencies" \
       --zip-file fileb://universal_reward_layer.zip \
       --compatible-runtimes python3.9 python3.10 python3.11 python3.12 \
       --compatible-architectures x86_64 arm64
   ```

1. 在 AWS 管理控制台中将该层添加到 Lambda 函数（从自定义层中选择 preset-function-layer，并添加 AWSSDKPandas-Python312 以获取 numpy 依赖项）

1. 在 Lambda 代码中导入并使用：

   ```
   from prime_code import compute_score  # For code evaluation
   from prime_math import compute_score  # For math evaluation
   ```

**prime\$1code 函数**  
**用途**：通过针对测试用例执行代码并衡量正确性来评测 Python 代码生成任务。

**评测输入数据集格式示例**：

```
{"messages":[{"role":"user","content":"Write a function that returns the sum of two numbers."}],"reference_answer":{"inputs":["3\n5","10\n-2","0\n0"],"outputs":["8","8","0"]}}
{"messages":[{"role":"user","content":"Write a function to check if a number is even."}],"reference_answer":{"inputs":["4","7","0","-2"],"outputs":["True","False","True","True"]}}
```

**主要特征**：
+ 从 Markdown 代码块中自动提取代码
+ 函数检测与基于调用的测试
+ 带超时保护的测试用例执行
+ 语法验证与编译检查
+ 包含回溯信息的详细错误报告

**prime\$1math 函数**  
**用途**：依托符号计算能力，评测模型的数学推理与问题求解水平。

**输入格式**：

```
{"messages":[{"role":"user","content":"What is the derivative of x^2 + 3x?."}],"reference_answer":"2*x + 3"}
```

**主要特征**：
+ 使用 SymPy 进行符号计算评测
+ 支持多种答案格式（LaTeX、纯文本、符号）
+ 数学等价性检查
+ 表达式归一化与化简

**最佳实践**  
使用预设奖励函数时，请遵循以下最佳实践：
+ 在测试用例中使用正确的数据类型（整数与字符串、布尔值与 True）
+ 在代码问题中提供清晰的函数签名
+ 在测试输入中包括边缘情况（零、负数、空输入）
+ 在参考答案中统一设置数学表达式的格式
+ 在部署前使用样本数据测试奖励函数

## 创建奖励函数


**Lambda ARN**  
必须遵循以下格式来表示 Lambda ARN：

```
"arn:aws:lambda:*:*:function:*SageMaker*"
```

如果 Lambda 不遵循此命名方案，作业将失败并显示以下错误：

```
[ERROR] Unexpected error: lambda_arn must contain one of: ['SageMaker', 'sagemaker', 'Sagemaker'] when running on SMHP platform (Key: lambda_arn)
```

**Lambda 函数结构**  
Lambda 函数接收批量的模型输出并返回奖励分数。以下是一个实现示例：

```
from typing import List, Any
import json
import re
from dataclasses import asdict, dataclass


@dataclass
class MetricResult:
    """Individual metric result."""
    name: str
    value: float
    type: str


@dataclass
class RewardOutput:
    """Reward service output."""
    id: str
    aggregate_reward_score: float
    metrics_list: List[MetricResult]


def lambda_handler(event, context):
    """ Main lambda handler """
    return lambda_grader(event)


def lambda_grader(samples: list[dict]) -> list[dict]:
    """ Core grader function """
    scores: List[RewardOutput] = []

    for sample in samples:
        print("Sample: ", json.dumps(sample, indent=2))

        # Extract components
        idx = sample.get("id", "no id")
        if not idx or idx == "no id":
            print(f"ID is None/empty for sample: {sample}")

        ground_truth = sample.get("reference_answer")

        if "messages" not in sample:
            print(f"Messages is None/empty for id: {idx}")
            continue

        if ground_truth is None:
            print(f"No answer found in ground truth for id: {idx}")
            continue

        # Get model's response (last turn is assistant turn)
        last_message = sample["messages"][-1]

        if last_message["role"] != "nova_assistant":
            print(f"Last message is not from assistant for id: {idx}")
            continue

        if "content" not in last_message:
            print(f"Completion text is empty for id: {idx}")
            continue

        model_text = last_message["content"]

        # --- Actual scoring logic (lexical overlap) ---
        ground_truth_text = _extract_ground_truth_text(ground_truth)

        # Calculate main score and individual metrics
        overlap_score = _lexical_overlap_score(model_text, ground_truth_text)

        # Create two separate metrics as in the first implementation
        accuracy_score = overlap_score  # Use overlap as accuracy
        fluency_score = _calculate_fluency(model_text)  # New function for fluency

        # Create individual metrics
        metrics_list = [
            MetricResult(name="accuracy", value=accuracy_score, type="Metric"),
            MetricResult(name="fluency", value=fluency_score, type="Reward")
        ]

        ro = RewardOutput(
            id=idx,
            aggregate_reward_score=overlap_score,
            metrics_list=metrics_list
        )

        print(f"Response for id: {idx} is {ro}")
        scores.append(ro)

    # Convert to dict format
    result = []
    for score in scores:
        result.append({
            "id": score.id,
            "aggregate_reward_score": score.aggregate_reward_score,
            "metrics_list": [asdict(metric) for metric in score.metrics_list]
        })

    return result


def _extract_ground_truth_text(ground_truth: Any) -> str:
    """
    Turn the `ground_truth` field into a plain string.
    """
    if isinstance(ground_truth, str):
        return ground_truth

    if isinstance(ground_truth, dict):
        # Common patterns: { "explanation": "...", "answer": "..." }
        if "explanation" in ground_truth and isinstance(ground_truth["explanation"], str):
            return ground_truth["explanation"]
        if "answer" in ground_truth and isinstance(ground_truth["answer"], str):
            return ground_truth["answer"]
        # Fallback: stringify the whole dict
        return json.dumps(ground_truth, ensure_ascii=False)

    # Fallback: stringify anything else
    return str(ground_truth)


def _tokenize(text: str) -> List[str]:
    # Very simple tokenizer: lowercase + alphanumeric word chunks
    return re.findall(r"\w+", text.lower())


def _lexical_overlap_score(model_text: str, ground_truth_text: str) -> float:
    """
    Simple lexical overlap score in [0, 1]:
      score = |tokens(model) ∩ tokens(gt)| / |tokens(gt)|
    """
    gt_tokens = _tokenize(ground_truth_text)
    model_tokens = _tokenize(model_text)

    if not gt_tokens:
        return 0.0

    gt_set = set(gt_tokens)
    model_set = set(model_tokens)
    common = gt_set & model_set

    return len(common) / len(gt_set)


def _calculate_fluency(text: str) -> float:
    """
    Calculate a simple fluency score based on:
    - Average word length
    - Text length
    - Sentence structure

    Returns a score between 0 and 1.
    """
    # Simple implementation - could be enhanced with more sophisticated NLP
    words = _tokenize(text)

    if not words:
        return 0.0

    # Average word length normalized to [0,1] range
    # Assumption: average English word is ~5 chars, so normalize around that
    avg_word_len = sum(len(word) for word in words) / len(words)
    word_len_score = min(avg_word_len / 10, 1.0)

    # Text length score - favor reasonable length responses
    ideal_length = 100  # words
    length_score = min(len(words) / ideal_length, 1.0)

    # Simple sentence structure check (periods, question marks, etc.)
    sentence_count = len(re.findall(r'[.!?]+', text)) + 1
    sentence_ratio = min(sentence_count / (len(words) / 15), 1.0)

    # Combine scores
    fluency_score = (word_len_score + length_score + sentence_ratio) / 3

    return fluency_score
```

**Lambda 请求格式**  
Lambda 函数接收以下格式的数据：

```
[
  {
    "id": "sample-001",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Do you have a dedicated security team?"
          }
        ]
      },
      {
        "role": "nova_assistant",
        "content": [
          {
            "type": "text",
            "text": "As an AI developed by Company, I don't have a dedicated security team in the traditional sense. However, the development and deployment of AI systems like me involve extensive security measures, including data encryption, user privacy protection, and other safeguards to ensure safe and responsible use."
          }
        ]
      }
    ],
    "reference_answer": {
      "compliant": "No",
      "explanation": "As an AI developed by Company, I do not have a traditional security team. However, the deployment involves stringent safety measures, such as encryption and privacy safeguards."
    }
  }
]
```

**注意**  
消息结构包含嵌套的 `content` 数组，与输入数据格式相匹配。角色为 `nova_assistant` 的最后一条消息包含模型生成的响应。

**Lambda 响应格式**  
Lambda 函数必须按以下格式返回数据：

```
[
  {
    "id": "sample-001",
    "aggregate_reward_score": 0.75,
    "metrics_list": [
      {
        "name": "accuracy",
        "value": 0.85,
        "type": "Metric"
      },
      {
        "name": "fluency",
        "value": 0.90,
        "type": "Reward"
      }
    ]
  }
]
```

**响应字段**：
+ `id`：必须与输入样本 ID 匹配
+ `aggregate_reward_score`：总体得分（通常为 0.0 到 1.0）
+ `metrics_list`：各项指标组成的数组，包含以下字段：
  + `name`：指标标识符（例如 accuracy、fluency）
  + `value`：指标得分（通常为 0.0 到 1.0）
  + `type`：Metric（用于报告）或 Reward（用于训练）

## IAM 权限


**所需的权限**  
SageMaker AI 执行角色必须具有调用 Lambda 函数的权限。将此策略添加到 SageMaker AI 执行角色：

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "lambda:InvokeFunction"
      ],
      "Resource": "arn:aws:lambda:region:account-id:function:function-name"
    }
  ]
}
```

**Lambda 执行角色**  
Lambda 函数的执行角色需要基本的 Lambda 执行权限：

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}
```

**其他权限**：如果 Lambda 函数访问其他 AWS 服务（例如用于参考数据的 Amazon S3、用于日志记录的 DynamoDB），请将这些权限添加到 Lambda 执行角色。

## 执行评测作业


1. **准备数据**
   + 根据数据格式要求对评测数据进行格式化
   + 将 JSONL 文件上传到 Amazon S3：`s3://your-bucket/eval-data/eval_data.jsonl`

1. **配置配方**

   使用配置更新示例配方：
   + 将 `model_name_or_path` 设置为模型路径
   + 将 `lambda_arn` 设置为奖励函数 ARN
   + 将 `output_s3_path` 设置为目标输出位置
   + 根据需要调整 `inference` 参数

   将配方另存为 `rft_eval_recipe.yaml`

1. **运行评测**

   使用提供的笔记本执行评测作业：[Nova 模型评测笔记本](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model-evaluation.html#nova-model-evaluation-notebook)

1. **监控进度**

   通过以下方式监控评测作业：
   + SageMaker AI 控制台：检查作业状态与日志
   + CloudWatch Logs：查看详细执行日志
   + Lambda 日志：调试奖励函数相关问题

## 了解评测结果


**输出格式**  
评测作业会以 JSONL 格式将结果输出到指定的 Amazon S3 位置。每行包含一个样本的评测结果：

```
{
  "id": "sample-001",
  "aggregate_reward_score": 0.75,
  "metrics_list": [
    {
      "name": "accuracy",
      "value": 0.85,
      "type": "Metric"
    },
    {
      "name": "fluency",
      "value": 0.90,
      "type": "Reward"
    }
  ]
}
```

**注意**  
RFT 评测作业输出格式与 Lambda 响应格式完全一致。评测服务会原样透传 Lambda 函数的响应，确保奖励计算结果与最终输出保持一致。

**解析结果**  
**奖励总分**：
+ 取值范围：通常为 0.0（最差）到 1.0（最佳），具体取决于实现逻辑
+ 用途：以单一数值概括整体性能
+ 应用场景：模型对比、跟踪训练过程中的效果提升

**各项指标**：
+ 指标类型：用于分析的参考性指标
+ 奖励类型：RFT 训练过程中使用的指标
+ 结果解读：数值越高通常表示性能越好（除非设计了反向指标）

**性能基准**  
何种表现为“良好”取决于实际使用案例：


| 分数区间 | 评估结果 | 处理建议 | 
| --- |--- |--- |
| 0.8 – 1.0 | 优秀 | 模型可直接部署 | 
| 0.6 – 0.8 | 良好 | 可进行小幅优化 | 
| 0.4 – 0.6 | 一般 | 需大幅优化提升 | 
| 0.0 – 0.4 | 较差 | 检查训练数据和奖励函数 | 

**重要**  
以上仅为通用准则。请根据业务需求、基线模型性能、领域特定约束以及进一步训练的成本效益分析，自行定义阈值。