/ Модель

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

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

codet5-small

Языковая модель7 профессий

Небольшая предварительно обученная модель Salesforce для понимания и генерации кода, предназначенная для дообучения под конкретные задачи разработки.

15 152скачиваний за 30 дней81лайквеса обновлены21 янв 2025

Бенчмарки

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

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

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

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

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

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

Salesforce/codet5-small — небольшая предварительно обученная модель CodeT5, разработанная Salesforce Research и представленная в статье о моделях кодирования и генерации кода с учетом идентификаторов. Это плотный энкодер-декодер Transformer семейства T5 с 38,5 млн параметров и контекстом до 512 токенов; модель распространяется в формате PyTorch. Она обучена на CodeSearchNet и дополнительных корпусах C/CSharp, чтобы поддерживать задачи понимания и генерации кода. Модель предназначена прежде всего для дальнейшей настройки под конкретную задачу: суммаризации, генерации и перевода кода, его рефакторинга, обнаружения дефектов и поиска клонов. Также её можно применять для предсказания замаскированных фрагментов.

CodeT5 использует специализированный для кода BPE-токенизатор и связывает программный код с естественно-языковыми комментариями. Это предварительно обученная базовая модель, а не готовое решение для конкретной прикладной задачи, поэтому качество в целевом сценарии зависит от дообучения и проверки. Карточка отмечает, что модель не оценивалась для всех вариантов применения и рекомендует проверять точность и безопасность перед внедрением. Лицензия — Apache 2.0.

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

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

Ограничения

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

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

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

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

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

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

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

Открыть на Hugging Face

CodeT5 (small-sized model)

Pre-trained CodeT5 model. It was introduced in the paper CodeT5: Identifier-aware Unified Pre-trained Encoder-Decoder Models for Code Understanding and Generation by Yue Wang, Weishi Wang, Shafiq Joty, Steven C.H. Hoi and first released in this repository.

Disclaimer: The team releasing CodeT5 did not write a model card for this model so this model card has been written by the Hugging Face team (more specifically, nielsr).

Model description

From the abstract:

"We present CodeT5, a unified pre-trained encoder-decoder Transformer model that better leverages the code semantics conveyed from the developer-assigned identifiers. Our model employs a unified framework to seamlessly support both code understanding and generation tasks and allows for multi-task learning. Besides, we propose a novel identifier-aware pre-training task that enables the model to distinguish which code tokens are identifiers and to recover them when they are masked. Furthermore, we propose to exploit the user-written code comments with a bimodal dual generation task for better NL-PL alignment. Comprehensive experiments show that CodeT5 significantly outperforms prior methods on understanding tasks such as code defect detection and clone detection, and generation tasks across various directions including PL-NL, NL-PL, and PL-PL. Further analysis reveals that our model can better capture semantic information from code."

Intended uses & limitations

This repository contains the pre-trained model only, so you can use this model for masked span prediction, as shown in the code example below. However, the main use of this model is to fine-tune it for a downstream task of interest, such as:

  • code summarization
  • code generation
  • code translation
  • code refinement
  • code defect detection
  • code clone detection.

See the model hub to look for fine-tuned versions on a task that interests you.

How to use

Here is how to use this model:

from transformers import RobertaTokenizer, T5ForConditionalGeneration

tokenizer = RobertaTokenizer.from_pretrained('Salesforce/codet5-small')
model = T5ForConditionalGeneration.from_pretrained('Salesforce/codet5-small')

text = "def greet(user): print(f'hello <extra_id_0>!')"
input_ids = tokenizer(text, return_tensors="pt").input_ids

# simply generate a single sequence
generated_ids = model.generate(input_ids, max_length=10)
print(tokenizer.decode(generated_ids[0], skip_special_tokens=True))
# this prints "user: {user.name}"

Training data

The CodeT5 model was pretrained on CodeSearchNet Husain et al., 2019. Additionally, the authors collected two datasets of C/CSharp from BigQuery1 to ensure that all downstream tasks have overlapped programming languages with the pre-training data. In total, around 8.35 million instances are used for pretraining.

Training procedure

Preprocessing

This model uses a code-specific BPE (Byte-Pair Encoding) tokenizer. One can prepare text (or code) for the model using RobertaTokenizer, with the files from this repository.

Evaluation results

For evaluation results on several downstream benchmarks, we refer to the paper.

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

@misc{wang2021codet5,
      title={CodeT5: Identifier-aware Unified Pre-trained Encoder-Decoder Models for Code Understanding and Generation}, 
      author={Yue Wang and Weishi Wang and Shafiq Joty and Steven C. H. Hoi},
      year={2021},
      eprint={2109.00859},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

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

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

GPU в ailist

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

Нельзя запустить

У модели не указана задача.

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

0 моделей