Amazon SageMaker Jumpstart Text2Text Generation 대규모 언어 모델로 일괄 변환 수행 | 아마존 웹 서비스

Amazon SageMaker Jumpstart Text2Text Generation 대규모 언어 모델로 일괄 변환 수행 | 아마존 웹 서비스

오늘 우리는 이제 다음을 사용하여 일괄 변환을 수행할 수 있음을 발표하게 되어 기쁩니다. Amazon SageMaker 점프스타트 Text2Text 생성을 위한 대규모 언어 모델(LLM). 일괄 변환은 응답이 실시간일 필요가 없으므로 대규모 데이터 집합에 대해 일괄적으로 추론을 수행할 수 있는 상황에서 유용합니다. 배치 변환의 경우 배치 입력을 데이터 세트 및 사전 학습된 모델로 사용하고 데이터 세트의 각 데이터 포인트에 대한 예측을 출력하는 배치 작업이 실행됩니다. 배치 변환은 영구 하드웨어가 있는 실시간 호스팅 엔드포인트와 달리 작업이 완료되면 배치 변환 클러스터가 해체되므로 배치 작업 기간 동안에만 하드웨어가 사용되기 때문에 비용 효율적입니다.

일부 사용 사례에서는 실시간 또는 거의 실시간 응답을 생성하기 위해 일괄 처리를 위해 실시간 추론 요청을 작은 일괄 처리로 그룹화할 수 있습니다. 예를 들어 대기 시간이 짧고 처리량이 높은 연속 데이터 스트림을 처리해야 하는 경우 각 요청에 대해 개별적으로 실시간 엔드포인트를 호출하면 더 많은 리소스가 필요하고 처리가 순차적으로 수행되기 때문에 모든 요청을 처리하는 데 시간이 더 오래 걸릴 수 있습니다. . 더 나은 접근 방식은 일부 요청을 그룹화하고 배치 추론 모드에서 실시간 엔드포인트를 호출하는 것입니다. 이 모드는 모델의 한 번의 순방향 패스에서 요청을 처리하고 요청에 대한 대량 응답을 실시간 또는 거의 실시간으로 반환합니다. . 응답 대기 시간은 함께 그룹화하는 요청 수와 인스턴스 메모리 크기에 따라 달라지므로 대기 시간 및 처리량에 대한 비즈니스 요구 사항에 따라 배치 크기를 조정할 수 있습니다. 우리는 이것을 부른다 실시간 일괄 추론 실시간 응답을 제공하면서 일괄 처리의 개념을 결합하기 때문입니다. 실시간 배치 추론을 사용하면 짧은 대기 시간과 높은 처리량 사이의 균형을 달성하여 적시에 효율적인 방식으로 대량의 데이터를 처리할 수 있습니다.

Text2Text Generation 모델을 위한 Jumpstart 배치 변환을 사용하면 처리량을 추가로 늘리고 대기 시간을 최소화하는 환경 변수를 통해 배치 하이퍼 매개변수를 전달할 수 있습니다.

JumpStart는 기계 학습(ML)을 시작하는 데 도움이 되는 광범위한 문제 유형에 대한 사전 학습된 오픈 소스 모델을 제공합니다. 배포 전에 이러한 모델을 증분식으로 교육하고 조정할 수 있습니다. JumpStart는 또한 일반적인 사용 사례를 위한 인프라를 설정하는 솔루션 템플릿과 ML을 위한 실행 가능한 예제 노트북을 제공합니다. 아마존 세이지 메이커. 다음의 JumpStart 랜딩 페이지를 통해 선행 학습된 모델, 솔루션 템플릿 및 예제에 액세스할 수 있습니다. 아마존 세이지 메이커 스튜디오. SageMaker Python SDK를 사용하여 JumpStart 모델에 액세스할 수도 있습니다.

이 게시물에서는 최첨단 사전 훈련된 text2text FLAN T5 모델 배치 변환 및 실시간 배치 추론을 위한 Hugging Face에서.

솔루션 개요

사전 훈련된 Text2Text FLAN T5 모델의 일괄 변환을 보여주는 노트북 포옹하는 얼굴 다음에서 사용 가능 GitHub 저장소. 이 노트북은 Hugging Face의 데이터를 사용합니다. cnn_데일리메일 SageMaker SDK를 사용하는 텍스트 요약 작업을 위한 데이터 세트.

다음은 배치 변환 및 실시간 배치 추론을 구현하기 위한 주요 단계입니다.

  1. 전제 조건을 설정합니다.
  2. 선행 학습된 모델을 선택합니다.
  3. 모델에 대한 아티팩트를 검색합니다.
  4. 일괄 변환 작업 하이퍼파라미터를 지정합니다.
  5. 일괄 변환을 위한 데이터를 준비합니다.
  6. 일괄 변환 작업을 실행합니다.
  7. 다음을 사용하여 요약을 평가합니다. RED (Gisting Evaluation을 위한 Recall-Oriented Understudy) 점수.
  8. 실시간 배치 추론을 수행합니다.

전제 조건 설정

노트북을 실행하기 전에 몇 가지 초기 설정 단계를 완료해야 합니다. 사용자 대신 AWS 서비스를 실행할 수 있는 권한을 갖도록 SageMaker 실행 역할을 설정해 보겠습니다.

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 모델을 사용합니다. 선택적으로 JumpStart에서 사용 가능한 Text2Text 모델 목록을 검색하고 원하는 모델을 선택할 수 있습니다. 이 방법은 동일한 노트북을 사용하여 다른 모델 ID를 선택하는 간단한 방법을 제공합니다. 데모 목적으로 huggingface-text2text-flan-t5-large 모델을 사용합니다.

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

