Заставить LLM выполнять определенные задачи долгое время было постоянной проблемой. В то время как LLM демонстрируют впечатляющий интеллект и возможности естественного языка, заставить LLM выводить определенные структурированные форматы по-прежнему сложно. Например, если LLM проходит тест с множественным выбором — в то время как люди могут выбирать конкретные варианты ответов или кружиться в кружке на листе ответов, LLM могут отвечать только с выходным текстом. Чтобы автоматически извлечь свой ответ, LLM должен вывести свой ответ в определенном формате (например, в квадратных скобках или в круглых скобках). Вот конкретный пример:

USER: 
If Bob has 15 apples and eats 5, how many are left?
(A) 15
(B) 20
(C) 10
(D) 5
Vicuna-7B v1.5:
If Bob has 15 apples and eats 5, then he is left with 15 - 5 = 10 apples. Therefore, the answer is (C) 10.

Для человека совершенно очевидно, что чат-бот смог правильно ответить, что осталось C) 10 яблок. Но как мы можем разобрать ответ для автоматической оценки?

Мы могли бы попробовать некоторые эвристики, чтобы определить ответ чат-бота из его необработанного ответа, например, поиск заглавных букв A, B, C и D в ответе, но это столкнется с такими проблемами, как поиск других непреднамеренных «ответов» (например, B в ответе). «Боб»).

Кроме того, что, если чат-бот начнет разглагольствовать, чтобы объяснить, почему другие ответы неверны, как это?

If Bob has 15 apples and eats 5, then he is left with 15 - 5 = 10 apples. Therefore, the answer is (C) 10.
The correct answer is not (A) because Bob ate 5, so there must be less than 15. 
The correct answer is not (B) because Bob ate 5, so there must be less than 15.
The correct answer is not (D) because Bob only ate 5, so there must be 10.

Вместо этого нам нужно, чтобы чат-бот понимал и следовал определенному формату. Например, мы можем заставить чат-бота разделять свои мысли и помещать окончательный ответ на новую строку в круглых скобках, например:

Thought: If Bob has 15 apples and eats 5, then he is left with 15 - 5 = 10 apples. 
Final Answer: (C) 10.

Но как мы можем заставить чат-бота следовать определенному формату?

Быстрые инструкции

Нам нужно включить в подсказку инструкции, описывающие указанный формат, например:

USER: 
Answer the following multiple choice question and follow this format:
```
USER: [user's question]
ASSISTANT: Thought: [assistant's thoughts here]
Final Answer: [place your final answer (A, B, C, D, ...) in parentheses here]
```
If Bob has 15 apples and eats 5, how many are left?
(A) 15
(B) 20
(C) 10
(D) 5
Vicuna-7B v1.5:
Thought: It's important to express the final answer in the same units as the initial quantity. In this case, since Bob ate 5  
apples, there are now 15 - 5 = 10 apples left.                                                                                

Final Answer: (C) 10

Теперь мы можем легко разобрать ответ, найдя строку со словами «Окончательный ответ» и найдя ответ с заглавной буквы в скобках.

Но просто указание формата не всегда работает. Вот другой пример, где нам нужно сгенерировать вопросы для заполнения в определенном формате с учетом отрывка, который потенциально можно использовать в классах:

USER:
Given the provided context, come up with 3 fill in the blank questions. Place your questions in the following format:
[context provided here]
1. [question 1, with ___ where the blank will be] (A) [the correct answer to the blank]
2. [question 2, with ___ where the blank will be] (A) [the correct answer to the blank]
3. [question 3, with ___ where the blank will be] (A) [the correct answer to the blank]
...

