Search

Search papers and lessons

CodeT5: Identifier-aware Encoder-Decoder Models for Code

Yue Wang, Weishi Wang, Shafiq Joty et al. · 2021

CodeT5 is a T5-style encoder-decoder pre-trained on source code, with an objective that teaches it which tokens are identifiers and a bimodal task that pairs code with its comments.

On this page

  • Colour = topic mix
  • Discrete math
  • Architectures
  • Calculus
  • Neural network basics
  • Linear algebra
  • Probability
  • ReadReady to readNot yet

TL;DR

CodeT5 is a model that reads and writes source code, and it is pre-trained on unlabelled code the way language models are pre-trained on text. Its key idea is that code has a structure plain text lacks: developers choose meaningful names for functions and variables, so the model is trained to tell identifiers from other tokens and to recover them when they are hidden. It also learns from code paired with its comments, in both directions. One model handles both understanding tasks, such as detecting bugs, and generation tasks, such as writing a summary or a function.

Builds on: Exploring the Limits of Transfer Learning (T5), Abstract Syntax Tree, Cross-Entropy Loss, Subword Tokenization · Leads to: code-specific encoder-decoder models, and identifier-aware objectives as a way to give a code model structure without a full parser at test time.

Why it mattered

Before this paper, most pre-trained code models were either encoder-only, which suits understanding tasks such as search and classification, or decoder-only, which suits generation. Each needed extra machinery for the other kind of task. The paper's authors argue that an encoder-decoder can do both with one set of weights, and they show it on the CodeXGLUE benchmark, which groups code tasks into understanding and generation sub-tasks.

The paper reports state-of-the-art results on most of the fourteen CodeXGLUE sub-tasks it covers, with models of 60 million (small) and 220 million (base) parameters. The pre-training corpus is about 8.35 million instances, drawn from CodeSearchNet's six languages plus C and C# files collected from public GitHub repositories through BigQuery. Pre-training took 5 days for the small model and 12 days for the base model on 16 A100 GPUs. The paper also reports a tokenizer change that shortens code sequences by 30 to 45 percent on downstream tasks, which speeds up training and makes generation cheaper.

The problem

Earlier pre-training for code treated source code the way it treats English: as a sequence of tokens. A model trained that way sees binarySearch as a sequence of subword pieces, with no sign that it names a function. It also cannot tell an identifier from a keyword or a bracket, although that distinction carries much of the meaning in code.

A second gap is between code and its documentation. Most code in public repositories has a comment or docstring that describes it, so there are many natural pairs of natural language and code. Models that train on code alone do not use that alignment directly. The paper asks two questions: can the model be given the token-type information that a parser provides, and can the pairs of comments and code be used to train it to translate in both directions?

How it works

Here is one function traced through the pipeline. The code is def add(a, b): return a + b, and it comes with the docstring "returns the sum of two numbers".

flowchart TD
  A["Docstring and code joined with separators"] --> B["Parse code into an AST; label each token identifier or not"]
  B --> C["Choose one objective at random, with equal chance"]
  C --> D["Span masking: hide about 15 percent of tokens in spans"]
  C --> E["Identifier tagging: predict identifier or not for each token"]
  C --> F["Masked identifier prediction: hide every identifier and predict them"]
  D --> G["Bimodal dual generation: docstring to code and code to docstring"]
  E --> G
  F --> G
  G --> H["Fine-tune for a task, with a task prompt for multi-task training"]
  1. Join the two parts. The docstring words go first, then a separator, then the code tokens, then a final separator. For this function, the input is the docstring followed by the code. Without a docstring, the first part is empty.

  2. Parse the code and label the identifiers. The code is parsed into an abstract syntax tree with the tree-sitter parser, and each token is labelled 1 if its node is an identifier and 0 otherwise. The tokens of def add(a, b): return a + b are def, add, (, a, ,, b, ), :, return, a, +, b. Their labels are 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1. The function name add and the variables a and b are identifiers; the keywords and symbols are not.

  3. Pick one pre-training objective. The model alternates among three objectives with equal chance. Each one builds a different skill.

    • Masked span prediction hides about 15 percent of the tokens in short spans and asks the decoder to write the hidden spans back. It follows the T5 objective, and it teaches general syntax.
    • Identifier tagging asks the encoder to label each token as identifier or not. It teaches the model which tokens name things.
    • Masked identifier prediction hides every identifier in the code, giving each distinct name one placeholder, and asks the decoder to output the names. For our function, the masked input is def S0(S1, S2): return S1 + S2, where S0, S1 and S2 stand for the sentinel tokens the model uses, and the target is S0 add S1 a S2 b. The model must work out from the code what each placeholder stands for, and it must link every occurrence of a to the same placeholder.
  4. Use the pairs in both directions. The docstring-and-code pair is turned into two training examples: docstring to code, and code to docstring. A language tag such as "java" or "en" is added to tell the model which direction it is in. This is the bimodal dual generation step.

  5. Adapt to a task. For generation tasks, such as summarising a function, the fine-tuned model writes its output directly. For understanding tasks, the model either writes the label as a word, as in defect detection, or produces a sequence embedding that is compared with another, as in clone detection.

  6. Optionally train on several tasks at once. A short task prefix, such as "Translate Java to CSharp:", is added to each input so one model can serve many tasks. Tasks are sampled in a balanced way so that large datasets do not drown out small ones.

