CodeGen

## [](#overview)Overview

The CodeGen model was proposed in [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and Caiming Xiong.

CodeGen is an autoregressive language model for program synthesis trained sequentially on [The Pile](https://pile.eleuther.ai/), BigQuery, and BigPython.

The abstract from the paper is the following:

_Program synthesis strives to generate a computer program as a solution to a given problem specification. We propose a conversational program synthesis approach via large language models, which addresses the challenges of searching over a vast program space and user intent specification faced in prior approaches. Our new approach casts the process of writing a specification and program as a multi-turn conversation between a user and a system. It treats program synthesis as a sequence prediction problem, in which the specification is expressed in natural language and the desired program is conditionally sampled. We train a family of large language models, called CodeGen, on natural language and programming language data. With weak supervision in the data and the scaling up of data size and model size, conversational capacities emerge from the simple autoregressive language modeling. To study the model behavior on conversational program synthesis, we develop a multi-turn programming benchmark (MTPB), where solving each problem requires multi-step synthesis via multi-turn conversation between the user and the model. Our findings show the emergence of conversational capabilities and the effectiveness of the proposed conversational program synthesis paradigm. In addition, our model CodeGen (with up to 16B parameters trained on TPU-v4) outperforms OpenAI’s Codex on the HumanEval benchmark. We make the training library JaxFormer including checkpoints available as open source contribution: [this https URL](https://github.com/salesforce/codegen)._

This model was contributed by [Hiroaki Hayashi](https://huggingface.co/rooa). The original code can be found [here](https://github.com/salesforce/codegen).

## [](#checkpoint-naming)Checkpoint Naming

-   CodeGen model [checkpoints](https://huggingface.co/models?other=codegen) are available on different pre-training data with variable sizes.
-   The format is: `Salesforce/codegen-{size}-{data}`, where
    -   `size`: `350M`, `2B`, `6B`, `16B`
    -   `data`:
        -   `nl`: Pre-trained on the Pile
        -   `multi`: Initialized with `nl`, then further pre-trained on multiple programming languages data
        -   `mono`: Initialized with `multi`, then further pre-trained on Python data
-   For example, `Salesforce/codegen-350M-mono` offers a 350 million-parameter checkpoint pre-trained sequentially on the Pile, multiple programming languages, and Python.

## [](#how-to-use)How to use

```
>>> from transformers import AutoModelForCausalLM, AutoTokenizer

>>> checkpoint = "Salesforce/codegen-350M-mono"
>>> model = AutoModelForCausalLM.from_pretrained(checkpoint)
>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)

>>> text = "def hello_world():"

>>> completion = model.generate(**tokenizer(text, return_tensors="pt"))

>>> print(tokenizer.decode(completion[0]))
def hello_world():
    print("Hello World")

hello_world()```

## [](#documentation-resources)Documentation resources

-   [Causal language modeling task guide](../tasks/language_modeling)

## [](#transformers.CodeGenConfig)CodeGenConfig

### class transformers.CodeGenConfig

[](#transformers.CodeGenConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/configuration_codegen.py#L44)

( vocab\_size = 50400n\_positions = 2048n\_ctx = 2048n\_embd = 4096n\_layer = 28n\_head = 16rotary\_dim = 64n\_inner = Noneactivation\_function = 'gelu\_new'resid\_pdrop = 0.0embd\_pdrop = 0.0attn\_pdrop = 0.0layer\_norm\_epsilon = 1e-05initializer\_range = 0.02use\_cache = Truebos\_token\_id = 50256eos\_token\_id = 50256tie\_word\_embeddings = False\*\*kwargs )

This is the configuration class to store the configuration of a [CodeGenModel](/docs/transformers/v4.30.0/en/model_doc/codegen#transformers.CodeGenModel). It is used to instantiate a CodeGen model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the CodeGen [Salesforce/codegen-2B-mono](https://huggingface.co/Salesforce/codegen-2B-mono) architecture. Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Example:

```
>>> from transformers import CodeGenConfig, CodeGenModel

>>> 
>>> configuration = CodeGenConfig()

>>> 
>>> model = CodeGenModel(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.CodeGenTokenizer)CodeGenTokenizer

### class transformers.CodeGenTokenizer

[](#transformers.CodeGenTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/tokenization_codegen.py#L98)

( vocab\_filemerges\_fileerrors = 'replace'unk\_token = '
'bos\_token = '
'eos\_token = '
'pad\_token = Noneadd\_prefix\_space = Falseadd\_bos\_token = False\*\*kwargs )

Parameters

-   [](#transformers.CodeGenTokenizer.vocab_file)**vocab\_file** (`str`) — Path to the vocabulary file.
-   [](#transformers.CodeGenTokenizer.merges_file)**merges\_file** (`str`) — Path to the merges file.
-   [](#transformers.CodeGenTokenizer.errors)**errors** (`str`, _optional_, defaults to `"replace"`) — Paradigm to follow when decoding bytes to UTF-8. See [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
-   [](#transformers.CodeGenTokenizer.unk_token)**unk\_token** (`str`, _optional_, defaults to `
`) — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
-   [](#transformers.CodeGenTokenizer.bos_token)**bos\_token** (`str`, _optional_, defaults to `
`) — The beginning of sequence token.
-   [](#transformers.CodeGenTokenizer.eos_token)**eos\_token** (`str`, _optional_, defaults to `
`) — The end of sequence token.
-   [](#transformers.CodeGenTokenizer.add_prefix_space)**add\_prefix\_space** (`bool`, _optional_, defaults to `False`) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (CodeGen tokenizer detect beginning of words by the preceding space).

Construct a CodeGen tokenizer. Based on byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will

be encoded differently whether it is at the beginning of the sentence (without space) or not:

```
>>> from transformers import CodeGenTokenizer

>>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
>>> tokenizer("Hello world")["input_ids"]
[15496, 995]

>>> tokenizer(" Hello world")["input_ids"]
[18435, 995]```

You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### save\_vocabulary

[](#transformers.CodeGenTokenizer.save_vocabulary)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/tokenization_codegen.py#L284)

( save\_directory: strfilename\_prefix: typing.Optional\[str\] = None )

## [](#transformers.CodeGenTokenizerFast)CodeGenTokenizerFast

### class transformers.CodeGenTokenizerFast

[](#transformers.CodeGenTokenizerFast)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/tokenization_codegen_fast.py#L63)

( vocab\_file = Nonemerges\_file = Nonetokenizer\_file = Noneunk\_token = '
'bos\_token = '
'eos\_token = '
'add\_prefix\_space = False\*\*kwargs )

Parameters

-   [](#transformers.CodeGenTokenizerFast.vocab_file)**vocab\_file** (`str`) — Path to the vocabulary file.
-   [](#transformers.CodeGenTokenizerFast.merges_file)**merges\_file** (`str`) — Path to the merges file.
-   [](#transformers.CodeGenTokenizerFast.errors)**errors** (`str`, _optional_, defaults to `"replace"`) — Paradigm to follow when decoding bytes to UTF-8. See [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
-   [](#transformers.CodeGenTokenizerFast.unk_token)**unk\_token** (`str`, _optional_, defaults to `
`) — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
-   [](#transformers.CodeGenTokenizerFast.bos_token)**bos\_token** (`str`, _optional_, defaults to `
`) — The beginning of sequence token.
-   [](#transformers.CodeGenTokenizerFast.eos_token)**eos\_token** (`str`, _optional_, defaults to `
`) — The end of sequence token.
-   [](#transformers.CodeGenTokenizerFast.add_prefix_space)**add\_prefix\_space** (`bool`, _optional_, defaults to `False`) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (CodeGen tokenizer detect beginning of words by the preceding space).
-   [](#transformers.CodeGenTokenizerFast.trim_offsets)**trim\_offsets** (`bool`, _optional_, defaults to `True`) — Whether or not the post-processing step should trim offsets to avoid including whitespaces.

Construct a “fast” CodeGen tokenizer (backed by HuggingFace’s _tokenizers_ library). Based on byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will

be encoded differently whether it is at the beginning of the sentence (without space) or not:

```
>>> from transformers import CodeGenTokenizerFast

>>> tokenizer = CodeGenTokenizerFast.from_pretrained("Salesforce/codegen-350M-mono")
>>> tokenizer("Hello world")["input_ids"]
[15496, 995]

>>> tokenizer(" Hello world")["input_ids"]
[18435, 995]```

You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since the model was not pretrained this way, it might yield a decrease in performance.

When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.

This tokenizer inherits from [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### decode

[](#transformers.CodeGenTokenizerFast.decode)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/tokenization_codegen_fast.py#L186)

( token\_ids: typing.Union\[int, typing.List\[int\], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')\]skip\_special\_tokens: bool = Falseclean\_up\_tokenization\_spaces: bool = Nonetruncate\_before\_pattern: typing.Optional\[typing.List\[str\]\] = None\*\*kwargs ) → `str`

Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces.

Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.

”\]\`. kwargs (additional keyword arguments, _optional_): Will be passed to the underlying model specific decode method.

## [](#transformers.CodeGenModel)CodeGenModel

### class transformers.CodeGenModel

[](#transformers.CodeGenModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/modeling_codegen.py#L409)

( config )

Parameters

-   [](#transformers.CodeGenModel.config)**config** ([CodeGenConfig](/docs/transformers/v4.30.0/en/model_doc/codegen#transformers.CodeGenConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare CodeGen Model transformer outputting raw hidden-states without any specific head on top. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.CodeGenModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/modeling_codegen.py#L432)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor\]\]\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneposition\_ids: typing.Optional\[torch.LongTensor\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Noneuse\_cache: typing.Optional\[bool\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.BaseModelOutputWithPast](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) or `tuple(torch.FloatTensor)`

The [CodeGenModel](/docs/transformers/v4.30.0/en/model_doc/codegen#transformers.CodeGenModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

```
>>> from transformers import AutoTokenizer, CodeGenModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/codegen-2B-mono")
>>> model = CodeGenModel.from_pretrained("Salesforce/codegen-2B-mono")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state```

## [](#transformers.CodeGenForCausalLM)CodeGenForCausalLM

### class transformers.CodeGenForCausalLM

[](#transformers.CodeGenForCausalLM)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/modeling_codegen.py#L602)

( config )

Parameters

-   [](#transformers.CodeGenForCausalLM.config)**config** ([CodeGenConfig](/docs/transformers/v4.30.0/en/model_doc/codegen#transformers.CodeGenConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The CodeGen Model transformer with a language modeling head on top.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.CodeGenForCausalLM.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/codegen/modeling_codegen.py#L646)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor\]\]\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneposition\_ids: typing.Optional\[torch.LongTensor\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneuse\_cache: typing.Optional\[bool\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.CausalLMOutputWithPast](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) or `tuple(torch.FloatTensor)`

The [CodeGenForCausalLM](/docs/transformers/v4.30.0/en/model_doc/codegen#transformers.CodeGenForCausalLM) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

```
>>> import torch
>>> from transformers import AutoTokenizer, CodeGenForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/codegen-2B-mono")
>>> model = CodeGenForCausalLM.from_pretrained("Salesforce/codegen-2B-mono")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logits```