자체 스크립트를 가져오는 Hugging Face Amazon SageMaker 컨테이너를 사용하여 요약기 모델 미세 조정 및 배포

NLP 영역에서 최근 많은 발전이 있었습니다. 사전 훈련된 모델과 완전 관리형 NLP 서비스는 NLP에 대한 액세스 및 채택을 민주화했습니다. 아마존 이해 사전 ML 경험 없이도 데이터에서 통찰력을 추출하기 위해 사용자 지정 엔터티 인식, 주제 모델링, 감정 분석 등과 같은 NLP 작업을 수행할 수 있는 완전 관리형 서비스입니다.

작년에 AWS는 다음과 같이 발표했습니다. 파트너십포옹하는 얼굴 NLP(자연어 처리) 모델을 더 빠르게 생산할 수 있도록 지원합니다. Hugging Face는 NLP에 중점을 둔 오픈 소스 AI 커뮤니티입니다. 그들의 Python 기반 라이브러리(변압기)은 BERT, RoBERTa 및 GPT와 같은 인기 있는 최신 Transformer 아키텍처를 쉽게 사용할 수 있는 도구를 제공합니다. 이러한 모델을 텍스트 분류, 정보 추출 및 질문 답변과 같은 다양한 NLP 작업에 적용할 수 있습니다. 다른 사람.

아마존 세이지 메이커 는 개발자와 데이터 과학자가 기계 학습(ML) 모델을 빠르게 구축, 교육 및 배포할 수 있는 기능을 제공하는 완전 관리형 서비스입니다. SageMaker는 ML 프로세스의 각 단계에서 무거운 작업을 제거하여 고품질 모델을 더 쉽게 개발할 수 있도록 합니다. SageMaker Python SDK는 다양한 ML 및 딥 러닝 프레임워크를 사용하여 SageMaker에서 모델을 교육하고 배포하기 위한 오픈 소스 API 및 컨테이너를 제공합니다.

SageMaker와 Hugging Face 통합을 통해 자신의 도메인별 사용 사례에 따라 Hugging Face 모델을 대규모로 구축할 수 있습니다.

이 게시물에서는 SageMaker에서 맞춤형 포옹 얼굴 텍스트 요약기를 구축하고 배포하는 방법의 예를 안내합니다. 이를 위해 Pegasus[1]를 사용합니다. 이 모델은 추상적인 텍스트 요약을 위해 맞춤화된 목표에 대해 특별히 사전 훈련된 최초의 Transformer 기반 모델입니다. BERT는 문장에서 임의의 단어를 마스킹하도록 사전 훈련됩니다. 대조적으로, Pegasus의 사전 훈련 동안에는 입력 문서에서 문장이 마스킹됩니다. 그런 다음 모델은 마스크되지 않은 모든 문장을 컨텍스트로 사용하여 누락된 문장을 단일 출력 시퀀스로 생성하여 결과적으로 문서의 요약을 생성합니다.

HuggingFace 라이브러리의 유연성 덕분에 이 게시물에 표시된 코드를 t5, BART 등과 같은 다른 유형의 변압기 모델에 쉽게 적용할 수 있습니다.

자신의 데이터 세트를 로드하여 포옹 얼굴 모델을 미세 조정합니다.

CSV 파일에서 사용자 정의 데이터 세트를 로드하려면 다음을 사용합니다. load_dataset Transformers 패키지의 메소드. 다음을 사용하여 로드된 데이터 세트에 토큰화를 적용할 수 있습니다. datasets.Dataset.map 함수. 그만큼 map 함수는 로드된 데이터 세트를 반복하고 각 예제에 토큰화 함수를 적용합니다. 토큰화된 데이터 세트는 모델을 미세 조정하기 위해 트레이너에게 전달할 수 있습니다. 다음 코드를 참조하십시오.

# Python
def tokenize(batch):
    tokenized_input = tokenizer(batch[args.input_column], padding='max_length', truncation=True, max_length=args.max_source)
    tokenized_target = tokenizer(batch[args.target_column], padding='max_length', truncation=True, max_length=args.max_target)
    tokenized_input['target'] = tokenized_target['input_ids']

    return tokenized_input
    

def load_and_tokenize_dataset(data_dir):
    for file in os.listdir(data_dir):
        dataset = load_dataset("csv", data_files=os.path.join(data_dir, file), split='train')
    tokenized_dataset = dataset.map(lambda batch: tokenize(batch), batched=True, batch_size=512)
    tokenized_dataset.set_format('numpy', columns=['input_ids', 'attention_mask', 'labels'])
    
    return tokenized_dataset

Hugging Face SageMaker 추정기를 위한 훈련 스크립트 빌드

포스트에서 설명했듯이 AWS와 Hugging Face가 협력하여 자연어 처리 모델 채택을 단순화하고 가속화, SageMaker에서 포옹 얼굴 모델을 훈련하는 것이 그 어느 때보다 쉬워졌습니다. 우리는 Hugging Face estimator를 사용하여 그렇게 할 수 있습니다. 세이지메이커 SDK.

다음 코드 스니펫은 데이터세트에서 Pegasus를 미세 조정합니다. 당신은 또한 많은 것을 찾을 수 있습니다 샘플 노트북 변환기 GitHub 리포지토리에서 직접 사용할 수 있는 다양한 유형의 모델을 미세 조정하는 방법을 안내합니다. 분산 교육을 활성화하려면 다음을 사용할 수 있습니다. 데이터 병렬화 라이브러리 HuggingFace Trainer API에 내장된 SageMaker에서 데이터 병렬 처리를 활성화하려면 다음을 정의해야 합니다. distribution 포옹 얼굴 추정기의 매개변수입니다.

# Python
from sagemaker.huggingface import HuggingFace
# configuration for running training on smdistributed Data Parallel
distribution = {'smdistributed':{'dataparallel':{ 'enabled': True }}}
huggingface_estimator = HuggingFace(entry_point='train.py',
                                    source_dir='code',
                                    base_job_name='huggingface-pegasus',
                                    instance_type= 'ml.g4dn.16xlarge',
                                    instance_count=1,
                                    transformers_version='4.6',
                                    pytorch_version='1.7',
                                    py_version='py36',
                                    output_path=output_path,
                                    role=role,
                                    hyperparameters = {
                                        'model_name': 'google/pegasus-xsum',
                                        'epoch': 10,
                                        'per_device_train_batch_size': 2
                                    },
                                    distribution=distribution)
huggingface_estimator.fit({'train': training_input_path, 'validation': validation_input_path, 'test': test_input_path})

구성할 수 있는 최대 훈련 배치 크기는 사용된 인스턴스의 모델 크기와 GPU 메모리에 따라 다릅니다. SageMaker 분산 교육이 활성화된 경우 총 배치 크기는 각 장치/GPU에 분산된 모든 배치의 합계입니다. ml.g4dn.xlarge 인스턴스 대신 분산 훈련과 함께 ml.g16dn.4xlarge를 사용하는 경우 ml.g8dn.xlarge 인스턴스(4 GPU)보다 1배(XNUMX GPU) 많은 메모리가 있습니다. 장치당 배치 크기는 동일하게 유지되지만 XNUMX개의 장치가 병렬로 훈련됩니다.

SageMaker에서 평소와 같이 train.py 스크립트 모드와 함께 사용하고 훈련을 위해 하이퍼파라미터를 전달하는 스크립트. Pegasus에 대한 다음 코드 스니펫은 모델을 로드하고 Transformers를 사용하여 교육합니다. Trainer 수업:

# Python
from transformers import (
    AutoModelForSeq2SeqLM,
    AutoTokenizer,
    Seq2SeqTrainer,
    Seq2seqTrainingArguments
)

model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to(device)
    
training_args = Seq2seqTrainingArguments(
    output_dir=args.model_dir,
    num_train_epochs=args.epoch,
    per_device_train_batch_size=args.train_batch_size,
    per_device_eval_batch_size=args.eval_batch_size,
    warmup_steps=args.warmup_steps,
    weight_decay=args.weight_decay,
    logging_dir=f"{args.output_data_dir}/logs",
    logging_strategy='epoch',
    evaluation_strategy='epoch',
    saving_strategy='epoch',
    adafactor=True,
    do_train=True,
    do_eval=True,
    do_predict=True,
    save_total_limit = 3,
    load_best_model_at_end=True,
    metric_for_best_model='eval_loss'
    # With the goal to deploy the best checkpoint to production
    # it is important to set load_best_model_at_end=True,
    # this makes sure that the last model is saved at the root
    # of the model_dir” directory
)
    
trainer = Seq2SeqTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset['train'],
    eval_dataset=dataset['validation']
)

trainer.train()
trainer.save_model()

