반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Guide - Speech to text

2023. 3. 5. 21:39 | Posted by 솔웅


반응형

https://platform.openai.com/docs/guides/speech-to-text

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Speech to text

Learn how to turn audio into text

 

오디오를 어떻게 텍스트로 바꾸는지 배워 봅시다.

 

Introduction

The speech to text API provides two endpoints, transcriptions and translations, based on our state-of-the-art open source large-v2 Whisper model. They can be used to:

 

음성을 텍스트로 바꿔 주는 API는 두개의 endpoint를 제공합니다. 필사와 번역입니다. 이것은 최신 오픈 소스인 large-v2 Whisper 모델을 기반으로 합니다.

  • Transcribe audio into whatever language the audio is in.
  • 어떤 언어의 오디오든 그것을 글로 옮겨 씁니다.
  • Translate and transcribe the audio into english.
  • 오디오를 영어로 번역해서 옮겨 씁니다.

File uploads are currently limited to 25 MB and the following input file types are supported: mp3, mp4, mpeg, mpga, m4a, wav, and webm.

 

오디오 파일 업로드는 현재까지 25MB로 제한 됩니다. 그리고 다음과 같은 파일 형식을 따라야 합니다.

mp3, mp4, mpeg, mpga, m4a, wav, and webm.

 

Quickstart

Transcriptions

The transcriptions API takes as input the audio file you want to transcribe and the desired output file format for the transcription of the audio. We currently support multiple input and output file formats.

 