모델에 대한 아티팩트 검색

SageMaker를 사용하면 먼저 새 데이터 세트에서 미세 조정하지 않고도 사전 훈련된 모델에서 추론을 수행할 수 있습니다. 우리는 deploy_image_uri, deploy_source_urimodel_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_데일리메일 Hugging Face의 데이터 세트:

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

각 데이터 항목을 검토하고 필요한 형식으로 입력 데이터를 생성합니다. 우리는 articles.jsonl 파일을 입력 페이로드로 요약해야 하는 기사가 포함된 테스트 데이터 파일로 저장합니다. 이 파일을 만들 때 프롬프트를 추가합니다. "Briefly summarize this text:" 각 테스트 입력 행에. 각 테스트 입력에 대해 서로 다른 하이퍼파라미터를 사용하려는 경우 데이터 세트 생성의 일부로 해당 하이퍼파라미터를 추가할 수 있습니다.

우리는 highlights.jsonl 테스트 파일에 저장된 각 기사의 하이라이트를 포함하는 실측 파일로 articles.jsonl. 우리는 두 테스트 파일을 아마존 단순 스토리지 서비스 (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 테스트 파일. 이 파일의 레코드에는 다음과 일치하는 ID가 있습니다. predict.jsonl Hugging Face Text2Text 모델의 출력으로 요약된 레코드를 표시하는 파일 레코드. 마찬가지로 Ground Truth 파일에도 데이터 레코드와 일치하는 ID가 있습니다. 테스트 파일, Ground Truth 파일 및 출력 파일에서 ID가 일치하면 입력 레코드를 출력 레코드와 연결하여 결과를 쉽게 해석할 수 있습니다.

다음은 요약을 위해 제공되는 예제 입력 레코드입니다.

{"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.']}

다음은 모델 평가 목적을 위한 ground truth 요약입니다.

{"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 ."}

다음으로 모델 평가를 위해 ground truth와 예측 결과를 사용합니다.

ROUGE 점수를 사용하여 모델 평가¶

RED, 또는 Gisting Evaluation을 위한 Recall-Oriented Understudy는 자연어 처리에서 자동 요약 및 기계 번역을 평가하는 데 사용되는 일련의 메트릭 및 소프트웨어 패키지입니다. 메트릭은 자동으로 생성된 요약 또는 번역을 참조(사람이 생성한) 요약 또는 번역 또는 참조 집합과 비교합니다.

다음 코드에서는 예측 요약과 원래 요약을 공통 키에 결합하여 결합합니다. 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}

실시간 일괄 추론 수행

다음으로 입력을 목록으로 제공하여 엔드포인트에서 실시간 배치 추론을 실행하는 방법을 보여줍니다. 테스트 데이터 세트에서 몇 개의 레코드를 가져와 실시간 엔드포인트를 호출하는 데 사용한다는 점을 제외하고 이전과 동일한 모델 ID와 데이터 세트를 사용합니다.

다음 코드는 실시간 배치 추론을 위한 실시간 엔드포인트를 만들고 배포하는 방법을 보여줍니다.

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 점수를 사용했습니다.

또한 스트리밍 입력 데이터와 같은 시나리오를 위해 대기 시간과 처리량 사이의 균형을 달성하기 위해 소량의 데이터 배치를 실시간 엔드포인트로 보낼 수 있는 실시간 배치 추론을 시연했습니다. 실시간 일괄 추론은 실시간 요청 처리량을 높이는 데 도움이 됩니다.

지금 SageMaker에서 Text2Text Generation 모델로 일괄 변환을 시도하고 피드백을 알려주세요!


저자 소개

Amazon SageMaker Jumpstart Text2Text Generation 대규모 언어 모델을 사용하여 일괄 변환 수행 | Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.헤만트 싱 Amazon SageMaker JumpStart 및 Amazon SageMaker 내장 알고리즘에 대한 경험이 있는 기계 학습 엔지니어입니다. 그는 Courant Institute of Mathematical Sciences에서 석사 학위를, IIT Delhi에서 B.Tech를 취득했습니다. 그는 자연어 처리, 컴퓨터 비전 및 시계열 분석 영역 내에서 다양한 기계 학습 문제에 대한 작업 경험이 있습니다.

Amazon SageMaker Jumpstart Text2Text Generation 대규모 언어 모델을 사용하여 일괄 변환 수행 | Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.라크나 차다 AWS Strategic Accounts의 수석 솔루션 아키텍트 AI/ML입니다. Rachna는 AI의 윤리적이고 책임 있는 사용이 미래 사회를 개선하고 경제적, 사회적 번영을 가져올 수 있다고 믿는 낙관론자입니다. 여가 시간에 Rachna는 가족과 함께 시간을 보내고, 하이킹을 하고, 음악을 듣는 것을 좋아합니다.

Amazon SageMaker Jumpstart Text2Text Generation 대규모 언어 모델을 사용하여 일괄 변환 수행 | Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.Ashish Khetan 박사 Amazon SageMaker 내장 알고리즘을 사용하는 수석 응용 과학자이며 기계 학습 알고리즘 개발을 돕습니다. 그는 University of Illinois Urbana-Champaign에서 박사 학위를 받았습니다. 그는 기계 학습 및 통계적 추론 분야에서 활동적인 연구원이며 NeurIPS, ICML, ICLR, JMLR, ACL 및 EMNLP 컨퍼런스에서 많은 논문을 발표했습니다.

타임 스탬프 :

더보기 AWS 기계 학습