본문 바로가기
ML&DL/NLP(LLM)

[NLP][Prompt Engineering] What is Prompt Optimization

by 거북이주인장 2024. 5. 3.

Prompt Engineering

바야흐로 LLM의 시대이다. chatgpt를 시작으로 llama, mistral, mixtral, claude 등 다양한 llm이 쏟아져나오고 있는 가운데, 자연스럽게 프롬프트 엔지니어링 기술이 주목을 받고 있다.

프롬프트란, 인간이 컴퓨터와 대화하는 언어이고 필자는 프롬프트 엔지니어링은 인간이 llm과 얼마나 잘 대화를 나눌 수 있는지에 대한 기술이라고 생각한다. 똑같은 llm이라도 사람마다 llm과 대화하는 수준의 차이가 있다. 사람들끼리의 대화는 소통의 꽉 막힘에서 끝나겠지만 llm과의 대화는 이를 얼마나 잘 하느냐에 따라서 llm으로부터 양질의 정보를 얻을 수도, 그렇지 않을 수도 있다. 실제로 프롬프트를 잘 작성하는 인력을 고연봉에 채용하겠다는 회사도 많이 있다.

https://www.newspim.com/news/view/20230619000801

 

[프롬프트 엔지니어]② '억대 연봉에 모십니다'...인재 선점 나선 AI 기업들

[서울=뉴스핌] 양태훈 기자 = 프롬프트 엔지니어링이 생성 AI의 성능 향상을 가져올 수 있다는 점에서 기업들은 프롬프트 엔지니어 채용에 적극적인 모습이다. 미국의 AI 스타트업 '앤스로픽'과 '

newspim.com

처음에는 고작 프롬프트를 잘 작성하는 것으로 억대 연봉을 주나? 프롬프트, 코드도 아니고 그냥 자연어인데 이걸로 억대 연봉을 주나? 라는 생각이 들었는데 최근에 프롬프트 최적화 작업을 진행하다보니까 프롬프트 엔지니어링을 얼마나 숙련도 있게 하느냐에 따라서 결과물이 상당히 달라질 수도 있겠구나, 라는 생각이 들었다.

그러면 구체적으로 프롬프트 엔지니어링을 하면 결과물이 어떻게 달라질까? ollama에서 llama2:latest 모델을 불러온 후에 간단하게 대화를 시도해보자. (참고로 ollama는 편리하게 llm과 대화할 수 있는 응용프로그램을 제공해서 필자는 많이 이용한다.)

https://ollama.com/

 

Ollama

Get up and running with large language models.

ollama.com

먼저, 인간이 바로 작성할 수 있는 간단한 프롬프트 하나를 예시로 입력해보자.

 

>>> what is harry potter?
Harry Potter is a series of fantasy novels written by J.K. Rowling. The series follows the
adventures of a young wizard named Harry Potter and his friends at Hogwarts School of Witchcraft and
Wizardry. The stories are set in a magical world where magic is a part of everyday life, but also
deal with themes such as friendship, love, and the struggle between good and evil. The series has
become incredibly popular and has been translated into many languages, inspiring a dedicated fan
base and a successful film franchise.

 

llama에게 해리포터에 대해서 물어보았다. 언뜻 보면, 나름 잘 대답한 것으로 보인다. 이제 프롬프트 엔지니어링을 한 후의 프롬프트를 살펴보자.

 

>>> When asked about any aspect of Harry Potter, provide a comprehensive answer that includes the most relevant information about the character, book, movie, or related Harry Potter universe topic. Ensure the response is accurate, detailed, and contextualized based on the user's question. The answer should be informative for both newcomers and fans familiar with the subject matter, giving a clear and engaging overview of the topic, with additional interesting facts if pertinent.

 

단순히 해리포터에 대해서 물어보는 것이 아니라, 가장 관련있는 정보를 뽑되, 대답이 정확하고 구체적이며 질문과 문맥이 맞아야 한다고 추가적으로 요구한다. 게다가 해리포터를 아예 모르는 사람이나 팬들에게 친숙하게 대답하라고 주문한다. 프롬프트가 상당히 구체적으로 탈바꿈했다! 사실, llm과 대화할 때 일반인들은 단순히 what is harry potter? 라고 물어볼 것이다. 근데 프롬프트 엔지니어링을 잘 하는 사람은 위와 같이 물어볼 것이고.. 그에 대한 대답을 바로 아래에서 살펴보자!

 

Ah, an eager fan asking about the magical world of Harry Potter! 🧙‍♂️🔮🎓

