AWS Marketplace에서 파인튜닝한 Command 모델 배포하기
AWS Marketplace에서 파인튜닝한 Command 모델 배포하기
이 문서는 직접 파인튜닝한 모델을 Amazon SageMaker로 가져와 배포하는 방법을 안내해요. 어댑터 가중치를 병합하고, TensorRT-LLM 추론 엔진으로 내보낸 뒤, SageMaker 엔드포인트로 서빙하는 전체 과정을 차근차근 살펴볼게요.
출처: 문서
본문
이 문서는 직접 파인튜닝한 HuggingFace Command-R 모델을 Amazon SageMaker를 사용해 배포하는 방법을 보여줘요. 더 구체적으로 말하면, 이미 직접 파인튜닝한 Command 모델의 어댑터 가중치(adapter weights)나 병합 가중치(merged weights)를 갖고 있다고 가정하고, 다음을 수행하는 방법을 다룰게요:
- 어댑터 가중치만 가져왔다면 어댑터 가중치를 베이스 모델의 가중치와 병합하기
- Amazon SageMaker를 사용해 병합된 가중치를 TensorRT-LLM 추론 엔진으로 내보내기
- 엔진을 SageMaker 엔드포인트로 배포해 비즈니스 사용 사례를 서빙하기
동작하는 코드 샘플이 담긴 보조 노트북도 함께 확인할 수 있어요.
사전 준비물 (Prerequisites)
- 사용하는 IAM 역할이
AmazonSageMakerFullAccess를 갖고 있어야 해요 - 모델을 성공적으로 배포하려면 다음 중 하나를 충족해야 해요:
- IAM 역할에 다음 세 가지 권한이 있고, 관련 AWS 계정에서 AWS Marketplace 구독을 할 권한이 있다면:
aws-marketplace:ViewSubscriptionsaws-marketplace:Unsubscribeaws-marketplace:Subscribe
- 또는 AWS 계정에 Cohere Bring Your Own Fine-tuning 패키지에 대한 구독이 있다면. 이 경우 아래의 "bring your own finetuning 알고리즘 구독" 단계를 건너뛸 수 있어요.
- IAM 역할에 다음 세 가지 권한이 있고, 관련 AWS 계정에서 AWS Marketplace 구독을 할 권한이 있다면:
NOTE: 보조 노트북을 실행한다면, 이 노트북에는 Jupyter 인터페이스에서 제대로 렌더링되는 요소가 포함되어 있으므로, Amazon SageMaker Notebook Instance 또는 Amazon SageMaker Studio에서 열어야 해요.
1단계: bring your own finetuning 알고리즘 구독하기
알고리즘을 구독하려면:
- Cohere Bring Your Own Fine-tuning 알고리즘 등록 페이지를 열어요.
- AWS Marketplace 등록에서 Continue to Subscribe 버튼을 클릭해요.
- Subscribe to this software 페이지에서 EULA, 가격, 지원 조건에 동의한다면 Accept Offer를 검토하고 클릭해요. Configure and launch 페이지에서 해당 리전에 표시된 ARN이 아래에서 사용할 ARN과 일치하는지 확인해요.
2단계: 사전 설정 (Preliminary setup)
먼저 Python 패키지를 설치하고 임포트해요.
pip install "cohere>=5.11.0"
PYTHON
import cohere
import os
import sagemaker as sage
from sagemaker.s3 import S3Uploader
AWS 계정의 리소스에 접근 권한이 있는지 확인해요. 예를 들어 aws configure sso 명령으로 AWS 프로필을 구성하고(Amazon 문서 참고), 아래 명령을 실행해 환경 변수 AWS_PROFILE을 자신의 프로필 이름으로 설정할 수 있어요.
PYTHON
# Change "<aws_profile>" to your own AWS profile name
os.environ["AWS_PROFILE"] = "<aws_profile>"
마지막으로 다음 변수들을 모두 자신의 정보로 설정해야 해요. 이러한 경로에 후행 슬래시를 추가하지 않는 게 좋아요. 추가하면 일부 부분이 올바르게 작동하지 않을 수 있기 때문이에요. Cohere Bring Your Own Fine-tuning의 instance_type으로는 ml.p4de.24xlarge 또는 ml.p5.48xlarge를 사용할 수 있는데, 내보내기와 추론(엔드포인트 생성)에 사용하는 instance_type은 반드시 동일해야 해요.
PYTHON
# The AWS region
region = "<region>"
# Get the arn of the bring your own finetuning algorithm by region
cohere_package = "cohere-command-r-v2-byoft-8370167e649c32a1a5f00267cd334c2c"
algorithm_map = {
"us-east-1": f"arn:aws:sagemaker:us-east-1:865070037744:algorithm/{cohere_package}",
"us-east-2": f"arn:aws:sagemaker:us-east-2:057799348421:algorithm/{cohere_package}",
"us-west-2": f"arn:aws:sagemaker:us-west-2:594846645681:algorithm/{cohere_package}",
"eu-central-1": f"arn:aws:sagemaker:eu-central-1:446921602837:algorithm/{cohere_package}",
"ap-southeast-1": f"arn:aws:sagemaker:ap-southeast-1:192199979996:algorithm/{cohere_package}",
"ap-southeast-2": f"arn:aws:sagemaker:ap-southeast-2:666831318237:algorithm/{cohere_package}",
"ap-northeast-1": f"arn:aws:sagemaker:ap-northeast-1:977537786026:algorithm/{cohere_package}",
"ap-south-1": f"arn:aws:sagemaker:ap-south-1:077584701553:algorithm/{cohere_package}",
}
if region not in algorithm_map:
raise Exception(f"Current region {region} is not supported.")
arn = algorithm_map[region]
# The local directory of your adapter weights. No need to specify this, if you bring your own merged weights
adapter_weights_dir = "<adapter_weights_dir>"
# The local directory you want to save the merged weights. Or the local directory of your own merged weights, if you bring your own merged weights
merged_weights_dir = "<merged_weights_dir>"
# The S3 directory you want to save the merged weights
s3_checkpoint_dir = "<s3_checkpoint_dir>"
# The S3 directory you want to save the exported TensorRT-LLM engine. Make sure you do not reuse the same S3 directory across multiple runs
s3_output_dir = "<s3_output_dir>"
# The name of the export
export_name = "<export_name>"
# The name of the SageMaker endpoint
endpoint_name = "<endpoint_name>"
# The instance type for export and inference. Now "ml.p4de.24xlarge" and "ml.p5.48xlarge" are supported
instance_type = "<instance_type>"
3단계: 병합된 가중치 만들기
HuggingFace의 PEFT를 사용해 Cohere Command를 파인튜닝하고 어댑터 가중치를 얻었다고 가정하면, 아래처럼 어댑터 가중치를 베이스 모델 가중치에 병합해 병합된 가중치(merged weights)를 얻을 수 있어요. 이미 병합된 가중치가 있다면 이 단계를 건너뛰어요.
PYTHON
import torch
from peft import PeftModel
from transformers import CohereForCausalLM
def load_and_merge_model(base_model_name_or_path: str, adapter_weights_dir: str):
"""
Load the base model and the model finetuned by PEFT, and merge the adapter weights to the base weights to get a model with merged weights
"""
base_model = CohereForCausalLM.from_pretrained(base_model_name_or_path)
peft_model = PeftModel.from_pretrained(base_model, adapter_weights_dir)
merged_model = peft_model.merge_and_unload()
return merged_model
def save_hf_model(output_dir: str, model, tokenizer=None, args=None):
"""
Save a HuggingFace model (and optionally tokenizer as well as additional args) to a local directory
"""
os.makedirs(output_dir, exist_ok=True)
model.save_pretrained(output_dir, state_dict=None, safe_serialization=True)
if tokenizer is not None:
tokenizer.save_pretrained(output_dir)
if args is not None:
torch.save(args, os.path.join(output_dir, "training_args.bin"))
# Get the merged model from adapter weights
merged_model = load_and_merge_model("CohereForAI/c4ai-command-r-08-2024", adapter_weights_dir)
# Save the merged weights to your local directory
save_hf_model(merged_weights_dir, merged_model)
4단계: 병합된 가중치를 S3에 업로드하기
PYTHON
sess = sage.Session()
merged_weights = S3Uploader.upload(merged_weights_dir, s3_checkpoint_dir, sagemaker_session=sess)
print("merged_weights", merged_weights)
5단계: 병합된 가중치를 TensorRT-LLM 추론 엔진으로 내보내기
Cohere 클라이언트를 생성하고 이를 사용해 병합된 가중치를 TensorRT-LLM 추론 엔진으로 내보내요. 내보낸 TensorRT-LLM 엔진은 파일 이름이 export_name과 동일한 {s3_output_dir}/{export_name}.tar.gz tar 파일로 S3에 저장돼요.
PYTHON
co = cohere.SagemakerClient(aws_region=region)
co.sagemaker_finetuning.export_finetune(
arn=arn,
name=export_name,
s3_checkpoint_dir=s3_checkpoint_dir,
s3_output_dir=s3_output_dir,
instance_type=instance_type,
role="ServiceRoleSagemaker",
)
6단계: 내보낸 엔진에서 추론용 엔드포인트 생성하기
Cohere 클라이언트는 추론용 엔드포인트를 생성하는 내장 메서드를 제공해요. 방금 내보낸 TensorRT-LLM 엔진에서 모델을 자동으로 배포해줘요.
PYTHON
co.sagemaker_finetuning.create_endpoint(
arn=arn,
endpoint_name=endpoint_name,
s3_models_dir=s3_output_dir,
recreate=True,
instance_type=instance_type,
role="ServiceRoleSagemaker",
)
7단계: 엔드포인트를 호출해 실시간 추론 수행하기
이제 방금 배포한 엔드포인트를 호출해 실시간 추론을 수행할 수 있어요.
PYTHON
# If the endpoint is already deployed, you can directly connect to it
co.sagemaker_finetuning.connect_to_endpoint(endpoint_name=endpoint_name)
message = "Classify the following text as either very negative, negative, neutral, positive or very positive: mr. deeds is , as comedy goes , very silly -- and in the best way."
result = co.sagemaker_finetuning.chat(message=message)
print(result)
평가 데이터셋을 사용해 파인튜닝한 모델을 평가할 수도 있어요. 다음은 ScienceQA 평가를 데이터로 수행하는 예시예요:
PYTHON
import json
from tqdm import tqdm
eval_data_path = "<path_to_scienceQA_eval.jsonl>"
total = 0
correct = 0
for line in tqdm(open(eval_data_path).readlines()):
total += 1
question_answer_json = json.loads(line)
question = question_answer_json["messages"][0]["content"]
answer = question_answer_json["messages"][1]["content"]
model_ans = co.sagemaker_finetuning.chat(message=question, temperature=0).text
if model_ans == answer:
correct += 1
print(f"Accuracy of finetuned model is %.3f" % (correct / total))
8단계: 엔드포인트 삭제하기 (선택 사항)
추론을 성공적으로 수행한 후에는 계속 비용이 청구되지 않도록 배포한 엔드포인트를 삭제할 수 있어요.
PYTHON
co.sagemaker_finetuning.delete_endpoint()
co.sagemaker_finetuning.close()
9단계: 등록 구독 취소하기 (선택 사항)
모델 패키지 구독을 취소하고 싶다면 다음 단계를 따라가요. 구독을 취소하기 전에 모델 패키지나 알고리즘에서 생성된 배포 가능한 모델이 없는지 확인해요.
Note: 이 정보는 모델과 연결된 컨테이너 이름을 보면 알 수 있어요.
방법은 다음과 같아요:
- Your Software subscriptions 페이지의 Machine Learning 탭으로 이동해요;
- 구독을 취소하려는 등록을 찾은 다음 Cancel Subscription을 선택해 구독을 취소해요.