本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
針對文字摘要準確性評估 Amazon Bedrock 模型
您可以使用高階 ModelRunner 包裝函式,根據 JumpStart 外部託管的模型建立自訂評估。
本教學課程說明如何載入 Amazon Bedrock 中提供的 Anthropic Claude 2 模型
本教學課程說明如何執行以下動作:
-
設定您的環境。
-
執行您的模型評估。
-
檢視您的分析結果。
設定您的環境
先決條件
-
在開始本教學課程之前,請使用基礎 Python 3.10 核心環境和
ml.m5.2xlargeAmazon Elastic Compute Cloud (Amazon EC2) 執行個體。如需執行個體類型及其建議使用案例的其他相關資訊,請參閱可與 Amazon SageMaker Studio Classic 筆記本搭配使用的執行個體類型。
設定 Amazon Bedrock
在您可以使用 Amazon Bedrock 模型之前,必須先請求該模型的存取權。
-
登入您的 AWS 帳戶。
-
如果您沒有 AWS帳戶,請參閱設定 Amazon Bedrock 中的註冊 AWS帳戶。
-
-
在開啟的歡迎使用 Amazon Bedrock!區段中,選擇管理模型存取。
-
在出現的模型存取區段中,選擇管理模型存取。
-
在出現的基礎模型區段中,勾選模型的 Anthropic子區段下列出的 Claude 旁邊的方塊。
-
選擇請求模型存取。
-
如果您的請求成功,已授予存取權的核取記號應該會出現在所選模型旁邊的存取狀態下。
-
您可能需要重新登入 AWS 帳戶,才能存取模型。
安裝必要的程式庫
-
在您的程式碼中,安裝
fmeval和boto3程式庫,如下所示:!pip install fmeval !pip3 install boto3==1.28.65 -
匯入程式庫、設定平行化因素,以及調用 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 擴展控制項。
-
-
將範例
JSON Lines資料集 sample-dataset.jsonl下載到您目前的工作目錄。 -
檢查您的環境是否包含範例輸入檔案,如下所示:
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")
將範例推論請求傳送至您的模型
-
定義模型和提示的
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: """如需如何建構請求內文的詳細資訊,請參閱模型調用請求內文欄位。其他模型可能有不同的格式。
-
將範例請求傳送至您的模型。您的請求內文包含提示和您要設定的任何其他參數。
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值會指示模型產生更多隨機且多樣化的回應。較低的值會產生更能預測的回應。介於temperature與0之間的1範圍,預設值為 0.5。 -
topP- 透過限制產生下一個字符時要考慮的字符集來控制隨機性。較高的topP值允許包含更廣泛詞彙的集合,而較低的值會將字符集合限制為更有可能的字詞。topP的範圍為0到1,預設值為1。 -
topK- 將模型預測限制為前k個最可能的字符。較高的topK值允許更多創意的回應。較低的值會產生更連貫的回應。topK的範圍為0到500,預設值為250。 -
max_tokens_to_sample- 透過限制模型傳回的字符數量來限制回應的長度。max_tokens_to_sample的範圍為0到4096,預設值為200。 -
stop_sequences- 指定字元序列清單,這些序列會告知您的模型停止產生回應。模型輸出會在輸出中第一次遇到任何列出的字串時停止。回應不會包含停止序列。例如,您可以使用回車序列,將模型回應限制為單行。您可以設定最多4個停止序列。
如需您可以在請求中指定之參數的詳細資訊,請參閱 Anthropic Claude 模型。
-
設定 FMEval
-
載入執行 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 -
為您的輸入資料集設定資料組態。
下列範例輸入是來自
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" )如需其他任務所需的資料欄資訊的詳細資訊,請參閱自動模型評估中的使用自訂輸入資料集一節。
-
設定自訂
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}}" -
-
-
執行您的模型評估
定義和執行您的評估演算法
-
定義您的評估演算法。下列範例展示如何定義
SummarizationAccuracy演算法,用來判斷文字摘要任務的準確性:eval_algo = SummarizationAccuracy(SummarizationAccuracyConfig())如需計算其他評估任務之指標的演算法範例,請參閱 使用 fmeval 程式庫執行自動評估 中的評估模型。
-
執行您的評估演算法。下列程式碼範例使用先前定義的資料組態,以及使用
Human和Assistant金鑰的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 模型預期格式的提示。
檢視您的分析結果
-
從評估演算法傳回的
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 } ]先前的範例輸出會顯示三個準確度分數:Meteor
、Rouge 和 BERTScore 、輸入 prompt_template、category_score(如果您已請求一個)、任何錯誤,以及output_path。您將在下列步驟中使用output_path來建立Pandas DataFrame。 -
匯入您的結果並將其讀入
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
。