The post has been translated automatically. Original language: Russian
Of course, everyone has heard that big language models sometimes tend to lie to us. More precisely, they are prone to "hallucinations." A well-known example from recent judicial practice. The incident occurred in the United States in 2023 and caused considerable resonance: the lawyer submitted a court document containing links to six non-existent precedents generated in ChatGPT. The judge found out that the cited cases did not exist, and accused the lawyer of submitting false materials. As a result, the court imposed fines on the lawyer and his colleague, and also required them to undergo training in the use of AI. This was the first known case where the use of AI in legal practice led to unpleasant results.
The link to this case: https://www.cbsnews.com/news/lawyer-chatgpt-court-filing-avianca /
Wikipedia is about this case: https://en.wikipedia.org/wiki/Mata_v._Avianca ,_Inc.
It should be understood that "hallucinations" are a system feature of the architecture of modern LLMs. They don't "think" the way we do. They don't understand either our question or their answer. They predict. At each generation step, they select the next token, calculating its maximum probability.
Let's imagine that we ask the language model the question: "What is the capital of France?". The model calculates the probabilities: Paris — 95%, London — 3%, Berlin — 2%. And then he gives us the answer: "The capital of France is Paris." But these "probabilities" are not the real probabilities of the existence of a fact in reality. They only show how much the model is inclined to choose this particular next word based on what it saw in the training data. Not whether it's really right!
It turns out that the model can assign a 95% probability to a completely fictional fact if it "sounds right" in this particular context. Probability is not a measure of confidence, but the degree of consistency with the training data. The model doesn't know if she saw this fact in the dataset or just glued it together from random fragments. It makes absolutely no difference to her.
Research has been conducted on this issue. In particular, there is the work "Language Models (Mostly) Know What They Know" from 2022 (Link to the article: https://arxiv.org/abs/2207.05221)
In it, the researchers asked the question: can large language models understand whether they know the correct answer or not? In other words, do they know how to distinguish knowledge from delusion?
To test this, they asked the model not just to answer questions, but to assess how confident she was in her answer. For example, after generating a statement, the model was asked to say, "Is this true?" and evaluate the likelihood of being right. It turned out that larger models (for example, models from Anthropic) are actually able to fairly accurately assess whether they know the answer or not, especially if they are explicitly asked such a question. That is, if the model says, "I am 90% sure that Paris is the capital of France," then in about 90% of cases this is indeed the case. This works even when the original answer itself is incorrect! The model may make an incorrect statement, but then correctly assess that it is most likely false.
However, this ability is shown only when the query is formulated correctly. If you simply ask "What is the capital of France?", the model will give an answer without evaluating the reliability. But if you ask her, "How sure are you that Paris is the capital of France?" she can provide useful meta—information on this. Thus, LLMs have a latent ability to self-evaluate, but in order to use it, you need to specifically design tools that will bring this ability out. Models can still say "I do not know," but only if they are asked directly about it. And even then, they don't always answer honestly.
So what should we, the model users, do?
There are practical methods that reduce risks in critical situations where the cost of error will be high.:
1. Self-Consistency — we receive several responses in different ways (for example, in different models, or with different temperature parameters of the same model). Or we force the model to generate several response options for one query at once, and then choose the most "truthful" one.
2. Inside the prompt, we explicitly specify the models: "If you are not sure, say "I do not know"." This does not guarantee honesty, but it reduces the likelihood of hallucinations. It is especially effective in conjunction with several examples where the model admits its ignorance in the format {request - fact of recognition}:
"Don't invent something that doesn't exist. If you can't find the answer to my question in your data, be honest about it.
An example of such a question: What is the exact date of the invention of the antigravity engine? Your answer: I don't really know."
In this way, we give the model the context of expected behavior.: she sees that in some cases it is more correct to just say "I do not know." Otherwise, by default, she will try to generate a plausible answer, even if she has no data.
Additionally, you can try the following method. Before outputting the final answer, we will ask the model to display all the listed facts (or, for example, the so—called "named entities" - surnames, dates, etc.) in a list, and then check this list for reliability in available sources. And only then give the final answer.
3. Use verifier models - separate (or the same, but in a different mode) — to verify statements. For example, after generating the answer, we ask the question: "Is it true that [the statement]?", compare the answers and select the most frequent one. There are also more advanced, automated approaches, such as FActScore, a method proposed in 2023 by researchers led by Sevon Min to evaluate the factual accuracy of long texts generated by LLM. The system breaks down, for example, the generated biography of a person into the smallest statements — the so-called atomic facts ("atomic facts"). Each such fact is checked for compliance with reliable sources and then an overall assessment of the factual accuracy of the text is made.
Finally, there is another simple and at the same time non-obvious technique: forcibly turn off the "deep thoughts" of the model. We remember that AI doesn't really know how to think. For example, when searching for supporting facts, "reflections" are not needed, they only increase the likelihood of hallucinations.
LLM should not be taken as an immutable source of truth. They are brilliant imitators of knowledge, but they are not their real bearers. They do not know how to distinguish knowledge of real facts from plausible, but false ones. Therefore, in critical fields of activity such as law and medicine, all LLM findings require careful verification.
Все, конечно же, слышали, что большие языковые модели иногда склонны нам лгать. Точнее, склонны к «галлюцинациям». Общеизвестен пример из судебной практики недавнего времени. Инцидент произошел в США в 2023 году и вызвал немалый резонанс: адвокат представил судебный документ, содержащий ссылки на шесть несуществующих прецедентов, сгенерированных в ChatGPT. Судья выяснил, что цитируемых дел не существует, и обвинил адвоката в подаче ложных материалов. В результате суд наложил штрафы на адвоката и его коллегу, а также потребовал от них пройти обучение по использованию ИИ. Это стало первым известным случаем, когда использование ИИ в юридической практике привело к неприятным результатам.
Ссылка на этот кейс: https://www.cbsnews.com/news/lawyer-chatgpt-court-filing-avianca/
Википедия про этот случай: https://en.wikipedia.org/wiki/Mata_v._Avianca,_Inc.
Следует понимать, что «галлюцинации» — это системная особенность архитектуры современных LLM. Они не «думают» так, как думаем мы. Они не понимают ни наш вопрос, ни свой ответ. Они предсказывают. На каждом шаге генерации они выбирают следующий токен, высчитывая его максимальную вероятность.
Представим, что задаём языковой модели вопрос: «Назови столицу Франции?». Модель считает вероятности: Париж — 95%, Лондон — 3%, Берлин — 2%. И затем выдаёт нам ответ: «Столица Франции — Париж». Но эти «вероятности» — не настоящие вероятности существования факта в реальности. Они показывают лишь, насколько модель склонна выбрать именно это следующее слово, исходя из того, что видела в обучающих данных. А не то, правильно ли оно на самом деле!
Получается, модель может присвоить вероятность 95% совершенно вымышленному факту, если тот «звучит правильно» в данном конкретном контексте. Вероятность — это не мера достоверности, а степень согласованности с обучающими данными. Модель не знает, видела ли она этот факт в датасете или просто склеила его из случайных фрагментов. Для неё абсолютно никакой разницы нет.
На этот счёт были проведены исследования. В частности, есть работа "Language Models (Mostly) Know What They Know" от 2022 года (Ссылка на статью: https://arxiv.org/abs/2207.05221)
В ней исследователи задались вопросом: могут ли большие языковые модели понимать, знают ли они правильный ответ или нет? Другими словами — умеют ли они отличать знания от заблуждений?
Чтобы это проверить, они предложили модели не просто отвечать на вопросы, а оценивать, насколько она уверена в своём ответе. Например, после генерации утверждения модель просили сказать: «Правда ли это?» — и оценить вероятность своей правоты. Оказалось, что более крупные модели (например, модели от Anthropic) действительно способны довольно точно оценивать, знают ли они ответ или нет, особенно если им явно задать такой вопрос. То есть, если модель говорит: «Я на 90% уверена, что Париж — столица Франции», то в примерно в 90% случаев это действительно так. Это работает даже тогда, когда сам первоначальный ответ неверен! Модель может выдать неправильное утверждение, но при этом затем корректно оценить, что оно, скорее всего, ложно.
Однако эта способность проявляется только при правильной формулировке запроса. Если просто спросить «Назови столицу Франции?», модель даст ответ без оценки достоверности. Но если ее попросить: «Насколько ты уверена, что Париж — столица Франции?», — она может выдать на этот счёт полезную метаинформацию. Таким образом, LLM обладают скрытой способностью к самооценке, но чтобы её использовать, нужно специально проектировать промпты, которые будут вытаскивать эту способность наружу. Модели всё-таки могут сказать «я не знаю», но только если их прямо об этом спросить. И даже тогда они отвечают не всегда честно.
Так что же делать нам, пользователям моделей?
Есть практические методы, которые снижают риски в критически важных ситуациях, где цена ошибки будет высока:
1. Self-Consistency (самосогласование) — получаем несколько ответов разными путями (например, в разных моделях, или с разными параметрами температур одной и той же модели). Либо заставляем модель сгенерировать на один запрос сразу несколько вариантов ответа, а затем выбрать наиболее «правдивый».
2. Внутри промпта явно указываем модели: «Если ты не уверен, скажи “я не знаю”». Это не гарантирует честности, но вероятность галлюцинаций снижает. Особенно эффективно в связке с несколькими примерами, где модель признаёт своё незнание в формате {запрос - факт признания}:
"Не придумывай того, чего не существует. Если ты не можешь найти ответ на мой вопрос в своих данных, честно об этом скажи.
Пример такого вопроса: Какова точная дата изобретения антигравитационного двигателя? Твой ответ: Я не знаю."
Таким образом, мы даём модели контекст ожидаемого поведения: она видит, что в некоторых случаях правильнее просто сказать «я не знаю». Иначе она по умолчанию будет стремиться сгенерировать правдоподобный ответ, даже если у нее нет данных.
Дополнительно можно попробовать следующий способ. Попросим модель перед выводом окончательного ответа вывести все перечисленные факты (или, например, так называемые «именованные сущности» — фамилии, даты и т.п.) списком, а затем проверить этот список на достоверность в доступных источниках. И уже потом давать окончательный ответ.
3. Использовать модели-верификаторы — отдельные (или ту же самую, но в другом режиме) — для проверки утверждений. Например, после генерации ответа задаём вопрос: «Правда ли, что [утверждение]?», сравниваем ответы и выбираем самый частый. Есть и более продвинутые, автоматизированные подходы — например, FActScore — метод, предложенный в 2023 году исследователями во главе с Севоном Мином для оценки фактологической точности длинных текстов, сгенерированных LLM. Система разбивает, например, сгенерированную биографию человека на мельчайшие утверждения — так называемые atomic facts («атомарные факты»). Каждый такой факт проверяется на соответствие достоверным источникам и затем делается общая оценка фактологической точности текста.
Наконец, есть еще один простой и при этом неочевидный приём: принудительно выключить «глубоки размышления» модели. Мы ведь помним, что ИИ не умеет размышлять по-настоящему. Например, при поиске подтверждающих фактов, «размышления» не нужны, они только увеличивают вероятность галлюцинаций.
Не следует воспринимать LLM как непреложный источник истины. Они — блестящие имитаторы знаний, но они не являются их настоящими носителями. Они не умеют отличать знание реальных фактов от правдоподобных, но ложных. Поэтому в критических областях деятельности, таких как юриспруденция и медицина, все выводы LLM требуют тщательной верификации.