בצע טרנספורמציות אצווה עם Amazon SageMaker Jumpstart Text2Text Generation דגמי שפות גדולים | שירותי האינטרנט של אמזון

בצע טרנספורמציות אצווה עם Amazon SageMaker Jumpstart Text2Text Generation דגמי שפות גדולים | שירותי האינטרנט של אמזון

היום אנו נרגשים לבשר שכעת אתה יכול לבצע טרנספורמציות אצווה עם אמזון SageMaker JumpStart מודלים של שפה גדולה (LLMs) עבור Text2Text Generation. טרנספורמציות אצווה שימושיות במצבים שבהם התגובות אינן צריכות להיות בזמן אמת ולכן אתה יכול לעשות מסקנות באצווה עבור מערכי נתונים גדולים בכמויות גדולות. עבור טרנספורמציה אצווה, מופעלת עבודת אצווה שלוקחת קלט אצווה כמערך נתונים ומודל מאומן מראש, ומוציאה תחזיות עבור כל נקודת נתונים במערך הנתונים. טרנספורמציה אצווה היא חסכונית מכיוון שבניגוד לנקודות קצה מתארחות בזמן אמת שיש להן חומרה מתמשכת, אשכולות טרנספורמציה אצווה נקרעים כאשר העבודה הושלמה ולכן החומרה משמשת רק למשך עבודת האצווה.

במקרים מסוימים, ניתן לקבץ בקשות להסקת מסקנות בזמן אמת בקבוצות קטנות לעיבוד אצווה כדי ליצור תגובות בזמן אמת או כמעט בזמן אמת. לדוגמה, אם אתה צריך לעבד זרם רציף של נתונים עם חביון נמוך ותפוקה גבוהה, הפעלת נקודת קצה בזמן אמת עבור כל בקשה בנפרד תדרוש יותר משאבים ויכולה לקחת זמן רב יותר לעבד את כל הבקשות מכיוון שהעיבוד מתבצע באופן סדרתי. גישה טובה יותר תהיה לקבץ חלק מהבקשות ולקרוא לנקודת הקצה בזמן אמת במצב הסקת אצווה, המעבדת את הבקשות שלך במעבר אחד קדימה של המודל ומחזירה את התגובה המרובה לבקשה בזמן אמת או כמעט בזמן אמת. זמן האחזור של התגובה יהיה תלוי במספר הבקשות שתקבץ יחד ובגודל הזיכרון של המופעים, לכן אתה יכול לכוון את גודל האצווה בהתאם לדרישות העסקיות שלך לאחזור ותפוקה. אנחנו קוראים לזה מסקנות אצווה בזמן אמת מכיוון שהוא משלב את הרעיון של אצווה ועדיין מספק תגובות בזמן אמת. עם הסקת אצווה בזמן אמת, אתה יכול להשיג איזון בין זמן אחזור נמוך לתפוקה גבוהה, מה שמאפשר לך לעבד כמויות גדולות של נתונים בזמן וביעילות.

המרת אצווה Jumpstart עבור מודלים של Text2Text Generation מאפשרת לך להעביר את ההיפרפרמטרים של האצווה דרך משתני סביבה שמגדילים עוד יותר את התפוקה ומצמצמים את השהייה.

JumpStart מספקת מודלים מאומנים מראש, קוד פתוח עבור מגוון רחב של סוגי בעיות כדי לעזור לך להתחיל עם למידת מכונה (ML). אתה יכול לאמן ולכוון את הדגמים האלה בהדרגה לפני הפריסה. JumpStart מספקת גם תבניות פתרונות שמגדירות תשתית למקרי שימוש נפוצים, ומחברות לדוגמה הניתנות להפעלה עבור ML עם אמזון SageMaker. אתה יכול לגשת למודלים שהוכשרו מראש, תבניות פתרונות ודוגמאות דרך דף הנחיתה של JumpStart ב סטודיו SageMaker של אמזון. אתה יכול גם לגשת לדגמי JumpStart באמצעות SageMaker Python SDK.

בפוסט זה, אנו מדגימים כיצד להשתמש במאומנים המתקדמים ביותר text2text דגמי FLAN T5 מ-Hugging Face להמרת אצווה והסקת אצווה בזמן אמת.

סקירת פתרונות