Harry Potter is a series of fantasy novels written by J.K. Rowling that follows the adventures of a
young wizard named Harry Potter and his friends at Hogwarts School of Witchcraft and Wizardry. The
stories are set in a magical world where magic is an integral part of everyday life, but also delve
into themes such as friendship, love, and the eternal struggle between good and evil. 💫

Here are some key points to get you started:

1. Hogwarts School of Witchcraft and Wizardry: The primary setting for most of the series, Hogwarts
is a school for young wizards and witches where they learn magic and how to use it 🏰🧙‍♂️
2. Harry Potter's backstory: Harry is an orphan who lives with his cruel and neglectful relatives, the Dursleys, until he discovers he's a wizard and starts attending Hogwarts. His parents were killed by the dark wizard Lord Voldemort (or Tom Riddle), known as "He Who Must Not
Be Named." 🧚‍♂️
3. The Order of the Phoenix: A group of wizards dedicated to fighting against the evil Lord Voldemort and his followers, known as Death Eaters. Harry's godfather, Sirius Black, is a member of
this order. 🔥👊
4. Quidditch: A popular sport in the magical world, played on broomsticks with four balls (two for
each team) and six players per side. Harry is an excellent player and becomes the Seeker (the
fastest player) on the Gryffindor Quidditch team. 🏈⚽️
5. Hogsmeade: A wizarding village near Hogwarts where students can go for treats, souvenirs, and
other fun activities. 🍰🛍️
6. The Triwizard Tournament: An inter-school magical competition held every five years, in which
three students from different schools compete in a series of challenges to win the title of
"Champion." Harry is unexpectedly chosen as a participant during his third year at Hogwarts. 🏆🔥
7. The Horcruxes: Small objects that contain pieces of Lord Voldemort's soul, making him almost
invulnerable to death. Harry and his friends must find and destroy all seven Horcruxes to defeat the
Dark Lord once and for all. 💀🔥
8. The Deathly Hallows: Three powerful magical objects that are said to make their owner the most
powerful wizard of all time. The Hallows are a Sword of Gryffindor, a Cloak of Invisibility, and a
Resurrection Stone. Harry and his friends must find and use these objects to defeat Voldemort. 🔥⚔️
9. The Weasley family: A loving and witty family of wizards who become close friends of Harry's
during his time at Hogwarts. They are known for their red hair, freckles, and love of food,
especially treacle fudge! 🍬👪
10. The Fat Lady: A portrait of a former Hogwarts teacher who has been turned into a magical
painting that can only be seen by those with the "Opening Charm." Harry must use this charm to free
himself and his friends from her frame during their fourth year at Hogwarts. 🎨🔥

These are just some of the many fascinating aspects of the Harry Potter universe! If you have any
specific questions or topics you'd like to learn more about, feel free to ask! 😊

 

결과가 상당히 놀라웠는데 몇가지 포인트를 정리해보면 아래와 같다.

  • 중간중간 이모지를 섞어서 굉장히 친숙한 느낌이 들었다.
  • 두괄식의 형태로, 처음에 전체적으로 정리해준 후에 일목요연하게 해리포터에서 포인트가 되는 주제를 설명해준다.

자, 이쯤되면 프롬프트 엔지니어링 실력에 따라서 받을 수 있는 답변이 달라진다는 것이 실감이 나는가?

그러면 여기서 의문이 들 것이다.

 

>>> When asked about any aspect of Harry Potter, provide a comprehensive answer that includes the most relevant information about the character, book, movie, or related Harry Potter universe topic. Ensure the response is accurate, detailed, and contextualized based on the user's question. The answer should be informative for both newcomers and fans familiar with the subject matter, giving a clear and engaging overview of the topic, with additional interesting facts if pertinent.

 

이렇게 길고 구체적인 프롬프트를 어떻게 적을지.. 솔직히 걱정되지 않는가? 이걸 잘 적는 것이 프롬프트 엔지니어의 일이지만.. 사실 더 좋은 프롬프트를 엔지니어가 찾지 못하는 것일수도 있다. 잠깐, 그러면 프롬프트 엔지니어는 노가다 직업일까? what is harry potter 라는 프롬프트를 엔지니어링할 때, 가능한 모든 경우의 수를 시도해봐야할까? 애초에 자연어인데 이게 가능한 것일까? 이런 배경에서 Prompt Optimization이라는 분야가 최근 활발하게 연구되고 있다.

Prompt Optimization

