챗봇 애플리케이션을 위한 GPT-NeoXT-Chat-Base-20B 기반 모델이 이제 Amazon SageMaker | 아마존 웹 서비스

챗봇 애플리케이션을 위한 GPT-NeoXT-Chat-Base-20B 기반 모델이 이제 Amazon SageMaker | 아마존 웹 서비스

오늘 우리는 Together Computer의 GPT-NeoXT-Chat-Base-20B 언어 기반 모델을 다음을 사용하는 고객이 사용할 수 있음을 발표하게 되어 기쁩니다. Amazon SageMaker 점프스타트. GPT-NeoXT-Chat-Base-20B는 대화형 봇을 구축하기 위한 오픈 소스 모델입니다. 이 모델을 쉽게 시험해보고 JumpStart와 함께 사용할 수 있습니다. JumpStart는 다음의 기계 학습(ML) 허브입니다. 아마존 세이지 메이커 ML을 빠르게 시작하는 데 도움이 되는 기본 제공 알고리즘 및 종단 간 솔루션 템플릿 외에도 기초 모델에 대한 액세스를 제공합니다.

이 게시물에서는 GPT-NeoXT-Chat-Base-20B 모델 내에서 모델을 호출하고 오픈챗킷 대화형 쉘. 이 데모는 애플리케이션 내에서 사용할 수 있는 오픈 소스 기반 모델 챗봇을 제공합니다.

JumpStart 모델은 딥 자바 라이브러리(DJL)를 딥 자바 라이브러리와 함께 사용하여 모델을 최적화하고 추론 대기 시간을 최소화하는 딥 자바 서빙을 사용합니다. JumpStart의 기본 구현은 다음과 유사한 구현을 따릅니다. 수첩. JumpStart 모델 허브 고객은 SageMaker SDK 외부에서 모델 스크립트를 유지하지 않고도 향상된 성능을 얻을 수 있습니다. JumpStart 모델은 또한 네트워크 격리를 가능하게 하는 엔드포인트로 향상된 보안 상태를 달성합니다.

SageMaker의 기초 모델

JumpStart는 SageMaker의 ML 개발 워크플로 내에서 사용할 수 있는 Hugging Face, PyTorch Hub 및 TensorFlow Hub를 포함하여 인기 있는 모델 허브의 다양한 모델에 대한 액세스를 제공합니다. 최근 ML의 발전으로 다음과 같은 새로운 종류의 모델이 등장했습니다. 기초 모델, 일반적으로 수십억 개의 매개변수에 대해 교육을 받고 텍스트 요약, 디지털 아트 생성 및 언어 번역과 같은 광범위한 사용 사례 범주에 적용할 수 있습니다. 이러한 모델은 교육하는 데 비용이 많이 들기 때문에 고객은 이러한 모델을 직접 교육하기보다는 기존의 사전 교육된 기초 모델을 사용하고 필요에 따라 미세 조정하기를 원합니다. SageMaker는 SageMaker 콘솔에서 선택할 수 있는 선별된 모델 목록을 제공합니다.

이제 JumpStart 내에서 다양한 모델 공급자의 기초 모델을 찾을 수 있으므로 기초 모델을 빠르게 시작할 수 있습니다. 다양한 업무나 모델 제공자를 기반으로 기반 모델을 찾을 수 있으며, 모델 특성 및 사용 조건을 쉽게 검토할 수 있습니다. 테스트 UI 위젯을 사용하여 이러한 모델을 시험해 볼 수도 있습니다. 기반 모델을 규모에 맞게 사용하려는 경우 모델 공급자의 사전 구축된 노트북을 사용하여 SageMaker를 종료하지 않고도 쉽게 수행할 수 있습니다. 모델이 AWS에서 호스팅되고 배포되기 때문에 규모에 따라 모델을 평가하거나 사용하는 데 데이터를 사용하는 경우 데이터가 제XNUMX자와 절대 공유되지 않으므로 안심할 수 있습니다.

GPT-NeoXT-Chat-Base-20B 기반 모델

투게더 컴퓨터 20억 매개변수 언어 모델인 GPT-NeoXT-Chat-Base-20B를 개발했습니다. 이 언어 모델은 ElutherAI의 GPT-NeoX 모델에서 40천만 개 이상의 명령으로 미세 조정되어 대화 스타일 상호 작용에 중점을 둡니다. 또한 이 모델은 질문 답변, 분류, 추출 및 요약과 같은 여러 작업에서 조정됩니다. 이 모델은 LAION 및 Ontocord와 공동으로 만든 OIG-43M 데이터 세트를 기반으로 합니다.

