/ Модель

Характеристики

Контекст
512 токенов
Параметры
38,5 млн
Лицензия
OpenRAIL
Архитектура
t5 · dense
Опубликована
7 апр 2023

Cadet-Tiny

Генерация текстаТекст → текст3 профессии

Небольшая англоязычная разговорная модель на базе T5 для генерации ответов, в том числе на устройствах с ограниченными ресурсами.

655скачиваний за 30 дней6лайковвеса обновлены12 мая 2023

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

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

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Cadet-Tiny — небольшая разговорная модель, созданная Todd Goldfarb по мотивам Cosmo-XL и дообученная на наборе данных SODA от AI2. Она основана на предварительно обученной модели Google t5-small и предназначена для генерации ответов в диалоге, в том числе на маломощных устройствах вроде Raspberry Pi с 2 ГБ оперативной памяти.

Модель использует архитектуру T5 с последовательным преобразованием текста в текст, содержит 38,5 млн параметров и рассчитана на контекст до 512 токенов. Указана поддержка английского языка. Репозиторий содержит веса PyTorch, а лицензия — OpenRAIL.

Малый размер упрощает запуск на периферийных устройствах, однако модель обучена на SODA и ориентирована на простые разговорные сценарии; качество и надёжность для сложных задач или иных областей в карточке не заявлены.

Сценарии применения

  • генерация реплик в простом диалоге
  • создание разговорного прототипа на маломощном устройстве
  • эксперименты с обучением seq2seq-модели на SODA

Ограничения

Модель очень мала и обучена на SODA, поэтому её применение рассчитано на простые разговорные сценарии; качество на сложных задачах и за пределами английского языка не заявлено. Контекст ограничен 512 токенами.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

What is Cadet-Tiny?

Inspired by Allen AI's Cosmo-XL, Cadet-Tiny is a very small conversational model trained off of the SODA dataset. Cadet-Tiny is intended for inference at the edge (on something as small as a 2GB RAM Raspberry Pi).

Cadet-Tiny is trained off of the t5-small pretrained model from Google, and is, as a result, is about 2% of the size of the Cosmo-3B model.

This is my first SEQ2SEQ NLP Model I've ever made! I'm very excited to share it here on HuggingFace! :)

If you have any questions, or any comments on improvements, please contact me at: tcgoldfarb@gmail.com

Google Colab Link

Here is the link to the Google Colab file, where I walk through the process of training the model and using the SODA public dataset from AI2.

https://colab.research.google.com/drive/1cx3Yujr_jGQkseqzXZW-2L0vEyEjds_s?usp=sharing

Get Started With Cadet-Tiny

Use the code snippet below to get started with Cadet-Tiny!

import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import colorful as cf

cf.use_true_colors()
cf.use_style('monokai')
class CadetTinyAgent:
    def __init__(self):
        print(cf.bold | cf.purple("Waking up Cadet-Tiny..."))
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.tokenizer = AutoTokenizer.from_pretrained("t5-small", model_max_length=512)
        self.model = AutoModelForSeq2SeqLM.from_pretrained("ToddGoldfarb/Cadet-Tiny", low_cpu_mem_usage=True).to(self.device)
        self.conversation_history = ""

    def observe(self, observation):
        self.conversation_history = self.conversation_history + observation
        # The number 400 below is just a truncation safety net. It leaves room for 112 input tokens.
        if len(self.conversation_history) > 400:
            self.conversation_history = self.conversation_history[112:]

    def set_input(self, situation_narrative="", role_instruction=""):
        input_text = "dialogue: "

        if situation_narrative != "":
            input_text = input_text + situation_narrative

        if role_instruction != "":
            input_text = input_text + " <SEP> " + role_instruction

        input_text = input_text + " <TURN> " + self.conversation_history

        # Uncomment the line below to see what is fed to the model.
        # print(input_text)

        return input_text

    def generate(self, situation_narrative, role_instruction, user_response):
        user_response = user_response + " <TURN> "
        self.observe(user_response)

        input_text = self.set_input(situation_narrative, role_instruction)

        inputs = self.tokenizer([input_text], return_tensors="pt").to(self.device)
        
        # I encourage you to change the hyperparameters of the model! Start by trying to modify the temperature.
        outputs = self.model.generate(inputs["input_ids"], max_new_tokens=512, temperature=0.75, top_p=.95,
                                      do_sample=True)
        cadet_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
        added_turn = cadet_response + " <TURN> "
        self.observe(added_turn)

        return cadet_response

    def reset_history(self):
        self.conversation_history = []

    def run(self):
        def get_valid_input(prompt, default):
            while True:
                user_input = input(prompt)
                if user_input in ["Y", "N", "y", "n"]:
                    return user_input
                if user_input == "":
                    return default

        while True:
            continue_chat = ""

            # MODIFY THESE STRINGS TO YOUR LIKING :)
            situation_narrative = "Imagine you are Cadet-Tiny talking to ???."
            role_instruction = "You are Cadet-Tiny, and you are talking to ???."

            self.chat(situation_narrative, role_instruction)
            continue_chat = get_valid_input(cf.purple("Start a new conversation with new setup? [Y/N]:"), "Y")
            if continue_chat in ["N", "n"]:
                break

        print(cf.blue("CT: See you!"))

    def chat(self, situation_narrative, role_instruction):
        print(cf.green(
            "Cadet-Tiny is running! Input [RESET] to reset the conversation history and [END] to end the conversation."))
        while True:
            user_input = input("You: ")
            if user_input == "[RESET]":
                self.reset_history()
                print(cf.green("[Conversation history cleared. Chat with Cadet-Tiny!]"))
                continue
            if user_input == "[END]":
                break
            response = self.generate(situation_narrative, role_instruction, user_input)
            print(cf.blue("CT: " + response))


def main():
    print(cf.bold | cf.blue("LOADING MODEL"))

    CadetTiny = CadetTinyAgent()
    CadetTiny.run()


if __name__ == '__main__':
    main()

Citations and Special Thanks

Special thanks to Hyunwoo Kim for discussing with me the best way to use the SODA dataset. If you haven't looked into their work with SODA, Prosocial-Dialog, or COSMO, I recommend you do so! As well, read the paper on SODA! The article is listed below.

@article{kim2022soda,
    title={SODA: Million-scale Dialogue Distillation with Social Commonsense Contextualization},
    author={Hyunwoo Kim and Jack Hessel and Liwei Jiang and Peter West and Ximing Lu and Youngjae Yu and Pei Zhou and Ronan Le Bras and Malihe Alikhani and Gunhee Kim and Maarten Sap and Yejin Choi},
    journal={ArXiv},
    year={2022},
    volume={abs/2212.10465}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Класс архитектуры
T5ForConditionalGeneration
Ревизия весов
04d1210

0 моделей