프롬프트 엔지니어링을 프롬프트 최적화 문제로 바꿔서 생각하는 분야이다. 얼핏 생각해보면 프롬프트 엔지니어링을 노가다 문제, 또는 글을 잘 쓰는 문과의 영역(?)이라고 생각할 수 있는데, 사실 llm이 좋아하는 형태의 프롬프트를 작성하는게 포인트이다. llm이 좋아하는 포인트는 나중에 살펴보기로 하고.. 본 포스팅에서는 어떻게 프롬프트를 사람 손을 타지 않고 자동으로 최적화할 수 있을까?에 대해 얘기해보고자 한다.

Objective function

흔히들 생각하는 최적화 문제는 최적화하고자 하는 파라미터가 있고 목적 함수가 있다. 프롬프트 최적화 문제도 똑같다. 최적화하고자 하는 파라미터는 프롬프트, 목적 함수는 상황에 맞게 정의한다. 프롬프트 최적화 분야에서 꽤나 유명해 보이는 논문 (Large language models are human-level prompt engineers)은 프롬프트 최적화 문제의 목적 함수를 formal하게 정의하는데, 그 이전에 notation을 짚고 넘어가자.

  • $\mathcal{D}_{train} = \{ (Q,A) \}$: input / output 데이터세트
  • $\mathcal{M}$: prompted model. 나의 프롬프트를 받을 llm
  • $\rho$: instruction, 또는 prompt. $(Q,A)$라는 데이터의 상황 설명
  • $[\rho; Q]$가 $\mathcal{M}$에 주어졌을 때, $A$를 잘 뽑아내는지가 관심이다.
  • $f(\rho, Q, A)$: score function. 상황에 따라서 다르게 정의한다.

이런 세팅에서 프롬프트 최적화 문제는 아래와 같이 정의된다.

프롬프트 엔지니어링을 단순히 노가다로 인식했던 필자에게는 상당히 흥미로운 접근법이다. 사실 최적화 문제로 치환하면 자연스럽게 떠오르는 목적 함수이지만.. 이런 식으로 접근하면 1) score function을 정의하고 2) 데이터 세트를 준비해야함을 알 수 있다.

위의 최적화 접근법은 프롬프트를 마치 sample로 인식한다는 점에서 또한 흥미로웠다. 프롬프트 최적화 논문을 읽어보면 대부분 프롬프트 후보, 즉 샘플을 llm으로부터 뽑는데 통계적인 접근과 유사하게 모집단에서 샘플을 뽑는 방식과 유사해서 친숙하게 느껴지기도 했다.

Category of prompts to be optimized

사람과 대화를 나눈다고 생각하면, 상당히 다양한 종류의 화법이 있다. llm과의 대화도 마찬가지이다. 명확한 정답을 요구하는 프롬프트가 있는 반면, 열린 질문인 경우도 있다. 예를 들어서, 리뷰에 스포일러가 있는지 없는지 판단해달라고 llm에게 물어볼 수 있는데 이는 명확한 정답을 요구하므로 score function을 정의할 수 있다. 맞으면 1, 틀리면 0이기 때문이다. 반면에, 비판적인 리뷰를 생성해달라고 하는 경우에는 명확한 score function이 없으므로 위의 최적화 방법으로는 접근하기 힘들다. 정리해보면 아래와 같다.

  • classification과 같이 명확하게 정답이 있는 문제
    • score function을 정의하고 목적 함수에 따라 프롬프트를 최적화한다.
  • generation과 같이 명확하게 정답이 없는 문제
    • 다른 최적화 방법을 사용한다.
    • 논문에 따라서 ranking을 metric으로 삼기도 한다.

Conclusion

프롬프트 엔지니어링의 예시부터, 최근에 프롬프트 엔지니어링을 최적화 관점에서 접근하는 연구 동향까지 간략하게 살펴보았다. 개인적으로 프롬프트 엔지니어링은 노가다, 사람 손이 타는 영역이라고 생각했는데 그게 아니라는 사실을 알게 되어서 상당히 흥미로웠고 써먹을 곳은 상당히 많을 것 같다는 생각이 들었다. 또한 chatgpt와 같은 모델은 backbone에 접근할 수 없어서 프롬프트 엔지니어링 기술이 상당히 중요한데, 이렇게 프롬프트를 최적화하다보면 양질의 답변을 얻을 수 있지 않을까라는 생각을 했다. 다음에는 구체적으로 최적화 논문들을 살펴보고 github에 구현되어있는 코드를 통해 간단하게 실습을 해보고자 한다.

댓글