The math

Definition (the pre-training objective). CodeT5 optimises three losses, and each training step uses one of them. Let x\mathbf{x} be the input sequence, θ\theta the model parameters, and θe\theta_e the encoder parameters. The input is

x=([CLS],w1,…,wn,[SEP],c1,…,cm,[SEP]),\mathbf{x} = \left(\text{[CLS]}, w_1, \dots, w_n, \text{[SEP]}, c_1, \dots, c_m, \text{[SEP]}\right),

where w1w_1 to wnw_n are the docstring words and c1c_1 to cmc_m are the code tokens.

Step 2 in symbols: the identifier labels

Each code token gets a label yi∈{0,1}y_i \in \{0, 1\}, so y∈{0,1}m\mathbf{y} \in \{0, 1\}^m, with yi=1y_i = 1 when token cic_i is an identifier. The model outputs a probability pip_i that token ii is an identifier. Identifier tagging minimises the binary cross-entropy summed over the code tokens,

LIT(θe)=∑i=1m−[yilog⁡pi+(1−yi)log⁡(1−pi)].\mathcal{L}_{IT}(\theta_e) = \sum_{i=1}^{m} -\left[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \right].

This is the per-token version of

. Each token adds one term, and the term is small when pip_i is close to yiy_i.

Step 3 in symbols: span masking

Span masking hides spans of kk tokens in total, with an average span length of 3 tokens, and asks the decoder to recover them in order. The masked input is written x\mask\mathbf{x}^{\backslash \text{mask}}, and the hidden tokens are x1mask,…,xkmask\mathbf{x}^{\text{mask}}_1, \dots, \mathbf{x}^{\text{mask}}_k. The loss is

LMSP(θ)=∑t=1k−log⁡Pθ(xtmask∣x\mask,x<tmask).\mathcal{L}_{MSP}(\theta) = \sum_{t=1}^{k} -\log P_\theta\left(\mathbf{x}^{\text{mask}}_t \mid \mathbf{x}^{\backslash \text{mask}}, \mathbf{x}^{\text{mask}}_{<t}\right).

The term Pθ(⋅∣⋅)P_\theta(\cdot \mid \cdot) is the probability the model assigns to the correct hidden token given the visible input and the hidden tokens already written.

Step 4 in symbols: masked identifier prediction

Let I\mathbf{I} be the target sequence that lists each distinct identifier after its sentinel, with ∣I∣|\mathbf{I}| entries, and let I<j\mathbf{I}_{<j} be the entries written so far. The loss is

LMIP(θ)=∑j=1∣I∣−log⁡Pθ(Ij∣x\I,I<j),\mathcal{L}_{MIP}(\theta) = \sum_{j=1}^{|\mathbf{I}|} -\log P_\theta\left(\mathbf{I}_j \mid \mathbf{x}^{\backslash \mathbf{I}}, \mathbf{I}_{<j}\right),

where x\I\mathbf{x}^{\backslash \mathbf{I}} is the input with every identifier hidden. Each identifier is predicted once in the target, no matter how many times it appears in the code.

Step 5 in symbols: choosing the objective

Each training step samples one of the three losses with equal probability, so the expected loss is 13(LMSP+LIT+LMIP)\frac{1}{3}\left(\mathcal{L}_{MSP} + \mathcal{L}_{IT} + \mathcal{L}_{MIP}\right). The bimodal step does not add a new formula. It applies the same sequence-to-sequence loss in both directions, one for docstring to code and one for code to docstring.

Balanced sampling across tasks

When several datasets are mixed, the paper samples each one with probability qiq_i. Let nin_i be the number of examples in dataset ii and NN the number of datasets. Then