המחברת מציגה שינוי אצווה של דגמי Text2Text FLAN T5 מאומנים מראש פנים מחבקות זמין בהמשך מאגר GitHub. מחברת זו משתמשת בנתונים מהפנים המחבקים cnn_daymail מערך נתונים עבור משימת סיכום טקסט באמצעות SageMaker SDK.

להלן השלבים העיקריים ליישום טרנספורמציה אצווה והסקת אצווה בזמן אמת:

  1. הגדר דרישות מוקדמות.
  2. בחר דגם מאומן מראש.
  3. אחזר חפצים עבור הדגם.
  4. ציין היפרפרמטרים של עבודת טרנספורמציה אצווה.
  5. הכן נתונים עבור המרת האצווה.
  6. הפעל את עבודת המרת האצווה.
  7. הערך את הסיכום באמצעות א אדום (Recall-oriented Understudy for Gisting Evaluation).
  8. בצע הסקת אצווה בזמן אמת.

הגדר דרישות מוקדמות

לפני שתפעיל את המחברת, עליך להשלים כמה שלבי הגדרה ראשוניים. בואו נגדיר את תפקיד הביצוע של SageMaker כך שיהיו לו הרשאות להפעיל שירותי AWS בשמכם:

sagemaker_session = Session()
aws_role = sagemaker_session.get_caller_identity_arn()
aws_region = boto3.Session().region_name
sess = sagemaker.Session()

בחר דגם מאומן מראש

אנו משתמשים במודל huggingface-text2text-flan-t5-large כמודל ברירת מחדל. לחלופין, תוכל לאחזר את רשימת הדגמים הזמינים של Text2Text ב-JumpStart ולבחור את הדגם המועדף עליך. שיטה זו מספקת דרך פשוטה לבחור מזהי דגמים שונים באמצעות אותה מחברת. למטרות הדגמה, אנו משתמשים במודל huggingface-text2text-flan-t5-large:

model_id, model_version, = ( "huggingface-text2text-flan-t5-large", "*",
)

אחזר חפצים עבור הדגם

עם SageMaker, אנו יכולים לבצע הסקה על המודל שהוכשר מראש, אפילו מבלי לכוונן אותו תחילה על מערך נתונים חדש. אנו מתחילים בשליפת ה deploy_image_uri, deploy_source_uri, ו model_uri עבור הדגם שהוכשר מראש:

inference_instance_type = "ml.p3.2xlarge" # Retrieve the inference docker container uri. This is the base HuggingFace container image for the default model above.
deploy_image_uri = image_uris.retrieve(
region=None,
framework=None, # automatically inferred from model_id
image_scope="inference",
model_id=model_id,
model_version=model_version,
instance_type=inference_instance_type,
) # Retrieve the model uri.
model_uri = model_uris.retrieve(
model_id=model_id, model_version=model_version, model_scope="inference"
) #Create the SageMaker model instance
model = Model(
image_uri=deploy_image_uri,
model_data=model_uri,
role=aws_role,
predictor_cls=Predictor)

ציין היפרפרמטרים של עבודת טרנספורמציה אצווה

אתה יכול להעביר כל תת-קבוצה של היפרפרמטרים כמשתני סביבה לעבודת המרת האצווה. אתה יכול גם להעביר את ההיפרפרמטרים האלה במטען JSON. עם זאת, אם אתה מגדיר משתני סביבה עבור היפרפרמטרים כמו שהקוד הבא מציג, אזי לא ייעשה שימוש בפרמטרים המתקדמים מהדוגמאות הבודדות במטען קווי JSON. אם אתה רוצה להשתמש בהיפרפרמטרים מהמטען, אולי תרצה להגדיר את hyper_params_dict פרמטר בתור null במקום זאת.

#Specify the Batch Job Hyper Params Here, If you want to treate each example hyperparameters different please pass hyper_params_dict as None
hyper_params = {"batch_size":4, "max_length":50, "top_k": 50, "top_p": 0.95, "do_sample": True}
hyper_params_dict = {"HYPER_PARAMS":str(hyper_params)}

הכן נתונים להמרת אצווה

עכשיו אנחנו מוכנים לטעון את cnn_daymail מערך נתונים מ-Huging Face:

cnn_test = load_dataset('cnn_dailymail','3.0.0',split='test')

