Авторы : Yue Wang, wang.y@salesforce.com (Salesforce Research Asia) Weishi Wang, weishi.wang@salesforce.com (Salesforce Research Asia; Nanyang Technological University, Singapore) Shafiq Joty, sjoty@salesforce.com (Salesforce Research Asia; Nanyang Technological University, Singapore) Steven C.H. Hoi, shoi@salesforce.com (Salesforce Research Asia) Авторы : Ю Уанг, wang.y@salesforce.com (Salesforce Research Asia) Weishi Wang, weishi.wang@salesforce.com (Salesforce Research Asia; Nanyang Technological University, Сингапур) Shafiq Joty, sjoty@salesforce.com (Salesforce Research Asia; Nanyang Technological University, Сингапур) Стивен Х. Хой, shoi@salesforce.com (Salesforce Research Asia) абстрактный Несмотря на их успех, большинство современных методов либо опираются на кодировочную (или декодер-только) предварительную подготовку, которая является субоптималной для генерирования (или понимания) заданий или обработки кодового фрагмента так же, как и NL, пренебрегая специальными характеристиками PL, таких как типы токенов. Мы представляем CodeT5, унифицированную модель дефендера-декодера-трансформера, которая лучше использует семантику кода, передаваемую от выпущенных идентификаторов. Наша модель использует унифицированную структуру для бесперебойной поддержки задач по генерированию кода и задач по генерированию PL, и позволяет многозадачному обучению. Кроме того, мы предлагаем новую идентификационно-тренировочную модель . https://github.com/salesforce/CodeT5 1 Введение Наличие специальных языковых моделей, таких как BERT ( , ГК РФ ( , , а также Т5 ( , ) значительно повысили производительность в широком спектре задач обработки естественного языка (NLP). Они обычно используют парадигму предварительного обучения, а затем тонкого тонуса, которая направлена на получение генерических языковых представлений посредством самонаблюдательного обучения по крупномасштабным неэтикетированным данным, которые могут быть переданы в пользу множества задач в дальнейшем, особенно тех с ограниченной аннотацией данных. Вдохновленные их успехом, есть много недавних попыток адаптировать эти методы предварительного обучения к языку программирования (PL) ( , · , · , ), показывая многообещающие результаты по задачам, связанным с кодом. Дельфин и др. 2019 Рэдфорд и др. 2019 Рафаэль и др. 2020 Свитковский и Аль. 2020 Канада и др. 2020 Фэн и аль. 2020 Однако, несмотря на их успех, большинство этих моделей полагаются либо на код-только модель, похожую на BERT ( , · , ) или только декодерную модель, такую как GPT ( , Используется для решения задач, связанных с разработкой, разработкой и внедрением программного обеспечения, в том числе с использованием программного обеспечения, например, CodeBERT ( , Кроме того, большинство существующих методов просто используют традиционные методы предварительной подготовки НЛП по исходному коду, рассматривая его как последовательность токенов, таких как НЛ. Это в значительной степени игнорирует богатую структурную информацию в коде, которая жизненно важна для полного понимания семантики кода. Святковский и др. 2020 Фэн и аль. 2020 Канада и Аль. 2020 Фэн и аль. 2020 В этой работе мы представляем CodeT5, предварительно подготовленную модель кодекса-декодера, которая рассматривает информацию типа токенов в коде. , (Seq2Seq) предварительное обучение и было показано, что это полезно как для понимания, так и для генерирования задач на естественном языке. Кроме того, мы предлагаем использовать идентификаторы, выделенные разработчиком, в коде. Идентификатор «binarySearch» на рисунке Чтобы объединить такие специфические для кода знания, мы предлагаем новый идентификатор-сознательный объект, который тренирует модель, чтобы отличить токены, которые являются идентификаторами, и восстановить их, когда они маскируются. Рафаэль и др. 2020 ЕГЭ , 2 Кроме того, мы предлагаем использовать код и сопутствующие ему комментарии для изучения лучшего выравнивания NL-PL. Разработчики часто предоставляют документацию для программ для облегчения лучшего технического обслуживания программного обеспечения ( , В частности, мы рассматриваем генерацию NL→PL и генерацию PL→NL как двойные задачи и одновременно оптимизируем модель на них. Соуса и др. 2005 Мы предварительно обучаем CodeT5 на данных CodeSearchNet ( , Следующая статья ( , ) который состоит из как унимодальных (только PL) так и бимодальных (PL-NL) данных на шести PL. Кроме того, мы дополнительно собираем дополнительные данные C/C# из репозиториев Github с открытым исходным кодом. , ), включая две задачи понимания: обнаружение дефектов кода и обнаружение клонов, а также задачи генерации, такие как кодирование, генерация, перевод и усовершенствование. , мы также изучаем многозадачное обучение, чтобы тонко настроить CodeT5 на несколько задач одновременно, используя код управления задачами в качестве отправки источника. Хусейн и др. 2019 Фэн и аль. 2020 Лу и Аль. 2021 1 Мы представляем одну из первых унифицированных моделей кодировщика-декодера CodeT5, которая поддерживает как понимание кода, так и задачи генерации, а также позволяет многозадачное обучение. Мы предлагаем новый объект предварительного обучения, осведомленный о идентификаторе, который учитывает важную информацию типа токенов (идентификаторы) из кода. Кроме того, мы предлагаем использовать пары NL-PL, которые естественно доступны в исходном коде, чтобы узнать лучшее кросс-модальное выравнивание. Обширные эксперименты показывают, что CodeT5 дает самые современные результаты по четырнадцати подзадачам в CodeXGLUE. Дальнейший анализ показывает, что наш CodeT5 может лучше улавливать семантику кода с предложенной идентификаторно-осознанной предварительной подготовкой и бимодальным двойным генерированием преимущественно для задач NL↔PL. 2 Связанная работа Модели, основанные на архитектуре Трансформера ( , Опыт работы с небулайзером можно условно разделить на три основные категории: ( , Рубль ( , ) и ЭЛЕКТРА ( , , только декодерные модели, такие как GPT ( , , и кодировщик-декодерные модели, такие как MASS ( , ), BART ( , , а также Т5 ( , По сравнению с моделями только с кодировкой и только с декодером, которые соответственно способствуют пониманию и генерированию задач, модели с кодировкой-декодером могут хорошо поддерживать оба типа задач.Они часто используют денозирующие цели предварительного обучения последовательности к последовательности, которые коррумпируют исходный ввод и требуют, чтобы декодер восстановил их.В этой работе мы расширяем T5 на язык программирования и предлагаем новый идентификатор-сознательный денозирующий объект, который позволяет модели лучше понимать код. Pre-training on Natural Language. Васильев и др. 2017 Дельфин и др. 2019 Лиу и Аль. 2019б Кларк и др. 2020 Рэдфорд и др. 2019 Песня и аль. 2019 Льюис и Аль. 2020 Рафаэль и др. 2020 Предварительная подготовка к языку программирования является зарождающейся областью, где много недавней работы пытается расширить методы предтренировки НЛП до исходного кода. , ) и CodeBERT ( , CUBERT использует мощный объектив маскированного языкового моделирования BERT для получения генерического кодоспецифического представления, а CodeBERT дополнительно добавляет замененное обнаружение токенов ( , ) задание изучить НЛ-ПЛ кросс-модальное представление. Помимо моделей в стиле BERT, (на ) и (на ) используют соответственно GPT и UniLM ( , ) для выполнения задания кода. Транскодер ( , В отличие от них, мы исследуем модели кодера-декодера на основе T5 для предварительного обучения языку программирования и поддерживаем более комплексный набор задач. Pre-training on Programming Language. Kanade et al. 2020 Фэн и Аль. 2020 Кларк и др. 2020 Святковский и др. 2020 Иоанн и Аль. 2020 Донг и Аль. 2019 Роджерс и др. 2020 Некоторые возникающие работы ( , · , · , ) в недавней литературе также исследуют рамки Т5 по коду, но они сосредоточены только на ограниченном подсчете задач генерации и не поддерживают задачи понимания, как мы. , ) based on another encoder-decoder model BART can also support both understanding and generation tasks. However, all the above prior work simply processes code in the same way as natural language and largely ignores the code-specific characteristics. Instead, we propose to leverage the identifier information in code for pre-training. Климент и др. 2020 Мавзолей и др. 2021 Ельцин и др. 2021 Ахмад и аль. 2021 Recently, GraphCodeBERT ( , ) включает потоки данных, извлеченные из структуры кода в CodeBERT, в то время как (на ) предложить цель размытия, чтобы использовать структурный аспект PL. Эти модели сосредоточены только на подготовке лучшего кодоспецифического кодера. (на ) предлагает запечатлеть относительные расстояния между кодовыми токенами по структуре кода. Напротив, мы специально ориентируемся на идентификаторы, которые резервируют богатую семантику кода и сливают такую информацию в модель Seq2Seq через две новые задания маркировки идентификаторов и прогнозирования. Иоанн и Аль. 2021 Роджерс и др. 2021 Зюгнер и др. 2021 3 Кодекс5 Наш CodeT5 строится на кодексе-декодере рамки с той же архитектурой, что и T5 ( , Она направлена на получение генерических представлений для языков программирования (PL) и естественного языка (NL) через предварительную подготовку к необозначенному исходному коду. , мы расширяем денозирующую цель Seq2Seq в T5 путем предложения двух заданий маркировки идентификаторов и прогнозирования, чтобы позволить модели лучше использовать информацию типа токенов от PL, которые являются идентификаторами, присвоенными разработчиками. Рафаэль и др. 2020 2 Ниже мы представляем, как CodeT5 кодирует входы PL и NL (§ ) и наши предложенные задания идентификатора-осознания (§ ), с последующим тонким настройкой с конкретными задачами трансферного обучения и многозадачного обучения (§ ) 3.1 3.2 3.3 3.1 Кодирование NL и PL На этапе предварительного обучения наша модель получала бы либо PL-only, либо NL-PL в качестве входов в зависимости от того, сопровождает ли код фрагмент описания NL или нет. Для NL-PL бимодальных входов мы соединяем их в последовательность с токеном разграничителя [SEP] и представляем всю последовательность ввода в формате как = ([См. по ссылке] ) 1*, ..., ВНЖ*, [СЭП], 1*, ..., см*, [СЭП]), где и обозначить количество NL слов токенов и PL код токенов, соответственно. NL слово последовательность будет пустой для PL-только одномодальных входов. x w c n m Чтобы запечатлеть более специфические функции кода, мы предлагаем использовать информацию типа токенов из кода. наименования функций и переменные), поскольку они являются одной из самых PL-агностических особенностей и сохраняют богатую семантику кода. В частности, мы преобразуем сегмент PL в абстрактное синтаксическое дерево (AST) и извлекаем типы узлов для каждого токена кода. ∈ {0*, * 1} для сегмента PL, где каждый ∈ {0*,* 1} представляет собой токен кода Это идентификатор или нет. ЕГЭ , y m Ии ЦИ 3.2 Предварительные тренировочные задачи Теперь мы представляем наши предложенные предтренировочные задачи, которые позволяют CodeT5 изучать полезные паттерны либо из PL-только, либо из бимодальных данных NL-PL. Показано, что предотвращение шумоизоляции последовательности к последовательности (Seq2Seq) является достаточно эффективным в широком наборе задач НЛП ( , · , · , Этот денозирующий объектив обычно сначала коррумпирует исходную последовательность с некоторыми шумовыми функциями, а затем требует, чтобы декодер восстановил оригинальные тексты. , ) that randomly masks spans with arbitrary lengths and then predicts these masked spans combined with some sentinel tokens at the decoder. We refer this task to Как показано на рисунке а) в Identifier-aware Denoising Pre-training. Песня и аль. 2019 Раф-фель и др. 2020 Lewis et al. 2020 Raffel et al. 2020 Masked Span Prediction (MSP) 2 В частности, мы используем тот же уровень коррупции в 15%, что и в T5, и обеспечиваем, чтобы средняя длина диапазона составляла 3, путем равномерного отбора проб в диапазоне от 1 до 5 токенов. путем отбора пробных диапазонов перед токенизацией подсчетов, которая направлена на то, чтобы избежать маскировки частичных субтокенов и оказалась полезной ( , Примечательно, что мы предварительно обучаем совместную модель для различных PL, чтобы выучить прочные кросс-языковые представления. whole word masking Солнце и Аль. 2019 где θ являются параметрами модели, x \mask является маскированным вводом, x mask является маскированной последовательностью, чтобы предсказать из декодера с k обозначающим количество токенов в x mask, и xmask <t является последовательностью span, созданной до сих пор. Для слияния более кодоспецифической структурной информации (тип идентификатора узла в AST) в модель мы предлагаем две дополнительные задачи: и В дополнение к предварительному тренингу. Идентификационные теги (IT) Предсказание маскированного идентификатора (MIP) • Она направлена на то, чтобы уведомить модель о том, является этот токен кода идентификатором или нет, что разделяет аналогичный дух синтаксиса в некоторых инструментах, поддерживаемых разработчиками. (b) мы отображаем окончательные скрытые состояния сегмента PL на коде CodeT5 в последовательность вероятностей • ( 1*, ..., pm*), и вычислите двоичную потерю перекрестной энтропии для маркировки последовательности: Identifier Tagging (IT) 2 p p where Обратите внимание, что, выбрасывая задание в качестве проблемы маркировки последовательности, ожидается, что модель будет улавливать синтаксис кода и структуры потока данных кода. будет • В отличие от маскировки случайного диапазона в MSP, мы маскируем все идентификаторы в сегменте PL и используем уникальный токен Sentinel для всех возникновений одного конкретного идентификатора. где изменение имен идентификаторов не влияет на семантику кода. ( ), мы организуем уникальные идентификаторы с токенами Sentinel в целевую последовательность as shown in Figure Затем мы предсказываем его ауторегрессивным образом: Masked Identifier Prediction (MIP) Заблуждение Роджерс и др. 2021 I 2 where \I является маскированным вводом.Заметьте, что Это более сложная задача, которая требует, чтобы модель понимала семантику кода, основанную на запутанном коде, и связывала случаи одних и тех же идентификаторов. x deobfuscation Мы поочередно оптимизируем эти три потери с одинаковой вероятностью, что составляет нашу предложенную идентификатор-осознание денозирования предварительной подготовки. В предтренировочной фазе декодер видит только дискретные маскированные диапазоны и идентификаторы, что отличается от последующих задач, где декодер должен генерировать либо текущие тексты NL, либо синтаксически корректировать фрагменты кода. Чтобы закрыть разрыв между предтренировкой и тонким настройкой, мы предлагаем использовать бимодальные данные NL-PL для обучения модели для двунаправленной конверсии, как показано на рисунке (d) В частности, мы рассматриваем генерацию NL→PL и генерацию PL→NL как двойные задачи и одновременно оптимизируем модель на них. Bimodal Dual Generation. 2 PL bimodal datapoint, we construct two training instances with reverse directions and add language ids ( <java> и <en> для Java PL и English NL, соответственно). Эта операция также может рассматриваться как особый случай маскировки диапазона T5 путем маскировки полного сегмента NL или PL от бимодальных входов. e.g., 3.3 Файн-тунинг CodeT5 После предварительного обучения по крупномасштабным неэтикетированным данным мы адаптируем CodeT5 к последующим задачам с помощью специального обучения передаче задач или многозадачного обучения. Задачи, связанные с кодом, можно разделить на генерирование и понимание задач. Для первого, наш CodeT5 может быть естественно адаптирован с его рамкой Seq2Seq. Для понимания задач мы исследуем два способа либо генерировать этикетку как последовательность целей unigram ( , ), or predicting it from the vocabulary of class labels based on the last decoder hidden state following (на ). Task-specific Transfer Learning: Generation vs. Understanding Tasks. Raffel et al. 2020 Льюис и Аль. 2020 We also explore a multi-task learning setting by training a shared model on multiple tasks at a time. Multi-task learning is able to reduce computation cost by reusing the most of model weights for many tasks and has been shown to improve the model generalization capability in NL pre-training ( , ). We follow ( ) использовать одну и ту же унифицированную модель для всех задач без добавления каких-либо специфических для задачи сетей, но позволяя выбрать разные лучшие контрольные точки для разных задач. Чтобы уведомить модель о том, с какой задачей она имеет дело, мы разрабатываем унифицированный формат кодов управления задачами и подготавливаем его в исходные входы, как показано на рисунке Например, мы используем «Перевести Java на CSharp»: в качестве источника для задачи перевода кода на код из Java в CSharp. Multi-task Learning. Иоанн и Аль. 2019a Raffel et al. 2020 1 Поскольку различные задачи имеют разные размеры наборов данных, мы следуем Conneau и Lample (2019) для использования стратегии сбалансированного отбора образцов. Для N числа наборов данных (или задач), с вероятностью {qi} N i=1, мы определяем следующее многономическое распределение для выборки из: where ni is number of examples for i-th task and α is set to 0.7. This balanced sampling aims to alleviate the bias towards high-resource tasks. 4 Experimental Setup 4.1 Pre-training Dataset We follow Feng et al. (2020) to employ CodeSearchNet (Husain et al., 2019) to pre-train CodeT5, which consists of six PLs with both unimodal and bimodal data. Apart from that, we additionally collect two datasets of C/CSharp from BigQuery1 to ensure that all downstream tasks have overlapped PLs with the pre-training data. In total, we employ around 8.35 million instances for pretraining. Table 1 shows some basic statistics. To obtain the identifier labels from code, we leverage the tree-sitter2 to convert the PL into an abstract syntax tree and then extract its node type information. We filter out reserved keywords for each PL from its identifier list. We observe that PLs have different identifier rates, where Go has the least rate of 19% and Ruby has the highest rate of 32%. 4.2 Кодоспецифический токенизатор Tokenization is a key ingredient for the success of pre-trained language models like BERT and GPT. They often employ a Byte-Pair Encoding (BPE) to-kenizer ( , ) to alleviate the Out-of-Vocabulary (OoV) issues. Specifically, we train a Byte-level BPE tokenizer following ( ) and set the vocabulary size to 32,000 as T5. We add additional special tokens ([PAD], [CLS], [SEP], [MASK0], ..., [MASK99]). This tokenzier is trained on all of our pre-training data with non-printable characters and low-frequent tokens (occurring <3 times) filtered. We compare it with T5’s default tokenizer and find that our tokenizer largely reduces the length of tokenized code sequence by 30% - 45% on downstream tasks. This will accelerate the training and especially benefit generation tasks due to the shorter sequence to predict. We also spot a severe problem for applying the T5’s default tokenizer on source code, where it would encode some common code tokens such as brackets [‘{’, ‘}’] into unknown tokens. Sennrich et al. 2016 Radford et al. 2019 4.3 Downstream Tasks and Metrics We cover most generation and understanding tasks in the CodeXGLUE benchmark ( , ) and employ the provided public datasets and the same data splits following it for all these tasks. Лу и Аль. 2021 We first consider two cross-modal generation tasks. aims to summarize a function-level code snippet into English descriptions. The dataset consists of six PLs including Ruby, JavaScript, Go, Python, Java, and PHP from CodeSearchNet ( , ). We employ the smoothed BLEU-4 ( , ) to eval-uate this task. Для этого используется специальная схема, основанная на описаниях, используемых в программе «Спец-перевод» ( , ) в Java, где ввод содержит как тексты NL, так и контексты класса, и выход является функцией. , ) that considers syntactic and semantic matches based on the code structure in addition to the n-gram match. Code summarization Husain et al. 2019 Lin and Och 2004 Code generation Iyer et al. 2018 Рен и Аль. 2020 Кроме того, мы рассматриваем две задачи генерации кода-кода. Мы стремимся к миграции прежнего программного обеспечения из одного PL в другой, где мы фокусируемся на переводе функций из Java в CSharp и наоборот. aims to convert a buggy function into a correct one. We employ two Java datasets provided by (на ) with various function lengths: small (fewer than 50 tokens) and medium (50-100 tokens). We use BLEU-4 and exact match to evaluate them. Code translation Code refinement Tufano et al. 2019 We also investigate how CodeT5 performs on two understanding-based tasks. The first one is that aims to predict whether a code is vulnerable to software systems or not. We use the C dataset provided by (на для эксперимента; вторая задача заключается в which aims to measure the similarity between two code snippets and predict whether they have the same functionality. We experiment with the Java data provided by ( ). We employ F1 score and accuracy for evaluating these two tasks respectively. In total, our CodeT5 supports six tasks and fourteen sub-tasks in CodeXGLUE with a unified encoder-decoder model. defect detection Zhou et al. 2019 clone detection Wang et al. 2020 4.4 Comparison Models We compare CodeT5 with state-of-the-art (SOTA) pre-trained models that can be categorized into three types: encoder-only, decoder-only, and encoder-decoder models. As models, we consider RoBERTa ( , ), RoBERTa (code) trained with masked language modeling (MLM) on code, CodeBERT ( , ) обученные как MLM, так и замененной токенной детекции ( , , Графический код БЕРТ ( , ) using data flow from code, and DOBF ( , Обратите внимание, что хотя DOBF использует модель Seq2Seq во время предварительной подготовки, она направлена только на обучение лучшего кодера для последующих задач, не исследуя потенциальных преимуществ предварительно обученного декодера. encoder-only Liu et al. 2019b Feng et al. 2020 Clark et al. 2020 Иоанн и Аль. 2021 Роджерс и др. 2021 For models, we compare GPT-2 ( , ) and its adaptations on code domain including CodeGPT-2, and CodeGPT-adapted. The difference is that the latter one utilizes a GPT-2 checkpoint for model initialization while the former one is trained from scratch. As models, the current SOTA model for the CodeXGLUE benchmark is PLBART ( , ) based on BART ( , ) architecture. For pre-training data, most of these models employ CodeSearchNet ( , DOBF предварительно обучен на 7.9M Java и 3.6M Python файлах от BigQuery, в то время как PLBART использует гораздо большие данные с 470M Python и 210M Java функций, и 47M NL постов от StackOverflow. decoder-only Radford et al. 2019 encoder-decoder Ah-mad et al. 2021 Lewis et al. 2020 Husain et al. 2019 4.5 Model Configurations We build CodeT5 based on Huggingface’s T5 ( , Внедрение PyTorch and employ two sizes of CodeT5-small (60M) and CodeT5-base (220M). We set the maximum source and target sequence lengths to be 512 and 256, respectively. We use the mixed precision of FP16 to accelerate the pre-training. We set the batch size to 1024 and employ the peak learning rate of 2e-4 with linear decay. We pre-train the model with the denoising objective for 100 epochs and bimodal dual training for further 50 epochs on a cluster of 16 NVIDIA A100 GPUs with 40G memory. The total training time for CodeT5-small and CodeT5-base is 5 and 12 days, respectively. Раф-фель и др. 2020 3 На этапе тонкого настройки мы обнаруживаем, что задачи в CodeXGLUE ( , ) are quite sensitive to some hyper parameters such as learning rate, training steps, and batch size. We conduct a grid search and select the best parameters based on the validation set. In multi-task learning, we cover all downstream tasks except clone detection. Lu et al. 2021 5 Results and Analysis In this section, we compare CodeT5 with SOTA models on a broad set of CodeXGLUE downstream tasks (§ ), and investigate the effects of our bimodal dual generation and multi-task learning (§ ), followed by a detailed analysis on the proposed identifier-aware pre-training (§ ). 5.1 5.2 5.3 5.1 CodeXGLUE Downstream Tasks We evaluate two sizes of our model: CodeT5-small and CodeT5-base that are pre-trained with identifier-aware denoising. In addition, we consider the model that continues to train with bimodal dual generation (dual-gen) and show the results with multi-task fine-tuning. The results of all comparison models are obtained from their original papers and also the CodeXGLUE paper ( , ). Лу и Аль. 2021 We show code summarization results of smoothed BLEU-4 on six PL data in Table . We observe all our model variants significantly outperform prior work with either an encode-only (RoBERTa, CodeBERT, DOBF) or encoder-decoder framework (PLBART). Moreover, the salient performance gap between these two groups of models confirms that encode-only frameworks are suboptimal for generation tasks. Compared to the SOTA encoder-decoder model PLBART, we find that even our CodeT5-small yields better overall scores (also on Python and Java) given that our model is much smaller (60M vs. 140M) and PLBART is pre-trained with much larger Python and Java data (> 100 times). We attribute such improvement to our identifier-aware denoising pre-training and better employment of bi-modal training data Увеличивая размер модели, наша база CodeT5 повышает общую производительность более чем на 1,2 абсолютных пункта по сравнению с PLBART. Code Summarization. 2 4 We compare CodeT5 with GPT-style models and PLBART in Table Наш небольшой код CodeT5 превосходит все модули, использующие только декодер, а также SOTA PLBART, что вновь подтверждает превосходство моделей декодера-кодера при генерировании фрагментов кода. Кроме того, наша база CodeT5 значительно повышает результаты SOTA по трем показателям. Code Generation. 3 We compare two code-to-code generation tasks: code translation and code refinement in Table and further consider one naive copy baseline by copying the source input as the target prediction. In the code translation task, our CodeT5-small outperforms most of base-lines and obtains comparable results with PLBART, which shows the advantages of encoder-decoder models in the code-to-code generation setting. Our CodeT5-base further achieves consistent improvements over PLBART across various metrics for translating from Java to C# and vice versa. Code-to-Code Generation Tasks. 4 Здесь мы показываем выход одного CodeT5 от перевода C# на Java на рисунке В этом случае, несмотря на плохой балл BLEU, CodeT5 способен генерировать функцию, которая сохраняет ту же функциональность и даже имеет лучшую четкость по сравнению с базовой правдой. Это показывает, что CodeT5 имеет хорошую способность генерализации вместо того, чтобы запоминать и повторять то, что он видел раньше. 3 Another code-to-code generation task is code refinement, a challenging task that requires detecting which parts of code are buggy and fix them via generating a bug-free code sequence. Due to the large overlap of source and target code, even the naive copy approach yields very high BLEU scores but zero exact matches. Therefore, we focus on the exact match (EM) metric to evaluate on this task. As shown in Table , we observe that EM scores for the small data are consistently higher than the medium one, indicating that it is harder to fix bugs for a longer code snippet. Our CodeT5-base significantly outperforms all baselines on EM and especially boosts over 4.8 points for the more challenging medium task (13.96 vs. GraphCodeBERT’s 9.10), reflecting its strong code understanding capability. 4 We compare with two understanding tasks of defect detection and clone detection in Table 5. Understanding Tasks. Specifically, we generate the binary labels as a unigram sequence from the decoder for the defect detection task, while for the clone detection task, we first obtain the sequence embedding of each code snippet using the last decoder state following ( ) и затем предсказать этикетки, измеряя их сходство. Как CodeT5-small, так и CodeT5-base превосходят все базовые показатели по заданию по обнаружению дефектов, в то время как CodeT5-base приносит 2,6 точного улучшения, чем PLBART. Для задания по обнаружению клонов наши модели CodeT5 достигают сопоставимых результатов с моделями SOTA GraphCodeBERT и PLBART. Эти результаты демонстрируют, что с рамкой кодирования-декодера наш CodeT5 все еще может быть хорошо адаптирован для понимания задач. Льюис и Аль. 2020 5.2 Последствия бимодального двойного поколения и многозадачного обучения We examine the effects of bimodal dual generation at pre-training and multi-task learning at fine-tuning. The bimodal pre-training brings consistent improvements for code summarization and generation tasks on both CodeT5-small and CodeT5-base. However, this pre-training task does not help and even sometimes slightly hurts the performance for PL-PL generation and understanding tasks. We anticipate this is because bimodal dual generation learns a better alignment between PL and NL that naturally benefits the former tasks involving both PL and NL. As a side effect, this objective could bias the model towards the PL-NL tasks and affect its performance on PL-PL tasks. In multi-task learning, it generally improves most of downstream tasks except the code translation and defect detection. Particularly, it largely boosts the performance on code summarization, which is not surprising as code summarization takes up the largest portion of sub tasks (six out of thirteen) and thereby benefit the most from the multi-task learning. Besides, we observe that multi-task learning consistently improves the performance of code refinement, which might benefit from the joint training of both small and medium refinement data. Another possible reason is that multi-task training with defect detection would enable the model to better comprehend the code semantics for bug detection, which is also a necessary intermediate step for code refinement. 5.3 Analyzing Identifier-aware Pre-training We provide an ablation study to examine the contribution of each component in our identifier-aware objective. Specifically, we compare the performance of our CodeT5-small on four selected tasks by ablating each of the three objectives: masked span prediction (MSP), identifier tagging (IT), and masked identifier prediction (MIP). As shown in Table , we observe that generally removing one of the objectives would reduce the performance for all tasks, indicating that all objectives contribute to the better code understanding of our CodeT5. However, the effect of each objective differs across tasks. Specifically, removing MSP would largely reduce the performance of all generation tasks but instead increase the defect detection performance. This shows that masked span prediction is more crucial for capturing syntactic information for generation tasks. On the contrary, removing MIP would hurt the defect detection task the most, indicating that it might focus more on code semantic understanding. By combining these objectives, our CodeT5 can better capture both syntactic and semantic information from code. 6 We further provide outputs from CodeT5 and its variant without MIP and IT on code generation in Figure . We observe that CodeT5 can correctly generate the exact function, while the model without MIP and IT fails to recover the identifiers of “s2” and “hasField”. This shows our identifier-aware denoising pre-training can better distinguish and leverage the identifier information. 4 We also investigate the identifier tagging performance and find it achieves over 99% F1 for all PLs, showing that our CodeT5 can confidently distinguish identifiers in code. We then check whether MSP and MIP tasks would have conflicts as they employ the same sentinel tokens for masking. In identifier masking, all occurrences of one unique identifier are replaced with the same sentinel token, resulting in a many-to-one mapping compared to the one-to-one mapping in span prediction. We compare models pre-trained with either MSP or MIP, and both on these two tasks in Table . We report the prediction accuracy and also the ratio of how often they can generate the same number of predictions as the sentinel tokens. We observe that pre-training only with either MIP or MSP would bias the model towards that task, achieving poor accuracy and higher mismatch in number of predictions when applied to the other task. Interestingly, we find that MIP-only objective can better recover the correct number of predictions in the MSP task than MSP-only does for the MIP task, meaning that it is easier to adapt from many-to-one mapping to one-to-one mapping and difficult for the opposite. At last, combining them can help our model to make a good trade-off on both tasks. 7 6 Conclusion We have presented CodeT5, a pre-trained encoder-decoder model that incorporates the token type information from code. We propose a novel identifier-aware pre-training objective to better leverage the identifiers and propose a bimodal dual generation task to learn a better NL-PL alignment using code and its comments. Our unified model can support both code understanding and generation tasks and allow for multi-task learning. Experiments show that CodeT5 significantly outperforms all prior work in most CodeXGLUE tasks. Further analysis also reveals its better code comprehension capability across various programming languages. Broader Impact and Ethical Consideration Our work generally belongs to NLP applications for software intelligence. With the goal of improving the development productivity of software with machine learning methods, software intelligence research has attracted increasing attention in both academia and industries over the last decade. Software code intelligence techniques can help developers to reduce tedious repetitive workloads, enhance the programming quality and improve the overall software development productivity. This would considerably decrease their working time and also could potentially reduce the computation and operational cost, as a bug might degrade the system performance or even crash the entire system. Our work addresses the fundamental challenge of software code pre-training, our study covers a wide range of code intelligence applications in the software development lifecycle, and the proposed CodeT5 method achieves the state-of-the-art performance on many of the benchmark tasks, showing its great potential benefit towards this goal. We further discuss the ethical consideration of training CodeT5 and the potential risks when applying it into real-world downstream applications: The training datasets in our study are source code including user-written comments from open source Github repositories and publicly available, which do not tie to any specific application. However, it is possible that these datasets would encode some stereotypes like race and gender from the text comments or even from the source code such as variables, function and class names. As such, social biases would be intrinsically embedded into the models trained on them. As suggested by ( ), interventions such as filtration or modulation of generated outputs may help to mitigate these biases in code corpus. Dataset bias. Chen et al. 2021 Our model pre-training requires non-trivial computational resources though we have tried our best to carefully design our experiments and improve experiments to save unnecessary computation costs. In fact, compared to the recent large-scale language model Codex ( , ), наша база CodeT5 имеет гораздо меньший размер модели 220M, чем их 12B (∼ 55×). Кроме того, мы экспериментируем с Google Cloud Platform, которая покупает углеродные кредиты, чтобы уменьшить свой углеродный след, training CodeT5-base produced around 49.25 kg CO2 which was totally off-set by the provider. Furthermore, we release our pre-trained models publicly to avoid repeated training for the code intelligence research community. Computational cost. Chen et al. 2021 e.g., As CodeT5 can be deployed to provide coding assistance such as code generation for aiding developers, automation bias of machine learning systems should be carefully considered, especially for developers who tend to over-rely on the model-generated outputs. Sometimes these systems might produce functions that superficially appear correct but do not actually align with the developer’s intents. If developers unintentionally adopt these incorrect code suggestions, it might cause them much longer time on debugging and even lead to some significant safety issues. We suggest practitioners using CodeT5 should always bear in mind that its generation outputs should be only taken as references which require domain experts for further correctness and security checking. Automation bias. Мы обучаем CodeT5 на существующем корпусе кода, включая CodeSearchNet ( , ) и небольшая часть Google BigQuery, оба из которых изначально собраны из публичных хранилищ Github. personal addresses or identification numbers) from the training data. Though we have conducted multi-rounds of data cleaning to mitigate this before training our models, it is still possible that some sensitive information cannot be completely removed. Besides, due to the non-deterministic nature of generation models like CodeT5, it might produce some vulnerable code to harmfully affect the software and even be able to benefit more advanced malware development when deliberately misused. Security implications. Husain et al. 2019 e.g., Acknowledgements We thank Akhilesh Deepak Gotmare, Amrita Saha, Junnan Li, and Chen Xing for valuable discussions. We thank Kathy Baxter for the ethical review. We also thank our anonymous reviewers for their insightful feedback on our paper. References Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray и Kai-Wei Chang. . In , pages 2655–2668. Association for Computational Linguistics. Unified pre-training Для понимания программы и генерации Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2021, Online, June 6-11, 2021 Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harrison Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, Alex Ray, Raul Puri, Gretchen Krueger, Michael Petrov, Heidy Khlaaf, Girish Sastry, Pamela Mishkin, Brooke Chan, Scott Gray, Nick Ryder, Mikhail Pavlov, Alethea Power, Lukasz Kaiser, Mohammad Bavarian, Clemens Win-ter, Philippe Tillet, Felipe Petroski Such, Dave Cum-mings, Matthias Plappert, Fotios Chantzis, Eliza-beth Barnes, Ariel Herbert-Voss, William Hebgen Guss, Alex Nichol, Alex Paino, Nikolas Tezak, Jie Tang, Igor Babuschkin, Suchir Balaji, Shantanu Jain, William Saunders, Christopher Hesse, Andrew N. Carr, Jan Leike, Joshua Achiam, Vedant Misra, Evan Morikawa, Alec Radford, Matthew Knight, Miles Brundage, Mira Murati, Katie Mayer, Peter Welin-der, Bob McGrew, Dario Amodei, Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba. 2021. . , абс/2107.03374. Оценка больших языковых моделей, обученных коду CoRR Kevin Clark, Minh-Thang Luong, Quoc V. Le и Christopher D. Manning. . In . OpenReview.net. ELECTRA: pre-training text encoders as discriminators rather than generators 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020 Colin B. Clement, Dawn Drain, Jonathan Timcheck, Alexey Svyatkovskiy и Neel Sundaresan. В , страницы 9052–9065 Ассоциация вычислительной лингвистики. Pymt5: многорежимный перевод естественного языка and python code with transformers Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing, EMNLP 2020, Online, November 16-20, 2020 Alexis Conneau and Guillaume Lample. 2019. . In , pages 7057–7067. Cross-lingual language model pretraining Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada Sergio Cozzetti B. de Souza, Nicolas Anquetil и Káthia Marçal de Oliveira. В Страницы A study of the documentation essential to software maintenance Proceedings of the 23rd Annual International Conference on Design of Communication: documenting & Designing for Pervasive Information, SIGDOC 2005, Coventry, UK, September 21-23, 2005 68 – 75 АКМ. Jacob Devlin, Ming-Wei Chang, Kenton Lee и Kristina Toutanova. . In , pages 4171–4186. BERT: pre-training of Глубокие двунаправленные трансформаторы для понимания языка Процедуры Конференции 2019 Североамериканской главы Ассоциации вычислительной лингвистики: технологии человеческого языка, NAACL-HLT 2019, Миннеаполис, МН, США, 2-7 июня 2019 года, том 1 (Долгие и короткие документы) Li Dong, Nan Yang, Wenhui Wang, Furu Wei, Xi-aodong Liu, Yu Wang, Jianfeng Gao, Ming Zhou и Hsiao-Wuen Hon. . In , pages 13042–13054. Unified language model pre-training for natural language understanding and generation Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada Ahmed Elnaggar, Wei Ding, Llion Jones, Tom Gibbs, Tamas Feher, Christoph Angerer, Silvia Severini, Florian Matthes, and Burkhard Rost. 2021. . , абс/2104.02443. Code-Trans: На пути к разрыву языка силикона кодирование через самонаблюдение глубокого обучения и высокое performance computing Корр Zhangyin Feng, Daya Guo, Duyu Tang, Nan Duan, Xi-aocheng Feng, Ming Gong, Linjun Shou, Bing Qin, Ting Liu, Daxin Jiang и Ming Zhou. . In , pages 1536–1547. Association for Computational Linguistics. Код-Берт: предварительно подготовленная модель для программирования и естественных языков Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings, EMNLP 2020, Online Event, 16-20 November 2020 Daya Guo, Shuo Ren, Shuai Lu, Zhangyin Feng, Duyu Tang, Shujie Liu, Long Zhou, Nan Duan, Alexey Svyatkovskiy, Shengyu Fu, Michele Tu-fano, Shao Kun Deng, Colin B. Clement, Dawn Drain, Neel Sundaresan, Jian Yin, Daxin Jiang и Ming Zhou. . In . OpenReview.net. Graphcodebert: Pre-training Представления кода с потоком данных 9th International Conference on Learning Representations, ICLR 2021, Virtual Event, Austria, May 3-7, 2021 Hamel Husain, Ho-Hsiang Wu, Tiferet Gazit, Miltiadis Allamanis и Marc Brockschmidt. . , abs/1909.09436. Code-searchnet challenge: Evaluating the state of semantic code search CoRR Srinivasan Iyer, Ioannis Konstas, Alvin Cheung, and Luke Zettlemoyer. 2018. . In , pages 1643–1652. Association for Computational Linguistics. Mapping language to code В программистском контексте Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, Brussels, Belgium, October 31 - November 4, 2018 Aditya Kanade, Petros Maniatis, Gogul Balakrishnan и Kensen Shi. . In , volume 119 of , pages 5110–5121. PMLR. Learning and evaluating Контекстуальное встраивание исходного кода Proceedings of the 37th International Conference on Machine Learning, ICML 2020, 13-18 July 2020, Virtual Event Proceedings of Machine Learning Research Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Veselin Stoyanov, and Luke Zettlemoyer. 2020. В , pages 7871–7880. Association for Computational Linguistics. BART: denoising sequence-to-sequence pre-training for natural language generation, translation, и понимание Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, ACL 2020, Online, July 5-10, 2020 Chin-Yew Lin and Franz Josef Och. 2004. В . ORANGE: Метод оценки автоматической метрики оценки для машинного перевода COLING 2004, 20th International Conference on Computational Linguistics, Proceedings of the Conference, 23-27 August 2004, Geneva, Switzerland Fang Liu, Ge Li, Yunfei Zhao, and Zhi Jin. 2020. . In Страницы 473 - 485. Multi-task learning based pre-trained language model for code completion 35th IEEE/ACM International Conference on Automated Software Engineering, ASE 2020, Melbourne, Australia, September 21-25, 2020 Xiaodong Liu, Pengcheng He, Weizhu Chen и Jian-feng Gao. . In , pages 4487–4496. Association for Computational Linguistics. Multi-task deep neural networks Для естественного понимания языка Proceedings of the 57th Conference of the Association for Computational Linguistics, ACL 2019, Florence, Italy, July 28- August 2, 2019, Volume 1: Long Papers Иньхан Лю, Майл Отт, Наман Гойал, Дзинфай Ду, Ман-дар Джоши, Дэнки Чен, Омер Леви, Майк Льюис, Люк Зеттлемойер и Веселин Стоянов. . . , abs/1907.11692. Roberta: A robustly optimized BERT pretraining approach Корр Shuai Lu, Daya Guo, Shuo Ren, Junjie Huang, Alexey Svyatkovskiy, Ambrosio Blanco, Colin B. Clement, Dawn Drain, Daxin Jiang, Duyu Tang, Ge Li, Li-dong Zhou, Linjun Shou, Long Zhou, Michele Tu-fano, Ming Gong, Ming Zhou, Nan Duan, Neel Sun-daresan, Shao Kun Deng, Shengyu Fu, and Shujie Liu. 2021. . . , abs/2102.04664. Codexglue: A machine learning benchmark dataset for code understanding and generation CoRR Antonio Mastropaolo, Simone Scalabrino, Nathan Cooper, David Nader-Palacio, Denys Poshyvanyk, Rocco Oliveto, and Gabriele Bavota. 2021. В Страницы 336 - 347. Studying the usage of text-to-text transfer transformer to Поддержка задач, связанных с кодом 43rd IEEE/ACM International Conference on Software Engineering, ICSE 2021, Madrid, Spain, 22-30 May 2021 Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei и Ilya Sutskever. . , 1(8):9. Language Модели – неконтролируемые многозадачные учащиеся OpenAI blog Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. 2020. . . , 21:140:1–140:67. Исследуя границы Трансферное обучение с помощью унифицированного текстового трансформатора J. Mach. Learn. Res. Shuo Ren, Daya Guo, Shuai Lu, Long Zhou, Shujie Liu, Duyu Tang, Neel Sundaresan, Ming Zhou, Am-brosio Blanco, and Shuai Ma. 2020. . АБС 2009 г. 10297. Кодекс: А method for automatic evaluation of code synthesis CoRR Baptiste Rozière, Marie-Anne Lachaux, Lowik Chanussot, and Guillaume Lample. 2020. В Unsupervised translation of programming languages Advances in Neural Information Processing Systems 33: Annual Conference on Neural Information Processing Systems 2020, NeurIPS 2020, December . 6-12 декабря 2020 года, виртуальный Baptiste Rozière, Marie-Anne Lachaux, Marc Szafraniec и Guillaume Lample. . , abs/2102.07492. DOBF: Цель предварительной подготовки к размыванию для языков программирования CoRR Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016. . In Ассоциация компьютерной лингвистики. Neural machine translation of rare words with Подводные единицы Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics, ACL 2016, August 7-12, 2016, Berlin, Germany, Volume 1: Long Papers Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, and Tie-Yan Liu. 2019. . In Объем 97 , pages 5926–5936. PMLR. MASS: masked sequence to se-quence pre-training for language generation Proceedings of the 36th International Conference on Machine Learning, ICML 2019, 9-15 June 2019, Long Beach, California, USA Proceedings of Machine Learning Research Yu Sun, Shuohuan Wang, Yu-Kun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, and Hua Wu. 2019. . . , abs/1904.09223. ERNIE: enhanced representation through knowledge integration CoRR Алексей Свиатковский, Шао Кун Денг, Шэнью Фу и Нил Сундаресан. . In , страницы 1433–1443. Intellicode compose: Создание кода с использованием трансформатора ESEC/FSE ’20: 28th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering, Virtual Event, USA, November 8-13, 2020 Michele Tufano, Cody Watson, Gabriele Bavota, Massimiliano Di Penta, Martin White и Denys Poshy-vanyk. . . , 28(4):19:1–19:29. Эмпирическое исследование об обучении Исправление ошибок в дикой природе через нейронную машину перевод ACM Trans. Softw. Eng. Methodol. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser и Illia Polosukhin. В , pages 5998–6008. Внимание – это все Вам нужно Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, USA Wenhan Wang, Ge Li, Bo Ma, Xin Xia, and Zhi Jin. 2020. . In Страницы 261 - 271. Detecting code clones with graph neural network and flow-augmented abstract syntax tree 27th IEEE International Conference on Software Analysis, Evolution and Reengineering, SANER 2020, London, ON, Canada, February 18-21, 2020 Yaqin Zhou, Shangqing Liu, Jing Kai Siow, Xiaon-ing Du, and Yang Liu. 2019. . In , страницы 10197–10207. Devign: Effective Идентификация уязвимости путем изучения всеобъемлющей семантики программ с помощью графических нейронных сетей Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada Даниэль Цюгнер, Тобиас Киршштейн, Мишеле Катаста, Юре Лесковец и Стефан Гюннеманн. В Открыть OpenReview.net Языково-агностическое представление обучения источнику Код из структуры и контекста IX Международная конференция по образовательным представительствам, ICLR 2021, Виртуальное мероприятие, Австрия, 3-7 мая 2021 года Эта статья доступна в архиве под лицензией CC by 4.0 Deed (Attribution 4.0 International). Эта статья доступна в архиве под лицензией CC by 4.0 Deed (Attribution 4.0 International).