針對文字摘要準確性評估 Amazon Bedrock 模型 - Amazon SageMaker AI

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

針對文字摘要準確性評估 Amazon Bedrock 模型

您可以使用高階 ModelRunner 包裝函式,根據 JumpStart 外部託管的模型建立自訂評估。

本教學課程說明如何載入 Amazon Bedrock 中提供的 Anthropic Claude 2 模型,並要求此模型摘要說明文字提示。然後,本教學課程說明如何使用 Rouge-LMeteorBERTScore 指標,針對準確性評估模型回應。

本教學課程說明如何執行以下動作:

  • 設定您的環境。

  • 執行您的模型評估。

  • 檢視您的分析結果。

設定您的環境

先決條件
設定 Amazon Bedrock

在您可以使用 Amazon Bedrock 模型之前,必須先請求該模型的存取權。

  1. 登入您的 AWS 帳戶。

    1. 如果您沒有 AWS帳戶,請參閱設定 Amazon Bedrock 中的註冊 AWS帳戶

  2. 開啟 Amazon Bedrock 主控台

  3. 在開啟的歡迎使用 Amazon Bedrock!區段中,選擇管理模型存取

  4. 在出現的模型存取區段中,選擇管理模型存取

  5. 在出現的基礎模型區段中,勾選模型Anthropic子區段下列出的 Claude 旁邊的方塊。

  6. 選擇請求模型存取

  7. 如果您的請求成功,已授予存取權的核取記號應該會出現在所選模型旁邊的存取狀態下。

  8. 您可能需要重新登入 AWS 帳戶,才能存取模型。

安裝必要的程式庫
  1. 在您的程式碼中,安裝 fmevalboto3 程式庫,如下所示:

    !pip install fmeval !pip3 install boto3==1.28.65
  2. 匯入程式庫、設定平行化因素,以及調用 Amazon Bedrock 用戶端,如下所示:

    import boto3 import json import os # Dependent on available hardware and memory os.environ["PARALLELIZATION_FACTOR"] = "1" # Bedrock clients for model inference bedrock = boto3.client(service_name='bedrock') bedrock_runtime = boto3.client(service_name='bedrock-runtime')

    在先前的程式碼範例中,下列適用:

    • PARALLELIZATION_FACTOR - 傳送至運算執行個體之並行批次數量的乘數。如果您的硬體允許平行化,您可以設定此數字來乘以評估任務的調用次數。例如,如果您具有 100 個調用,且 PARALLELIZATION_FACTOR 設定為 2,則您的任務將執行 200 個調用。您最多可以將 PARALLELIZATION_FACTOR 增加至 10,或完全移除變數。若要閱讀有關 AWSLambda 如何使用的部落格,PARALLELIZATION_FACTOR請參閱 Kinesis 和 DynamoDB 事件來源的新 Lambda 擴展控制項

  3. 將範例 JSON Lines 資料集 sample-dataset.jsonl 下載到您目前的工作目錄。

  4. 檢查您的環境是否包含範例輸入檔案,如下所示:

    import glob # Check for the built-in dataset if not glob.glob("sample-dataset.jsonl"): print("ERROR - please make sure file exists: sample-dataset.jsonl")