앞서 언급한 미세 조정 외에도 GPT-NeoXT-Chat-Base-20B-v0.16은 소량의 피드백 데이터를 통해 추가 미세 조정을 거쳤습니다. 이를 통해 모델은 대화에서 인간의 선호도에 더 잘 적응할 수 있습니다. GPT-NeoXT-Chat-Base-20B는 챗봇 애플리케이션에서 사용하도록 설계되었으며 의도된 범위를 벗어난 다른 사용 사례에서는 제대로 작동하지 않을 수 있습니다. Ontocord와 LAION은 공동으로 OpenChatKit을 출시했습니다. OpenChatKit은 비슷한 기능 세트를 갖춘 ChatGPT의 오픈 소스 대안입니다. OpenChatKit은 Apache-2.0 라이선스로 출시되어 소스 코드, 모델 가중치 및 교육 데이터 세트에 대한 완전한 액세스 권한을 부여합니다. OpenChatKit이 즉시 사용할 수 있는 몇 가지 작업이 있습니다. 여기에는 요약 작업, 구조화되지 않은 문서에서 구조화된 정보를 추출할 수 있는 추출 작업, 문장이나 단락을 다른 범주로 분류하는 분류 작업이 포함됩니다.

JumpStart에서 GPT-NeoXT-Chat-Base-20B 모델을 사용하는 방법을 살펴보겠습니다.

솔루션 개요

SageMaker에서 GPT-NeoXT-Chat-Base-20B의 배포를 보여주는 코드와 다음에서 명령 셸을 사용하여 배포된 모델을 대화 방식으로 사용하는 방법의 예를 찾을 수 있습니다. GitHub 노트북.

다음 섹션에서는 각 단계를 자세히 확장하여 모델을 배포한 다음 이를 사용하여 다양한 작업을 해결합니다.

  1. 전제 조건을 설정합니다.
  2. 선행 학습된 모델을 선택합니다.
  3. 아티팩트를 검색하고 엔드포인트를 배포합니다.
  4. 엔드포인트를 쿼리하고 응답을 구문 분석합니다.
  5. OpenChatKit 셸을 사용하여 배포된 엔드포인트와 상호 작용합니다.

전제 조건 설정

이 노트북은 다음의 ml.t3.medium 인스턴스에서 테스트되었습니다. 아마존 세이지 메이커 스튜디오 Python 3(Data Science) 커널과 conda_python3 커널이 있는 SageMaker 노트북 인스턴스.

노트북을 실행하기 전에 다음 명령을 사용하여 설정에 필요한 몇 가지 초기 단계를 완료하십시오.

%pip install --upgrade sagemaker –quiet

선행 학습된 모델 선택

평소처럼 Boto3를 사용하여 SageMaker 세션을 설정한 다음 배포할 모델 ID를 선택합니다.

model_id, model_version = "huggingface-textgeneration2-gpt-neoxt-chat-base-20b-fp16", "*"

아티팩트 검색 및 엔드포인트 배포

SageMaker를 사용하면 먼저 새 데이터 세트에서 미세 조정하지 않고도 사전 훈련된 모델에서 추론을 수행할 수 있습니다. 우리는 instance_type, image_urimodel_uri 사전 학습된 모델의 경우. 사전 훈련된 모델을 호스팅하기 위해 다음 인스턴스를 생성합니다. 세이지메이커.모델.모델 배포합니다. 다음 코드는 추론 끝점에 ml.g5.24xlarge를 사용합니다. 배포 방법은 몇 분 정도 걸릴 수 있습니다.