Maxwell's equations, or Maxwell–Heaviside equations, are a set of coupled partial differential equations that, together with the Lorentz force law, form the foundation of classical electromagnetism, classical optics, and electric circuits. The equations provide a mathematical model for electric, optical, and radio technologies, such as power generation, electric motors, wireless communication, lenses, radar, etc. They describe how electric and magnetic fields are generated by charges, currents, and changes of the fields. The equations are named after the physicist and mathematician James Clerk Maxwell, who, in 1861 and 1862, published an early form of the equations that included the Lorentz force law. Maxwell first used the equations to propose that light is an electromagnetic phenomenon. The modern form of the equations in their most common formulation is credited to Oliver Heaviside. Maxwell's equations may be combined to demonstrate how fluctuations in electromagnetic fields (waves) propagate at a constant speed in vacuum, c (299792458 m/s). Known as electromagnetic radiation, these waves occur at various wavelengths to produce a spectrum of radiation from radio waves to gamma rays. The equations have two major variants. The microscopic equations have universal applicability but are unwieldy for common calculations. They relate the electric and magnetic fields to total charge and total current, including the complicated charges and currents in materials at the atomic scale. The macroscopic equations define two new auxiliary fields that describe the large-scale behaviour of matter without having to consider atomic-scale charges and quantum phenomena like spins. However, their use requires experimentally determined parameters for a phenomenological description of the electromagnetic response of materials. The term "Maxwell's equations" is often also used for equivalent alternative formulations. Versions of Maxwell's equations based on the electric and magnetic scalar potentials are preferred for explicitly solving the equations as a boundary value problem, analytical mechanics, or for use in quantum mechanics. The covariant formulation (on spacetime rather than space and time separately) makes the compatibility of Maxwell's equations with special relativity manifest. Maxwell's equations in curved spacetime, commonly used in high-energy and gravitational physics, are compatible with general relativity. In fact, Albert Einstein developed special and general relativity to accommodate the invariant speed of light, a consequence of Maxwell's equations, with the principle that only relative movement has physical consequences.

Vicuna-7B v1.5:
1. What are Maxwell's equations? (A) A set of mathematical equations that describe the behavior of electric and magnetic fields
2. Who first published an early form of Maxwell's equations? (A) James Clerk Maxwell
3. What is the speed at which electromagnetic waves propagate in vacuum? (A) 299792458 m/s

Это не вопросы для заполнения — это обычные вопросы.

Несколько выстрелов

LLM явно не понимает задачу или формат — он думает, что нам нужны простые пары вопрос-ответ, хотя на самом деле нам нужны вопросы, заполняющие пустые места. Вместо этого нам нужно использовать метод, известный как несколько подсказок, когда мы показываем LLM формат, который мы ожидаем, или примеры задачи, которую мы хотели бы, чтобы он выполнил, чтобы направлять его. к правильному ответу. В частности, мы предоставляем примеры с подсказками и модельными ответами в подсказке, из которых LLM будет учиться, чтобы понять формат или задачу, которую вы хотите, и в конечном итоге сделать свой вывод в указанном формате.

В задании на заполнение пробелов мы можем добавить пример о Париже в подсказку с модельным ответом:

USER:
Given the provided context, come up with 3 fill in the blank questions. Place your questions in the following format:
[context provided here]
1. [question 1, with ___ where the blank will be] (A) [the correct answer to the blank]
2. [question 2, with ___ where the blank will be] (A) [the correct answer to the blank]
3. [question 3, with ___ where the blank will be] (A) [the correct answer to the blank]
...

Paris is the capital and most populous city of France, ...
1. Paris is the ___ of France. (A) capital
2. Paris had a ___ of €765 billion in 2021. (A) GDP
3. Paris has been one of the world's major centres of ___, diplomacy, commerce, culture, fashion, gastronomy. (A) finance

Maxwell's equations, or Maxwell–Heaviside equations, ...

Vicuna-7B v1.5:
1. Maxwell's equations are a set of ___ that describe the behavior of electric and magnetic fields. (A) differential equations
2. The modern form of Maxwell's equations was first published by ___ in 1861 and 1862. (A) James Clerk Maxwell
3. Maxwell's equations are often used to explain the behavior of ___, including electric motors and wireless communication. (A) electric and magnetic fields

Ура! LLM смог понять вопрос и задать нам прекрасные вопросы, заполняющие пустые места!

Однако даже несколько подсказок не всегда работают. Вот еще один пример, в котором мы хотим сгенерировать вопросы на соответствие (два набора элементов слева и справа и определить, какой элемент соответствует какому).

USER:
Given the provided context, come up with a matching question with three items on both sides. Place your questions in the following format:
[context provided here]
Left side:
1. [left item 1]
2. [left item 2]
3. [left item 3]

Right side:
A. [right item 1]
B. [right item 2]
C. [right item 3]

Matching answers:
1. [A, B, or C]
2. [A, B, or C]
3. [A, B, or C]

Paris is the capital and most populous city of France...
Left side:
1. Paris
2. 12,271,794
3. 105 km2

Right side:
A. population of Paris
B. area of Paris
C. capital of France

Matching answers:
1. C
2. A
3. B