אנו עוברים על כל הזנת נתונים ויוצרים את נתוני הקלט בפורמט הנדרש. אנחנו יוצרים א articles.jsonl קובץ כקובץ נתוני בדיקה המכיל מאמרים שיש לסכם אותם כמטען קלט. בזמן שאנו יוצרים קובץ זה, אנו מוסיפים את ההנחיה "Briefly summarize this text:" לכל שורת קלט בדיקה. אם ברצונך לקבל היפרפרמטרים שונים עבור כל קלט בדיקה, תוכל להוסיף את ההיפרפרמטרים הללו כחלק מיצירת מערך הנתונים.

אנו יוצרים highlights.jsonl כקובץ האמת המכיל דגשים של כל מאמר המאוחסן בקובץ הבדיקה articles.jsonl. אנו מאחסנים את שני קבצי הבדיקה ב-an שירות אחסון פשוט של אמזון דלי (Amazon S3). ראה את הקוד הבא:

#You can specify a prompt here
prompt = "Briefly summarize this text: "
#Provide the test data and the ground truth file name
test_data_file_name = "articles.jsonl"
test_reference_file_name = 'highlights.jsonl' test_articles = []
test_highlights =[] # We will go over each data entry and create the data in the input required format as described above
for id, test_entry in enumerate(cnn_test): article = test_entry['article'] highlights = test_entry['highlights'] # Create a payload like this if you want to have different hyperparameters for each test input # payload = {"id": id,"text_inputs": f"{prompt}{article}", "max_length": 100, "temperature": 0.95} # Note that if you specify hyperparameter for each payload individually, you may want to ensure that hyper_params_dict is set to None instead payload = {"id": id,"text_inputs": f"{prompt}{article}"} test_articles.append(payload) test_highlights.append({"id":id, "highlights": highlights}) with open(test_data_file_name, "w") as outfile: for entry in test_articles: outfile.write("%sn" % json.dumps(entry)) with open(test_reference_file_name, "w") as outfile: for entry in test_highlights: outfile.write("%sn" % json.dumps(entry)) # Uploading the data s3 = boto3.client("s3")
s3.upload_file(test_data_file_name, output_bucket, os.path.join(output_prefix + "/batch_input/articles.jsonl"))

הפעל את עבודת המרת האצווה

כאשר אתה מתחיל עבודת טרנספורמציה אצווה, SageMaker משיק את משאבי המחשוב הדרושים לעיבוד הנתונים, כולל מופעי CPU או GPU בהתאם לסוג המופע הנבחר. במהלך משימת השינוי האצווה, SageMaker מספקת ומנהלת אוטומטית את משאבי המחשוב הנדרשים לעיבוד הנתונים, כולל מופעים, משאבי אחסון ומשאבי רשת. כאשר עבודת ההמרה האצווה הושלמה, משאבי המחשוב מנקים אוטומטית על ידי SageMaker. המשמעות היא שהמופעים והאחסון שבהם נעשה שימוש במהלך העבודה נעצרים ומוסרים, משחררים משאבים וממזערים את העלות. ראה את הקוד הבא:

# Creating the Batch transformer object
batch_transformer = model.transformer( instance_count=1, instance_type=inference_instance_type, output_path=s3_output_data_path, assemble_with="Line", accept="text/csv", max_payload=1, env = hyper_params_dict
) # Making the predications on the input data
batch_transformer.transform(s3_input_data_path, content_type="application/jsonlines", split_type="Line") batch_transformer.wait()

להלן רשומה אחת לדוגמה מה- articles.jsonl קובץ בדיקה. שים לב שלרשומה בקובץ הזה יש מזהה שתואם אליו predict.jsonl רשומות קובץ המציגות רשומה מסוכמת כפלט מדגם Hugging Face Text2Text. באופן דומה, לקובץ האמת הבסיסית יש גם מזהה תואם עבור רשומת הנתונים. המזהה התואם על פני קובץ הבדיקה, קובץ האמת הקרקע וקובץ הפלט מאפשר קישור בין רשומות קלט לרשומות פלט לפירוש קל של התוצאות.

להלן רשומת הקלט לדוגמה שסופקה לסיכום:

