模型:
A generative model based on sberbank-ai/rugpt3large_based_on_gpt2 for restoring complete text of dialogues from context.
Suppose the last 2 lines of the dialogue are as follows:
- Как тебя зовут? - Джульетта Мао
The model allows obtaining the complete text of the last utterance, with resolved anaphora, ellipsis, etc.:
Меня зовут Джульетта Мао
The resolved utterance enables the use of many classical NLP tools for processing, including regular expressions, intent classifiers, etc.
For more details on the situations handled by the model, please refer to the end of the page and этом документе .
This model works in a prototype диалоговой системы . It does not require any pre- or post-processing, apart from the standard practices for GPT models, making it very simple to use:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "inkoziev/rugpt_interpreter"
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.add_special_tokens({'bos_token': '<s>', 'eos_token': '</s>', 'pad_token': '<pad>'})
model = AutoModelForCausalLM.from_pretrained(model_name)
model.to(device)
model.eval()
# На вход модели подаем последние 2-3 реплики диалога. Каждая реплика на отдельной строке, начинается с символа "-"
# В конце добавляем символ "#"
input_text = """<s>- Как тебя зовут?
- Джульетта Мао #"""
#input_text = """<s>- Что Предтечи забрали у Предшественников?
#- Они узурпировали у них Мантию — защиту всего живого в галактике #"""
encoded_prompt = tokenizer.encode(input_text, add_special_tokens=False, return_tensors="pt").to(device)
output_sequences = model.generate(input_ids=encoded_prompt, max_length=100, num_return_sequences=1, pad_token_id=tokenizer.pad_token_id)
text = tokenizer.decode(output_sequences[0].tolist(), clean_up_tokenization_spaces=True)[len(input_text)+1:]
text = text[: text.find('</s>')]
print(text)
The model receives tokenized input data consisting of 2 or 3 recent dialogues. The first token should be <s>. Each utterance should start with the prefix "- ". Utterances are separated by newline characters. The last utterance, to be restored, should have the substring " #" added to it.
<s>- Как тебя зовут? - Джульетта Мао #
The model is being developed for use in чатботе . It supports some atypical situations in chat that are listed below.
In the examples, after the ⇒ symbol, the expected resolved utterance is shown, which the model should generate.
- Как же тебя зовут, а? - Меня – Стас, а тебя? ⇒ Меня зовут Стас. Как тебя зовут?
In rare cases, the main word in a phrase can be omitted, and the model will attempt to restore it:
- Мама, купи мне собаку. - А ты будешь за ней ухаживать? - А ты мне здоровую купи. ⇒ купи мне здоровую собаку
Анафора :
- Ты собак любишь? - Не люблю я их ⇒ я не люблю собак
Sometimes, resolving the complete utterance requires the use of common sense, and the model will rely on pre-training statistics for this:
- Мне на голову упала коробка. - А что в ней было? ⇒ что было в коробке|голове?
Гэппинг :
- Ты кошек любишь? - Их – нет ⇒ я не люблю кошек
Complex gapping:
- В 25 лет вы получаете пенсию? - Не я - отец. ⇒ Я не получаю пенсию. Отец получает пенсию
Restoration of optional pronoun subjects (see pro drop ):
- Согласна? - Да ⇒ я согласна
The model tries to "read between the lines" and restore implied parts of the utterance:
- Ты разве ещё не ел? - Тебя ждал ⇒ я еще не ел. я ждал тебя.
Negations in dialogue:
- Я не прав? - Нет. (Да.) ⇒ ты не прав
Interpretation does not involve copying words from the context, and sometimes the model needs to add words associated with the situation:
- Как прошли выходные? - В Простоквашино ездила... ⇒ я на выходных ездила в Простоквашино
All of the above can occur in different combinations simultaneously:
- Где твой кот? - Жена к ветеринару повезла. ⇒ жена повезла моего кота к ветеринару - Заболел? ⇒ твой кот заболел?
Complex sentences:
- Я сварила суп, иди ешь. - Из чего? ⇒ из чего ты сварила суп?
The replacement of the subject is made if it improves the understanding of the utterance:
- Как себя чувствует твой попугай? - Бедняга умер... ⇒ мой попугай умер
Sometimes, only an adverb remains from the utterance, and the model will restore everything else:
- Девушка, а Вы животных любите? - Очень! ⇒ я очень люблю животных
The form of the predicate can sometimes change for the sake of agreement:
- Рабинович, как думаете, что будет делать правительство, если завтра население разом бросит курить? - Таки, поднимут акцизы на алкоголь... ⇒ правительно поднимет акцизы на алкоголь, если завтра население разом бросит курить
In all cases, the model does not provide any information about where it got the substitution for replacement or filling in the output text. The resulting text is simply the utterance in the way a human would say it, without any additional references or markers:
- У тебя брат есть? - Да, есть - Где он работает? ⇒ Где работает твой брат?
In this example, the model will not tell us where it got the substitution "твой брат" for the pronoun "он". This greatly simplifies the manual annotation of the training corpus and does not interfere with the dialogue system much.
In many cases, the model arranges the word order to a more or less canonical one. More precisely, it tries to output text with a word order that is typically used by language speakers in the given dialogue context. If Russian speakers prefer OVS instead of the formal SVO, the model will output OVS:
- У тебя штрафы были? - Нет, их никогда не было ⇒ у меня никогда не было штрафов
The model usually includes personal pronouns even if the verb form allows avoiding them:
- Жару любишь? - Ненавижу ее ⇒ я ненавижу жару
Complex coordinated responses are split into separate clauses, so that the downstream pipeline can process them sequentially:
- Тебя как зовут? - Кортана, а тебя как? ⇒ Меня зовут Кортана. Как тебя зовут?
You can provide the last 2 or 3 utterances as context. Longer relations are rare and do not justify complicating the dataset. In addition, in many cases, it is sufficient to apply the model recursively - feed the output of the initial dialogue utterances to the model instead of the original ones:
- Где живешь? - В Шанхае ⇒ я живу в Шанхае - Давно? ⇒ ты давно живешь в Шанхае? - Два года уже ⇒ я уже два года живу в Шанхае - Как там погода? ⇒ как там погода в Шанхае?
Lastly, it should be noted that the model is only trained on short dialogue data (chitchat). It is almost incapable of resolving anaphora in literary texts, although this is not a limitation of the model, but a feature of the training dataset.
The first column contains the dialogue модели читчата with itself, and the second column contains the results of the model's utterance resolution:
- Добрый вечер, бро! | - Чё, будем общаться? | Мы будем общаться? - Ага, а как же | Мы будем общаться - О чем хочешь говорить? | О чем ты хочешь говорить? - Давай о чем-нибудь хорошем | Я хочу говорить о чем-нибудь хорошем - Мне нравится обсуждать компьютерные игры | Мне нравится обсуждать компьютерные игры - О, компьютерные игры меня тоже интересуют | Меня тоже интересуют компьютерные игры - Ты играл в Minecraft? | Ты играл в Minecraft? - Неа, но хотел бы | Я не играл в игру Minecraft. Я хочу поиграть в игру Minecraft.
Training data without augmentation: inkoziev/incomplete_utterance_restoration .
If you have any questions about using this model or suggestions for its improvement, please contact me at mentalcomputing@gmail.com
@MISC{rugpt_interpreter,
author = {Ilya Koziev},
title = {Incomplete Utterance Restoration in Russian Chit-Chat conversations},
url = {https://huggingface.co/inkoziev/rugpt_interpreter},
year = 2022
}