# Get rid of unused checkpoints inside the container to limit the model.tar.gz size
os.system(f"rm -rf {args.model_dir}/checkpoint-*/")

전체 코드는 GitHub의.

훈련된 포옹 얼굴 모델을 SageMaker에 배포

Hugging Face의 친구들은 다음 덕분에 SageMaker for Transformers 모델에 대한 추론을 그 어느 때보다 간단하게 만들었습니다. SageMaker 포옹 얼굴 추론 도구 키트. 환경 변수를 설정하기만 하면 이전에 훈련된 모델을 직접 배포할 수 있습니다. "HF_TASK":"summarization" (지침은 참조 페가수스 모델), 고르는 배포, 그리고 선택 아마존 세이지 메이커, 추론 스크립트를 작성할 필요가 없습니다.

그러나 예를 들어 다양한 텍스트 생성 매개변수 목록을 기반으로 몇 가지 요약 제안을 생성하는 것과 같이 예측을 생성하거나 사후 처리하는 특정 방법이 필요한 경우 고유한 추론 스크립트를 작성하는 것이 유용하고 비교적 간단할 수 있습니다.

# Python
# inference.py script

import os
import json
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def model_fn(model_dir):
    # Create the model and tokenizer and load weights
    # from the previous training Job, passed here through "model_dir"
    # that is reflected in HuggingFaceModel "model_data"
    tokenizer = AutoTokenizer.from_pretrained(model_dir)
    model = AutoModelForSeq2SeqLM.from_pretrained(model_dir).to(device).eval()
    
    model_dict = {'model':model, 'tokenizer':tokenizer}
    
    return model_dict
        

def predict_fn(input_data, model_dict):
    # Return predictions/generated summaries
    # using the loaded model and tokenizer on input_data
    text = input_data.pop('inputs')
    parameters_list = input_data.pop('parameters_list', None)
    
    tokenizer = model_dict['tokenizer']
    model = model_dict['model']

    # Parameters may or may not be passed    
    input_ids = tokenizer(text, truncation=True, padding='longest', return_tensors="pt").input_ids.to(device)
    
    if parameters_list:
        predictions = []
        for parameters in parameters_list:
            output = model.generate(input_ids, **parameters)
            predictions.append(tokenizer.batch_decode(output, skip_special_tokens=True))
    else:
        output = model.generate(input_ids)
        predictions = tokenizer.batch_decode(output, skip_special_tokens=True)
    
    return predictions
    
    
def input_fn(request_body, request_content_type):
    # Transform the input request to a dictionary
    request = json.loads(request_body)
    return request

앞의 코드에서 볼 수 있듯이 SageMaker의 HuggingFace에 대한 이러한 추론 스크립트에는 다음 템플릿 기능만 필요합니다.

  • model_fn () – 교육 작업 종료 시 내부에 저장한 내용을 읽습니다. SM_MODEL_DIR, 또는 tar.gz 파일로 저장된 기존 모델 가중치 디렉토리에서 아마존 단순 스토리지 서비스 (아마존 S3). 훈련된 모델 및 관련 토크나이저를 로드하는 데 사용됩니다.
  • input_fn () – 엔드포인트에 대한 요청에서 수신된 데이터를 형식화합니다.
  • predict_fn () – 의 출력을 호출합니다. model_fn() (모델 및 토크나이저) 출력에 대한 추론 실행 input_fn() (포맷된 데이터).

선택적으로 다음을 생성할 수 있습니다. output_fn() 의 출력을 사용하여 추론 형식화를 위한 함수 predict_fn(), 이 게시물에서 시연하지 않았습니다.

그런 다음 연결된 추론 스크립트와 함께 훈련된 Hugging Face 모델을 다음을 사용하여 SageMaker에 배포할 수 있습니다. 포옹 얼굴 SageMaker 모델 수업:

# Python
from sagemaker.huggingface import HuggingFaceModel

model = HuggingFaceModel(model_data=huggingface_estimator.model_data,
                     role=role,
                     framework_version='1.7',
                     py_version='py36',
                     entry_point='inference.py',
                     source_dir='code')
                     
predictor = model.deploy(initial_instance_count=1,
                         instance_type='ml.g4dn.xlarge'
                         )

배포된 모델 테스트