{"id": 0, "text_inputs": "Briefly summarize this text: (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice," he said, according to an ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court's treaty should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the group. "What's objectionable is the attempts to undermine international justice, not Palestine's decision to join a treaty to which over 100 countries around the world are members." In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it "strongly" disagreed with the court's decision. "As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC," the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. "We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace," it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would "conduct its analysis in full independence and impartiality." The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder and Faith Karimi contributed to this report."}

להלן הפלט החזוי עם סיכום:

{'id': 0, 'generated_texts': ['The Palestinian Authority officially became a member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories.']}

להלן סיכום האמת הבסיסי למטרות הערכת מודל:

{"id": 0, "highlights": "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .nIsrael and the United States opposed the move, which could open the door to war crimes investigations against Israelis ."}

לאחר מכן, אנו משתמשים באמיתות הקרקע ובתפוקות החזויות להערכת מודל.

הערכת המודל באמצעות ציון ROUGE¶

אדום, או Recall-Oriented Understudy for Gisting Evaluation, הוא סט של מדדים וחבילת תוכנה המשמשת להערכת סיכום אוטומטי ותרגום מכונה בעיבוד שפה טבעית. המדדים משווים סיכום או תרגום שהופק אוטומטית מול סיכום או תרגום של הפניות (מייצור אנושי) או קבוצה של הפניות.

בקוד הבא, אנו משלבים את הסיכומים החזויים והמקוריים על ידי הצטרפותם על המפתח המשותף id והשתמש בזה כדי לחשב את ציון ROUGE:

# Downloading the predictions
s3.download_file(
output_bucket, output_prefix + "/batch_output/" + "articles.jsonl.out", "predict.jsonl"
) with open('predict.jsonl', 'r') as json_file:
json_list = list(json_file) # Creating the prediction list for the dataframe
predict_dict_list = []
for predict in json_list:
if len(predict) > 1:
predict_dict = ast.literal_eval(predict)
predict_dict_req = {"id": predict_dict["id"], "prediction": predict_dict["generated_texts"][0]}
predict_dict_list.append(predict_dict_req) # Creating the predictions dataframe
predict_df = pd.DataFrame(predict_dict_list) test_highlights_df = pd.DataFrame(test_highlights) # Combining the predict dataframe with the original summarization on id to compute the rouge score
df_merge = test_highlights_df.merge(predict_df, on="id", how="left") rouge = evaluate.load('rouge')
results = rouge.compute(predictions=list(df_merge["prediction"]),references=list(df_merge["highlights"]))
print(results)
{'rouge1': 0.32749078992945646, 'rouge2': 0.126038645005132, 'rougeL': 0.22764277967933363, 'rougeLsum': 0.28162915746368966}

בצע הסקת אצווה בזמן אמת

לאחר מכן, אנו מראים לך כיצד להפעיל הסקת אצווה בזמן אמת על נקודת הקצה על ידי אספקת התשומות כרשימה. אנו משתמשים באותו מזהה מודל ובאותו מערך נתונים כמו קודם, אלא שאנו לוקחים כמה רשומות ממערך הנתונים של הבדיקה ומשתמשים בהם כדי להפעיל נקודת קצה בזמן אמת.

הקוד הבא מראה כיצד ליצור ולפרוס נקודת קצה בזמן אמת להסקת אצווה בזמן אמת:

from sagemaker.utils import name_from_base
endpoint_name = name_from_base(f"jumpstart-example-{model_id}")
# deploy the Model. Note that we need to pass Predictor class when we deploy model through Model class,
# for being able to run inference through the sagemaker API.
model_predictor = model.deploy( initial_instance_count=1, instance_type=inference_instance_type, predictor_cls=Predictor, endpoint_name=endpoint_name
)

לאחר מכן, אנו מכינים את מטען הקלט שלנו. לשם כך, אנו משתמשים בנתונים שהכנו קודם ומחלצים את 10 כניסות הבדיקה הראשונות ומצרפים את קלט הטקסט עם היפרפרמטרים שאנו רוצים להשתמש בהם. אנו מספקים את המטען הזה בזמן אמת invoke_endpoint. לאחר מכן, מטען התגובה מוחזר כרשימה של תגובות. ראה את הקוד הבא:

#Provide all the text inputs to the model as a list
text_inputs = [entry["text_inputs"] for entry in test_articles[0:10]] # The information about the different Parameters is provided above
payload = { "text_inputs": text_inputs, "max_length": 50, "num_return_sequences": 1, "top_k": 50, "top_p": 0.95, "do_sample": True, "batch_size": 4
} def query_endpoint_with_json_payload(encoded_json, endpoint_name):
client = boto3.client("runtime.sagemaker")
response = client.invoke_endpoint(
EndpointName=endpoint_name, ContentType="application/json", Body=encoded_json
)
return response query_response = query_endpoint_with_json_payload(
json.dumps(payload).encode("utf-8"), endpoint_name=endpoint_name
) def parse_response_multiple_texts(query_response):
model_predictions = json.loads(query_response["Body"].read())
return model_predictions generated_text_list = parse_response_multiple_texts(query_response)
print(*generated_text_list, sep='n')

לנקות את

לאחר שבדקת את נקודת הקצה, ודא שאתה מוחק את נקודת הקצה של SageMaker ומחק את המודל כדי להימנע מחיובים.

סיכום

במחברת זו, ביצענו טרנספורמציה אצווה כדי להציג את המודל Hugging Face Text2Text Generator עבור משימות סיכום. שינוי אצווה הוא יתרון בהשגת מסקנות ממערכי נתונים גדולים ללא צורך בנקודת קצה מתמשכת. קישרנו רשומות קלט עם מסקנות כדי לסייע בפרשנות התוצאות. השתמשנו בציון ROUGE כדי להשוות את סיכום נתוני המבחן עם הסיכום שנוצר על ידי המודל.

בנוסף, הדגמנו הסקת אצווה בזמן אמת, שבה אתה יכול לשלוח אצווה קטנה של נתונים לנקודת קצה בזמן אמת כדי להשיג איזון בין חביון לתפוקה עבור תרחישים כמו הזרמת נתוני קלט. הסקת אצווה בזמן אמת עוזרת להגדיל את התפוקה עבור בקשות בזמן אמת.

נסה את השינוי האצווה עם דגמי Text2Text Generation ב- SageMaker היום וספר לנו את המשוב שלך!


על המחברים

בצע טרנספורמציות אצווה עם Amazon SageMaker Jumpstart Text2Text Generation דגמי שפות גדולים | Amazon Web Services PlatoBlockchain Data Intelligence. חיפוש אנכי. איי.המנט סינג הוא מהנדס למידת מכונה עם ניסיון באלגוריתמים מובנים של Amazon SageMaker JumpStart ו-Amazon SageMaker. הוא קיבל את התואר השני שלו מ-Courant Institute of Mathematical Sciences ו-B.Tech מ- IIT Delhi. יש לו ניסיון בעבודה על מגוון רחב של בעיות למידת מכונה בתחום של עיבוד שפה טבעית, ראייה ממוחשבת וניתוח סדרות זמן.

בצע טרנספורמציות אצווה עם Amazon SageMaker Jumpstart Text2Text Generation דגמי שפות גדולים | Amazon Web Services PlatoBlockchain Data Intelligence. חיפוש אנכי. איי.רחנה צ'דהא הוא אדריכל פתרונות ראשי AI/ML בחשבונות אסטרטגיים ב-AWS. רחנה היא אופטימית המאמינה ששימוש אתי ואחראי בבינה מלאכותית יכול לשפר את החברה בעתיד ולהביא לשגשוג כלכלי וחברתי. בזמנה הפנוי, רחנה אוהבת לבלות עם משפחתה, לטייל ולהאזין למוזיקה.

בצע טרנספורמציות אצווה עם Amazon SageMaker Jumpstart Text2Text Generation דגמי שפות גדולים | Amazon Web Services PlatoBlockchain Data Intelligence. חיפוש אנכי. איי.ד"ר אשיש חתן הוא מדען יישומי בכיר עם אלגוריתמים מובנים של Amazon SageMaker ועוזר בפיתוח אלגוריתמים של למידת מכונה. הוא קיבל את הדוקטורט שלו מאוניברסיטת אילינוי אורבנה-שמפיין. הוא חוקר פעיל בלמידת מכונה והסקה סטטיסטית, ופרסם מאמרים רבים בכנסים NeurIPS, ICML, ICLR, JMLR, ACL ו-EMNLP.

בול זמן:

עוד מ למידת מכונות AWS