ri=ni∑k=1Nnk,qi=riα∑j=1Nrjα,α=0.7.r_i = \frac{n_i}{\sum_{k=1}^{N} n_k}, \qquad q_i = \frac{r_i^{\alpha}}{\sum_{j=1}^{N} r_j^{\alpha}}, \qquad \alpha = 0.7.

Setting α\alpha below 1 flattens the distribution, so small datasets are sampled more often than their size alone would give.

Worked examples

Example
Example 1: one token in identifier tagging (tiny)

Take the four tokens of return a + b, with labels y=(0,1,0,1)\mathbf{y} = (0, 1, 0, 1) for return, a, plus and b. Suppose the model outputs p=(0.1,0.9,0.2,0.8)p = (0.1, 0.9, 0.2, 0.8).

  1. For return, y=0y = 0 and p=0.1p = 0.1, so the term is −ln⁡(1−0.1)=−ln⁡0.9≈0.1054-\ln(1 - 0.1) = -\ln 0.9 \approx 0.1054.
  2. For a, y=1y = 1 and p=0.9p = 0.9, so the term is −ln⁡0.9≈0.1054-\ln 0.9 \approx 0.1054.
  3. For plus, y=0y = 0 and p=0.2p = 0.2, so the term is −ln⁡0.8≈0.2231-\ln 0.8 \approx 0.2231.
  4. For b, y=1y = 1 and p=0.8p = 0.8, so the term is −ln⁡0.8≈0.2231-\ln 0.8 \approx 0.2231.
  5. Add the four terms: 0.1054+0.1054+0.2231+0.2231=0.65700.1054 + 0.1054 + 0.2231 + 0.2231 = 0.6570.

Interpretation: the loss is small because the model is right on every token. A wrong confident guess, such as p=0.1p = 0.1 for an identifier, would add −ln⁡0.1≈2.30-\ln 0.1 \approx 2.30 on its own.

Example
Example 2: how many spans are masked (standard)

Take a 20-token input. The corruption rate is 15 percent, so 0.15×20=30.15 \times 20 = 3 tokens are hidden.

  1. Span lengths are drawn uniformly from 1 to 5. The mean is (1+2+3+4+5)/5=3(1 + 2 + 3 + 4 + 5) / 5 = 3.
  2. The average span has 3 tokens, so the 3 hidden tokens form about 3/3=13 / 3 = 1 span.
  3. The decoder therefore has one short target to write, and the loss LMSP\mathcal{L}_{MSP} has about three terms, one per hidden token.

Interpretation: at this length, most inputs get a single masked span. Longer inputs get more spans, but the rate stays at about 15 percent of the tokens.

Example
Example 3: the ablation on a real task (realistic)

The paper's ablation (its Table 6) trains CodeT5-small without one objective at a time and reports Python summarisation BLEU, where the full model scores 20.04.

  1. Remove masked identifier prediction: the score is 19.81. The drop is 20.04−19.81=0.2320.04 - 19.81 = 0.23.
  2. Remove identifier tagging: the score is 19.73. The drop is 20.04−19.73=0.3120.04 - 19.73 = 0.31.
  3. Remove span masking: the score is 18.93. The drop is 20.04−18.93=1.1120.04 - 18.93 = 1.11.
  4. Span masking matters most for generation. Removing it costs 3.95 CodeBLEU on code generation (41.39 to 37.44), the largest drop in the table, and the paper credits it with the syntax that generation needs.

Interpretation: each objective helps, but in different places. The ablation also shows that span masking is not the only source of gains. On defect detection, removing span masking raises accuracy from 63.40 to 64.02, which is why the paper says each objective's effect differs across tasks.

Try it: the paper reports that removing masked identifier prediction changes code refinement exact match on the small set from 19.06 to 18.32. What is the change, and in which direction? Answer: the change is 18.32−19.06=−0.7418.32 - 19.06 = -0.74, a drop of 0.74 exact-match points.

Results

The table lists headline numbers from the paper, against the best comparison the paper reports for the same metric. Higher is better in every row.

Task (CodeXGLUE)MetricCodeT5Closest comparison in the paper
Code summarisation, six languages, overallSmoothed BLEU-419.77 (base, multi-task)PLBART: 18.32
Code generation (Concode, Java)CodeBLEU43.20 (base)PLBART: 38.52
Code translation, Java to C#BLEU84.03 (base)PLBART: 83.02
Code refinement, mediumExact match13.96 (base)GraphCodeBERT: 9.10
Defect detectionAccuracy65.78 (base)PLBART: 63.18
Clone detectionF197.2 (base)PLBART and GraphCodeBERT: 97.2 and 97.1