將範例推論請求傳送至您的模型
  1. 定義模型和提示的 MIME 類型。對於託管在 Amazon Bedrock 上的 Anthropic Claude 2 模型,您的提示必須建構如下:

    import json model_id = 'anthropic.claude-v2' accept = "application/json" contentType = "application/json" # Ensure that your prompt has the correct format prompt_data = """Human: Who is Barack Obama? Assistant: """

    如需如何建構請求內文的詳細資訊,請參閱模型調用請求內文欄位。其他模型可能有不同的格式。

  2. 將範例請求傳送至您的模型。您的請求內文包含提示和您要設定的任何其他參數。max_tokens_to_sample 設定為 500 的範例請求如下:

    body = json.dumps({"prompt": prompt_data, "max_tokens_to_sample": 500}) response = bedrock_runtime.invoke_model( body=body, modelId=model_id, accept=accept, contentType=contentType ) response_body = json.loads(response.get("body").read()) print(response_body.get("completion"))

    在先前的程式碼範例中,您可以設定下列參數:

    • temperature - 控制所產生文字的隨機性,並接受正值。較高的 temperature 值會指示模型產生更多隨機且多樣化的回應。較低的值會產生更能預測的回應。介於 temperature0 之間的 1 範圍,預設值為 0.5。

    • topP - 透過限制產生下一個字符時要考慮的字符集來控制隨機性。較高的 topP 值允許包含更廣泛詞彙的集合,而較低的值會將字符集合限制為更有可能的字詞。topP 的範圍為 01,預設值為 1

    • topK - 將模型預測限制為前 k 個最可能的字符。較高的 topK 值允許更多創意的回應。較低的值會產生更連貫的回應。topK 的範圍為 0500,預設值為 250

    • max_tokens_to_sample - 透過限制模型傳回的字符數量來限制回應的長度。max_tokens_to_sample 的範圍為 04096,預設值為 200

    • stop_sequences - 指定字元序列清單,這些序列會告知您的模型停止產生回應。模型輸出會在輸出中第一次遇到任何列出的字串時停止。回應不會包含停止序列。例如,您可以使用回車序列,將模型回應限制為單行。您可以設定最多 4 個停止序列。

    如需您可以在請求中指定之參數的詳細資訊,請參閱 Anthropic Claude 模型

設定 FMEval
  1. 載入執行 FMEval 所需的程式庫,如下所示:

    from fmeval.data_loaders.data_config import DataConfig from fmeval.model_runners.bedrock_model_runner import BedrockModelRunner from fmeval.constants import MIME_TYPE_JSONLINES from fmeval.eval_algorithms.summarization_accuracy import SummarizationAccuracy, SummarizationAccuracyConfig
  2. 為您的輸入資料集設定資料組態。

    下列範例輸入是來自 sample-dataset.jsonl 的一行:

    { "document": "23 October 2015 Last updated at 17:44 BST\nIt's the highest rating a tropical storm can get and is the first one of this magnitude to hit mainland Mexico since 1959.\nBut how are the categories decided and what do they mean? Newsround reporter Jenny Lawrence explains.", "summary": "Hurricane Patricia has been rated as a category 5 storm.", "id": "34615665", }

    先前的範例輸入包含要在 document 金鑰內摘要說明的文字。要針對其評估模型回應的參考位於 summary 金鑰中。您必須在資料組態內使用這些金鑰,來指定哪些資料欄包含 FMEval 評估模型回應所需的資訊。

    您的資料組態必須識別模型應該在 model_input_location 中摘要說明的文字。您必須使用 target_output_location 識別參考值。

    下列資料組態範例參考先前的輸入範例,以指定文字摘要任務所需的資料欄、名稱、統一資源識別碼 (URI) 和 MIME。類型:

    config = DataConfig( dataset_name="sample-dataset", dataset_uri="sample-dataset.jsonl", dataset_mime_type=MIME_TYPE_JSONLINES, model_input_location="document", target_output_location="summary" )

    如需其他任務所需的資料欄資訊的詳細資訊,請參閱自動模型評估中的使用自訂輸入資料集一節。

  3. 設定自訂 ModelRunner,如下列程式碼範例所示:

    bedrock_model_runner = BedrockModelRunner( model_id=model_id, output='completion', content_template='{"prompt": $prompt, "max_tokens_to_sample": 500}' )

    先前的程式碼範例會指定下列項目:

    • model_id - 用來指定模型的 ID。

    • output - 從 Anthropic Claude 2 模型擷取輸出,這會以 completion 金鑰傳回其回應。

    • content_template - 指定您的模型如何與請求互動。下列範例組態範本只是為了解釋先前範例而詳細說明的 (如下所示),並非必要。

      • 在先前的 content_template 範例中,下列適用:

        • 變數 prompt 會指定輸入提示,擷取使用者提出的請求。

        • 變數 max_tokens_to_sample 會將字符數量上限指定為 500,以限制回應的長度。

          如需您可以在請求中指定之參數的詳細資訊,請參閱 Anthropic Claude 模型

        content_template 參數的格式取決於 LLM 支援的輸入和參數。在本教學課程中,Anthropic 的 Claude 2 模型使用下列 content_template

        "content_template": "{\"prompt\": $prompt, \"max_tokens_to_sample\": 500}"

        另一個範例是,Falcon 7b 模型可以支援下列 content_template

        "content_template": "{\"inputs\": $prompt, \"parameters\":{\"max_new_tokens\": \ 10, \"top_p\": 0.9, \"temperature\": 0.8}}"