endpoint_name = name_from_base(f"jumpstart-example-{model_id}") # Retrieve the inference instance type for the specified model.
instance_type = instance_types.retrieve_default( model_id=model_id, model_version=model_version, scope="inference"
) # Retrieve the inference docker container uri.
image_uri = image_uris.retrieve( region=None, framework=None, image_scope="inference", model_id=model_id, model_version=model_version, instance_type=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. The inference script is prepacked with the model artifact.
model = Model( image_uri=image_uri, model_data=model_uri, role=aws_role, predictor_cls=Predictor, name=endpoint_name,
) # Set the serializer/deserializer used to run inference through the sagemaker API.
serializer = JSONSerializer()
deserializer = JSONDeserializer() # Deploy the Model.
predictor = model.deploy( initial_instance_count=1, instance_type=instance_type, predictor_cls=Predictor, endpoint_name=endpoint_name, serializer=serializer, deserializer=deserializer
)

엔드포인트 쿼리 및 응답 구문 분석

다음으로 하이퍼파라미터의 하위 집합을 사용하여 엔드포인트를 호출하는 방법의 예를 보여줍니다.

payload = { "text_inputs": "<human>: Tell me the steps to make a pizzan<bot>:", "max_length": 500, "max_time": 50, "top_k": 50, "top_p": 0.95, "do_sample": True, "stopping_criteria": ["<human>"],
}
response = predictor.predict(payload)
print(response[0][0]["generated_text"])

다음은 우리가 받은 응답입니다.

<human>: Tell me the steps to make a pizza
<bot>: 1. Choose your desired crust, such as thin-crust or deep-dish. 2. Preheat the oven to the desired temperature. 3. Spread sauce, such as tomato or garlic, over the crust. 4. Add your desired topping, such as pepperoni, mushrooms, or olives. 5. Add your favorite cheese, such as mozzarella, Parmesan, or Asiago. 6. Bake the pizza according to the recipe instructions. 7. Allow the pizza to cool slightly before slicing and serving.
<human>:

여기에서 페이로드 인수를 제공했습니다. "stopping_criteria": ["<human>"], 단어 시퀀스의 생성으로 모델 응답이 종료되었습니다. <human>. JumpStart 모델 스크립트는 문자열 목록을 원하는 중지 단어로 받아들이고 이 목록을 유효한 stops_criteria 키워드 인수 변환기가 API를 생성하고 출력 시퀀스에 지정된 중지 단어가 포함되면 텍스트 생성을 중지합니다. 이는 두 가지 이유에서 유용합니다. 첫째, 엔드포인트가 불용어 외에 원하지 않는 텍스트를 계속 생성하지 않기 때문에 추론 시간이 단축되고, 둘째, 다른 중지 기준이 충족될 때까지 OpenChatKit 모델이 추가 인간 및 봇 응답을 환각하지 않도록 방지합니다. .

OpenChatKit 셸을 사용하여 배포된 엔드포인트와 상호 작용

OpenChatKit은 챗봇과 상호 작용할 수 있는 명령줄 셸을 제공합니다. 이 단계에서는 배포된 엔드포인트와 상호 작용할 수 있는 이 셸 버전을 생성합니다. 배포된 SageMaker 엔드포인트와 상호 작용할 수 있는 이 OpenChatKit 리포지토리에서 추론 스크립트의 기본 단순화를 제공합니다.

여기에는 두 가지 주요 구성 요소가 있습니다.

  • 쉘 인터프리터(JumpStartOpenChatKitShell) 모델 엔드포인트의 반복적 추론 호출을 허용합니다.
  • 대화 객체(Conversation) 이전 인간/챗봇 상호 작용을 대화형 셸 내에 로컬로 저장하고 미래의 추론 컨텍스트를 위해 과거 대화의 형식을 적절하게 지정합니다.

XNUMXD덴탈의 Conversation 개체는 OpenChatKit 리포지토리에서 있는 그대로 가져옵니다. 다음 코드는 끝점과 상호 작용할 수 있는 사용자 지정 셸 인터프리터를 만듭니다. 이것은 OpenChatKit 구현의 단순화된 버전입니다. OpenChatKit 리포지토리를 탐색하여 이 컨텍스트 내에서 토큰 스트리밍, 중재 모델 및 검색 증강 생성과 같은 보다 심층적인 기능을 사용할 수 있는 방법을 확인하는 것이 좋습니다. 이 노트북의 컨텍스트는 JumpStart 끝점이 있는 최소한의 실행 가능한 챗봇을 시연하는 데 중점을 둡니다. 여기에서 필요에 따라 복잡성을 추가할 수 있습니다.

쇼케이스를 위한 짧은 데모 JumpStartOpenChatKitShell 다음 비디오에 나와 있습니다.

다음 스니펫은 코드 작동 방식을 보여줍니다.

class JumpStartOpenChatKitShell(cmd.Cmd): intro = ( "Welcome to the OpenChatKit chatbot shell, modified to use a SageMaker JumpStart endpoint! Type /help or /? to " "list commands. For example, type /quit to exit shell.n" ) prompt = ">>> " human_id = "<human>" bot_id = "<bot>" def __init__(self, predictor: Predictor, cmd_queue: Optional[List[str]] = None, **kwargs): super().__init__() self.predictor = predictor self.payload_kwargs = kwargs self.payload_kwargs["stopping_criteria"] = [self.human_id] if cmd_queue is not None: self.cmdqueue = cmd_queue def preloop(self): self.conversation = Conversation(self.human_id, self.bot_id) def precmd(self, line): command = line[1:] if line.startswith('/') else 'say ' + line return command def do_say(self, arg): self.conversation.push_human_turn(arg) prompt = self.conversation.get_raw_prompt() payload = {"text_inputs": prompt, **self.payload_kwargs} response = self.predictor.predict(payload) output = response[0][0]["generated_text"][len(prompt):] self.conversation.push_model_response(output) print(self.conversation.get_last_turn()) def do_reset(self, arg): self.conversation = Conversation(self.human_id, self.bot_id) def do_hyperparameters(self, arg): print(f"Hyperparameters: {self.payload_kwargs}n") def do_quit(self, arg): return True

이제 이 셸을 명령 루프로 실행할 수 있습니다. 이것은 반복적으로 프롬프트를 발행하고, 입력을 수락하고, 입력 명령을 구문 분석하고, 조치를 발송합니다. 결과 쉘이 무한 루프에서 활용될 수 있기 때문에 이 노트북은 기본 명령 대기열(cmdqueue) 대기 중인 입력 라인 목록으로. 마지막 입력이 명령이기 때문에 /quit, 대기열이 소진되면 쉘이 종료됩니다. 이 챗봇과 동적으로 상호 작용하려면 cmdqueue.

cmd_queue = [ "Hello!",
]
JumpStartOpenChatKitShell( endpoint_name=endpoint_name, cmd_queue=cmd_queue, max_new_tokens=128, do_sample=True, temperature=0.6, top_k=40,
).cmdloop()

예 1: 대화 컨텍스트가 유지됨

다음 프롬프트는 챗봇이 후속 질문에 답하기 위해 대화의 맥락을 유지할 수 있음을 보여줍니다.

Welcome to the OpenChatKit chatbot shell, modified to use a SageMaker JumpStart endpoint! Type /help or /? to list commands. For example, type /quit to exit shell. <<< Hello! How may I help you today? >>> What is the capital of US? <<< The capital of US is Washington, D.C. >>> How far it is from PA ? <<< It is approximately 1100 miles.

예 2: 감정 분류

다음 예에서 챗봇은 문장의 감정을 식별하여 분류 작업을 수행했습니다. 보시다시피 챗봇은 긍정적 감정과 부정적 감정을 성공적으로 분류할 수 있었습니다.

Welcome to the OpenChatKit chatbot shell, modified to use a SageMaker JumpStart endpoint! Type /help or /? to list commands. For example, type /quit to exit shell. <<< Hello! How may I help you today? >>> What is the sentiment of this sentence "The weather is good and I am going to play outside, it is sunny and warm" <<< POSITIVE >>> What is the sentiment of this sentence " The news this morning was tragic and it created lot of fear and concerns in city" <<< NEGATIVE

예 3: 요약 작업

다음으로 챗봇 셸을 사용하여 요약 작업을 시도했습니다. 다음 예는 긴 텍스트가 아마존 이해 한 문장으로 요약되었고 챗봇은 텍스트에 대한 후속 질문에 답할 수 있었습니다.

Welcome to the OpenChatKit chatbot shell, modified to use a SageMaker JumpStart endpoint! Type /help or /? to list commands. For example, type /quit to exit shell. <<< Hello! How may I help you today? >>> Write a short summary for this text: 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. nYou 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. nAll 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. nAmazon 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. <<< Amazon Comprehend is a natural language processing (NLP) service that uses deep learning and other advanced AI techniques to extract insights from unstructured text. >>> What kind of files does custom entity recognition accept as inputs? <<< Image files, PDF files, and Word files

예 4: 구조화되지 않은 텍스트에서 구조화된 정보 추출

다음 예에서는 자유 형식 언어로 제공되는 정보를 사용하여 프로젝트 계획을 생성하기 위해 챗봇을 사용하여 헤더, 행 및 열이 있는 마크다운 테이블을 생성했습니다.

Welcome to the OpenChatKit chatbot shell, modified to use a SageMaker JumpStart endpoint! Type /help or /? to list commands. For example, type /quit to exit shell. <<< Hello! How may I help you today? >>> Generate a table summarizing the options outlined in this email. Team, we need to plan a project. The first task is for creating a web app and will take 3 developers, 2 testers with duration of 3 weeks. This is priority 1 The second task is for refactoring a web app and will take 2 developers, 5 testers with duration of 4 weeks. This is priority 2 A markdown table with 2 rows and six columns: (1) Task ID , (2) Task Description, (3) Developers, (4) Testers, (5) Duration, (6) Priority <<< | Task ID | Task Description | Developers | Testers | Duration | Priority |
| --------- | --------- | --------- | --------- | --------- | --------- |
| 1 | Create a web app | 3 | 2 | 3 weeks | 1 |
| 2 | Refactor a web app | 2 | 5 | 4 weeks | 2 |

예 5: 챗봇에 대한 입력으로 사용되는 명령

다음과 같은 명령으로 입력을 제공할 수도 있습니다. /hyperparameters 하이퍼파라미터 값을 확인하고 /quit 명령 셸을 종료하려면:

>>> /hyperparameters <<< Hyperparameters: {'max_new_tokens': 128, 'do_sample': True, 'temperature': 0.6, 'top_k': 40, 'stopping_criteria': ['<human>']} >>> /quit

이러한 예는 OpenChatKit이 뛰어난 작업 중 일부를 보여줍니다. 다양한 프롬프트를 시도하고 사용 사례에 가장 적합한 것이 무엇인지 확인하는 것이 좋습니다.

정리

엔드포인트를 테스트한 후 비용이 발생하지 않도록 SageMaker 추론 엔드포인트와 모델을 삭제해야 합니다.

결론

이 게시물에서는 SageMaker를 사용하여 GPT-NeoXT-Chat-Base-20B 모델을 테스트 및 사용하고 흥미로운 챗봇 애플리케이션을 구축하는 방법을 보여주었습니다. 오늘 SageMaker에서 기초 모델을 시험해보고 피드백을 알려주세요!

이 지침은 정보 제공의 목적으로만 제공됩니다. 귀하는 여전히 독립적인 평가를 수행해야 하며 귀하의 특정 품질 관리 관행 및 표준, 귀하와 귀하의 콘텐츠 및 이 지침에서 참조하는 타사 모델. AWS는 이 지침에 언급된 제XNUMX자 모델에 대한 통제권이나 권한이 없으며 제XNUMX자 모델이 안전하고 바이러스가 없으며 운영 가능하거나 프로덕션 환경 및 표준과 호환된다는 진술이나 보증을 하지 않습니다. AWS는 이 지침의 정보가 특정 결과를 초래할 것이라고 진술, 보증 또는 보장하지 않습니다.


저자 소개

이제 Amazon SageMaker | 챗봇 애플리케이션을 위한 GPT-NeoXT-Chat-Base-20B 기반 모델을 사용할 수 있습니다. Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.라크나 차다 AWS Strategic Accounts의 수석 솔루션 아키텍트 AI/ML입니다. Rachna는 AI의 윤리적이고 책임 있는 사용이 미래의 사회를 개선하고 경제적, 사회적 번영을 가져올 수 있다고 믿는 낙관론자입니다. 여가 시간에 Rachna는 가족과 함께 시간을 보내고, 하이킹을 하고, 음악을 듣는 것을 좋아합니다.

이제 Amazon SageMaker | 챗봇 애플리케이션을 위한 GPT-NeoXT-Chat-Base-20B 기반 모델을 사용할 수 있습니다. Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.카일 울리히 박사 는 응용 과학자입니다. Amazon SageMaker 내장 알고리즘 팀. 그의 연구 관심사는 확장 가능한 기계 학습 알고리즘, 컴퓨터 비전, 시계열, 베이지안 비모수 및 가우시안 프로세스를 포함합니다. Duke University에서 박사 학위를 받았으며 NeurIPS, Cell 및 Neuron에 논문을 발표했습니다.

이제 Amazon SageMaker | 챗봇 애플리케이션을 위한 GPT-NeoXT-Chat-Base-20B 기반 모델을 사용할 수 있습니다. Amazon Web Services PlatoBlockchain 데이터 인텔리전스. 수직 검색. 일체 포함.Ashish Khetan 박사 Amazon SageMaker 내장 알고리즘을 사용하는 수석 응용 과학자이며 기계 학습 알고리즘 개발을 돕습니다. 그는 University of Illinois Urbana-Champaign에서 박사 학위를 받았습니다. 그는 기계 학습 및 통계적 추론 분야에서 활동적인 연구원이며 NeurIPS, ICML, ICLR, JMLR, ACL 및 EMNLP 컨퍼런스에서 많은 논문을 발표했습니다.

타임 스탬프 :

더보기 AWS 기계 학습