Transcriptions API 작업은 transcribe하고 싶은 오디오 피일과 원하는 output file 형식을 같이 입력하시면 됩니다. OpenAI는 현재 여러 입력, 출력 파일 형식을 지원하고 있습니다.

 

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai
audio_file= open("/path/to/file/audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)

 

By default, the response type will be json with the raw text included.

 

기본으로 response 형식은 raw text가 포함된 json 형식입니다.

 

{ "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. .... }

 

To set additional parameters in a request, you can add more --form lines with the relevant options. For example, if you want to set the output format as text, you would add the following line:

 

Request에 추가적인 파라미터를 세팅하기 위해 관련 옵션과 함께 --form 라인을 추가하시면 됩니다. 예를 들어 여러분이 output 형식을 text로 세팅하고 싶으면 아래와 같이 하면 됩니다.

...
--form file=@openai.mp3 \
--form model=whisper-1 \
--form response_format=text

 

Translations

The translations API takes as input the audio file in any of the supported languages and transcribes, if necessary, the audio into english. This differs from our /Transcriptions endpoint since the output is not in the original input language and is instead translated to english text.

 

번역 API 작업은 지원되는 언어들중 사용자가 제공하는 어떤 것을 입력값으로 받게 됩니다. 그리고 transcribe를 하고 필요하면 오디오를 영어로 번역합니다.  /Transcriptions endpoint와 다른점은 output이 입력된 원래 언어와 다른 언어가 된다는 것입니다. 그리고 그 언어를 영어 text번역 합니다.

 

 

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai
audio_file= open("/path/to/file/german.mp3", "rb")
transcript = openai.Audio.translate("whisper-1", audio_file)

 

In this case, the inputted audio was german and the outputted text looks like:

 

이 경우 입력된 오디오는독일어이고 출력된 텍스트는 아래와 같게 됩니다.

 

Hello, my name is Wolfgang and I come from Germany. Where are you heading today?

 

We only support translation into english at this time.

 

현재로는 영어 이외의 언어를 영어로 번역하는 것만 지원합니다.

 

Supported languages

 

We currently support the following languages through both the transcriptions and translations endpoint:

 

OpenAI는 현재 다음과 같은 언어들을 transcriptions와 translations endpoint에 지원 됩니다.

 

Afrikaans, Arabic, Armenian, Azerbaijani, Belarusian, Bosnian, Bulgarian, Catalan, Chinese, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, Galician, German, Greek, Hebrew, Hindi, Hungarian, Icelandic, Indonesian, Italian, Japanese, Kannada, Kazakh, Korean, Latvian, Lithuanian, Macedonian, Malay, Marathi, Maori, Nepali, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish, Swahili, Swedish, Tagalog, Tamil, Thai, Turkish, Ukrainian, Urdu, Vietnamese, and Welsh.

 

 

While the underlying model was trained on 98 languages, we only list the languages that exceeded <50% word error rate (WER) which is an industry standard benchmark for speech to text model accuracy. The model will return results for languages not listed above but the quality will be low.

 

기본 모델은 98개 언어로 훈련이 되어 있습니다. OpenAI는 speech to text 모델의 정확도에 대한 업계 표준 벤치마크인 word error rate (WER) 이 50% 미만인 언어만 리스트 합니다.

 

Longer inputs

By default, the Whisper API only supports files that are less than 25 MB. If you have an audio file that is longer than that, you will need to break it up into chunks of 25 MB's or less or used a compressed audio format. To get the best performance, we suggest that you avoid breaking the audio up mid-sentence as this may cause some context to be lost.

 

기본적으로 Whisper API는 25MB 이하의 파일들만 지원합니다. 그보다 크기가 큰 오디오 파일은 25MB 이하로 나누거나 압축된 오디오 형식을 사용해야 합니다. 파일을 나눌 때 최고의 성능을 얻으려면 일부 context가 손실되는 것을 방비하기 위해 문장 중간을 끊지 않는 것이 좋습니다.

 

One way to handle this is to use the PyDub open source Python package to split the audio:

 

이렇게 하기 위한 방법 중 한가지는 PyDub open source Python package 를 사용해서 오디오를 잘르는 겁니다.

 

from pydub import AudioSegment

song = AudioSegment.from_mp3("good_morning.mp3")

# PyDub handles time in milliseconds
ten_minutes = 10 * 60 * 1000

first_10_minutes = song[:ten_minutes]

first_10_minutes.export("good_morning_10.mp3", format="mp3")

OpenAI makes no guarantees about the usability or security of 3rd party software like PyDub.

 

OpenAI는 PyDub와 같은 타사 소프트웨어의 usability나 security에 대한 어떠한 보장도 하지 않습니다.

 

Prompting

In the same way that you can use a prompt to influence the output of our language models, you can also use one to improve the quality of the transcripts generated by the Whisper API. The model will try to match the style of the prompt, so it will be more likely to use capitalization and punctuation if the prompt does too. Here are some examples of how prompting can help in different scenarios:

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Prompt를 사용하여 우리의 language 모델의 output에 영향을 미칠 수 있는 것과 마찬가지로 Whisper API에 의해 생성된 transcript의 질을 향상시키기 위해 이 prompt를 사용할 수 있습니다. 이 Whisper API 모델은 프롬프트의 스타일을 match 시키려고 시도합니다. 그러니까 프롬프트가 하는 것과 마찬가지로 capitalization 과 punctuation 을 사용할 가능성이 높습니다. 여기 다양한 시나리오에서 프롬프트가 어떻게 도움이 되는지에 대한 몇가지 예를 보여 드립니다.

 

1. Prompts can be very helpful for correcting specific words or acronyms that the model often misrecognizes in the audio. For example, the following prompt improves the transcription of the words DALL·E and GPT-3, which were previously written as "GDP 3" and "DALI".

 

프롬프트는 모델이 오디오에서 종종 잘 못 인식하는 특정 단어나 약어를 수정하는데 매우 유용할 수 있습니다. 예를 들어 다음 프롬프트는 이전에 GDP 3 나 DALI 로 기록 되었던 DALL-E 및 GPT-3 라는 단어의 표기를 개선합니다.

 

The transcript is about OpenAI which makes technology like DALL·E, GPT-3, and ChatGPT with the hope of one day building an AGI system that benefits all of humanity

 

2. To preserve the context of a file that was split into segments, you can prompt the model with the transcript of the preceding segment. This will make the transcript more accurate, as the model will use the relevant information from the previous audio. The model will only consider the final 224 tokens of the prompt and ignore anything earlier.

 

segment들로 나누어진 파일의 context를 유지하기 위해 여러분은 이전 세그먼트의 기록으로 모델에 메시지를 표시할 수 있습니다. 이렇게 하면 모델이 이전 오디오의 관련 정보를 사용하므로 transcript 가 더욱 정확해 집니다. 모델은 프롬프트의 마지막 224개 토큰만 고려하고 이전의 것들은 무시합니다.

 

3. Sometimes the model might skip punctuation in the transcript. You can avoid this by using a simple prompt that includes punctuation:

 

때떄로 이 모델은 transcript의 punctuation을 skip 할 수 있습니다. 이것은  punctuation을 포함하는 간단한 프롬프트를 사용함으로서 해결 할 수 있습니다.

 

Hello, welcome to my lecture.

 

4. The model may also leave out common filler words in the audio. If you want to keep the filler words in your transcript, you can use a prompt that contains them:

 

이 모델은 오디오에서 일반적인 filler words를 생략할 수 있습니다. transcript에 이러한 filler word들을 유지하려면 filler word를 포함하는 프롬프트를 사용하면 됩니다.

 

Umm, let me think like, hmm... Okay, here's what I'm, like, thinking."

 

filler word : 말 사이에 의미없이 하는 말. Um.. uhh... like... 같은 말

 

5. Some languages can be written in different ways, such as simplified or traditional Chinese. The model might not always use the writing style that you want for your transcript by default. You can improve this by using a prompt in your preferred writing style.

 

어떤 언어들은 다른 방법으로 표기가 됩니다. 예를 들어 중국어에는 간체와 번체가 있죠. 이 모델은 기본적으로 transcript에 대해 원하는 쓰기 스타일을 항상 사용하지 않을 수 있습니다. 원하는 쓰기 스타일이 있다면 프롬프트를 사용하여 원하는 결과를 얻도록 유도할 수 있습니다.

 

 

 

 

반응형

'Open AI > GUIDES' 카테고리의 다른 글

Guide - Error codes  (0) 2023.03.05
Guide - Rate limits  (0) 2023.03.05
Guide - Chat completion (ChatGPT API)  (0) 2023.03.05
Guides - Production Best Practices  (0) 2023.01.10
Guides - Safety best practices  (0) 2023.01.10
Guides - Moderation  (0) 2023.01.10
Guides - Embeddings  (0) 2023.01.10
Guides - Fine tuning  (0) 2023.01.10
Guide - Image generation  (0) 2023.01.09
Guide - Code completion  (0) 2023.01.09

Guide - Chat completion (ChatGPT API)

2023. 3. 5. 01:16 | Posted by 솔웅


반응형

 

Chat completions

ChatGPT is powered by gpt-3.5-turbo, OpenAI’s most advanced language model.

ChatGPT는 gpt-3.5-turbo 모델을 사용합니다. 이는 OpenAI의 가장 진보된 language 모델입니다.

 

Using the OpenAI API, you can build your own applications with gpt-3.5-turbo to do things like:

OpenAI API를 사용해서 여러분은 gpt-3.5-turbo 모델로 여러분의 앱을 개발할 수 있고 다음과 같은 작업들이 가능합니다.

 

  • Draft an email or other piece of writing
  • 이메일이자 다른 종류의 글을 작성할 때 초안 만들기
  • Write Python code
  • 파이썬으로 코드 작성하기
  • Answer questions about a set of documents
  • 여러 문서들에 대해 질문에 답하기
  • Create conversational agents
  • 대화형 agent 생성하기
  • Give your software a natural language interface
  • 여러분의 소프트웨어에 자연 언어 인터페이스 구축하기
  • Tutor in a range of subjects
  • 다양한 주제에 대해 tutor 하기
  • Translate languages
  • 언어 번역하기
  • Simulate characters for video games and much more
  • 비디오 게임등을 위한 캐릭터 시뮬레이션 하기

 

This guide explains how to make an API call for chat-based language models and shares tips for getting good results. You can also experiment with the new chat format in the OpenAI Playground.

 

이 가이드는 채팅 기반 언어 모델에 대한 API 호출을 만드는 방법을 설명하고 좋은 결과를 얻기 위한 팁을 공유합니다.

여러분은 또한 OpenAI Playground에서 채로운 채팅 형식을 실험해 볼 수도 있습니다.

 

Introduction

Chat models take a series of messages as input, and return a model-generated message as output.

채팅 모델은 일련의 메세지를 입력값으로 받고 모델이 생성한 메세지를 output 으로 반환합니다.

 

Although the chat format is designed to make multi-turn conversations easy, it’s just as useful for single-turn tasks without any conversations (such as those previously served by instruction following models like text-davinci-003).

채팅 형식은 multi-turn 대화를 쉽게 할 수 있도록 디자인 되었지만 대화가 없는 Single-turn 작업에도 유용하게 사용할 수 있습니다. (예: text-davinci-003 같이 instruction 에 따르는 모델이 제공한 것 같은 서비스)

 

An example API call looks as follows: 예제 API 호출은 아래와 같습니다.

 

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai

openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

openai를 import 한 다음 openai.ChatCompletion.create() API 를 사용하면 됩니다.

 

 

The main input is the messages parameter. Messages must be an array of message objects, where each object has a role (either “system”, “user”, or “assistant”) and content (the content of the message). Conversations can be as short as 1 message or fill many pages.

 

주요 입력값들은 메세지의 파라미터 들입니다. 메세지들은 반드시 메세지 객체의 배열 형식이어야 합니다. 각 객체들에는 Role (역할) 이 주어집니다. (System, User, 혹은 Assistant 가 해당 메세지 객체의 Role이 됩니다.) 그리고 내용이 있습니다. (그 내용은 메세지가 됩니다.) 대화는 1개의 메세지로 된 짧은 형식이 될 수도 있고 여러 페이지에 걸친 많은 양이 될 수도 있습니다.

 

Typically, a conversation is formatted with a system message first, followed by alternating user and assistant messages.

 

일반적으로 대화는 먼저 System 메세지로 틀을 잡고 다음에 User와 Assistant 메세지가 번갈이 표시되게 됩니다.

 

The system message helps set the behavior of the assistant. In the example above, the assistant was instructed with “You are a helpful assistant.”

 

System 메세지는 Assistant의 행동을 설정하는데 도움이 됩니다. 위에 메세지에서 System 메세지는 Assistant에게 "당신은 도움을 주는 도우미 입니다" 라고 설정을 해 줬습니다.

 

The user messages help instruct the assistant. They can be generated by the end users of an application, or set by a developer as an instruction.

 

User 메세지는 Assistant에게 instruct (지시) 하도록 도와 줍니다. 이 메세지는 해당 어플리케이션의 사용자가 생성하게 됩니다. 혹은 개발자가 instruction으로서 생성하게 될 수도 있습니다.

 

The assistant messages help store prior responses. They can also be written by a developer to help give examples of desired behavior.

 

Assistant 메세지는 prior responses를 저장하는데 도움을 줍니다. 이 메세지도 개발자가 작성할 수 있습니다. gpt-3.5-turbo 모델이 어떤 식으로 응대할지에 대한 예를 제공합니다. (캐주얼하게 작성을 하면 ChatAPI 모델은 그것에 맞게 캐주얼한 형식으로 답변을 제공하고 formal 하게 제시하면 그 모델은 그에 맞게 formal 한 형식으로 답변을 제공할 것입니다.)

 

Including the conversation history helps when user instructions refer to prior messages. In the example above, the user’s final question of “Where was it played?” only makes sense in the context of the prior messages about the World Series of 2020. Because the models have no memory of past requests, all relevant information must be supplied via the conversation. If a conversation cannot fit within the model’s token limit, it will need to be shortened in some way.

 

이미 오고간 대화들을 제공하면 user 가 instruction을 제공하기 이전의 메세지로서 참조가 됩니다. 즉 그 대화의 분위기나 형식에 맞는 응답을 받게 될 것입니다. 위의 에에서 user의 마지막 질문은 "Where was it played?" 입니다. 

 

이전의 대화들이 있어야지만이 이 질문이 무엇을 의미하는지 알 수 있습니다. 이전의 대화들이 2020년 월드 시리즈에 대한 내용들이었기 때문에 이 질문의 의미는 2020년 월드 시리즈는 어디에서 개최 됐느냐는 질문으로 모델을 알아 듣게 됩니다. 

 

이 모델은 과거 request들에 대한 기억이 없기 때문에 이런 식으로 관련 정보를 제공합니다. 

Request에는 모델별로 사용할 수 있는 Token 수가 정해져 있습니다. Request가 이 Token 수를 초과하지 않도록 작성해야 합니다.

 

Response format

이 API의 response는 아래와 같은 형식입니다.

 

{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}

파이썬에서 assistant의 응답은 다음과 같은 방법으로 추출 될 수 있습니다.

response[‘choices’][0][‘message’][‘content’]

 

Managing tokens

 

Language models read text in chunks called tokens. In English, a token can be as short as one character or as long as one word (e.g., a or apple), and in some languages tokens can be even shorter than one character or even longer than one word.

 

Language 모델은 토큰이라는 chunk로 텍스트를 읽습니다. 영어에서 토큰은 글자 하나인 경우도 있고 단어 하나인 경우도 있습니다. (예. a 혹은 apple). 영어 이외의 다른 언어에서는 토큰이 글자 하나보다 짧거나 단어 하나보다 길 수도 있습니다.

 

For example, the string “ChatGPT is great!” is encoded into six tokens: [“Chat”, “G”, “PT”, “ is”, “ great”, “!”].

 

예를 들어 ChatGPT is great! 이라는 문장은 다음과 같이 6개의 토큰으로 구성됩니다. [“Chat”, “G”, “PT”, “ is”, “ great”, “!”]

 

The total number of tokens in an API call affects: How much your API call costs, as you pay per token How long your API call takes, as writing more tokens takes more time Whether your API call works at all, as total tokens must be below the model’s maximum limit (4096 tokens for gpt-3.5-turbo-0301)

 

APPI 호출의 총 토큰수는 다음과 같은 사항들에 영향을 미칩니다. : 해당 API 호출에 얼마가 과금이 될지 여부. 대개 1000개의 토큰당 요금이 과금이 되기 때문에 토큰이 아주 길면 그만큼 과금이 더 될 수 있습니다. 이는 토큰이 많을 수록 API 호출을 처리하는데 시간이 더 걸리기 때문이죠. request의 전체 토큰 수는 제한량을 넘을 수 없습니다. (gpt-3.5-turbo-0301 의 경우 4096 개의 토큰이 제한량입니다.)

 

Both input and output tokens count toward these quantities. For example, if your API call used 10 tokens in the message input and you received 20 tokens in the message output, you would be billed for 30 tokens.

 

입력 및 출력 토큰 모두 해당 호출의 토큰수에 포함됩니다. 예를 들어 API 호출에서 입력값으로 10개의 토큰을 사용했고 output으로 20개의 토큰을 받을 경우 30개의 토큰에 대해 과금 됩니다.

 

To see how many tokens are used by an API call, check the usage field in the API response (e.g., response[‘usage’][‘total_tokens’]).

 

API 호출에서 사용되는 토큰의 수를 확인 하려면 API response 중 usage 필드를 확인하시면 됩니다. (e.g., response[‘usage’][‘total_tokens’]).

 

To see how many tokens are in a text string without making an API call, use OpenAI’s tiktoken Python library. Example code can be found in the OpenAI Cookbook’s guide on how to count tokens with tiktoken.

 

API를 호출하기 전에 미리 입력값에 대한 토큰수를 확인 하려면 OpenAI의 tiktoken 파이썬 라이브러리를 사용하세요. 예제 코드는 OpenAI Cookbook의 가이드에서 보실 수 있습니다. how to count tokens with tiktoken

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

위 내용은 제 블로그의 아래 글에서 한글로 설명 돼 있습니다.

https://coronasdk.tistory.com/1274

 

Openai cookbook - API usage - How to count tokens with tiktoken

How to count tokens with tiktoken 오늘 다를 예제는 아래 CookBook 페이지에 있는 토큰 관련 에제 입니다. https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb GitHub - openai/openai-cookbo

coronasdk.tistory.com

 

 

Each message passed to the API consumes the number of tokens in the content, role, and other fields, plus a few extra for behind-the-scenes formatting. This may change slightly in the future.

 

API에 전달된 각각의 메세지는 content, role 그리고 다른 필드들에서 토큰이 소비 됩니다. 그리고 이런 필드들 이외에도 서식관련 해서 공간을 사용해야 하기 때문에 토큰이 소비 되는 부분도 있습니다. 자세한 사항들은 차후에 변경될 수도 있습니다.

 

If a conversation has too many tokens to fit within a model’s maximum limit (e.g., more than 4096 tokens for gpt-3.5-turbo), you will have to truncate, omit, or otherwise shrink your text until it fits. Beware that if a message is removed from the messages input, the model will lose all knowledge of it.

 

대화에 토큰이 너무 많이 모델의 허용 한도 이내에서 작성할 수 없을 경우 (예: gpt-3.5-turbo의 경우 4096개가 제한량임) 그 한도수 이내가 될 때까지 자르거나 생략하거나 축소해야 합니다. message 입력값에서 message 부분이 제한량 초과로 날아가 버리면 모델은 이에 대한 모든 knowledge들을 잃게 됩니다.

 

Note too that very long conversations are more likely to receive incomplete replies. For example, a gpt-3.5-turbo conversation that is 4090 tokens long will have its reply cut off after just 6 tokens.

 

매우 긴 대화는 불완전한 답변을 받을 가능성이 더 높습니다. 이점에 유의하세요. 예를 들어 gpt-3.5-turbo 의 대화에 4090개의 토큰이 입력값에서 사용됐다면 출력값으로는 6개의 토큰만 받고 그 나무지는 잘려 나갑니다.

 

Instructing chat models

Best practices for instructing models may change from model version to version. The advice that follows applies to gpt-3.5-turbo-0301 and may not apply to future models.

 

모델에 instructing 하는 가장 좋은 방법은 모델의 버전마다 다를 수 있습니다. 다음에 나오는 내용은 gpt-3.5-turbo-0301 버전에 적용됩니다. 그 이후의 모델에는 적용될 수도 있고 적용되지 않을 수도 있습니다.

 

Many conversations begin with a system message to gently instruct the assistant. For example, here is one of the system messages used for ChatGPT:

 

assistant에게 젠틀하게 지시하는 system 메세지로 많은 대화들을 시작하세요. 예를 들어 ChatGPT에서 사용되는 시스템 메세지 중 하나를 아래에 보여드리겠습니다.

You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible. Knowledge cutoff: {knowledge_cutoff} Current date: {current_date}

 

In general, gpt-3.5-turbo-0301 does not pay strong attention to the system message, and therefore important instructions are often better placed in a user message.

 

일반적으로 gpt-3.5-turbo-0301은 System 메세지의 크게 주의를 기울이지 않으므로 핵심 instruction은 User 메세지에 주로 배치 됩니다.

 

If the model isn’t generating the output you want, feel free to iterate and experiment with potential improvements. You can try approaches like:

 

모델의 output 이 원하는 대로 안 나오면 잠재적인 개선을 이끌수 있는 반복과 실험을 하는데 주저하지 마세요. 예를 들어 아래와 같이 접근 할 수 있습니다.

 

  • Make your instruction more explicit
  • 명료하게 지시를 하세요.
  • Specify the format you want the answer in
  • 응답을 받고자 하는 형식을 특정해 주세요.
  • Ask the model to think step by step or debate pros and cons before settling on an answer
  • 모델이 최종 답을 결정하기 전에 단계별로 생각하거나 장단넘에 대해 debate을 해 보라고 요청하세요.

 

For more prompt engineering ideas, read the OpenAI Cookbook guide on techniques to improve reliability.

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

프롬프트 엔지니어링에 대한 좀 더 많은 사항은 OpenAI Cookbook guide에 있는 techniques to improve reliability를 참조하세요.

 

Beyond the system message, the temperature and max tokens are two of many options developers have to influence the output of the chat models. For temperature, higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. In the case of max tokens, if you want to limit a response to a certain length, max tokens can be set to an arbitrary number. This may cause issues for example if you set the max tokens value to 5 since the output will be cut-off and the result will not make sense to users.

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

System 메세지 이외에도 temperature와 max token은 채팅 모델의 output에 영향을 주는 많은 옵션 중 두가지 옵션 입니다.

Temperature의 경우 0.8 이상의 값은 output을 더 random 하게 만듭니다. 그보다 값이 낮으면 예를 들어 0.2 뭐 이렇게 되면 더 focused 하고 deterministic 한 답변을 내 놓습니다. max token의 경우 여러분이 답변을 특정 길이로 제한하고 싶을 때 이 max token을 임의의 숫자로 세팅할 수 있습니다. 이것을 사용할 때는 주의하셔야 합니다. 예를 들어 최대 토큰 값을 5처럼 아주 낮게 설정하면 output이 잘리고 사용자에게 의미가 없을 수 있기 때문에 문제가 발생할 수 있습니다.

 

 

Chat vs Completions

 

Because gpt-3.5-turbo performs at a similar capability to text-davinci-003 but at 10% the price per token, we recommend gpt-3.5-turbo for most use cases.

 

gpt-3.5-turbo는 text-davinci-003과 비슷한 성능을 보이지만 토큰당 가격은 10% 밖에 하지 않습니다. 그렇기 때문에 우리는 대부분의 사용 사례에 gpt-3.5-turbo를 사용할 것을 권장합니다.

 

For many developers, the transition is as simple as rewriting and retesting a prompt.

 

많은 개발자들에게 transition은 프롬프트를 rewriting 하고 retesting 하는 것 만큼 아주 간단합니다.

 

For example, if you translated English to French with the following completions prompt:

 

예를 들어 여러분이 영어를 불어로 아래와 같이 completions prompt로 번역한다면,

 

Translate the following English text to French: “{text}”

이 채팅 모델로는 아래와 같이 할 수 있습니다.

 

[
  {“role”: “system”, “content”: “You are a helpful assistant that translates English to French.”},
  {“role”: “user”, “content”: ‘Translate the following English text to French: “{text}”’}
]

혹은 이렇게 user 메세지만 주어도 됩니다.

[
  {“role”: “user”, “content”: ‘Translate the following English text to French: “{text}”’}
]

 

FAQ

Is fine-tuning available for gpt-3.5-turbo?

gpt-3.5-turbo에서도 fine-tuning이 가능한가요?

 

No. As of Mar 1, 2023, you can only fine-tune base GPT-3 models. See the fine-tuning guide for more details on how to use fine-tuned models.

 

아니오. 2023년 3월 1일 현재 GPT-3 모델 기반에서만 fine-tune을 할 수 있습니다. fine-tuned 모델을 어떻게 사용할지에 대한 자세한 사항은 fine-tuning guide 를 참조하세요.

 

 

Do you store the data that is passed into the API?

OpenAI는 API로 전달된 데이터를 저장해서 갖고 있습니까?

 

As of March 1st, 2023, we retain your API data for 30 days but no longer use your data sent via the API to improve our models. Learn more in our data usage policy.

 

2023년 3월 1일 현재 OpenAI는 여러분의 API 데이터를 30일간 유지하고 있습니다. 하지만 여러분이 API를 통해 보낸 데이터들은 오리의 모델을 개선하는데 사용하지는 않습니다. 더 자세한 사항은 data usage policy 를 참조하세요. 

 

 

Adding a moderation layer

조정 레이어 추가하기

 

If you want to add a moderation layer to the outputs of the Chat API, you can follow our moderation guide to prevent content that violates OpenAI’s usage policies from being shown.

 

 

Chat API의 output에 moderation 레이어를 추가할 수 있습니다. moderation 레이어를 추가하려는 경우 OpenAI의 사용 정책을 위반하는 내용이 표시되지 않도록 moderatin guide를 따라 주세요.

 

 

 

반응형

'Open AI > GUIDES' 카테고리의 다른 글

Guide - Error codes  (0) 2023.03.05
Guide - Rate limits  (0) 2023.03.05
Guide - Speech to text  (0) 2023.03.05
Guides - Production Best Practices  (0) 2023.01.10
Guides - Safety best practices  (0) 2023.01.10
Guides - Moderation  (0) 2023.01.10
Guides - Embeddings  (0) 2023.01.10
Guides - Fine tuning  (0) 2023.01.10
Guide - Image generation  (0) 2023.01.09
Guide - Code completion  (0) 2023.01.09


반응형

OpenAI Cookbook을 공부하고 있는 사이에 새롭게 올라온 글이 있습니다.

ChatGPT와 관련한 글인데요.

2023년 3월 1일에 최초로 올라왔습니다.

 

오늘은 이 글을 공부해 보도록 하겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

How to format inputs to ChatGPT models

ChatGPT는 gpt-3.5-turbo로 만들어 졌고 OpenAI의 가장 진보된 모델입니다.

OpenAI API를 사용해서 gpt-3.5-turbo로 여러분들만의 어플리케이션을 build 하실 수 있습니다.

 

Chat 모델은 일련의 메세지를 입력값으로 받고 AI 가 작성한 메세지를 output으로 반환합니다.

 

이 가이드는 몇가지 예제 API호출을 사용하여 채팅 형식을 보여 줍니다.

 

1. Import the openai library

# if needed, install and/or upgrade to the latest version of the OpenAI Python library
%pip install --upgrade openai

OpenAI 최신 버전으로 업데이트 하려면 pip install -- upgrade 명령으로 업데이트 합니다.

저는 윈도우즈 명령창에서 업데이트 했습니다.

2023년 3월 1일 ChatGPT API 가 OpenAI API 에 추가 됐습니다.

이 Chat API 콜의 모델 이름은  gpt-3.5-turbo 입니다. 이 모델은 ChatGPT 에서 사용되는 바로 그 모델입니다.

 

이와 관련한 Guide document도 추가 됐습니다.

https://platform.openai.com/docs/guides/chat

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

이 API를 사용하는 가격은 1천개의 토큰당 0.002 달러입니다. 

 

그 다음은 openai 모듈을 import 합니다.

 

저 같은 경우는 openai api key 를 파일에서 읽허서 보내기 때문에 그 부분도 넣었습니다.

 

2. An example chat API call

chat API 콜은 다음 두가지 입력값들이 요구 됩니다.

 

  • model: the name of the model you want to use (e.g., gpt-3.5-turbo)
  • 모델 : 사용하고자 할 모델 이름 (e.g., gpt-3.5-turbo)
  • messages: a list of message objects, where each object has at least two fields:
  • 메세지 : 메세지 객체 리스트. 각 객체들은 최소한 아래 두개의 field를 가지고 있어야 한다. 
    • role: the role of the messenger (either system, user, or assistant)
    • 역할 : 메센저의 역할 (시스템인지 사용자인지 혹은 조력자인지...)
    • content: the content of the message (e.g., Write me a beautiful poem)
    • 내용 : 메세지의 내용 (예. , 저에게 아름다운 시를 써 주세요.)

 

일반적으로 대화는 시스템 메세지로 시작하고 그 뒤에 사용자 및 조력자 메세지가 교대로 오지만 꼭 이 형식을 따를 필요는 없습니다.

ChatGPT 가 사용하는 Chat API가 실제로 어떻게 작동하는지 알아보기 위해 Chat API 를 호출하는 예제를 한번 살펴보겠습니다.

 

이 ChatGPT에서 사용하는 ChatAPI를 호출하는 방법은 openai.ChatCompletion.create() 을 호출하는 겁니다.

 

위 호출에 대한 response 객체는 여러 필드들이 있습니다.

 

  • choices: a list of completion objects (only one, unless you set n greater than 1)
  • choices : completion 객체의 리스트 (n을 1보다 높게 세팅하지 않는 한 한개만 존재한다.)
    • message: the message object generated by the model, with role and content
    • message : 모델에 의해 생성된 메세지 객체 (role, content)
    • finish_reason: the reason the model stopped generating text (either stop, or length if max_tokens limit was reached)
    • finish_reason: 모델이 텍스트 생성을 중지한 이유 (stop 이거나 max_tokens를 초과했을 경우는 그 길이)
    • index: the index of the completion in the list of choices
    • index: choices에 있는 리스트의 completion 의 index
  • created: the timestamp of the request
  • created : 해당 request의 요청 시간 정보
  • id: the ID of the request (해당 request의 ID)
  • model: the full name of the model used to generate the response
  • model ; response를 발생시키는데 사용된 모델의 full name
  • object: the type of object returned (e.g., chat.completion) 
  • object : 반환된 객체의 유형 (e.g., chat.completion)
  • usage: the number of tokens used to generate the replies, counting prompt, completion, and total
  • usage : response를 생성하는데 사용된 토큰 수. completion, prompt, totak 토큰 수

 

위 Request 에서 보면 messages 안에 있는 첫번째 아이템의 role 이 system 입니다.

이는 ChatGPT에게 현 상황을 설명하는 겁니다.

여기서는 너는 아주 도움을 잘 주는 조력자이다 라고 ChatGPT에게 규정했습니다.

그 다음의 user는 똑 똑 하고 노크를 하죠.

그 다음 조력자는 누구세요? 라고 묻습니다.

그 다음 user는 Orange 라고 대답하죠.

 

여기까지  ChatGPT에게 제공된 상황입니다.

 

그러면 그 다음은 ChatGPT가 알아서 그 다음에 올 수 있는 알맞는 대답을 response 할 차례입니다.

 

ChatGPT의 대답의 구조는 위에 설명 한 대로 입니다.

여기서 대답은 choices - message - content 에 있는 Orange who? 라는 겁니다.

 

나머지는 모두 이 request와 response 에 대한 데이터들입니다.

 

여기서 실제 ChatGPT가 상황에 맞게 대답한 부분만 받으려면 아래와 같이 하면 됩니다.

 

이렇게 하면 실제 ChatGPT가 대답한 Orange who? 라는 부분만 취할 수 있습니다.

 

대화 기반이 아닌 작업도 첫번째 user message 부분에 instruction을 넣음으로서 chat format 에 맞춰서 사용할 수 있습니다.

예를 들어 모델에게 비동기 프로그래밍을 설명하는데 검은 수염이 난 해적이 말하는 스타일로 설명하도록 요청하려면 대화를 다음과 같이 구성하시면 됩니다.

이렇게 하면 ChatGPT가 비동기 프로그래밍을 설명하는데 그 말투가 검은 수염난 해적이 말하는 것처럼 만들어서 대답을 합니다.

 

이것을 그 말투의 느낌까지 살려서 한글로 번역하는 것은 힘드니까 대충 구글 번역기를 돌려 보겠습니다.

 

어이 친구! 비동기 프로그래밍은 동시에 다른 작업을 수행하는 해적 선원을 갖는 것과 같습니다. 예, 다음 작업을 시작하기 전에 하나의 작업이 완료되기를 기다리는 대신 한 번에 여러 작업을 실행할 수 있습니다. 그것은 다른 사람들이 갑판을 청소하고 대포를 장전하는 동안 내 승무원이 돛을 올리는 것과 같습니다. 각 작업은 독립적으로 작동하지만 모두 배의 전반적인 성공에 기여합니다. 이는 기름칠이 잘 된 해적선이 더 빠르고 원활하게 항해할 수 있는 것처럼 코드를 더 빠르고 효율적으로 실행하는 강력한 방법입니다. Arr!

 

재밌네요.

 

상황 설명을 하는 system message 없이 한번 요청해 보겠습니다.

 

 

이렇게 해도 ChatGPT는 제대로 대답 합니다.

 

3. Tips for instructing gpt-3.5-turbo-0301

모델들에게 가장 잘 instructing 하는 방법은 모델의 버전에 따라 다를 수 있습니다. 아래 예제는 gpt-3.5-turbo-0301 버전에 적용할 때 가장 효과가 좋은 instructiong 입니다. 이후의 모델에서는 적용되지 않을 수 있습니다.

 

System messages

시스템 메세지는 다른 성격이나 행동 양식을 부여함으로서 assistant를 잘 준비 하도록 하는데 사용할 수 있습니다.

하지만 모델은 일반적으로 system message에 그렇게 절대적으로 주의를 기울이지는 않습니다. 그러므로 정말 중요한 부분은 user 메세지에 배치하라고 권고 드립니다.

 

다음은 assitant가 개념을 아주 깊이 있게 설명하도록 유도하는 system 메세지의 예 입니다.

 

# An example of a system message that primes the assistant to explain concepts in great depth
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a friendly and helpful teaching assistant. You explain concepts in great depth using simple terms, and you give examples to help people learn. At the end of each explanation, you ask a question to check for understanding"},
        {"role": "user", "content": "Can you explain how fractions work?"},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

 

아래는 Assitent 에게 간략하고 핵심적인 답변만 하라고 유도하는 system 메세지의 예입니다.

# An example of a system message that primes the assistant to give brief, to-the-point answers
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a laconic assistant. You reply with brief, to-the-point answers with no elaboration."},
        {"role": "user", "content": "Can you explain how fractions work?"},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

System message의 유도에 따라 대답을 자세하게 하거나 간력하게 하도록 하는 방법을 보았습니다.

 

Few-shot prompting

어떤 경우에는 당신이 원하는 것을 모델에게 설명하는 것 보다 그냥 보여주는게 더 편할 때가 있습니다.

이렇게 모델에게 당신이 무엇을 원하는지 보여주는 방법 중 하나는 fake example 메세지를 사용하는 것입니다.

 

모델이 비지니스 전문 용어를 더 간단한 말로 번역하도록 준비시키는 faked few-shot 대화를 넣어 주는 예제 입니다.

# An example of a faked few-shot conversation to prime the model into translating business jargon to simpler speech
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful, pattern-following assistant."},
        {"role": "user", "content": "Help me translate the following corporate jargon into plain English."},
        {"role": "assistant", "content": "Sure, I'd be happy to!"},
        {"role": "user", "content": "New synergies will help drive top-line growth."},
        {"role": "assistant", "content": "Things working well together will increase revenue."},
        {"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
        {"role": "assistant", "content": "Let's talk later when we're less busy about how to do better."},
        {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

제가 얻은 답은 위와 같습니다.

 

예제의 대화가 실제 대화가 아니고 이것을 다시 참조해서는 안된다는 점을 모델에게 명확하게 하기 위해 system message의 필드 이름을 example_user 와 example_assistant 로 바꾸어서 해 보겠습니다.

위의 few-shot 예제를 이렇게 좀 바꿔서 다시 시작해 보겠습니다.

 

# The business jargon translation example, but with example names for the example messages
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
        {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
        {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
        {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
        {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
        {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

제가 받은 답은 위와 같습니다.

 

엔지니어링 대화에 대한 모든 시도가 첫번째 시도에서 다 성공하는 것은 아닙니다.

 

첫번째 시도가 실패하면 다른 방법으로 priming을 하던가 혹은 모델의 condition들을 바꾸어서 다시 시도하는 실험을 두려워 하지 마세요. 

 

예를 들어 한 개발자는 모델이 더 높은 품질의 응답을 제공하도록 하기 위해 "지금까지 훌륭했어요. 완벽했습니다." 라는 사용자 메세지를 삽입했을 때 정확도가 더 증가한다는 것을 발견한 사례도 있습니다.

 

모델의 신뢰도를 높이는 방법에 대한 자세한 내용은   techniques to increase reliability 가이드를 참조하세요. 채팅용 모델용으로 작성된 것은 아니지만 기본 원칙은 동일하게 적용 될 수 있습니다.

https://coronasdk.tistory.com/1277

 

Openai cookbook : GPT-3 , Guide Techniques to improve reliability

오늘 공부할 내용은 답변의 신뢰성을 높이기 위한 여러 방법들을 알아보는 겁니다. 실습보다는 이론적인 것들이 많은 것 같습니다. 내용이 좀 긴데 일단 한번 시작해 보겠습니다. 원본 페이지는

coronasdk.tistory.com

 

4. Counting tokens

여러분이 Request를 submit 하면 API 는 그 메세지를 일련의 토큰들로 변환합니다.

 

여기서 토큰의 수는 다음과 같은 것들에 영향을 미칩니다.

  • the cost of the request
  • request에 대한 과금
  • the time it takes to generate the response
  • response를 발생시키는데 걸리느 ㄴ시간
  • when the reply gets cut off from hitting the maximum token limit (4096 for gpt-3.5-turbo)
  • 최대 토큰 수 제한 (gpt-3.5-turbo 의 경우 4096)에 다다랐을 때는 request 중 나머지는 잘려 나가게 됨

2023년 3월 1일부터 다음 함수를 사용해서 메세지 목록에서 사용될 토큰의 갯수를 미리 계산할 수 있습니다.

 

import tiktoken


def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
    """Returns the number of tokens used by a list of messages."""
    try:
        encoding = tiktoken.encoding_for_model(model)
    except KeyError:
        encoding = tiktoken.get_encoding("cl100k_base")
    if model == "gpt-3.5-turbo-0301":  # note: future models may deviate from this
        num_tokens = 0
        for message in messages:
            num_tokens += 4  # every message follows <im_start>{role/name}\n{content}<im_end>\n
            for key, value in message.items():
                num_tokens += len(encoding.encode(value))
                if key == "name":  # if there's a name, the role is omitted
                    num_tokens += -1  # role is always required and always 1 token
        num_tokens += 2  # every reply is primed with <im_start>assistant
        return num_tokens
    else:
        raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")

tiktoken을 import 합니다.

num_tokens_from_messages() 함수를 만듭니다.

이 함수의 입력값은 메세지와 모델명 입니다.

tiktoken의 encoding_for_model()을 사용해서 encoding을 정합니다.

여기서 에러가 날 경우 cl100k_base 를 사용합니다. (이는 임베딩에서 사용했던 인코딩 입니다.)

 

if 문에서 모델이 gpt-3.5-turbo-0301 인 경우 그 안의 내용을 실행하게 됩니다.

그 안의 for 문은 메세지 목록의 아이템 수 만큼 루프를 돕니다.

그리고 각각의 메세지마다 4를 + 해 줍니다.

그리고 그 각각의 메세지에 대한 토큰 값을 다음 for 문 안에서 len(encoding.encode(value) 를 사용해서 계산합니다.

key 가 name 인 경우 role은 항상 1개의 토큰만 사용하기 때문에 이 부분을 빼 줍니다.

그리고 각각의 reply 마다 2씩 더해 줍니다.

 

이렇게 해서 계산된 값을 반환합니다.

 

그 다음에 아래 messages를 정해 줍니다.

 

messages = [
    {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
    {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
    {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
    {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
    {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
    {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
]

그 다음에 이 메세지의를 파라미터로 num_tokens_from_messages() 함수를 호출해서 토큰 값을 받고 그것을 print 해 줍니다.

# example token count from the function defined above
print(f"{num_tokens_from_messages(messages)} prompt tokens counted.")

그러면 126개의 토큰이 사용됐다고 나옵니다.

 

참고로 이 글에서 만든 파이썬 소스코드는 아래와 같습니다.

 

# import the OpenAI Python library for calling the OpenAI API
import openai

def open_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as infile:
        return infile.read()

openai.api_key = open_file('openaiapikey.txt')

# Example OpenAI Python library request
MODEL = "gpt-3.5-turbo"
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Knock knock."},
        {"role": "assistant", "content": "Who's there?"},
        {"role": "user", "content": "Orange."},
    ],
    temperature=0,
)

response

response['choices'][0]['message']['content']

# example with a system message
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain asynchronous programming in the style of the pirate Blackbeard."},
    ],
    temperature=0,
)

print(response['choices'][0]['message']['content'])

# example without a system message
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "user", "content": "Explain asynchronous programming in the style of the pirate Blackbeard."},
    ],
    temperature=0,
)

print(response['choices'][0]['message']['content'])

# An example of a system message that primes the assistant to explain concepts in great depth
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a friendly and helpful teaching assistant. You explain concepts in great depth using simple terms, and you give examples to help people learn. At the end of each explanation, you ask a question to check for understanding"},
        {"role": "user", "content": "Can you explain how fractions work?"},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

# An example of a system message that primes the assistant to give brief, to-the-point answers
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a laconic assistant. You reply with brief, to-the-point answers with no elaboration."},
        {"role": "user", "content": "Can you explain how fractions work?"},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

# An example of a faked few-shot conversation to prime the model into translating business jargon to simpler speech
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful, pattern-following assistant."},
        {"role": "user", "content": "Help me translate the following corporate jargon into plain English."},
        {"role": "assistant", "content": "Sure, I'd be happy to!"},
        {"role": "user", "content": "New synergies will help drive top-line growth."},
        {"role": "assistant", "content": "Things working well together will increase revenue."},
        {"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
        {"role": "assistant", "content": "Let's talk later when we're less busy about how to do better."},
        {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

# The business jargon translation example, but with example names for the example messages
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
        {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
        {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
        {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
        {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
        {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

import tiktoken


def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
    """Returns the number of tokens used by a list of messages."""
    try:
        encoding = tiktoken.encoding_for_model(model)
    except KeyError:
        encoding = tiktoken.get_encoding("cl100k_base")
    if model == "gpt-3.5-turbo-0301":  # note: future models may deviate from this
        num_tokens = 0
        for message in messages:
            num_tokens += 4  # every message follows <im_start>{role/name}\n{content}<im_end>\n
            for key, value in message.items():
                num_tokens += len(encoding.encode(value))
                if key == "name":  # if there's a name, the role is omitted
                    num_tokens += -1  # role is always required and always 1 token
        num_tokens += 2  # every reply is primed with <im_start>assistant
        return num_tokens
    else:
        raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")

messages = [
    {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
    {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
    {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
    {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
    {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
    {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
]

# example token count from the function defined above
print(f"{num_tokens_from_messages(messages)} prompt tokens counted.")
반응형


반응형

오늘 공부할 Code Editing examples 원본 페이지는 아래에 있습니다.

 

https://github.com/openai/openai-cookbook/blob/main/code_editing_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Code editing example

OpenAI의 edits endpoint는 특별히 코드를 수정하는데 유용합니다.

Completions와 달리 Edits는 두개의 입력값을 받습니다. 수정할 코드와 instruction 입니다.

예를 들어 한 파이썬 함수를 수정하기를 원한다고 합시다. 당신은 그 함수와 'docstring을 추가하라' 같은 지시문을 함께 제공해야 할 것입니다.

 

Example text input to code-davinci-edit-001:

 

def tribonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 1
    elif n == 3:
        return 2
    else:
        return tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)

Example instruction inputs:

add a docstring
Add typing, using Python 3.9 conventions
improved the runtime
Add a test.
Translate to JavaScript (or Rust or Lisp or any language you like)

자바스크립트로 runtime과 translating을 개선시키고 난 후의 output 예제.

function tribonacci(n) {
  let a = 0;
  let b = 1;
  let c = 1;
  for (let i = 0; i < n; i++) {
    [a, b, c] = [b, c, a + b + c];
  }
  return a;
}

위에서 보는 바와 같이 code-davinci-edit-001은 exponential down을 통해 함수의 실행 시간을 성공적으로 줄였습니다. 그리고 파이썬을 자바스크립트로 변환까지 했습니다.

 

OpenAI Playground에서 code-davinci-edit-001을 사용하여 코드 편집을 실험해 보세요.

OpenAI Playground

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

반응형


반응형

오늘은 Openai cookbook의 Code explanation 예제 페이지를 살펴 보겠습니다.

https://github.com/openai/openai-cookbook/blob/main/code_explanation_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Code explanation examples

GPT의 코드에 대한 이해는 많은 use case들에 적용할 수 있습니다.

 

  • Generating in-code documentation (e.g., Python docstrings, git commit messages)
  • 코드 내 문서 생성 (예 파이썬 docstrings, git commit 메세지)
  • Generating out-of-code documentation (e.g., man pages)
  • 코드 외 문서 생성 (예 매뉴얼 페이지
  • An interactive code exploration tool
  • 대화형 코드 탐색 도구
  • Communicating program results back to users via a natural language interface
  • 프로그램 결과를 자연어 인터페이스를 통해 사용자에게 다시 전달

예를 들어 당신이 한 SQL 쿼리에 대해 이해하기를 원한다면 code-davinci-002 에게 아래 예제 프롬프트를 제공하는 방법을 사용할 수 있습니다.

 

A SQL query:
```
SELECT c.customer_id
FROM Customers c
JOIN Streaming s
ON c.customer_id = s.customer_id
WHERE c.signup_date BETWEEN '2020-03-01' AND '2020-03-31'
AND s.watch_date BETWEEN c.signup_date AND DATE_ADD(c.signup_date, INTERVAL 30 DAY)
GROUP BY c.customer_id
HAVING SUM(s.watch_minutes) > 50 * 60
```

Questions:
1. What does the SQL query do?
2. Why might someone be interested in this time period?
3. Why might a company be interested in this SQL query?

Answers:

 

Output

1. The SQL query finds all customers who signed up in March 2020 and watched more than 50 hours of content in the first 30 days after signing up.
2. The time period is interesting because it is the first month of the COVID-19 pandemic.
3. A company might be interested in this SQL query because it can help them understand how the pandemic has affected their business.

Note : code-davinci-002는 instruction을 따르도록 훈련되지 않았으므로 일반적으로 output을 조정하는데 도움이 되는 예제 또는 기타 structure와 생성을 제때에 멈출 수 있게 하는 stop sequence들이 필요합니다. 더 쉽게 프롬프트 하려면 text-davinci-003을 사용하세요.

 

반응형


반응형

오늘은 Openai cookbook의 Code writing 예제들을 설명한 페이지를 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/code_writing_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

Code writing examples

 

GPT-3 는 text뿐만이 아니라 code도 작성할 수 있습니다.

code-davinci-002 모델이 SQL 쿼리를 작성하는 예제를 보여드리겠습니다.

 

SQL tables (and columns):
* Customers(customer_id, signup_date)
* Streaming(customer_id, video_id, watch_date, watch_minutes)

A well-written SQL query that lists customers who signed up during March 2020 and watched more than 50 hours of video in their first 30 days:
```

Output

SELECT c.customer_id
FROM Customers c
JOIN Streaming s
ON c.customer_id = s.customer_id
WHERE c.signup_date BETWEEN '2020-03-01' AND '2020-03-31'
AND s.watch_date BETWEEN c.signup_date AND DATE_ADD(c.signup_date, INTERVAL 30 DAY)
GROUP BY c.customer_id
HAVING SUM(s.watch_minutes) > 50 * 60

code-davinci-002는 그 변수 이름에서 초론을 할 수 있습니다. 예를 들어 watch_minutes는 분단위 데이터 이기 때문에 50시간을 계산할 때 이것에 60을 곱해서 분단위로 바꾸어야 된다고 스스로 추론할 수 있습니다.

 

더 쉬운 프롬프팅을 하려면 text-davinci-003으로도 시도해 볼 수 있습니다.

 

 

반응형


반응형

오늘 공부할 내용 원본은 아래와 같습니다.

https://github.com/openai/openai-cookbook/blob/main/text_editing_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

Text editing examples

 

 completions API endpoint 에 추가해서 OpenAI 는 edits API endpoint를 제공합니다.  자세한 사항을 아래 링크를 참조하세요.

단일 텍스트 입력값만 받는 Completions 와 달리 Edits는 두가지 입력값을 받습니다. 지시문과 수정될 텍스트 입니다. 아래 예를 보여드리겠습니다.

 

instruction input :

Fix the OCR errors

Text input

Therewassomehostilityntheenergybehindthe researchreportedinPerceptrons....Part of ourdrivecame,aswequiteplainlyacknoweldgednourbook,fromhe facthatfundingndresearchnergywerebeingdissipatedon. . .misleadingttemptsouseconnectionistmethodsnpracticalappli-cations.

Output

There was some hostility in the energy behind the research reported in Perceptrons....Part of our drive came, as we quite plainly acknowledged in our book, from the fact that funding and research energy were being dissipated on...misleading attempts to use connectionist methods in practical applications.

 

일반적으로 instructions는 명령형, 현재형 혹은 과거형 일 수 있습니다. 사용 사례마다 가장 적합한 것이 무엇인지 직접 실험해 보세요.

 

Translation

이 Edit 애플리케이션 중 하나가 번역 프로그램입니다.

Large language 모델은 common language들 간의 번역에 아주 탁월합니다.

2021년 GPT-3는 WMT14 영어 - 프랑스어 benchmark에서 자율 번역 분야에서 새로운 state-of-the-art 기록을 세웠습니다.

 

다음은 Edits endpoint를 사용하여 텍스트를 번역하는 방법에 대한 예제 입니다.

 

Instruction input

translation into French

 

Text input

That's life.

Output

C'est la vie.

물론 Edits endpoint로 할수 있는 많은 작업들이 Completion endpoint로도 수행할 수 있습니다. 예를 들어 다음과 같이 명령을 앞에 추가하여 번역을 요청할 수 있습니다.

 

Translate the following text from English to French.

English: That's life.
French:

Output

 C'est la vie.

번역을 위한 팁에는 아래와 같은 것들이 있습니다.

 

  • Performance is best on the most common languages
  • 대부분의 일반적인 언어들에 있어서의 성능은 최고 입니다.
  • We've seen better performance when the instruction is given in the final language (so if translating into French, give the instruction Traduire le texte de l'anglais au français. rather than Translate the following text from English to French.)
  • instruction이 최종 언어로 제공될 때 그 성능은 더 좋게 나오는 것을 목격했습니다. (따라서 프랑스어로 번역하는 경우 instruction을 Translate the following text from English to French 이렇게 주는 것 보다 Traduire le texte de l'anglais au français. 이렇게 주는 것이 더 효과가 좋습니다.. )
  • Backtranslation (as described here) can also increase performance
  • 역변환 (here 참조)도 성능을 향상 시킬 수 있습니다.
  • Text with colons and heavy punctuation can trip up the instruction-following models, especially if the instruction uses colons (e.g., English: {english text} French:)
  • colon과 heavy punctuation 부호가 있는 텍스트는 instruction-following 모델에 문제를 일으킬 수 있습니다. 특히 instruction이 colon을 사용하는 경우 그렇습니다. (e.g., English: {english text} French:)
  • The edits endpoint sometimes repeats the original text input alongside the translation, which can be monitored and filtered
  • Edits endpoint는 번역문과 함께 원본 텍스트를 반복할 때도 있습니다. 이는 모니터링 및 필터링을 할 수 있습니다.

번역과 관련하여 large language 모델은 번역과 함께 다른 instruction을 결합하는데 탁월합니다. 예를 들어 여러분은 GPT-3에게 Slovenian을 English로 번역할 것을 요청할 수 있습니다. 하지만 모든 LaTeX 조판 명령은 바뀌지 않습니다. 다음 Jupyter Notebook은 슬로베니아 수학책을 영어로 어떻게 번역했는지 자세히 설명합니다.

 

Translation of a Slovenian math book into English

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

 

반응형


반응형

오늘 공부할 부분은 아래 페이지 입니다.

https://github.com/openai/openai-cookbook/blob/main/text_explanation_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

Text explanation examples

Large language 모델은 긴 텍스트에서 정보를 추출하는데 유용합니다. 응용분야는 다음과 같습니다.

 

  • Answering questions about a piece of text, e.g.:
  • 텍스트 조각에 대한 질문들에 답하기, 예) 
    • Querying an knowledge base to help people look up things they don't know
    • 사람들이 모르는 것들을 찾는데 도움을 주는 지식 기반의 문의
    • Querying an unfamiliar document to understand what it contains
    • 어떤 내용인지 이해해야 되는 잘 모르는 문서에 대한 문의
    • Querying a document with structured questions in order to extract tags, classes, entities, etc.
    • 태그, 클래스, entity들을 추출하기 위한 구조화된 질문들이 있는 문서에 대한 문의
  • Summarizing text, e.g.
  • 문서 요약하기, 예 :
    • Summarizing long documents
    • 긴 문서 요약하기
    • Summarizing back-and-forth emails or message threads
    • 주고 받고 한 이메일이나 일련의 메세지를 요약하기
    • Summarizing detailed meeting notes with key points and next steps
    • 회의록을 키 포인트와 다음 단계에 대한 정보로 자세하게 요약하기
  • Classifying text, e.g.:
  • 문서 분류, 예. : 
    • Classifying customer feedback messages by topic or type
    • 고객들이 피드백 한 메세지를 주제와 유형별로 분류하기
    • Classifying documents by topic or type
    • 문서를 주제와 유형별로 분류하기
    • Classifying the tone or sentiment of text
    • 문서의 어조와 감정들을 분류하기
  • Extracting entities, e.g.:
  • Entity들을 추출하기, 예.: 
    • Extracting contact information from a customer message
    • 고객들의 메세지로부터 연락처 정보 추출하기
    • Extracting names of people or companies or products from a document
    • 문서에서 사람이나 회사 혹은 상품 이름 추출하기
    • Extracting things mentioned in customer reviews or feedback
    • 고객의 리뷰나 피드백들 속에서 언급된 것들 추출하기

다음은 위 예들에 대한 간단한 예제들 입니다.

 

Answering questions about a piece of text

아래는 텍스트 조각에 대한 질문에 대해 대답하도록 하는 프롬프트 예제 입니다.

Using the following text, answer the following question. If the answer is not contained within the text, say "I don't know."

Text:
"""
Oklo Mine (sometimes Oklo Reactor or Oklo Mines), located in Oklo, Gabon on the west coast of Central Africa, is believed to be the only natural nuclear fission reactor. Oklo consists of 16 sites at which self-sustaining nuclear fission reactions are thought to have taken place approximately 1.7 billion years ago, and ran for hundreds of thousands of years. It is estimated to have averaged under 100 kW of thermal power during that time.
"""

Question: How many natural fission reactors have ever been discovered?

Answer:

Output:

 

 One. Oklo Mine is believed to be the only natural nuclear fission reactor.

 

질문하려는 텍스트가 토큰 제한 (text-davinci-002/-003의 경우 ~4,000개 토큰 및 이전 모델의 경우 ~2,000개 토큰)보다 긴 경우 텍스트를 더 작은 조각으로 나누고 관련성에 따라 순위를 매길 수 있습니다. 그런 다음 가장 관련성이 있어 보이는 부분만 사용해서 질문하세요. 이는  Question_answering_using_embeddings.ipynb 에 설명 돼 있습니다.

 

https://coronasdk.tistory.com/1264

 

Openai cookbook - Embeddings - Text comparison examples - Question answering using embeddings

요즘은 open ai cook book 의 예제들을 살펴 보고 있습니다. 이 cookbook 페이지는 이곳입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides

coronasdk.tistory.com

 

학생들이 시험을 잘 보기 위해서 그동안 적었던 노트를 보듯이 GPT-3는 질문과 함께 텍스트를 주어주면 질문에 더 잘 답할 수 있습니다.

필기 노트가 없다면 GPT-3는 자신의 아주 긴 memory에 의존해야 합니다. (예. internal weights), 그렇게 되면 파편적인 대답 혹은 약간 뜬그룸 같은 대답을 하게 될 수 있습니다.

 

Summarization

아래는 문서를 요약하는 간단한 prompt 예제입니다.

Summarize the following text.

Text:
"""
Two independent experiments reported their results this morning at CERN, Europe's high-energy physics laboratory near Geneva in Switzerland. Both show convincing evidence of a new boson particle weighing around 125 gigaelectronvolts, which so far fits predictions of the Higgs previously made by theoretical physicists.

"As a layman I would say: 'I think we have it'. Would you agree?" Rolf-Dieter Heuer, CERN's director-general, asked the packed auditorium. The physicists assembled there burst into applause.
"""

Summary:

Output:

CERN's director-general asked a packed auditorium if they agreed that two independent experiments had found convincing evidence of a new boson particle that fits predictions of the Higgs, to which the physicists assembled there responded with applause.

 

이 예제 프롬프트에서 사용된 따옴표 3개 부호 (""") 는 특별한 것이 아닙니다. GPT-3는 <>, {}, 또는 ### 를 포함한 대부분의 구분 기호를 인식 할 수 있습니다. 긴 텍스트의 경우 이러한 구분 기호를 사용하는 것이 좋습니다. 텍스트의 한 섹션이 끝나고 다음 섹션이 시작되는 위치를 명확하게 구분하는데 도움이 됩니다.

 

Classification

텍스트를 분류하려는 경우 가장 좋은 방법은 클래스들을 미리 알고 있는지 여부에 따라 다릅니다.

클래스들을 이미 알고 있는 경우 Fine-tuned_classification.ipynb에서 설명한 것처럼 Fine-tuned 모델을 사용하여 분류하는 것이 가장 좋습니다.

클래스가 미리 알려지지 않은 경우 (예: 그것들이 사용자에 의해 세팅되거나 즉석해서 생성된 경우) 클래스들이 포함된 instruction을 제공해서 zero-shot classification을 사용할 수 있습니다. 혹은 어떤 클래스 레이블 (혹은 분류된 텍스트들)이 텍스트와 가장 유사한지를 보기 위한 임베딩을 사용해도 됩니다.  (Zero-shot_classification_with_embeddings.ipynb 에서 설명 됨)

 

Entity extraction

아래는 Entity 추출을 위한 예제 프롬프트 입니다.

From the text below, extract the following entities in the following format:
Companies: <comma-separated list of companies mentioned>
People & titles: <comma-separated list of people mentioned (with their titles or roles appended in parentheses)>

Text:
"""
In March 1981, United States v. AT&T came to trial under Assistant Attorney General William Baxter. AT&T chairman Charles L. Brown thought the company would be gutted. He realized that AT&T would lose and, in December 1981, resumed negotiations with the Justice Department. Reaching an agreement less than a month later, Brown agreed to divestiture—the best and only realistic alternative. AT&T's decision allowed it to retain its research and manufacturing arms. The decree, titled the Modification of Final Judgment, was an adjustment of the Consent Decree of 14 January 1956. Judge Harold H. Greene was given the authority over the modified decree....

In 1982, the U.S. government announced that AT&T would cease to exist as a monopolistic entity. On 1 January 1984, it was split into seven smaller regional companies, Bell South, Bell Atlantic, NYNEX, American Information Technologies, Southwestern Bell, US West, and Pacific Telesis, to handle regional phone services in the U.S. AT&T retains control of its long distance services, but was no longer protected from competition.
"""

Output:

Companies: AT&T, Bell South, Bell Atlantic, NYNEX, American Information Technologies, Southwestern Bell, US West, Pacific Telesis
People & titles: William Baxter (Assistant Attorney General), Charles L. Brown (AT&T chairman), Harold H. Greene (Judge)

 

 

반응형


반응형

오늘 다룰 내용 원본은 아래 페이지입니다.

 

https://github.com/openai/openai-cookbook/blob/main/text_writing_examples.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

Text writing examples

Large language 모델들은 writing에 아주 탁월합니다. 그들은 모든 종류의 작업을 지원할 수 있습니다.

 

  • Blog posts
  • Email copy
  • Ad copy
  • Website copy
  • Product descriptions
  • Memos
  • Storytelling
  • Brainstorming
  • Question generation
  • etc.

GPT-3에서 prompt 하는 가장 쉬운 방법은 여러분이 하고 싶은 말을 하는 것입니다. 예를 들어 여러분이 이메일을 쓰기를 원한다면 아래와 같이 프롬프트를 사용할 수 있습니다.

Write an email to a colleague named Jill congratulating her on her promotion. The tone should be warm yet professional. Mention how you admire the work she's been putting in.  Include a joke about how her pet lizard Max enjoys eating grasshoppers. Mention how you're looking forward to the team off-site next week.

Output:

Subject: Congratulations on Your Promotion, Jill!

Dear Jill,

Congratulations on your promotion! I'm so proud of you and all the hard work you've been putting in. It's been inspiring to watch you grow in your career.

I'm sure Max the lizard is also celebrating with you. I hear he loves eating grasshoppers, so you should treat him to a special snack!

I'm looking forward to seeing you at the team off-site next week. I'm sure it will be a great opportunity to celebrate your success.

All the best,

[Your Name]

일반적으로 writing은 어떤 스타일의 prompt에도 작동합니다. 그것이 어떤 지시 (instruction)이든 따라야 할 일련의 예제들이든 관계 없이 작동합니다. 여러분이 하고 싶은 것을 실현하기 위해 가장 잘 작동 시킬 수 있는 방법은 무엇인지 직접 실험 해 보세요.

 

Writing은 또한 모든 유형의 모델들과 같이 작동할 수 있지만 각각 장 단점이 있습니다.

 

AdvantagesDisadvantages

Instruction-following models
(e.g., text-davinci-003)
Easiest to use Less diverse; less creative; sometimes harder to steer tone, style, etc.
Base models
(e.g., davinci)
Potentially more creative and diverse Harder to prompt well, more expensive (as examples in the prompt cost extra tokens)
Fine-tuned models Can train off of many examples; cheaper than including examples in the prompt Hard to gather training data; training makes iteration slower and more expensive

 

반응형


반응형

오늘 공부할 내용은 답변의 신뢰성을 높이기 위한 여러 방법들을 알아보는 겁니다.

실습보다는 이론적인 것들이 많은 것 같습니다.

내용이 좀 긴데 일단 한번 시작해 보겠습니다.

원본 페이지는 이곳입니다.

 

https://github.com/openai/openai-cookbook/blob/main/techniques_to_improve_reliability.md

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Techniques to improve reliability

 

GPT-3가 작업에 실패하면 여러분은 어떻게 해야 할까요?

 

  • Search for a better prompt that elicits more reliable answers?
  • 좀더 신뢰할 수 있는 답변을 이끌어내기 위해 더 좋은 prompt를 찾으시겠습니까?
  • Invest in thousands of examples to fine-tune a custom model?
  • custom 모델로 fine-tune 하기 위해 수천개의 예제들을 마련하는 일을 하시겠습니까?
  • Assume the model is incapable of the task, and move on?
  • 해당 모델이 그 작업에 적당하지 않다고 가정하고 그냥 진행 하시겠습니까?

간단하게 답할 수 있는 문제가 아닙니다. 상황에 따라 다르니까요. 하여간 여러분의 작업에 논리적 추론이나 복잡성이 있다면 좀 더 신뢰성 있는 결과를 도출하기 위해 그리고 고성능 prompt를 만들기 위해 이 글에서 제시하는 기술들을 고려해 보세요.

 

Why GPT-3 fails on complex tasks

GPT-3는 왜 복잡한 작업에 대해 실패 할까요?

 

여러분은 13 곱하기 17이 무엇이냐고 물으면 즉시 답할 수 있습니까?

대부분의 사람들은 그렇지 못할 겁니다. 그렇다고 해서 인간이 두자릿수 곱셈을 못 하는 것은 아닙니다.

몇초의 시간과 종이와 연필만 있으면 13 x 17 = 130 + 70 + 21 = 221 이라는 계산을 하는 것은 그리 어렵지 않습니다.

 

마찬가지로 GPT-3도 다음 token을 계산하는데 너무 복잡한 임무를 부여하면  잘못된 추측을 만들 수 있습니다. 위의 인간의 예와 마찬가지로 이것이 GPT-3가 해당 작업을 수행하지 못하는 것을 의미하는 것은 아닙니다. 문제를 추론할 충분한 시간과 공간이 있으면 그 모델은 여전히 안정적으로 대답할 수 있습니다.

 

예를 들어 text-davinci-002에게 저글링 공에 대한 다음 수학 문제를 묻는 다면 아마 대답을 잘 못 할 겁니다.

Q: A juggler has 16 balls. Half of the balls are golf balls and half of the golf balls are blue. How many blue golf balls are there?
A:
There are 8 blue golf balls.

16개의 공 중에 반은 골프공이다. 그리고 골프공의 반은 파란색이다. 파란 골프 공은 몇개가 있을까?

8개의 파란 골프공이 있다.

==> 이 대답은 틀렸죠. 8개 골프공 중에 반이 파란색이니까 4개가 되겠죠.

 

Q: A juggler has 16 balls. Half of the balls are golf balls and half of the golf balls are blue. How many blue golf balls are there?
A: Let's think step by step.
There are 16 balls in total. 
Half of the balls are golf balls. 
That means that there are 8 golf balls. 
Half of the golf balls are blue. 
That means that there are 4 blue golf balls.

이렇게 스텝 바이 스텝으로 생각하면 제대로 된 대답을 내 놓습니다.

 

물론 이 단계별 트릭이 일반적으로 적용되는 경우인지 혹은 운 좋게 특정 경우에만 적용 된 것인지는 이 한가지 예만 가지고 판단하기 어렵습니다. 어쨌든 이 질문에 대해서는 효과가 있었습니다. 이런식의 단어로 된 수학문제에서 이렇게 스텝 바이 스텝으로 생각하도록 함으로서 GPT-3가 문제를 제대로 해결하는 비율이 무의미한 18%에서 유의미한 79%로 엄청나게 높아 졌습니다.

 

Model capabilities depend on context

GPT-3으로 작업하는 방법을 배울 때 흔히 발생하는 개념적 실수 중 하나는 GPT-3의 기능이 모든 컨텍스트에서 고정되어 있다고 믿는 것입니다. 예를 들어 GPT-3가 간단한 논리 질문을 틀린다면 GPT-3는 간단한 논리 질문에 적합하지 않은것이다 라고 생각하는 것.

 

Let's think step by step 예제에서 알 수 있듯이 GPT-3의 명백한 오류는 때때로 올바른 output을 내 오는데 대해 스스로 조종하는 것에 도움이 되는 좀 더 나은 prompt줄 제공함으로서 해결될 수 있습니다.

 

How to improve reliability on complex tasks

이 문서의 나머지 부분에서는 복잡한 작업에서 Large language 모델의 신뢰성(안정성)을 개선할 수 있는 기술들을 공유합니다.

일부 기술은 특정 유형의 문제에만 적용 되지만 대부분은 다음과 같이 광범위한 상황에 적용할 수 있는 일반 원칙을 기반으로 합니다.

  • Give clearer instructions
  • 명확하게 지시한다.
  • Split complex tasks into simpler subtasks
  • 복잡한 임무는 좀 더 간단한 작은 임무들로 나눈다.
  • Structure the instruction to keep the model on task
  • 모델이 작업을 계속 수행할 수 있도록 지시를 구조화 한다.
  • Prompt the model to explain before answering
  • 모델이 대답을 하기전에 설명을 하도록 요구하는 내용을 Prompt에 넣어 작성한다.
  • Ask for justifications of many possible answers, and then synthesize
  • 많은 가능한 응답들의 정당성을 묻고 그것들을 종합한다.
  • Generate many outputs, and then use the model to pick the best one
  • 많은 output들을 생성한다. 그리고 모델을 사용해서 그 중에 가장 좋은 것을 선택하도록 한다.
  • Fine-tune custom models to maximize performance
  • Fine-tune 커스텀 모델로 성능을 최대화 한다.

Split complex tasks into simpler tasks

모델에게 생각할 시간과 space를 좀 더 많이 주는 방법 중 하나는 더 간단한 조각들로 임무를 나누는 것입니다.

 

예를 들어 어떤 텍스트에 대해 여러 가지의 보기를 주고 모델에게 물어본다고 했을 때를 생각해 보세요. (아래 예제 참조) 그냥 주관식으로 물어 본다면 text-davinci-002는 그 중 3번과 5번을 고를 수가 없습니다. 이렇게 되면 잘못된 대답을 할 확률이 높아 집니다.

하지만 보기를 5개를 주고 그 중 3번과 5번이 답이라면 text-davinci-002는 그 3번과 5번을 선택하던가 그 둘을 종합해서 좀 더 정답에 가깝거나 완전한 정답을 output으로 내 놓을 수 있습니다.

Use the following clues to answer the following multiple-choice question.
 
Clues:
1. Miss Scarlett was the only person in the lounge.
2. The person with the pipe was in the kitchen.
3. Colonel Mustard was the only person in the observatory.
4. Professor Plum was not in the library nor the billiard room.
5. The person with the candlestick was in the observatory.
 
Question: Was Colonel Mustard in the observatory with the candlestick?
(a) Yes; Colonel Mustard was in the observatory with the candlestick
(b) No; Colonel Mustard was not in the observatory with the candlestick
(c) Unknown; there is not enough information to determine whether Colonel Mustard was in the observatory with the candlestick
 
Solution:
(c) Unknown; there is not enough information to determine whether Colonel Mustard was in the observatory with the candlestick

 

3번과 5번이 Mustard 대령이 천문대에 있는 유일한 사람이고 천문데애 있는 사람이 촛대를 가지고 있다는 것을 설명하고 있지만 모델은 그것을 (a) Yes; .. 라고 정답으로 결함하지 못합니다.

 

이렇게 직접 묻는 대신 작업을 세 부분으로 나눌 수 있습니다.

 

  • First, go through the clues one by one and consider whether the clue is potentially relevant
  • 먼저 단서를 하나씩 살펴보고 단서가 잠재적으로 관련이 있는지 고려 하세요.
  • Second, combine the relevant clues to reason out the answer to the question\
  • 두번째로 관련 단서를 결합하여 질문에 대한 답을 추론하세요.
  • Third, write the final answer: either (a), (b), or (c)
  • 셋째 (a),(b) 혹은 (c) 중 하나의 최종 답변을 작성합니다.
Use the following clues to answer the following multiple-choice question, using the following procedure:
(1) First, go through the clues one by one and consider whether the clue is potentially relevant
(2) Second, combine the relevant clues to reason out the answer to the question
(3) Third, map the answer to one of the multiple choice answers: either (a), (b), or (c)
 
Clues:
1. Miss Scarlett was the only person in the lounge.
2. The person with the pipe was in the kitchen.
3. Colonel Mustard was the only person in the observatory.
4. Professor Plum was not in the library nor the billiard room.
5. The person with the candlestick was in the observatory.
 
Question: Was Colonel Mustard in the observatory with the candlestick?
(a) Yes; Colonel Mustard was in the observatory with the candlestick
(b) No; Colonel Mustard was not in the observatory with the candlestick
(c) Unknown; there is not enough information to determine whether Colonel Mustard was in the observatory with the candlestick
 
Solution:
(1) First, go through the clues one by one and consider whether the clue is potentially relevant:
Clue 1: Miss Scarlett was the only person in the lounge. This clue is not relevant.
Clue 2: The person with the pipe was in the kitchen. This clue is not relevant.
Clue 3: Colonel Mustard was the only person in the observatory. This clue is relevant.
Clue 4: Professor Plum was not in the library nor the billiard room. This clue is not relevant.
Clue 5: The person with the candlestick was in the observatory. This clue is relevant.
 
(2) Second, combine the relevant clues to reason out the answer to the question:
Clue 3 and Clue 5 both say that the person with the candlestick was in the observatory. Colonel Mustard was the only person in the observatory, so Colonel Mustard was the person with the candlestick.
 
(3) Third, write the final answer:
(a) Yes; Colonel Mustard was in the observatory with the candlestick

모델에게 생각할 시간과 공간을 더 주고 reasoning plan (추론 계획)에 따르는 가이드를 제공함으로써 모델은 (a) 라는 정답을 알아낼 수 있습니다.

 

복잡한 명령을 더 작은 하위 작업으로 분할하는 또 다른 잇점은 모델이 각 하위 작업에 집중하도록 도울 수 있다는 것입니다.

 

예를 들어 우리가 text-davinci-002에게 원래의 언어로 텍스트를 요약해달라고 부탁하면 모델은 다시 영어로 전환 될 수 있습니다.

 

Summarize the text using the original language of the text. The summary should be one sentence long.

Text:
"""
La estadística (la forma femenina del término alemán Statistik, derivado a su vez del italiano statista, "hombre de Estado")​ es una ciencia que estudia la variabilidad, colección, organización, análisis, interpretación, y presentación de los datos, así como el proceso aleatorio que los genera siguiendo las leyes de la probabilidad.​ La estadística es una ciencia formal deductiva, con un conocimiento propio, dinámico y en continuo desarrollo obtenido a través del método científico formal. En ocasiones, las ciencias fácticas necesitan utilizar técnicas estadísticas durante su proceso de investigación factual, con el fin de obtener nuevos conocimientos basados en la experimentación y en la observación. En estos casos, la aplicación de la estadística permite el análisis de datos provenientes de una muestra representativa, que busca explicar las correlaciones y dependencias de un fenómeno físico o natural, de ocurrencia en forma aleatoria o condicional.
"""

Summary:
The text explains that statistics is a science that studies the variability, collection, organization, analysis, interpretation, and presentation of data, as well as the random process that generates them following the laws of probability.

 

여기서 일단 모델에게 해당 언어를 판별하라고 지시할 수 있습니다. 그리고 난 후 그 내용을 요약하라고 하면 좀 더 신뢰도가 높은 답변을 얻을 수 있습니다.

First, identify the language of the text. Second, summarize the text using the original language of the text. The summary should be one sentence long.

Text:
"""
La estadística (la forma femenina del término alemán Statistik, derivado a su vez del italiano statista, "hombre de Estado")​ es una ciencia que estudia la variabilidad, colección, organización, análisis, interpretación, y presentación de los datos, así como el proceso aleatorio que los genera siguiendo las leyes de la probabilidad.​ La estadística es una ciencia formal deductiva, con un conocimiento propio, dinámico y en continuo desarrollo obtenido a través del método científico formal. En ocasiones, las ciencias fácticas necesitan utilizar técnicas estadísticas durante su proceso de investigación factual, con el fin de obtener nuevos conocimientos basados en la experimentación y en la observación. En estos casos, la aplicación de la estadística permite el análisis de datos provenientes de una muestra representativa, que busca explicar las correlaciones y dependencias de un fenómeno físico o natural, de ocurrencia en forma aleatoria o condicional.
"""

Language:
Spanish

La estadística es una ciencia que estudia la variabilidad, colección, organización, análisis, interpretación, y presentación de los datos, así como el proceso aleatorio que los genera siguiendo las leyes de la probabilidad.

 

Prompt the model to explain before answering

답변의 신뢰도를 향상 시킬 수 있는 또 다른 강력한 기술은 모델이 최종 답변을 곧바로 하도록 하는 대신 점진적으로 답변을 추론하도록 유도하는 것입니다.

Thinking aloud를 통해서 모델은 더 맞는 답에 도달할 가능성이 훨씬 커집니다.

 

Zero-shot

Method

Takeshi Kojima 등이 2022년에 발표한 모델이 더 옳은 답을 추론하도록 유도하는 가장 쉬운 방법을 보면 답 앞에 Let's think step by step을 추가 하는 것입니다.

그림 2는 이 예를 보여 줍니다.

Source:&nbsp;Large Language Models are Zero-Shot Reasoners&nbsp;by Takeshi Kojima et al. (2022).

Source: Large Language Models are Zero-Shot Reasoners by Takeshi Kojima et al. (2022).

 

Large Language Models are Zero-Shot Reasoners

Pretrained large language models (LLMs) are widely used in many sub-fields of natural language processing (NLP) and generally known as excellent few-shot learners with task-specific exemplars. Notably, chain of thought (CoT) prompting, a recent technique f

arxiv.org

 

Results

저자는 이 간단한 트릭을 MultiArith 수학 데이터 세트에 적용하여 Let's think step by step으로 정확도를 18%에서 79%로 4배로 높였다는 사실을 발견했습니다.

Source:&nbsp;Large Language Models are Zero-Shot Reasoners&nbsp;by Takeshi Kojima et al. (2022).

 

Implications

이 Let's think step by step 트릭이 수학 문제 에서는 잘 작동한다고 모든 작업에 효과적으로 적용 될 수 있는 것은 아닙니다. 저자는 이 방법이 multi-step 산술 문제, 상징적 추론 문제, 전략 문제 그리고 다른 추론 문제들에 아주 유용하게 적용될 수 있다는 것을 발견했습니다. 아주 간단한 수학문제나 아주 상식적인 질문에는 도움이 되지 않았으며 아마도 다른 많은 비추론 작업에도 도움이 되지 않을 것입니다.

Source:&nbsp;Large Language Models are Zero-Shot Reasoners&nbsp;by Takeshi Kojima et al. (2022).

 

논문 전체를 보려면 여기를 참조하세요.

full paper.

 

Large Language Models are Zero-Shot Reasoners

Pretrained large language models (LLMs) are widely used in many sub-fields of natural language processing (NLP) and generally known as excellent few-shot learners with task-specific exemplars. Notably, chain of thought (CoT) prompting, a recent technique f

arxiv.org

 

이 테크닉을 자신의 작업에 적용하는 경우 instruction을 customizing 하는 실험을 두려워 하지 마세요. Let's think step by step은 오히려 일반적입니다. 사용사례에 맞게 맞춤화 된 보다 엄격한 형식을 따르는 instruction을 통해 더 나은 성능을 찾을 수 있습니다. 예를 들어 더 구조화된 변형을 시도할 수 있다면 첫번째 X가 참일 수 있는 이유에 대해 Step by Step으로 생각 해 보세요.  두번째로 왜 Y가 참일 수 있는지를 step by step 으로 생각합니다. 그리고 세번쨰로 X 나 Y 중 어느게 더 나은지에 대해 step by step으로 생각하는 겁니다. 그리고 이 과정을 계속 이어나가는 예제 형식의 모델을 제공할 수도 있습니다.

예:

Using the IRS guidance below, answer the following questions using this format:
(1) For each criterion, determine whether it is met by the vehicle purchase
- {Criterion} Let's think step by step. {explanation} {yes or no, or if the question does not apply then N/A}.
(2) After considering each criterion in turn, phrase the final answer as "Because of {reasons}, the answer is likely {yes or no}."

IRS guidance:
"""
You may be eligible for a federal tax credit under Section 30D if you purchased a car or truck that meets the following criteria:
- Does the vehicle have at least four wheels?
- Does the vehicle weigh less than 14,000 pounds?
- Does the vehicle draw energy from a battery with at least 4 kilowatt hours that may be recharged from an external source?
- Was the vehicle purchased in a year before 2022?
  - If so, has the manufacturer sold less than 200,000 qualifying vehicles? (Tesla and GM have sold more than 200,000 qualifying vehicles.)
- Was the vehicle purchased in a year after 2022?
  - If so, is the vehicle present in the following list of North American-assembled vehicles? (The only electric vehicles assembled in North America are the Audi Q5, BMW 330e, BMW X5, Chevrolet Bolt EUV, Chevrolet Bolt EV, Chrysler Pacifica PHEV, Ford Escape PHEV, Ford F Series, Ford Mustang MACH E, Ford Transit Van, GMC Hummer Pickup, GMC Hummer SUV, Jeep Grand Cherokee PHEV, Jeep Wrangler PHEV, Lincoln Aviator PHEV, Lincoln Corsair Plug-in, Lucid Air, Nissan Leaf, Rivian EDV, Rivian R1S, Rivian R1T, Tesla Model 3, Tesla Model S, Tesla Model X, Tesla Model Y, Volvo S60, BMW 330e, Bolt EV, Cadillac Lyriq, Mercedes EQS SUV, and Nissan Leaf.)
"""

Question: Can I claim a federal tax credit for my Toyota Prius Prime bought in 2021?

Solution:

(1) For each criterion, determine whether it is met by the vehicle purchase
- Does the vehicle have at least four wheels? Let's think step by step.
 The Toyota Prius Prime has four wheels, so the answer is yes.
- Does the vehicle weigh less than 14,000 pounds? Let's think step by step. The Toyota Prius Prime weighs less than 14,000 pounds, so the answer is yes.
- Does the vehicle draw energy from a battery with at least 4 kilowatt hours that may be recharged from an external source? Let's think step by step. The Toyota Prius Prime has a battery with at least 4 kilowatt hours that may be recharged from an external source, so the answer is yes.
- Was the vehicle purchased in a year before 2022? Let's think step by step. The Toyota Prius Prime was purchased in 2021, which is before 2022, so the answer is yes.
- Was the vehicle purchased in a year after 2022? N/A
- If so, is the vehicle present in the following list of North American-assembled vehicles? N/A

(2) After considering each criterion in turn, phrase the final answer as "Because of {reasons}, the answer is likely {yes or no}."

Because the Toyota Prius Prime meets all of the criteria for a federal tax credit, the answer is likely yes.

 

Few-shot examples

Method

모델이 답을 추론하도록 유도하는 방법은 여러가지가 있습니다. 그 중 하나는 Jason Wei와 Denny Zhou 등이 구글에서 연구한 몇가지 예 (few-shot) 로 시연하는 것입니다. 다음은 few-shot 의 chain-of-thought 프롬프트 입니다.

Source: Chain of Thought Prompting Elicits Reasoning in Large Language Models Jason Wei and Denny Zhou et al. (2022)

 

인간 labeler가 적성한 reasoning chain의 추가 시연

 

 

Source: Chain of Thought Prompting Elicits Reasoning in Large Language Models Jason Wei and Denny Zhou et al. (2022)

(Note that it has been called into question whether pears actually float)

 

Results

초등학교 수학 문제를 테스트 한 결과, 저자들은 chain of thought 프롬프트가 해결률을 18%에서 57%로 세배 높인다는 사실을 발견했습니다.

 

Source: Chain of Thought Prompting Elicits Reasoning in Large Language Models Jason Wei and Denny Zhou et al. (2022)

 

 

수학 문제 외에도  chain of thought 프롬프트는 스포츠에 대한 이해, 동전 던지기 tracking 및 마지막 문자 연결과 관련된 질문에 대한 성과를 높였습니다. 대부분의 경우 성능 향상을 충족 시키는 데 필요한 예제가 많지 않았습니다(8 미만 정도).

 

Source: Chain of Thought Prompting Elicits Reasoning in Large Language Models Jason Wei and Denny Zhou et al. (2022)

To learn more, read the full paper.

 

Implications

Let's thin step by step 테크닉과 비교해서 few-shot example-based 접근법에는 한가지 강점은 format, length 그리고 추론의 스타일을 좀 더 쉽게 특정할 수 있다는 것입니다. 이 작업은 최종 답변을 확정하기 전에 모델이 하는 사전 작업입니다. 이것은 모델이 초기 추론을 깊게 혹은 옳은 방향이 아닌 쪽으로 할 경우 특히 도움이 됩니다.

 

Fine-tuned

Method

일반적으로 최대 성능을 얻으려면 fine-tune a custom 모델을 사용할 필요가 있습니다. 그런데 모델을 fine-tuning 하는 것은 작성하는데 비용이 드는 예제 explanation들을 수천개 이상을 사용해야 합니다.

 

2022년 Eric Zelikman과 Yuhuai We et al 은 모델을 fine-tune 하는데 사용될 수 있는 explanation 데이터 세트를 생성하기 위한 few-shot 프롬프트를 사용하기 위한 아주 현명한 procedure를 발표했습니다. 그것은 후보 explanation들을 생성하기 위한 few-shot 프롬프트를 사용하자는 아이디어 입니다. 그 후보 explanation들 중 정답을 생산한 explanation들만 keep 한다는 아이디어죠.

그 다음 오답에 대한 추가적인 explanation들을 얻기 위해 few-shot 프롬프트를 retry 하는 겁니다. 정답은 질문의 일 부분으로서 제공되게 됩니다. 저자들은 그 절차를 STaR(Self-taught Reasoner) 절차라고 부릅니다.

 

Source: STaR: Bootstrapping Reasoning With Reasoning by Eric Zelikman and Yujuai Wu et al. (2022)

 

STaR: Bootstrapping Reasoning With Reasoning

Generating step-by-step "chain-of-thought" rationales improves language model performance on complex reasoning tasks like mathematics or commonsense question-answering. However, inducing language model rationale generation currently requires either constru

arxiv.org

이 기술을 사용하면 수천개의 example explanation들을 작성할 필요 없습니다. 그러기 위해서 fine-tune의 강점과 chain-of-thought 프롬프팅의 장점을 결합할 수 있습니다.

 

Results

저자들이 이 기술을 Common Sense Q&A 데이타 세트에 적용 했을 때 그들은 이 STaR이 chain-of-thought 프롬프트만 사용했을 때 와 fine-tuning 만을 사용했을 때 보다 성능이 더 뛰어나게 나타난 다는 것을 발견했습니다. (73% > 37% , 73% > 60%)

 

Source: STaR: Bootstrapping Reasoning With Reasoning by Eric Zelikman and Yujuai Wu et al. (2022)

To learn more, read the full paper

 

STaR: Bootstrapping Reasoning With Reasoning

Generating step-by-step "chain-of-thought" rationales improves language model performance on complex reasoning tasks like mathematics or commonsense question-answering. However, inducing language model rationale generation currently requires either constru

arxiv.org

 

Implications

fine-tuning 데이터세트를 확장하거나 수정하기 위해 few-shot 프롬프트를 사용하는 것은 explanation 작성을 뛰어 넘어 일반화할 수 있게 해 주는 아이디어 입니다. 예를 들어 여러분이 train 하기 위한 구조화 되지 않은 텍스트를 많이 가지고 있는 경우 프롬프트를 이용해서 구조화되지 않은 텍스트에서 구조화 된 데이터 세트를 추출한 다음 그 구조화 된 데이터 세트에서 custom 모델을 fine-tune 하는 것입니다.

 

Extensions to chain-of-thought prompting

이 외에 chain-of-thought 의 확장관련한 발표도 몇개 더 있습니다.

 

Selection-inference prompting

Method

Published by Antonia Creswell et al., one extension of the chain-of-thought technique is to split the single prompt for generating explanations and answers into smaller parts. First, a prompt selects a relevant subset of facts from the text ('selection prompt'). Then, a second prompt infers a conclusion from the selected facts ('inference prompt'). These prompts are then alternated in a loop to generate multiple steps of reasoning and eventually land on a final answer. The authors illustrate the idea in the following figure:

 

Antonia Creswell 등이 발표한 chain-of-thought 테크닉의 확장은 explanation들을 생성하기 위해 단일 프롬프트를 분할하는 것입니다. 그 답변들은 좀 더 작은 부분으로 분할 되는 것이죠. 우선 프롬프트는 텍스트 (selection prompt)로부터 연관된 fact의 subset를 선택합니다. 그런 다음 두번째 프롬프트가 선택된 사실(inference prompt) 에서 결론을 추론합니다. 그런 다음 이러한 프롬프트는 루프에서 번갈아 가며 여러단계의 추론을 생성하고 결국 최종 답변에 도달합니다. 저자는 아래 그림으로 그 아이디어를 설명합니다.

 

Source: Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning by Antonia Creswell et al. (2022)

 

Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning

Large language models (LLMs) have been shown to be capable of impressive few-shot generalisation to new tasks. However, they still tend to perform poorly on multi-step logical reasoning problems. Here we carry out a comprehensive evaluation of LLMs on 50 t

arxiv.org

 

Results

7B-parameter 모델을 적용 했을 때 저자들은 selection-interference 프롬프팅이 bAbi 와 Proof Writer benchmark task들에 대해 chain-of-thought 프롬프팅과 비교해서 대체적으로 성능이 향상된다는 것을 발견했습니다.

(bAbi와 Proof Writer benchmark task들은 둘 다 더 긴 일련의 추론 단계들이 더 필요합니다.)

그들이 달성한 최고의 성능은 fine-tuning과 함께 selection-interferne 프롬프팅을 결합했을 때 달성했습니다.

Source: Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning by Antonia Creswell et al. (2022)

 

Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning

Large language models (LLMs) have been shown to be capable of impressive few-shot generalisation to new tasks. However, they still tend to perform poorly on multi-step logical reasoning problems. Here we carry out a comprehensive evaluation of LLMs on 50 t

arxiv.org

 

Implications

이러한 benchmark들로부터 얻는 이득은 컸고, 특히 더 긴 추론 sequence들이 필요한 경우에 선택 됐습니다. 많은 단계의 추론을 요구하지 않는 문제들에 대해서는 그 이득이 더 적을 수 있습니다.

 

결과는 large language 모델들에 대한 몇가지 일반적인 lessons를 강조합니다.

첫번째, 복잡한 작업을 더 작은 작업으로 나누는 것은 안정성과 성능을 향상시키는 좋은 방법 입니다.

작업이 더 atomic 할 수록 모델이 에러를 낼만한 공간이 더 줄어들게 되는 겁니다. 

두번째 최대 성능을 얻는 것은 종종 fine-tuning을 당신 이 선택한 다른 접근법과 결합함으로서 얻어질 수 있다는 것을 의미합니다.

 

좀 더 자세한 사항은 아래 문서를 참조하세요.  full paper

 

Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning

Large language models (LLMs) have been shown to be capable of impressive few-shot generalisation to new tasks. However, they still tend to perform poorly on multi-step logical reasoning problems. Here we carry out a comprehensive evaluation of LLMs on 50 t

arxiv.org

 

Faithful reasoning architecture

selection-inference 프롬프팅 테크닉을 발표한 다음 몇달 후 저자는 다음 논문에서 테크닉을 확장할 수 있는 다음과 같은 아이디어를 발표 했습니다.

 

  • figuring out when the selection-inference cycle should stop or continue
  • selection-inference 사이클이 언제 중단되고 언제 계속 되어야 하는지 알아내기
  • adding a value function to help search over multiple reasoning paths
  • 여러 추론 경로들에 대해 검색하는 것을 돕기 위한 value function 추가하기
  • reducing hallucination of fake facts by fine-tuning a model to reason about sentence labels (e.g., sen1) rather than writing out the sentences themselves
  • 문장 자체를 작성하는 대신 문장 레이블에 대한 추론을 위한 모델을 fine-tuning 함으로서 fake fact들의 hallucination (환각) 를 감소시키기

Method

In the original selection-inference technique, specialized 'selection' and 'inference' prompts are alternated to select facts and make inferences from those facts, combining to generate a sequence of reasoning steps.

 

오리지널 selection-inference 테크닉에서는 특별한 'selection' 과 'inference' (추론) 프롬프트 들은 fact들을 선택하는 것과 그러한 fact들을 가지고 추론을 만드는 것을 번갈아 가면서 하고 이 추론 과정들의 sequence를 발생시키기 위해 결합합니다.

저자들은 이 테크닉을 2개의 추가 구성 요소들로 확장합니다.

 

첫째, 저자들은 각각의 추론 단계 이후 'halter' 모델을 추가합니다. 이것은 이 추론들이 그 질문에 대한 대답으로서 충분한 것인지를 질문하기 위함입니다.

 

이 halter 모델은 몇가지 장점들이 있습니다.

 

  • it can tell the selection-inference process to stop or keep going, as necessary.
  • 이것은 필요에 따라 중지 하거나 아니면 계속 진행하기 위한 selection-inference 프로세스인지 여부를 알려 줄 수 있습니다.
  • if the process never halts, you'll get no answer, which is often preferable to a hallucinated guess
  • 만약 그 프로세스가 중단되지 않는다면 답을 얻지 못할 것입니다. 이것이 hallucinated guess 보다 나은 경우가 있기는 합니다.

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

 

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

 

두번쨰로 저자는 reasoning step (추론 단계)의 품질을 평가하고 여러 reasoning trajectory들을 검색하는데 사용되는 value 함수를 추가합니다. 이는 신뢰성(안정성)을 증가시키기 위한 일반적인 주제에 대한 대답입니다.

모델에서 single answer를 발생시키는 대신 여러 답변들을 발생시키고 여러 종류의 value function/discriminator/verifier 모델을 사용하는 겁니다.

 

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

 

이 두가지 확장에다가 추가적으로 저자들은 또한 fake fact들의 hallucination을 감소시키기 위한 트릭을 사용합니다. 모델에게 factual sentence들을 작성하도록 요구하는 대신 sentence label (e.g. sen1)들로 작업을 하도록 모델을 fine-tune 합니다. 이렇게 하면 프롬프트 context에 언급되지 않은 fake fact들을 hallucinating 하는 것을 방지하는데 도움이 됩니다.

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

Results

저자들은 두가지 benchmark들에 대한 자신들의 테크닉을  평가했습니다. 이 두가지 benchmark들은 ProofWriter task (not shown) 와 EntailmentBankQA (shown) 가 그 두가지 benchmark 들인데요. 

이 기술은 특히 더 어려운 추론 문제들에 대한 정확도를 높였습니다.

 

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)](https://arxiv.org/abs/2208.14271)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

또한 그들의 sentence label manipulation 트릭은 hallucination을 본질적으로 제거했습니다.

Source: Faithful Reasoning Using Large Language Models by Antonia Creswell et al. (2022)](https://arxiv.org/abs/2208.14271)

 

Faithful Reasoning Using Large Language Models

Although contemporary large language models (LMs) demonstrate impressive question-answering capabilities, their answers are typically the product of a single call to the model. This entails an unwelcome degree of opacity and compromises performance, especi

arxiv.org

 

Implications

이 논문은 large language 모델의 신뢰도를 개선시키는데 도움이 되는 여러가지 배울점들을 설명합니다.

  • Split complex tasks into smaller, more reliable subtasks
  • 복잡한 작업을 더 작고 안정적인 하위 작업으로 분할한다.
  • Generate your answer in a step-by-step fashion, evaluating it along the way
  • 스텝 바이 스텝 방식으로 답을 생성하고 그 과정에서 답을 평가한다.
  • Generate many possible answers and use another model or function to pick the ones that look best
  • 많은 가능한 답을 생성하고 그 중 가정 좋은 답을 다른 모델이나 function을 사용해서 선택한다.
  • Reduce hallucination by constraining what the model can say (e.g., by using sentence labels instead of sentences)
  • sentence 가 아니라 sentence label을 사용함으로서 모델의 말에 제한을 가함으로서 hallucination을 줄입니다.
  • Maximize performance of models by fine-tuning them on specialized tasks
  • 특정 임무들에 대해 fine-tuning 함으로서 그 모델의 성능을 최대화 합니다.

To learn more, read the full paper.

 

Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning

Large language models (LLMs) have been shown to be capable of impressive few-shot generalisation to new tasks. However, they still tend to perform poorly on multi-step logical reasoning problems. Here we carry out a comprehensive evaluation of LLMs on 50 t

arxiv.org

 

Least-to-most prompting

selectio-inference 에서는 잘 작동 하지만 긴 reasoning chains 에서는 제대로 작동 안하는 것에 더해서 chain-of-thought 프롬프팅은 task는 긴데 examples 는 짧을 때 특히 어려움을 겪을 수도 있습니다.

 

Method

Least-to-most 프롬프팅은 reasoning 임무를 좀 더 작고 신뢰할 수 있는 subtasks들로 분할하는 또 다른 기술입니다. 

이 아이디어는 To solve {question}, we need to first solve:   같은 프롬프팅에 의해 모델로부터 subtask를 반복하는 그런 아이디어 입니다. 그런 다음 해당 subtask를 사용하여 모델은 해결책을 만들어낼 수 있게 되는 겁니다.

솔루션 (해결책)은 원래의 question (질문) 에 추가 되고 이 프로세스는 최후 답변이 만들어 질 때까지 반복 됩니다.

 

Source: Least-to-most Prompting Enables Complex Reasoning in Large Language Models by Denny Zhou et al. (2022)

 

Least-to-Most Prompting Enables Complex Reasoning in Large Language Models

Although chain-of-thought prompting has shown impressive results on many natural language reasoning tasks, it often performs poorly on tasks which need to solve problems harder than the demonstration examples. To tackle such easy-to-hard generalization iss

arxiv.org

Results

code-davinci-002(코드에 최적화되어 있지만 여전히 텍스트를 이해할 수 있음)를 사용하여 긴 inference chain을 포함하는 벤치마크에 적용했을 때 저자들은 16%에서 99.7%까지의 신뢰도를 얻을 수 있었다고 합니다.

Source: Least-to-most Prompting Enables Complex Reasoning in Large Language Models by Denny Zhou et al. (2022)

 

Least-to-Most Prompting Enables Complex Reasoning in Large Language Models

Although chain-of-thought prompting has shown impressive results on many natural language reasoning tasks, it often performs poorly on tasks which need to solve problems harder than the demonstration examples. To tackle such easy-to-hard generalization iss

arxiv.org

Implications

위의 least-to-most 프롬프팅 방법으로 얻은 신뢰도 상승은 인상적이지만 그 방법은 긴 reasoning chains가 요구되는 아주 좁은 임무들의 세트들 위에서 측정됩니다.

 

아직 그것은 다음과 같은 방법들에 의해 신뢰도를 제고하는 common theme을 illustrate 합니다.

(a) 복잡한 임무들을 작은 subtasks들로 나눈다. 그리고 (b) 답을 찾아내기 위해 좀 더 많은 시간과 공간을 모델에게 제공한다.

 

To learn more, read the full paper.

 

Least-to-Most Prompting Enables Complex Reasoning in Large Language Models

Although chain-of-thought prompting has shown impressive results on many natural language reasoning tasks, it often performs poorly on tasks which need to solve problems harder than the demonstration examples. To tackle such easy-to-hard generalization iss

arxiv.org

 

Related ideas

Maieutic prompting

Method

정답을 받을 확률을 최대화 하려는 이전의 테크닉들과는 달리 다른 접근법은 (정답이든 오답이든) 가능한 explanation들 의 tree를 발생시키도록 하기 위해 GPT-3를 사용합니다. 그리고 나서 어떤 세트가 correct한지 를 알아내기 위해 그들의 관계들을 분석합니다. 이 테크닉은 2022년 5월에 정재훈 등에 의해 만들어진 coined maieutic 프롬프팅입니다.  (maieutic은 아이디어를 이끌어내기 위해 질문하는 소크라테스 식 방법과 관련 돼 있습니다.)

이 방법은 복잡합니다. 아래와 같이 작동합니다.

  • First, build a maieutic tree, where each node is a statement that could be true or false:
  • 첫째로 maieutic tree를 만듭니다. 각 노드는 참이나 거짓이 될 수 있는 하나의 statement 입니다.  
    • Start with a multiple-choice question or true/false statement (e.g. War cannot have a tie)
    • 객관식 질문 또는 참/거짓을 답할 수 있는 질문으로 시작합니다. (예. 전쟁은 무승부일 수 없다)
    • For each possible answer to the question, use the model to generate a corresponding explanation (with a prompt like War cannot have a tie? True, because)
    • 질문에 대해 각각의 가능한 answer 들에 대해 각각 상응하는 explanation을 생성하도록 모델을 사용합니다. (전쟁은 무승부일 수 없다? 참, 왜냐하면... 같은 프롬프트가 될 것입니다.)
    • Then, prompt the model with the question and the generated explanation, and ask it to produce the answer. If reversing the explanation (with a prefix like It is wrong to say that {explanation}) reverses the answer, then the explanation is considered 'logically integral.'
    • 그런 다음 질문과 생성된 explanation으로 모델의 프롬프트를 만듭니다. 그리고 나서 답을 만들도록 요청합니다. 만약 설명을 뒤집으면 (예를 들어 {explanation} 이라고 얘기하면 틀립니다와 같은 prifix를 만드는 방법)답도 뒤집어 집니다.  그러면 explanation은 "logically integral" 로 간주되게 됩니다.
    • If an explanation is not logically integral, then repeat the above process recursively, with each explanation turned into a True or False question, and generate more explanations for each new question.
    • 만약 explanation이 logically integral 되지 않았다면 위의 과정을 재귀적으로 반복합니다. (이 때 각각의 explanation은 True 나 False question으로 바뀌게 되는 것이죠. 그리고 각각의 새로운 질문들에 대한 좀 더 많은 explanation들을 생성합니다.
    • After all of the recursive explaining is done, you end up with a tree of explanations, where each leaf on the tree has the property that reversing the explanation reverses the model's answer.
    • 이렇게 모든 재귀적인 explaining이 종류된 후에 explanation tree를 얻게 됩니다. 나무에 있는 각각의 leaf (잎)들은 explanation을 뒤집으면 모델의 답도 뒤집어지는 그런 프로퍼티를 갖게 됩니다.
  • Second, convert the tree into a graph of relations:
  • 두번째, 그 tree를 관계 그래프로 변환합니다. 
    • For each node in the tree, calculate the model's relative belief in each node (inferred from the probability of getting an answer of True to given an explanation)
    • 그 나무의 각각의 노드들은 각 노드에 대한 모델의 상대적 신뢰도를 계산하게 됩니다. (주어진 explanation에 True라는 답을 얻기 위한 추정치로 부터 추론 합니다.)
    • For each pair of nodes in the tree, use the model to identify whether they are entailed (implied) or contradicted
    • 그 나무에 있는 노드들의 각 쌍들에 대해 그 쌍들이 그것들이 entailed (implied) 인지 contradicted (모순)인지의 여부를 모델을 사용하여 판정합니다.
  • Third, find the most consistent set of beliefs and take those to be true:
  • 세번째, 가장 일관성 있는 belief들을 찾아내서 그것들을 true라고 작업합니다. 
    • Specifically, using the strength of belief in each node and the logical relationships between them, formulate the problem as a weighted maximum satisfiability problem (MAX-SAT)
    • 특히 각 노드의 신뢰도의 강도와 그들간의 논리적인 관계를 사용하여 weighted maximum satisfiability problem (MAX-SAT)로 그 문제를 공식화 합니다.
    • Use a solver to the find the most self-consistent set of beliefs, and take those as true
    • Solver를 사용하여 가장 self-consistent 한 belief들의 세트를 찾아 냅니다. 그리고 그것들을 true로 취합니다.

 

Source: Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations by Jaehun Jung et al. (2022)

 

Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations

Despite their impressive capabilities, large pre-trained language models (LMs) struggle with consistent reasoning; recently, prompting LMs to generate explanations that self-guide the inference has emerged as a promising direction to amend this. However, t

arxiv.org

Results

Source: Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations by Jaehun Jung et al. (2022)

 

Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations

Despite their impressive capabilities, large pre-trained language models (LMs) struggle with consistent reasoning; recently, prompting LMs to generate explanations that self-guide the inference has emerged as a promising direction to amend this. However, t

arxiv.org

Implications

복잡한 것 이외에도 이 방법은 한가지 한계가 있습니다. 그것은 객관식으로 제시할 수 있는 질문에만 적용되는 것으로 보인다는 겁니다.

To learn more, read the full paper.

 

Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations

Despite their impressive capabilities, large pre-trained language models (LMs) struggle with consistent reasoning; recently, prompting LMs to generate explanations that self-guide the inference has emerged as a promising direction to amend this. However, t

arxiv.org

 

Extensions

Method

descrete set의 답변이 있는 task에 대해 신뢰도를 제고시킬 수 있는 간단한 방법 중 하나는 모델에서 여러 explanation 및 답변을 샘플링 한 다음에 (positive temperature를 사용) 가장 자주 등장하는 답변을 최종 답변으로 선택하는 겁니다.

Source: Self-Consistency Improves Chain of Thought Reasoning in Language Models by Xuezhi Wang et al. (2022)

 

Self-Consistency Improves Chain of Thought Reasoning in Language Models

Chain-of-thought prompting combined with pre-trained large language models has achieved encouraging results on complex reasoning tasks. In this paper, we propose a new decoding strategy, self-consistency, to replace the naive greedy decoding used in chain-

arxiv.org

 

Results

이 테크닉은 여러 수학과 reasoning benchmark들에서 정확도를 1~24 퍼센트 향상 시켰습니다. (아래 도표는 구글의 LamDa 모델의 결과 입니다. 구글의 larger PaLM 모델을 사용했습니다. 기준선은 높지만 그로부터 얻는 것은 약간 좀 더 작았습니다.)

Source: Self-Consistency Improves Chain of Thought Reasoning in Language Models by Xuezhi Wang et al. (2022)

 

Self-Consistency Improves Chain of Thought Reasoning in Language Models

Chain-of-thought prompting combined with pre-trained large language models has achieved encouraging results on complex reasoning tasks. In this paper, we propose a new decoding strategy, self-consistency, to replace the naive greedy decoding used in chain-

arxiv.org

 

Implications

이 테크닉은 구현이 간단하지만 비용이 많이 들 수 있습니다. 10개의 답변 세트를 생성하면 비용이 10배 증가합니다.

 

또한 많은 이러한 기술들과 마찬가지로 제한된 답변 세트가 있는 작업에만 적용할 수 있습니다. 각 답변이 유니크한 (시를 쓰는 것 처럼) 각각의 답변이 있는 open-ended 작업에 대해 가장 일반적인 답변을 하나 선택한다는 것은 과연 유의미한 건가에 대해서는 확언할 수는 없습니다.

 

마지막으로, 이 테크닉은 답을 얻기 위해 여러 경로나 여러 구문들이 있는 경우에 가장 유용합니다. 답변에 이르는 경로가 오직 하나 뿐이면 이 테크닉은 전혀 도움이 되지 않을 수 있습니다. 극단적인 예로 이 작업이 single token answer를 생성하는 것이라면 100개의 생성된 토큰 중 가장 일반적인 것을 가져오는 것은 가장 높은 logprobs(temperature=0 으로 생성된) 로 생성된 토큰을 가져오는 것과 다른 것이 없습니다.

 

Verifiers

작업 성능을 개선하기 위한 또 다른 주요한 테크닉은 main generative 모델의 output들을 평가하기 위한 verifier(검증자) 혹은 discriminator(판별자) 모델을 훈련 시키는 겁니다. 이 판별자가 output을 reject 한다면 acceptable output을 얻을 때까지 generative 모델을 resample 할 수 있습니다. 많은 경우 답을 만드는 것 보다 답을 판단하는 것이 더 쉽기 때문에 이 방법의 power를 설명하는데 도움이 됩니다.

 

Method

2021년에 OpenAI 연구자들은 이 테크닉을 아래와 같은 절차들을 사용해서 초등학교 수학 문제에 적용했습니다.

 

  • First, they fine-tuned a model on questions and solutions
  • 우선 질문과 솔루션에 대한 모델을 fine-tune 합니다.
  • For each problem in the training set, they generated 100 solutions
  • 훈련 세트에 있는 각 문제들에 대해 100개의 솔루션들을 생성합니다.
  • Each of those 100 solutions was automatically labeled as either correct or incorrect, based on whether the final answer was correct
  • 그 100개의 솔루션 각각은 정답인지 오답인지 자동적으로 label 됩니다. (정답/오답 근거는 최종 대답이 올바른지의 여부에 근거합니다.)
  • Using those solutions, with some labeled correct and some labeled incorrect, they fine-tuned a verifier model to classify whether a question and candidate solution was correct or incorrect
  • 이러한 솔루션을 사용하여 만든 어떤 레이블들은 옳고 또 어떤 레이블들은 그렇지 않았습니다. 그들은 문제와 후보 솔루션이 옳은지 옳지 않은지를 구별하는 verifier 모델을 fine-tune 했습니다.
  • Finally, at test time, the generative model creates 100 solutions to each problem, and the one with the highest score according to the verifier model is picked as the final answer
  • 마지막으로 테스트 할 때 generative 모델은 각 문제당 100개의 솔루션들을 만들었습니다. 그리고 그 verifier 모델에 의해 가장 높은 점수를 얻은 솔루션을 최종 답변으로 선택합니다.

Source: Training Verifiers to Solve Math Word Problems by Karl Cobbe et al. (2021)

 

Training Verifiers to Solve Math Word Problems

State-of-the-art language models can match human performance on many tasks, but they still struggle to robustly perform multi-step mathematical reasoning. To diagnose the failures of current models and support research, we introduce GSM8K, a dataset of 8.5

arxiv.org

 

Results

175B GPT-3 모델과 8천개의 training example들을 사용하여 이 테크닉은 초등학교 수학 문제에 대한 답변 정확도를 33%에서 55%로 높였습니다.

 

Source: Training Verifiers to Solve Math Word Problems by Karl Cobbe et al. (2021)

 

Training Verifiers to Solve Math Word Problems

State-of-the-art language models can match human performance on many tasks, but they still struggle to robustly perform multi-step mathematical reasoning. To diagnose the failures of current models and support research, we introduce GSM8K, a dataset of 8.5

arxiv.org

 

Implications

self-consistency 테크닉과 비슷하게 이 방법은 작업당 100개의 솔루션들을 생성하기 위해 100배의 비용이 더 들 수 있습니다. 

 

Theories of reliability

위에서 다룬 테크닉들은 그 접근 방식들이 다르지만 목표는 모두 복잡한 작업에 대한 신뢰도(안정성)를 개선시키기 위한 것들입니다. 그 테크닉들은 대개 아래와 같은 방식으로 작업을 수행합니다.

 

  • decomposing unreliable operations into smaller, more reliable operations (e.g., selection-inference prompting)
  • 신뢰도가 적은 작업을 더 작고 신뢰도가 높은 작업으로 분할 합니다. (예. selection-inference 프롬프팅)
  • using multiple steps or multiple relationships to make the system's reliability greater than any individual component (e.g., maieutic prompting)
  • 개별적인 component보다 더 높은 시스템의 신뢰도를 만들기 위해 여러 단계 혹은 여러 관계들을 사용합니다. (예 maieutic 프롬프팅)

Probabilistic graphical models

덜 신뢰할 수 있는 component들로부터 신뢰할 수 있는 시스템을 만들기 위한 이 패러다임은 probabilistic (확률적) 프로그래밍을 연상시킵니다. 그리고 그 분야의 많은 분석 기술들 또한 여기에 적용될 수 있습니다.

 

David Dohan 등이 작성한 Language Model Cascades 라는 논문에서는 확률적 그래픽 모델의 패러다임으로 위의 기술들을 해석합니다.

 

Chain of thought prompting

Source: Language Model Cascades by David Dohan et al. (2022)

 

Language Model Cascades

Prompted models have demonstrated impressive few-shot learning abilities. Repeated interactions at test-time with a single model, or the composition of multiple models together, further expands capabilities. These compositions are probabilistic models, and

arxiv.org

Fine-tuned chain of thought prompting / Self-taught reasoner

 

Source: Language Model Cascades by David Dohan et al. (2022)

 

Language Model Cascades

Prompted models have demonstrated impressive few-shot learning abilities. Repeated interactions at test-time with a single model, or the composition of multiple models together, further expands capabilities. These compositions are probabilistic models, and

arxiv.org

Selection-inference prompting

 

Source: Language Model Cascades by David Dohan et al. (2022)

 

Language Model Cascades

Prompted models have demonstrated impressive few-shot learning abilities. Repeated interactions at test-time with a single model, or the composition of multiple models together, further expands capabilities. These compositions are probabilistic models, and

arxiv.org

Verifiers

Source: Language Model Cascades by David Dohan et al. (2022)

 

Language Model Cascades

Prompted models have demonstrated impressive few-shot learning abilities. Repeated interactions at test-time with a single model, or the composition of multiple models together, further expands capabilities. These compositions are probabilistic models, and

arxiv.org

 

Implications

이러한 테크닉들을 확률적 그래픽 모델로서 공식화 하는 것은 특정 문제를 해결하는데 곧바로 유용한 방법으로 사용할 수는 없을 수 있습니다. 하지만 이 프레임워크는 새로운 기술을 선택, 결합 그리고 발견하는데 도움이 될 수 있습니다.

 

Closing thoughts

Large language 모델을 연구하는 것은 매우 활발하고 빠르게 발전하고 있습니다. 연구자들은 계속해서 모델을 개선할 뿐만 아니라 모델을 가장 잘 활용하는 방법에 대한 이해도 지속적으로 향상 시키고 있습니다. 위에서 공유한 모든 논문은 지난 12개월 이내에 출판된 것이라는 것이 최근에 더욱 활발하고 빠르게 발전하고 있다는 것을 보여 줍니다. (이 글은 2022년 9월에 작성함)

 

앞으로 더 나은 모델과 더 나은 기술이 발표 될 것으로 기대합니다. 여기에서 다룬 특정 기술이 미래의 새로운 모범 사례에 의해 잊혀지더라도 그 모델들에서 제시한 일반 원칙은 다른 전문가들의 유용한 도구의 핵심 개념으로 남을 것입니다.

 

Bibliography

Lesson                                                                                         Paper                                                                       Date

Break complex tasks into simpler subtasks (and consider exposing the intermediate outputs to users) AI Chains: Transparent and Controllable Human-AI Interaction by Chaining Large Language Model Prompts 2021 Oct
You can improve output by generating many candidates, and then picking the one that looks best Training Verifiers to Solve Math Word Problems 2021 Oct
On reasoning tasks, models do better when they reason step-by-step before answering Chain of Thought Prompting Elicits Reasoning in Large Language Models 2022 Jan
You can improve step-by-step reasoning by generating many explanation-answer outputs, and picking the most popular answer Self-Consistency Improves Chain of Thought Reasoning in Language Models 2022 Mar
If you want to fine-tune a step-by-step reasoner, you can do it with multiple-choice question & answer data alone STaR: Bootstrapping Reasoning With Reasoning 2022 Mar
The step-by-step reasoning method works great even with zero examples Large Language Models are Zero-Shot Reasoners 2022 May
You can do better than step-by-step reasoning by alternating a ‘selection’ prompt and an ‘inference’ prompt Selection-Inference: Exploiting Large Language Models for Interpretable Logical Reasoning 2022 May
On long reasoning problems, you can improve step-by-step reasoning by splitting the problem into pieces to solve incrementally Least-to-most Prompting Enables Complex Reasoning in Large Language Models 2022 May
You can have the model analyze both good and bogus explanations to figure out which set of explanations are most consistent Maieutic Prompting: Logically Consistent Reasoning with Recursive Explanations 2022 May
You can think about these techniques in terms of probabilistic programming, where systems comprise unreliable components Language Model Cascades 2022 Jul
You can eliminate hallucination with sentence label manipulation, and you can reduce wrong answers with a 'halter' prompt Faithful Reasoning Using Large Language Models 2022 Aug

 

 

반응형
이전 1 2 3 4 5 다음