執行您的模型評估

定義和執行您的評估演算法
  1. 定義您的評估演算法。下列範例展示如何定義 SummarizationAccuracy 演算法,用來判斷文字摘要任務的準確性:

    eval_algo = SummarizationAccuracy(SummarizationAccuracyConfig())

    如需計算其他評估任務之指標的演算法範例,請參閱 使用 fmeval 程式庫執行自動評估 中的評估模型

  2. 執行您的評估演算法。下列程式碼範例使用先前定義的資料組態,以及使用 HumanAssistant 金鑰的 prompt_template

    eval_output = eval_algo.evaluate(model=bedrock_model_runner, dataset_config=config, prompt_template="Human: $feature\n\nAssistant:\n", save=True)

    在先前的程式碼範例中,feature 包含 Amazon Bedrock 模型預期格式的提示。

檢視您的分析結果

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

    # parse report print(json.dumps(eval_output, default=vars, indent=4))

    先前的命令會傳回下列輸出:

    [ { "eval_name": "summarization_accuracy", "dataset_name": "sample-dataset", "dataset_scores": [ { "name": "meteor", "value": 0.2048823008681274 }, { "name": "rouge", "value": 0.03557697913367101 }, { "name": "bertscore", "value": 0.5406564395678671 } ], "prompt_template": "Human: $feature\n\nAssistant:\n", "category_scores": null, "output_path": "/tmp/eval_results/summarization_accuracy_sample_dataset.jsonl", "error": null } ]

    先前的範例輸出會顯示三個準確度分數:MeteorRougeBERTScore、輸入 prompt_templatecategory_score (如果您已請求一個)、任何錯誤,以及 output_path。您將在下列步驟中使用 output_path 來建立 Pandas DataFrame

  2. 匯入您的結果並將其讀入 DataFrame,然後將準確性分數連接到模型輸入、模型輸出和目標輸出,如下所示:

    import pandas as pd data = [] with open("/tmp/eval_results/summarization_accuracy_sample_dataset.jsonl", "r") as file: for line in file: data.append(json.loads(line)) df = pd.DataFrame(data) df['meteor_score'] = df['scores'].apply(lambda x: x[0]['value']) df['rouge_score'] = df['scores'].apply(lambda x: x[1]['value']) df['bert_score'] = df['scores'].apply(lambda x: x[2]['value']) df

    在此調用中,先前的程式碼範例會傳回下列輸出 (為了簡潔起見而簽訂合約):

    model_input model_output target_output prompt scores meteor_score rouge_score bert_score 0 John Edward Bates, formerly of Spalding, Linco... I cannot make any definitive judgments, as th... A former Lincolnshire Police officer carried o... Human: John Edward Bates, formerly of Spalding... [{'name': 'meteor', 'value': 0.112359550561797... 0.112360 0.000000 0.543234 ... 1 23 October 2015 Last updated at 17:44 BST\nIt'... Here are some key points about hurricane/trop... Hurricane Patricia has been rated as a categor... Human: 23 October 2015 Last updated at 17:44 B... [{'name': 'meteor', 'value': 0.139822692925566... 0.139823 0.017621 0.426529 ... 2 Ferrari appeared in a position to challenge un... Here are the key points from the article:\n\n... Lewis Hamilton stormed to pole position at the... Human: Ferrari appeared in a position to chall... [{'name': 'meteor', 'value': 0.283411142234671... 0.283411 0.064516 0.597001 ... 3 The Bath-born player, 28, has made 36 appearan... Okay, let me summarize the key points from th... Newport Gwent Dragons number eight Ed Jackson ... Human: The Bath-born player, 28, has made 36 a... [{'name': 'meteor', 'value': 0.089020771513353... 0.089021 0.000000 0.533514 ... ...

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

    如需包含本節所提供程式碼範例的筆記本,請參閱 bedrock-claude-summarization-accuracy.ipnyb