/ Модель

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

Контекст
2 048 токенов
Размер весов
64,3 ГБ
Лицензия
Apache 2.0
Архитектура
codegen · dense
Опубликована
26 апр 2023

codegen2-16B_P

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

CodeGen2-16B_P — авторегрессионная модель Salesforce на 16 млрд параметров для генерации и дополнения программного кода, включая заполнение пропусков.

45 500скачиваний за 30 дней45лайковвеса обновлены31 янв 2025

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CodeGen2-16B_P — авторегрессионная языковая модель для синтеза программного кода из семейства CodeGen2, разработанного Salesforce. Это плотная модель класса CodeGenForCausalLM с 16 млрд параметров; она принимает текст и генерирует продолжение, а также поддерживает заполнение пропусков в коде по контексту до 2048 токенов.

Модель предназначена прежде всего для генерации исполняемого кода по подсказкам на английском языке в виде комментариев и для завершения частично написанных программ. Обучение проводилось на permissive-подмножестве дедуплицированного Stack v1.1. В карточке перечислена поддержка языков программирования C, C++, C#, Dart, Go, Java, JavaScript, Kotlin, Lua, PHP, Python, Ruby, Rust, Scala, shell, SQL, Swift, TypeScript и Vue. Проверка включала HumanEval и HumanEval-Infill.

Модель распространяется в формате PyTorch по лицензии Apache-2.0. Авторы указывают, что выпуск предназначен для исследовательских целей; перед применением следует оценить точность и безопасность результатов. Модель лучше всего подходит для синтеза кода, а качество и уместность сгенерированных программ требуют проверки.

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

  • генерация кода Python по текстовому комментарию
  • автодополнение частично написанной программы
  • заполнение пропуска в исходном коде
  • создание функций по англоязычному описанию
  • генерация фрагментов кода на поддерживаемых языках программирования

Ограничения

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

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

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

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

Также подходит для

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

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

Открыть на Hugging Face

CodeGen2 (CodeGen2-16B)

Model description

CodeGen2 is a family of autoregressive language models for program synthesis, introduced in the paper:

CodeGen2: Lessons for Training LLMs on Programming and Natural Languages by Erik Nijkamp*, Hiroaki Hayashi*, Caiming Xiong, Silvio Savarese, Yingbo Zhou.

Unlike the original CodeGen model family (i.e., CodeGen1), CodeGen2 is capable of infilling, and supports more programming languages.

Four model sizes are released: 1B, 3.7B, 7B, 16B.

How to use

This model can be easily loaded using the AutoModelForCausalLM functionality.

Causal sampling

For regular causal sampling, simply generate completions given the context:

from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("Salesforce/codegen2-16B")
model = AutoModelForCausalLM.from_pretrained("Salesforce/codegen2-16B", trust_remote_code=True, revision="main")

text = "def hello_world():"
input_ids = tokenizer(text, return_tensors="pt").input_ids
generated_ids = model.generate(input_ids, max_length=128)
print(tokenizer.decode(generated_ids[0], skip_special_tokens=True))

Infill sampling

For infill sampling, we introduce three new special token types:

  • <mask_N>: N-th span to be masked. In practice, use <mask_1> to where you want to sample infill.
  • <sep>: Separator token between the suffix and the infilled sample. See below.
  • <eom>: "End-Of-Mask" token that model will output at the end of infilling. You may use this token to truncate the output.

For example, if we want to generate infill for the following cursor position of a function:

def hello_world():
    |
    return name

we construct an input to the model by

  1. Inserting <mask_1> token in place of cursor position
  2. Append <sep> token to indicate the boundary
  3. Insert another <mask_1> to indicate which mask we want to infill.

The final snippet looks as follows:

from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("Salesforce/codegen2-16B")
model = AutoModelForCausalLM.from_pretrained("Salesforce/codegen2-16B", trust_remote_code=True, revision="main")


def format(prefix, suffix):
  return prefix + "<mask_1>" + suffix + "<|endoftext|>" + "<sep>" + "<mask_1>"


prefix = "def hello_world():\n    "
suffix = "    return name"
text = format(prefix, suffix)
input_ids = tokenizer(text, return_tensors="pt").input_ids
generated_ids = model.generate(input_ids, max_length=128)
print(tokenizer.decode(generated_ids[0], skip_special_tokens=False)[len(text):])

You might want to truncate the model output with <eom>.

Training data

This checkpoint is trained on the stricter permissive subset of the deduplicated version of the Stack dataset (v1.1). Supported languages (and frameworks) are as follows: c, c++, c-sharp, dart, go, java, javascript, kotlin, lua, php, python, ruby, rust, scala, shell, sql, swift, typescript, vue.

Training procedure

CodeGen2 was trained using cross-entropy loss to maximize the likelihood of sequential inputs. The input sequences are formatted in two ways: (1) causal language modeling and (2) file-level span corruption. Please refer to the paper for more details.

Evaluation results

We evaluate our models on HumanEval and HumanEval-Infill. Please refer to the paper for more details.

Intended use and limitations

As an autoregressive language model, CodeGen2 is capable of extracting features from given natural language and programming language texts, and calculating the likelihood of them. However, the model is intended for and best at program synthesis, that is, generating executable code given English prompts, where the prompts should be in the form of a comment string. The model can complete partially-generated code as well.

Ethical Considerations

This release is for research purposes only in support of an academic paper. Our models, datasets, and code are not specifically designed or evaluated for all downstream purposes. We strongly recommend users evaluate and address potential concerns related to accuracy, safety, and fairness before deploying this model. We encourage users to consider the common limitations of AI, comply with applicable laws, and leverage best practices when selecting use cases, particularly for high-risk scenarios where errors or misuse could significantly impact people’s lives, rights, or safety. For further guidance on use cases, refer to our AUP and AI AUP.

BibTeX entry and citation info

@article{Nijkamp2023codegen2,
  title={CodeGen2: Lessons for Training LLMs on Programming and Natural Languages},
  author={Nijkamp, Erik and Hayashi, Hiroaki and Xiong, Caiming and Savarese, Silvio and Zhou, Yingbo},
  journal={arXiv preprint},
  year={2023}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей