제너레이티브 AI는 놀라운 성장의 한가운데에 있습니다. 가장 눈에 띄는 모델 클래스 중 하나인 대규모 언어 모델(LLM)과 함께 점점 더 많은 기능을 갖춘 기반 모델이 지속적으로 출시되고 있습니다. LLM은 광범위한 텍스트 말뭉치(최대 수천억 또는 심지어 XNUMX조 토큰)에 대해 훈련된 수십억 개의 매개변수로 구성된 모델입니다. 이러한 모델은 질문 답변에서 감정 분석에 이르기까지 광범위한 텍스트 기반 작업에 매우 효과적인 것으로 입증되었습니다.
LLM의 힘은 광범위하고 다양한 교육 데이터에서 학습하고 일반화하는 능력에서 비롯됩니다. 이러한 모델의 초기 교육은 감독, 비감독 또는 하이브리드와 같은 다양한 목표로 수행됩니다. 텍스트 완성 또는 대치는 가장 일반적인 비지도 목표 중 하나입니다. 텍스트 덩어리가 주어지면 모델은 다음에 오는 내용을 정확하게 예측하는 방법을 학습합니다(예: 다음 문장 예측). 일련의 작업을 수행하기 위해 레이블이 지정된 데이터를 사용하여 감독 방식으로 모델을 훈련할 수도 있습니다(예: 이 영화 리뷰가 긍정적인지, 부정적인지 또는 중립적인지). 모델이 텍스트 완성 또는 다른 작업을 위해 훈련되었는지 여부에 관계없이 고객이 모델을 사용하기를 원하는 작업이 아닌 경우가 많습니다.
특정 작업에 대한 사전 훈련된 LLM의 성능을 개선하기 위해 다음과 같은 프로세스에서 대상 작업의 예를 사용하여 모델을 조정할 수 있습니다. 명령 미세 조정. 명령 미세 조정은 {prompt, response} 쌍 형식의 레이블이 지정된 예제 집합을 사용하여 프롬프트가 주어진 응답을 적절하게 예측하도록 사전 훈련된 모델을 추가로 훈련합니다. 이 프로세스는 모델의 가중치를 수정합니다.
이 게시물에서는 다음을 사용하여 LLM, 즉 FLAN T5 XL의 명령 미세 조정을 수행하는 방법을 설명합니다. Amazon SageMaker 점프스타트. 다음에서 Jumpstart UI와 노트북을 모두 사용하여 이를 수행하는 방법을 시연합니다. 아마존 세이지 메이커 스튜디오. 당신은 찾을 수 있습니다 수첩 FBI 증오 범죄 보고서 amazon-sagemaker-예제 GitHub 저장소.
솔루션 개요
이 게시물의 목표 작업은 프롬프트에 텍스트 덩어리가 주어졌을 때 텍스트와 관련이 있지만 포함된 정보를 기반으로 답변할 수 없는 질문을 반환하는 것입니다. 이는 설명에서 누락된 정보를 식별하거나 쿼리에 응답하기 위해 추가 정보가 필요한지 여부를 식별하는 데 유용한 작업입니다.
FLAN T5 모델은 많은 일반적인 작업[1]에서 이러한 모델의 제로 샷 성능을 높이기 위해 광범위한 작업에 대해 미세 조정된 지침입니다. 특정 고객 작업에 대한 추가 지침 미세 조정은 이러한 모델의 정확도를 더욱 높일 수 있습니다. 특히 우리 작업의 경우와 같이 대상 작업이 FLAN T5 모델을 교육하는 데 이전에 사용되지 않은 경우 더욱 그렇습니다.
예제 작업에서는 관련이 있지만 답변이 없는 질문을 생성하는 데 관심이 있습니다. 이를 위해 Stanford Question Answering Dataset(SQuAD2)[2.0] 버전 2의 하위 집합을 사용하여 모델을 미세 조정합니다. 이 데이터 세트에는 일련의 Wikipedia 문서에서 사람 어노테이터가 제기한 질문이 포함되어 있습니다. 답변이 있는 질문 외에도 SQuAD2.0에는 답변할 수 없는 약 50,000개의 질문이 포함되어 있습니다. 이러한 질문은 그럴듯하지만 기사 내용에서 직접 답변할 수 없습니다. 답이 없는 질문만 사용합니다. 우리의 데이터는 JSON Lines 파일로 구성되어 있으며 각 줄에는 컨텍스트와 질문이 포함되어 있습니다.
사전 조건
시작하려면 Studio를 사용할 수 있는 AWS 계정만 있으면 됩니다. 아직 없는 경우 Studio용 사용자 프로필을 만들어야 합니다.
Jumpstart UI로 FLAN-T5 미세 조정
Jumpstart UI로 모델을 미세 조정하려면 다음 단계를 완료하십시오.
- SageMaker 콘솔에서 Studio를 엽니다.
- $XNUMX Million 미만 SageMaker 점프스타트 탐색 창에서 모델, 노트북, 솔루션.
미세 조정 가능으로 표시된 FLAN T5 XL을 포함하여 기본 모델 목록이 표시됩니다.
- 왼쪽 메뉴에서 모델 보기.
- $XNUMX Million 미만 데이터 소스, 훈련 데이터의 경로를 제공할 수 있습니다. 이 게시물에 사용된 데이터의 출처는 기본적으로 제공됩니다.
- 배포 구성(인스턴스 유형 포함), 보안 및 하이퍼파라미터에 대한 기본값을 유지할 수 있지만 좋은 결과를 얻으려면 에포크 수를 XNUMX개 이상으로 늘려야 합니다.
- 왼쪽 메뉴에서 Train
모델을 훈련합니다.
UI에서 학습 작업의 상태를 추적할 수 있습니다.
- 교육이 완료되면(이 경우 약 53분 후) 다음을 선택합니다. 배포 미세 조정된 모델을 배포합니다.
엔드포인트가 생성된 후(몇 분) 노트북을 열고 미세 조정된 모델을 사용할 수 있습니다.
Python 노트북을 사용하여 FLAN-T5 미세 조정
예제 노트북은 Jumpstart 및 SageMaker를 사용하여 FLAN T5 XL 모델을 프로그래밍 방식으로 미세 조정하고 배포하는 방법을 보여줍니다. Studio 또는 로컬에서 실행할 수 있습니다.
이 섹션에서는 먼저 몇 가지 일반적인 설정을 살펴봅니다. 그런 다음 SQuADv2 데이터 세트를 사용하여 모델을 미세 조정합니다. 다음으로 SageMaker 엔드포인트 뒤에 모델의 사전 훈련된 버전을 배포하고 미세 조정된 모델로 동일한 작업을 수행합니다. 마지막으로 엔드포인트를 쿼리하고 사전 학습 및 미세 조정된 모델의 출력 품질을 비교할 수 있습니다. 미세 조정된 모델의 출력 품질이 훨씬 높다는 것을 알 수 있습니다.
전제 조건 설정
필요한 패키지를 설치하고 업그레이드하여 시작하십시오. 다음 코드를 실행한 후 커널을 다시 시작합니다.
!pip install nest-asyncio==1.5.5 --quiet
!pip install ipywidgets==8.0.4 --quiet
!pip install --upgrade sagemaker --quiet
다음으로 현재 노트북 인스턴스와 연결된 실행 역할을 얻습니다.
import boto3
import sagemaker
# Get current region, role, and default bucket
aws_region = boto3.Session().region_name
aws_role = sagemaker.session.Session().get_caller_identity_arn()
output_bucket = sagemaker.Session().default_bucket()
# This will be useful for printing
newline, bold, unbold = "n", "33[1m", "33[0m"
print(f"{bold}aws_region:{unbold} {aws_region}")
print(f"{bold}aws_role:{unbold} {aws_role}")
print(f"{bold}output_bucket:{unbold} {output_bucket}"
미세 조정에 사용할 수 있는 모델 크기를 나열하는 편리한 드롭다운 메뉴를 정의할 수 있습니다.
import IPython
from ipywidgets import Dropdown
from sagemaker.jumpstart.filters import And
from sagemaker.jumpstart.notebook_utils import list_jumpstart_models
# Default model choice
model_id = "huggingface-text2text-flan-t5-xl"
# Identify FLAN T5 models that support fine-tuning
filter_value = And( "task == text2text", "framework == huggingface", "training_supported == true"
)
model_list = [m for m in list_jumpstart_models(filter=filter_value) if "flan-t5" in m]
# Display the model IDs in a dropdown, for user to select
dropdown = Dropdown(
value=model_id,
options=model_list,
description="FLAN T5 models available for fine-tuning:",
style={"description_width": "initial"},
layout={"width": "max-content"},
)
display(IPython.display.Markdown("### Select a pre-trained model from the dropdown below"))
display(dropdown)
Jumpstart는 선택한 모델에 대해 적절한 교육 및 추론 인스턴스 유형을 자동으로 검색합니다.
from sagemaker.instance_types import retrieve_default
model_id, model_version = dropdown.value, "*"
# Instance types for training and inference
training_instance_type = retrieve_default(
model_id=model_id, model_version=model_version, scope="training"
)
inference_instance_type = retrieve_default(
model_id=model_id, model_version=model_version, scope="inference"
)
print(f"{bold}model_id:{unbold} {model_id}")
print(f"{bold}training_instance_type:{unbold} {training_instance_type}")
print(f"{bold}inference_instance_type:{unbold} {inference_instance_type}") If you have chosen the FLAN T5 XL, you will see the following output: model_id: huggingface-text2text-flan-t5-xl training_instance_type: ml.p3.16xlarge inference_instance_type: ml.g5.2xlarge
이제 미세 조정을 시작할 준비가 되었습니다.
미세 조정 데이터 세트에서 모델 재교육
설정이 완료되면 다음 단계를 완료하십시오.
다음 코드를 사용하여 필요한 아티팩트의 URI를 검색합니다.
from sagemaker import image_uris, model_uris, script_uris
# Training instance will use this image
train_image_uri = image_uris.retrieve(
region=aws_region,
framework=None, # automatically inferred from model_id
model_id=model_id,
model_version=model_version,
image_scope="training",
instance_type=training_instance_type,
)
# Pre-trained model
train_model_uri = model_uris.retrieve(
model_id=model_id, model_version=model_version, model_scope="training"
)
# Script to execute on the training instance
train_script_uri = script_uris.retrieve(
model_id=model_id, model_version=model_version, script_scope="training"
)
print(f"{bold}image uri:{unbold} {train_image_uri}")
print(f"{bold}model uri:{unbold} {train_model_uri}")
print(f"{bold}script uri:{unbold} {train_script_uri}")
교육 데이터는 공개된 아마존 단순 스토리지 서비스 (Amazon S3) 버킷.
다음 코드를 사용하여 데이터 위치를 가리키고 계정의 버킷에서 출력 위치를 설정합니다.
from sagemaker.s3 import S3Downloader # We will use the train split of SQuAD2.0
original_data_file = "train-v2.0.json" # The data was mirrored in the following bucket
original_data_location = f"s3://sagemaker-sample-files/datasets/text/squad2.0/{original_data_file}"
S3Downloader.download(original_data_location, ".")
원래 데이터는 모델을 미세 조정하는 작업에 해당하는 형식이 아니므로 다시 형식화할 수 있습니다.
import json local_data_file = "task-data.jsonl" # any name with .jsonl extension with open(original_data_file) as f:
data = json.load(f) with open(local_data_file, "w") as f:
for article in data["data"]:
for paragraph in article["paragraphs"]:
# iterate over questions for a given paragraph
for qas in paragraph["qas"]:
if qas["is_impossible"]:
# the question is relevant, but cannot be answered
example = {"context": paragraph["context"], "question": qas["question"]}
json.dump(example, f)
f.write("n") template = { "prompt": "Ask a question which is related to the following text, but cannot be answered based on the text. Text: {context}", "completion": "{question}",
}
with open("template.json", "w") as f:
json.dump(template, f) from sagemaker.s3 import S3Uploader train_data_location = f"s3://{output_bucket}/train_data"
S3Uploader.upload(local_data_file, train_data_location)
S3Uploader.upload("template.json", train_data_location)
print(f"{bold}training data:{unbold} {train_data_location}")
이제 훈련을 위한 몇 가지 하이퍼파라미터를 정의할 수 있습니다.
from sagemaker import hyperparameters # Retrieve the default hyper-parameters for fine-tuning the model
hyperparameters = hyperparameters.retrieve_default(model_id=model_id, model_version=model_version) # We will override some default hyperparameters with custom values
hyperparameters["epochs"] = "3"
# TODO
# hyperparameters["max_input_length"] = "300" # data inputs will be truncated at this length
# hyperparameters["max_output_length"] = "40" # data outputs will be truncated at this length
# hyperparameters["generation_max_length"] = "40" # max length of generated output
print(hyperparameters)
이제 학습 작업을 시작할 준비가 되었습니다.
from sagemaker.estimator import Estimator
from sagemaker.utils import name_from_base model_name = "-".join(model_id.split("-")[2:]) # get the most informative part of ID
training_job_name = name_from_base(f"js-demo-{model_name}-{hyperparameters['epochs']}")
print(f"{bold}job name:{unbold} {training_job_name}") training_metric_definitions = [
{"Name": "val_loss", "Regex": "'eval_loss': ([0-9.]+)"},
{"Name": "train_loss", "Regex": "'loss': ([0-9.]+)"},
{"Name": "epoch", "Regex": "'epoch': ([0-9.]+)"},
] # Create SageMaker Estimator instance
sm_estimator = Estimator(
role=aws_role,
image_uri=train_image_uri,
model_uri=train_model_uri,
source_dir=train_script_uri,
entry_point="transfer_learning.py",
instance_count=1,
instance_type=training_instance_type,
volume_size=300,
max_run=360000,
hyperparameters=hyperparameters,
output_path=output_location,
metric_definitions=training_metric_definitions,
) # Launch a SageMaker training job over data located in the given S3 path
# Training jobs can take hours, it is recommended to set wait=False,
# and monitor job status through SageMaker console
sm_estimator.fit({"training": train_data_location}, job_name=training_job_name, wait=False)
미세 조정 데이터 및 선택한 모델의 크기에 따라 미세 조정에 최대 몇 시간이 걸릴 수 있습니다.
다음을 사용하여 교육 및 검증 손실과 같은 성능 메트릭을 모니터링할 수 있습니다. 아마존 클라우드 워치 훈련 중. 편리하게 다음 코드를 실행하여 메트릭의 최신 스냅샷을 가져올 수도 있습니다.
from sagemaker import TrainingJobAnalytics # This can be called while the job is still running
df = TrainingJobAnalytics(training_job_name=training_job_name).dataframe()
df.head(10) model uri: s3://sagemaker-us-west-2-802376408542/avkan/training-huggingface-text2text-huggingface-text2text-flan-t5-xl-repack.tar.gz
job name: jumpstart-demo-xl-3-2023-04-06-08-16-42-738
INFO:sagemaker:Creating training-job with name: jumpstart-demo-xl-3-2023-04-06-08-16-42-738
학습이 완료되면 다음 위치에서 미세 조정된 모델을 갖게 됩니다. model_uri
. 그것을 사용하자!
두 개의 추론 끝점을 생성할 수 있습니다. 하나는 사전 훈련된 원래 모델용이고 다른 하나는 미세 조정된 모델용입니다. 이렇게 하면 모델의 두 버전의 출력을 비교할 수 있습니다. 다음 단계에서는 선행 학습된 모델에 대한 추론 엔드포인트를 배포합니다. 그런 다음 미세 조정된 모델에 대한 엔드포인트를 배포합니다.
선행 학습된 모델 배포
추론 Docker 이미지 URI를 검색하는 미리 훈련된 모델을 배포하여 시작하겠습니다. 기본 Hugging Face 컨테이너 이미지입니다. 다음 코드를 사용하십시오.
from sagemaker import image_uris # Retrieve the inference docker image URI. This is the base HuggingFace container image
deploy_image_uri = image_uris.retrieve(
region=None,
framework=None, # automatically inferred from model_id
model_id=model_id,
model_version=model_version,
image_scope="inference",
instance_type=inference_instance_type,
)
이제 엔드포인트를 생성하고 선행 학습된 모델을 배포할 수 있습니다. SageMaker API를 통해 추론을 실행하려면 Model 클래스를 통해 모델을 배포할 때 Predictor 클래스를 전달해야 합니다. 다음 코드를 참조하십시오.
from sagemaker import model_uris, script_uris
from sagemaker.model import Model
from sagemaker.predictor import Predictor
from sagemaker.utils import name_from_base # Retrieve the URI of the pre-trained model
pre_trained_model_uri = model_uris.retrieve(
model_id=model_id, model_version=model_version, model_scope="inference"
) pre_trained_name = name_from_base(f"jumpstart-demo-pre-trained-{model_id}") # Create the SageMaker model instance of the pre-trained model
if ("small" in model_id) or ("base" in model_id):
deploy_source_uri = script_uris.retrieve(
model_id=model_id, model_version=model_version, script_scope="inference"
)
pre_trained_model = Model(
image_uri=deploy_image_uri,
source_dir=deploy_source_uri,
entry_point="inference.py",
model_data=pre_trained_model_uri,
role=aws_role,
predictor_cls=Predictor,
name=pre_trained_name,
)
else:
# For those large models, we already repack the inference script and model
# artifacts for you, so the `source_dir` argument to Model is not required.
pre_trained_model = Model(
image_uri=deploy_image_uri,
model_data=pre_trained_model_uri,
role=aws_role,
predictor_cls=Predictor,
name=pre_trained_name,
) print(f"{bold}image URI:{unbold}{newline} {deploy_image_uri}")
print(f"{bold}model URI:{unbold}{newline} {pre_trained_model_uri}")
print("Deploying an endpoint ...") # Deploy the pre-trained 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
pre_trained_predictor = pre_trained_model.deploy(
initial_instance_count=1,
instance_type=inference_instance_type,
predictor_cls=Predictor,
endpoint_name=pre_trained_name,
)
print(f"{newline}Deployed an endpoint {pre_trained_name}")
엔드포인트 생성 및 모델 배포는 몇 분 정도 걸릴 수 있으며, 그 후에 엔드포인트가 추론 호출을 수신할 준비가 됩니다.
미세 조정된 모델 배포
미세 조정된 모델을 자체 엔드포인트에 배포해 보겠습니다. 이 프로세스는 이전에 사전 훈련된 모델에 사용한 프로세스와 거의 동일합니다. 유일한 차이점은 미세 조정된 모델 이름과 URI를 사용한다는 것입니다.
from sagemaker.model import Model
from sagemaker.predictor import Predictor
from sagemaker.utils import name_from_base fine_tuned_name = name_from_base(f"jumpstart-demo-fine-tuned-{model_id}")
fine_tuned_model_uri = f"{output_location}{training_job_name}/output/model.tar.gz" # Create the SageMaker model instance of the fine-tuned model
fine_tuned_model = Model(
image_uri=deploy_image_uri,
model_data=fine_tuned_model_uri,
role=aws_role,
predictor_cls=Predictor,
name=fine_tuned_name,
) print(f"{bold}image URI:{unbold}{newline} {deploy_image_uri}")
print(f"{bold}model URI:{unbold}{newline} {fine_tuned_model_uri}")
print("Deploying an endpoint ...") # Deploy the fine-tuned model.
fine_tuned_predictor = fine_tuned_model.deploy(
initial_instance_count=1,
instance_type=inference_instance_type,
predictor_cls=Predictor,
endpoint_name=fine_tuned_name,
)
print(f"{newline}Deployed an endpoint {fine_tuned_name}")
이 프로세스가 완료되면 사전 훈련된 모델과 미세 조정된 모델이 자체 엔드포인트 뒤에 배포됩니다. 그들의 출력을 비교해 봅시다.
출력 생성 및 결과 비교
엔드포인트를 쿼리하고 응답을 구문 분석하는 몇 가지 유틸리티 함수를 정의합니다.
import boto3
import json # Parameters of (output) text generation. A great introduction to generation
# parameters can be found at https://huggingface.co/blog/how-to-generate
parameters = { "max_length": 40, # restrict the length of the generated text "num_return_sequences": 5, # we will inspect several model outputs "num_beams": 10, # use beam search
} # Helper functions for running inference queries
def query_endpoint_with_json_payload(payload, endpoint_name):
encoded_json = json.dumps(payload).encode("utf-8")
client = boto3.client("runtime.sagemaker")
response = client.invoke_endpoint(
EndpointName=endpoint_name, ContentType="application/json", Body=encoded_json
)
return response def parse_response_multiple_texts(query_response):
model_predictions = json.loads(query_response["Body"].read())
generated_text = model_predictions["generated_texts"]
return generated_text def generate_questions(endpoint_name, text):
expanded_prompt = prompt.replace("{context}", text)
payload = {"text_inputs": expanded_prompt, **parameters}
query_response = query_endpoint_with_json_payload(payload, endpoint_name=endpoint_name)
generated_texts = parse_response_multiple_texts(query_response)
for i, generated_text in enumerate(generated_texts):
print(f"Response {i}: {generated_text}{newline}")
다음 코드 스니펫에서는 프롬프트와 테스트 데이터를 정의합니다. 는 제공된 텍스트와 관련이 있지만 이를 기반으로 답변할 수 없는 질문을 생성하는 우리의 목표 작업을 설명합니다.
테스트 데이터는 세 개의 서로 다른 단락으로 구성되어 있습니다. Wikipedia 페이지의 처음 두 단락, 하나에 관한 아마존 엘라스틱 블록 스토어 (아마존 EBS)에서 아마존 EBS 설명서및 다음 중 하나 아마존 이해 인사말 Amazon Comprehend 설명서. 모델이 이러한 단락과 관련된 질문을 식별할 것으로 기대하지만 여기에 제공된 정보로는 답변할 수 없습니다.
prompt = "Ask a question which is related to the following text, but cannot be answered based on the text. Text: {context}" test_paragraphs = [ """
Adelaide is the capital city of South Australia, the state's largest city and the fifth-most populous city in Australia. "Adelaide" may refer to either Greater Adelaide (including the Adelaide Hills) or the Adelaide city centre.
The demonym Adelaidean is used to denote the city and the residents of Adelaide. The Traditional Owners of the Adelaide
region are the Kaurna people. The area of the city centre and surrounding parklands is called Tarndanya in the Kaurna language. Adelaide is situated on the Adelaide Plains north of the Fleurieu Peninsula, between the Gulf St Vincent in the west and
the Mount Lofty Ranges in the east. Its metropolitan area extends 20 km (12 mi) from the coast to the foothills of
the Mount Lofty Ranges, and stretches 96 km (60 mi) from Gawler in the north to Sellicks Beach in the south. """, """
Amazon Elastic Block Store (Amazon EBS) provides block level storage volumes for use with EC2 instances. EBS volumes behave like raw, unformatted block devices. You can mount these volumes as devices on your instances. EBS volumes that are attached to an instance are exposed as storage volumes that persist independently from the life of the instance. You can create a file system on top of these volumes, or use them in any way you would use a block device (such as a hard drive). You can dynamically change the configuration of a volume attached to an instance. We recommend Amazon EBS for data that must be quickly accessible and requires long-term persistence. EBS volumes are particularly well-suited for use as the primary storage for file systems, databases, or for any applications that require fine granular updates and access to raw, unformatted, block-level storage. Amazon EBS is well suited to both database-style applications that rely on random reads and writes, and to throughput-intensive applications that perform long, continuous reads and writes. """, """
Amazon Comprehend uses natural language processing (NLP) to extract insights about the content of documents. It develops insights by recognizing the entities, key phrases, language, sentiments, and other common elements in a document. Use Amazon Comprehend to create new products based on understanding the structure of documents. For example, using Amazon Comprehend you can search social networking feeds for mentions of products or scan an entire document repository for key phrases. You can access Amazon Comprehend document analysis capabilities using the Amazon Comprehend console or using the Amazon Comprehend APIs. You can run real-time analysis for small workloads or you can start asynchronous analysis jobs for large document sets. You can use the pre-trained models that Amazon Comprehend provides, or you can train your own custom models for classification and entity recognition. All of the Amazon Comprehend features accept UTF-8 text documents as the input. In addition, custom classification and custom entity recognition accept image files, PDF files, and Word files as input. Amazon Comprehend can examine and analyze documents in a variety of languages, depending on the specific feature. For more information, see Languages supported in Amazon Comprehend. Amazon Comprehend's Dominant language capability can examine documents and determine the dominant language for a far wider selection of languages. """
]
이제 예제 문서를 사용하여 엔드포인트를 테스트할 수 있습니다.
print(f"{bold}Prompt:{unbold} {repr(prompt)}")
for paragraph in test_paragraphs:
print("-" * 80)
print(paragraph)
print("-" * 80)
print(f"{bold}pre-trained{unbold}")
generate_questions(pre_trained_name, paragraph)
print(f"{bold}fine-tuned{unbold}")
generate_questions(fine_tuned_name, paragraph)
테스트 데이터: 애들레이드
다음 컨텍스트를 사용합니다.
delaide is the capital city of South Australia, the state's largest city and the fifth-most populous city in Australia. "Adelaide" may refer to either Greater Adelaide (including the Adelaide Hills) or the Adelaide city centre.
The demonym Adelaidean is used to denote the city and the residents of Adelaide. The Traditional Owners of the Adelaide
region are the Kaurna people. The area of the city centre and surrounding parklands is called Tarndanya in the Kaurna language. Adelaide is situated on the Adelaide Plains north of the Fleurieu Peninsula, between the Gulf St Vincent in the west and
the Mount Lofty Ranges in the east. Its metropolitan area extends 20 km (12 mi) from the coast to the foothills of
the Mount Lofty Ranges, and stretches 96 km (60 mi) from Gawler in the north to Sellicks Beach in the south.
사전 학습된 모델 응답은 다음과 같습니다.
Response 0: What is the area of the city centre and surrounding parklands called in the Kaurna language?
Response 1: What is the area of the city centre and surrounding parklands is called Tarndanya in the Kaurna language?
Response 2: What is the area of the city centre and surrounding parklands called in Kaurna?
Response 3: What is the capital city of South Australia?
Response 4: What is the area of the city centre and surrounding parklands known as in the Kaurna language?
미세 조정된 모델 응답은 다음과 같습니다.
Response 0: What is the second most populous city in Australia?
Response 1: What is the fourth most populous city in Australia?
Response 2: What is the population of Gawler?
Response 3: What is the largest city in Australia?
Response 4: What is the fifth most populous city in the world?
테스트 데이터: Amazon EBS
다음 컨텍스트를 사용합니다.
Amazon Elastic Block Store (Amazon EBS) provides block level storage volumes for use with EC2 instances. EBS volumes behave like raw, unformatted block devices. You can mount these volumes as devices on your instances. EBS volumes that are attached to an instance are exposed as storage volumes that persist independently from the life of the instance. You can create a file system on top of these volumes, or use them in any way you would use a block device (such as a hard drive). You can dynamically change the configuration of a volume attached to an instance. We recommend Amazon EBS for data that must be quickly accessible and requires long-term persistence. EBS volumes are particularly well-suited for use as the primary storage for file systems, databases, or for any applications that require fine granular updates and access to raw, unformatted, block-level storage. Amazon EBS is well suited to both database-style applications that rely on random reads and writes, and to throughput-intensive applications that perform long, continuous reads and writes.
사전 학습된 모델 응답은 다음과 같습니다.
esponse 0: What is the difference between Amazon EBS and Amazon Elastic Block Store (Amazon EBS)?
Response 1: What is the difference between Amazon EBS and Amazon Elastic Block Store?
Response 2: What is the difference between Amazon EBS and Amazon Simple Storage Service (Amazon S3)?
Response 3: What is Amazon Elastic Block Store (Amazon EBS)?
Response 4: What is the difference between Amazon EBS and a hard drive?
미세 조정된 모델 응답은 다음과 같습니다.
Response 0: What type of applications are not well suited to Amazon EBS?
Response 1: What behaves like formatted block devices?
Response 2: What type of applications are not suited to Amazon EBS?
Response 3: What type of applications are not well suited for Amazon EBS?
Response 4: What type of applications are not suited for Amazon EBS?
테스트 데이터: Amazon Comprehend
다음 컨텍스트를 사용합니다.
Amazon Comprehend uses natural language processing (NLP) to extract insights about the content of documents. It develops insights by recognizing the entities, key phrases, language, sentiments, and other common elements in a document. Use Amazon Comprehend to create new products based on understanding the structure of documents. For example, using Amazon Comprehend you can search social networking feeds for mentions of products or scan an entire document repository for key phrases. You can access Amazon Comprehend document analysis capabilities using the Amazon Comprehend console or using the Amazon Comprehend APIs. You can run real-time analysis for small workloads or you can start asynchronous analysis jobs for large document sets. You can use the pre-trained models that Amazon Comprehend provides, or you can train your own custom models for classification and entity recognition. All of the Amazon Comprehend features accept UTF-8 text documents as the input. In addition, custom classification and custom entity recognition accept image files, PDF files, and Word files as input. Amazon Comprehend can examine and analyze documents in a variety of languages, depending on the specific feature. For more information, see Languages supported in Amazon Comprehend. Amazon Comprehend's Dominant language capability can examine documents and determine the dominant language for a far wider selection of languages.
사전 학습된 모델 응답은 다음과 같습니다.
Response 0: What does Amazon Comprehend use to extract insights about the content of documents?
Response 1: How does Amazon Comprehend extract insights about the content of documents?
Response 2: What does Amazon Comprehend use to develop insights about the content of documents?
Response 3: How does Amazon Comprehend develop insights about the content of documents?
Response 4: What does Amazon Comprehend use to extract insights about the content of a document?
미세 조정된 모델 응답은 다음과 같습니다.
Response 0: What does Amazon Comprehend use to extract insights about the structure of documents?
Response 1: How does Amazon Comprehend recognize sentiments in a document?
Response 2: What does Amazon Comprehend use to extract insights about the content of social networking feeds?
Response 3: What does Amazon Comprehend use to extract insights about the content of documents?
Response 4: What type of files does Amazon Comprehend reject as input?
사전 학습된 모델과 미세 조정된 모델 간의 출력 품질 차이는 극명합니다. 미세 조정된 모델이 제공하는 질문은 더 넓은 범위의 주제를 다룹니다. 이는 체계적으로 의미 있는 질문이며, Amazon EBS 예제에서 설명한 것처럼 사전 훈련된 모델의 경우 항상 그런 것은 아닙니다.
이것이 공식적이고 체계적인 평가를 구성하지는 않지만 미세 조정 프로세스가 이 작업에 대한 모델 응답의 품질을 개선한 것은 분명합니다.
정리
마지막으로 끝점을 정리하고 삭제해야 합니다.
# Delete resources
pre_trained_predictor.delete_model()
pre_trained_predictor.delete_endpoint()
fine_tuned_predictor.delete_model()
fine_tuned_predictor.delete_endpoint()
결론
이 게시물에서는 Studio에서 실행되는 Jupyter 노트북 또는 Jumpstart UI를 사용하여 FLAN T5 모델에서 명령어 미세 조정을 사용하는 방법을 보여주었습니다. 대상 작업에 대한 데이터를 사용하여 모델을 재훈련하고 엔드포인트 뒤에 미세 조정된 모델을 배포하는 방법을 설명하는 코드를 제공했습니다. 이 게시물의 목표 작업은 입력에 제공된 텍스트 덩어리와 관련이 있지만 해당 텍스트에 제공된 정보를 기반으로 답변할 수 없는 질문을 식별하는 것이었습니다. 우리는 이 특정 작업에 대해 미세 조정된 모델이 사전 훈련된 모델보다 더 나은 결과를 반환한다는 것을 입증했습니다.
이제 Jumpstart로 모델을 미세 조정하는 방법을 배웠으므로 응용 프로그램에 맞게 사용자 지정된 강력한 모델을 만들 수 있습니다. 사용 사례에 대한 일부 데이터를 수집하여 Amazon S3에 업로드하고 Studio UI 또는 노트북을 사용하여 FLAN T5 모델을 조정하십시오!
참고자료
[1] 정형원 외. "명령 미세 조정 언어 모델 확장." arXiv 프리프린트 arXiv:2210.11416 (2022).
[2] Rajpurkar, Pranav, Robin Jia 및 Percy Liang. "당신이 모르는 것을 알고: SQuAD에 대한 대답할 수 없는 질문." 전산 언어학 협회 제56차 연례 회의 간행물(2권: 짧은 논문). 2018.
저자 소개
로랑 칼로 기본 모델 및 생성 AI에서 예측, 이상 탐지, 인과 관계 및 AI Ops에 이르기까지 다양한 기계 학습 문제를 연구한 AWS AI Labs의 수석 응용 과학자이자 관리자입니다.
안드레이 칸 기계 학습의 다양한 분야에 대한 관심과 경험이 있는 AWS AI Labs의 선임 응용 과학자입니다. 여기에는 기본 모델에 대한 연구와 그래프 및 시계열을 위한 ML 애플리케이션이 포함됩니다.
Ashish Khetan 박사 Amazon SageMaker 내장 알고리즘을 사용하는 수석 응용 과학자이며 기계 학습 알고리즘 개발을 돕습니다. 그는 University of Illinois Urbana Champaign에서 박사 학위를 받았습니다. 그는 기계 학습 및 통계적 추론 분야에서 활동적인 연구원이며 NeurIPS, ICML, ICLR, JMLR, ACL 및 EMNLP 컨퍼런스에서 많은 논문을 발표했습니다.
바리스 커트 AWS AI Labs의 응용 과학자입니다. 그의 관심은 시계열 이상 탐지 및 기반 모델에 있습니다. 그는 사용자 친화적인 ML 시스템 개발을 좋아합니다.
요나스 퀴블러 AWS AI Labs의 응용 과학자입니다. 그는 사용 사례별 애플리케이션을 용이하게 하는 것을 목표로 기초 모델에 대해 작업하고 있습니다.