이 데모에서 우리는 모델을 학습시켰습니다. 여성 전자상거래 의류 리뷰 데이터세트, 여기에는 의류 기사(입력 텍스트로 간주) 및 관련 제목(요약으로 간주)에 대한 리뷰가 포함됩니다. 제목이 누락된 기사를 제거하면 데이터세트에 19,675개의 리뷰가 포함됩니다. ml.p70xlarge 인스턴스에서 3.5개 에포크 동안 해당 기사의 3.16%를 포함하는 훈련 세트에서 Pegasus 모델을 미세 조정하는 데 약 XNUMX시간이 걸렸습니다.

그런 다음 모델을 배포하고 테스트 세트의 몇 가지 예제 데이터로 테스트할 수 있습니다. 다음은 스웨터를 설명하는 리뷰의 예입니다.

# Python
Review Text
"I ordered this sweater in green in petite large. The color and knit is beautiful and the shoulders and body fit comfortably; however, the sleeves were very long for a petite. I roll them, and it looks okay but would have rather had a normal petite length sleeve."

Original Title
"Long sleeves"

Rating
3

SageMaker 엔드포인트에서 호스팅되는 사용자 정의 추론 스크립트 덕분에 다양한 텍스트 생성 매개변수를 사용하여 이 검토에 대한 여러 요약을 생성할 수 있습니다. 예를 들어 끝점에 다른 길이 페널티를 지정하는 매우 짧거나 중간 정도로 긴 요약 범위를 생성하도록 요청할 수 있습니다(길이 페널티가 작을수록 생성된 요약은 더 짧음). 다음은 몇 가지 매개변수 입력 예와 후속 머신 생성 요약입니다.

# Python
inputs = {
    "inputs":[
"I ordered this sweater in green in petite large. The color and knit is   beautiful and the shoulders and body fit comfortably; however, the sleeves were very long for a petite. I roll them, and it looks okay but would have rather had a normal petite length sleeve."
    ],

    "parameters_list":[
        {
            "length_penalty":2
        },
	{
            "length_penalty":1
        },
	{
            "length_penalty":0.6
        },
        {
            "length_penalty":0.4
        }
    ]

result = predictor.predict(inputs)
print(result)

[
    ["Beautiful color and knit but sleeves are very long for a petite"],
    ["Beautiful sweater, but sleeves are too long for a petite"],
    ["Cute, but sleeves are long"],
    ["Very long sleeves"]
]

어떤 요약을 선호합니까? 처음 생성된 제목은 리뷰에 대한 모든 중요한 사실을 1분의 10의 단어로 캡처합니다. 대조적으로, 마지막은 스웨터의 가장 중요한 특징에 초점을 맞추기 위해 세 단어(원래 리뷰 길이의 XNUMX/XNUMX 미만)만을 사용합니다.

결론

사용자 정의 데이터 세트에서 텍스트 요약기를 미세 조정하고 SageMaker에서 프로덕션에 배포할 수 있는 이 간단한 예제는 GitHub의. 추가 샘플 노트북 SageMaker에서 Hugging Face 모델을 훈련하고 배포하는 것도 가능합니다.

언제나 그렇듯이 AWS는 피드백을 환영합니다. 의견이나 질문을 제출하십시오.

참고자료

[1] PEGASUS: 추상적인 요약을 위한 추출된 공백 문장을 사용한 사전 훈련


저자 소개

자체 스크립트 PlatoBlockchain Data Intelligence를 가져오는 Hugging Face Amazon SageMaker 컨테이너를 사용하여 요약 모델을 미세 조정하고 배포합니다. 수직 검색. 일체 포함. 빅토르 말레세비치 자연어 처리 및 MLOps에 대한 열정이 있는 AWS Professional Services의 기계 학습 엔지니어입니다. 그는 고객과 협력하여 도전적인 딥 러닝 모델을 개발하고 AWS의 프로덕션에 적용합니다. 여가 시간에는 레드 와인 한 잔과 치즈를 친구들과 나누는 것을 즐깁니다.

자체 스크립트 PlatoBlockchain Data Intelligence를 가져오는 Hugging Face Amazon SageMaker 컨테이너를 사용하여 요약 모델을 미세 조정하고 배포합니다. 수직 검색. 일체 포함.암나 나지미 AWS Professional Services의 데이터 과학자입니다. 그녀는 고객이 빅 데이터 및 인공 지능 기술로 혁신하여 데이터에서 비즈니스 가치와 통찰력을 활용하도록 돕는 데 열정을 쏟고 있습니다. 여가 시간에는 정원 가꾸기와 새로운 곳으로 여행하는 것을 즐깁니다.

타임 스탬프 :

더보기 AWS 기계 학습