/ Модель

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

Контекст
2 048 токенов
Архитектура
codegen · dense
Библиотека
transformers
Опубликована
28 июл 2023

pycompetitive-codegen350M-qlora

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

Дообученная на задачах соревнований модель CodeGen-350M-mono генерирует код на Python по текстовым инструкциям.

141скачиваний за 30 дней1лайквеса обновлены28 июл 2023

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

iamtarun/pycompetitive-codegen350M-qlora — дообученная модель для генерации кода на Python в задачах соревновательного программирования. Разработчик дообучил CodeGen-350M-mono на очищенном наборе задач для соревнований по программированию, используя инструкции в формате Alpaca. Модель построена на архитектуре CodeGenForCausalLM и работает через библиотеку Transformers.

Модель предназначена для генерации решений по текстовому условию задачи и помощи при написании кода для соревнований. Контекст модели составляет 2048 токенов. В карточке указана английская локаль; основная специализация — код на Python. Репозиторий содержит веса PyTorch и Safetensors и распространяется по лицензии базовой модели CodeGen: Apache-2.0.

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

  • генерация решения задачи по программированию на Python
  • создание черновика алгоритма по условию соревнования
  • дополнение Python-кода в стиле соревновательного программирования

Ограничения

Контекст ограничен 2048 токенами; качество решений и корректность кода README не характеризует. Модель специализируется на Python-задачах соревнований и может быть менее подходящей для других языков и общих задач программирования.

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

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

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

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

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

Открыть на Hugging Face

Competitive Programming LLM for Python Language

This model is a finetuned version of codegen350M-mono on cleaned coding competition dataset that uses alpaca style prompts while training.

Prompt function

'''
This function generates prompts using the problem description, sample input, and output examples.
@param1 description: str - text problem description
@param2 inputs: list - list of sample input examples
@param3 outputs: list - list of outputs corresponding to inputs
also, len(inputs) == len(outputs)
'''
def generate_prompt(description, inputs, outputs):
    text = ("Below is a problem description that describes the problem. Write code in Python that appropriately solves the problem.\n\n"
            "### Description:\n"
            f"{description}\n\n")
    assert len(inputs) == len(outputs)
    c = 1
    for inp, out in zip(inputs, outputs):
        text += ("### Input:\n"
                 f"{inp}\n"
                 "### Output:\n"
                 f"{out}\n\n")
        c += 1
        if c > 2:
            break
    text += "### Code:\n"
    return text

Usage

from transformers import AutoModelForCausalLM, AutoTokenizer

# load model and tokenizer
model = AutoModelForCausalLM.from_pretrained("iamtarun/pycompetitive-codegen350M-qlora", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("iamtarun/pycompetitive-codegen350M-qlora")

# loading model for inference
model.eval()

# inference function
'''
This function takes text prompt as input which is generated from the generate_prompt function and returns the generated response

@param1 prompt: str - text prompt generated using generate_prompt function.
'''
def pipe(prompt):
    device = "cuda"
    inputs = tokenizer(prompt, return_tensors="pt").to(device)
    with torch.no_grad():
        output = model.generate(**inputs, 
                                max_length=512,
                                do_sample=True,
                                temperature=0.5,
                                top_p=0.95,
                                repetition_penalty=1.15)
    return tokenizer.decode(output[0].tolist(), 
                            skip_special_tokens=True, 
                            clean_up_tokenization_space=False)

# generating code for a problem description
description = "Mr. Chanek has an integer represented by a string s. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit. Mr. Chanek wants to count the number of possible integer s, where s is divisible by 25. Of course, s must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X. As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes). Input One line containing the string s (1 ≤ |s| ≤ 8). The string s consists of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, _, and X. Output Output an integer denoting the number of possible integer s. Examples Input 25 Output 1 Input _00 Output 9 Input _XX Output 9 Input 0 Output 1 Input 0_25 Output 0 Note In the first example, the only possible s is 25. In the second and third example, s ∈ \{100, 200,300,400,500,600,700,800,900\}. In the fifth example, all possible s will have at least one leading zero."
inputs = ["0\n", "_XX\n", "_00\n", "0_25\n"]
outputs = ["1\n", "9\n", "9\n", "0\n"]
prompt = generate_prompt(description, inputs, outputs)
print(pipe(prompt))
print("\n", "="*100, "\n")

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
CodeGenForCausalLM
Ревизия весов
8cc741d

0 моделей