Maxwell's equations, or Maxwell–Heaviside equations...

Vicuna-7B v1.5
Left side:
1. James Clerk Maxwell
2. Oliver Heaviside
3. Lorentz force law

Right side:
A. physicist and mathematician
B. electromagnetic phenomenon
C. total charge and total current

Matching answers:
1. A
2. B
3. C

The Great Barrier Reef is the world's largest coral reef system...

LLM начинает генерировать другой пример, чтобы продолжить «шаблон», который он видел в подсказке.

Мы можем попробовать добавить разделители между разными примерами:

Vicuna-7B v1.5:
1. James Clerk Maxwell
2. Oliver Heaviside
3. Lorentz force law
...
23. general relativity
24. Albert Einstein

Right side:
A. James Clerk Maxwell
B. Oliver Heaviside
C. Lorentz force law

Matching answers:
1. C
2. B
3. A

Но LLM по-прежнему генерирует бессмысленный список из 24 физических терминов и пытается сопоставить их с первыми тремя терминами в списке.

Правильный способ делать подсказки с несколькими выстрелами

Проблема в том, что мы «пихали все в подсказку и надеялись, что LLM будет достаточно умен, чтобы понять это». Однако для того, чтобы сделать подсказку с несколькими повторениями более эффективной, нам нужно подумать о том, чего мы на самом деле пытаемся достичь с помощью подсказок с несколькими повторениями — мы пытаемся показать LLM примеры различных подсказок и моделей ответов. Так почему бы не поместить примеры в историю прошлых разговоров? Это упрощает задачу для LLM и позволяет LLM естественным образом оглянуться на свои прошлые ответы и экстраполировать прошлые примеры и указанный формат на новую подсказку. И это работает.

Возвращаясь к нашему примеру вопроса о сопоставлении: если мы добавим пример с Парижем как «фальшивый» обмен между пользователем и LLM, тогда LLM сможет успешно сгенерировать соответствующий вопрос и остановиться, не начав генерировать другой вопрос:

USER (fake):
Given the provided context, come up with a matching question with three items on both sides. Place your questions in the following format:
[context provided here]
Left side:
1. [left item 1]
2. [left item 2]
3. [left item 3]

Right side:
A. [right item 1]
B. [right item 2]
C. [right item 3]

Matching answers:
1. [A, B, or C]
2. [A, B, or C]
3. [A, B, or C]
Paris is the capital and most populous city of France, ...

Vicuna-7B v1.5 (fake):
Left side:
1. Paris
2. 12,271,794
3. 105 km2

Right side:
A. population of Paris
B. area of Paris
C. capital of France

Matching answers:
1. C
2. A
3. B

USER (real):
Given the provided context, come up with a matching question with three items on both sides. Place your questions in the following format:
[context provided here]
Left side:
1. [left item 1]
2. [left item 2]
3. [left item 3]

Right side:
A. [right item 1]
B. [right item 2]
C. [right item 3]

Matching answers:
1. [A, B, or C]
2. [A, B, or C]
3. [A, B, or C]
Maxwell's equations, or Maxwell–Heaviside equations, ...

Vicuna-7b-v1.5 (real):
Left side:
1. James Clerk Maxwell
2. Oliver Heaviside
3. Lorentz force law

Right side:
A. equations that describe electromagnetic phenomena
B. physicist who first published the equations
C. term used for the macroscopic equations

Matching answers:
1. A
2. B
3. C

Больше нет неправильного формата вывода. Больше не нужно генерировать новые примеры, чтобы «следовать шаблону». Нет больше создания длинных списков левых терминов без смысла.

Вместо этого LLM может оглянуться назад на свою историю разговоров и, естественно, понять, как он должен действовать, основываясь на том, как он действовал раньше.

Заключение

Заставить LLM следовать определенным форматам или адаптироваться к конкретным задачам имеет решающее значение для преобразования необработанных выходных данных LLM в полезный результат, который можно использовать в приложении ИИ. Однако LLM часто не слушают и не понимают инструкций, размещенных в подсказке. Использование нескольких подсказок показывает LLM примеры ответов модели, но все же приводит к таким проблемам, как создание совершенно новых примеров в выходных данных, а также потеря LLM и забвение формата. Вместо этого добавление примеров в виде истории прошлых разговоров, естественно, позволяет LLM понять правильный формат и адаптироваться к вашей конкретной задаче, чтобы помочь вам создать следующее мощное приложение.