What these mean. The gains are clearest on generation: on summarisation the base model beats the encoder-only baselines and PLBART, and on code generation it beats PLBART by about 4.7 CodeBLEU points. On defect detection the base model improves on PLBART by about 2.6 accuracy points. On clone detection it is only comparable to the best models, so the paper does not claim a win there.

The limits are stated in the paper too. The authors note that BLEU is an imperfect measure for code, since a correct rewrite can score poorly, and they show one translation that is semantically right but scores 50.23 BLEU-4 points. Bimodal dual generation helps the tasks that pair code with language, such as summarisation and generation, but it does not help and sometimes hurts the code-to-code tasks. The small model also trains on far less data than PLBART, which the authors acknowledge while arguing that their identifier-aware objective accounts for the gap. Hyperparameters were chosen by grid search on validation sets, and the results depend on that search.

Reading guide

Read the paper in this order, and use the lessons listed for each part.

  • Section 1 (Introduction) and Section 2 (Related Work). The pre-train then fine-tune recipe, and the three families of pre-trained models: encoder-only, decoder-only and encoder-decoder. Needs Transformer, Encoder-Decoder Architecture, Masked Language Modeling and BERT: Pre-training of Deep Bidirectional Transformers.
  • Section 3.1 (Encoding NL and PL). The input format and the identifier labels from the syntax tree. Needs Abstract Syntax Tree.
  • Section 3.2 (Pre-training tasks). The span masking, identifier tagging and masked identifier prediction losses, then bimodal dual generation. Needs Exploring the Limits of Transfer Learning (T5) for span masking and Cross-Entropy Loss for the identifier tagging loss.
  • Section 3.3 (Fine-tuning). Task-specific transfer and multi-task learning, with the balanced sampling formula. Needs no new prerequisites beyond the ones above.
  • Section 4 (Experimental setup). The data, the tokenizer, the tasks and the model sizes. The tokenizer is a byte-level version of the method in Subword Tokenization. The metrics are defined in BLEU Score. Read it with the Results section above.
  • Section 5 (Results and analysis). The main tables, then the ablations (Table 6) and the identifier-prediction analysis (Table 7).

Check yourself

QuestionName the three pre-training objectives in the identifier-aware denoising step, and say in one phrase what each one teaches.Show answer

Masked span prediction teaches general syntax by recovering hidden spans. Identifier tagging teaches the model which tokens are identifiers. Masked identifier prediction teaches it to recover identifier names from placeholders and to link all occurrences of the same name.

QuestionFor one code token that is an identifier, the label is y = 1, and the model gives p = 0.6. What is its term in the identifier tagging loss, in nats?Show answer

The term is −[1⋅ln⁡0.6+0⋅ln⁡0.4]=−ln⁡0.6≈0.51-\left[1 \cdot \ln 0.6 + 0 \cdot \ln 0.4\right] = -\ln 0.6 \approx 0.51. The second part is zero because y=1y = 1, so only the first term remains.

QuestionWhy does masked identifier prediction use one sentinel for each distinct identifier, instead of a new sentinel for each occurrence?Show answer

With one sentinel per identifier, every occurrence of a name is replaced by the same placeholder, so the model must work out that the occurrences refer to the same thing. A new sentinel for each occurrence would make the task a simpler copying problem, and the model would not learn to link the names across the code.

QuestionYou have code from a project with no comments, and you want a model that summarises functions. Should you rely on the bimodal dual generation objective during pre-training?Show answer

Not on your own data, since it needs code paired with natural language, and without comments there are no pairs to train on. You can still use a CodeT5 checkpoint pre-trained on paired data, because the paper shows that dual generation helps code summarisation and generation. Keep in mind that the paper found it does not help, and sometimes hurts, code-to-code tasks such as translation.

Sources

  • Wang, Y., Wang, W., Joty, S., Hoi, S. C. H. (2021). CodeT5: Identifier-aware Unified Pre-trained Encoder-Decoder Models for Code Understanding and Generation. arXiv:2109.00859. https://arxiv.org/abs/2109.00859
  • Raffel, C., et al. (2019). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. arXiv:1910.10683. https://arxiv.org/abs/1910.10683

Read the full paper

Yue Wang, Weishi Wang, Shafiq Joty et al., 2021. arXiv:2109.00859