Transformers documentation

CodeLlama

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

CodeLlama

Overview

Code Llama モデルはによって Code Llama: Open Foundation Models for Code で提案されました。 Baptiste Rozière, Jonas Gehring, Fabian Gloeckle, Sten Sootla, Itai Gat, Xiaoqing Ellen Tan, Yossi Adi, Jingyu Liu, Tal Remez, Jérémy Rapin, Artyom Kozhevnikov, Ivan Evtimov, Joanna Bitton, Manish Bhatt, Cristian Canton Ferrer, Aaron Grattafiori, Wenhan Xiong, Alexandre Défossez, Jade Copet, Faisal Azhar, Hugo Touvron, Louis Martin, Nicolas Usunier, Thomas Scialom, Gabriel Synnaeve. 論文の要約は次のとおりです。

私たちは Code Llama をリリースします。これは Llama 2 に基づくコードの大規模言語モデル ファミリであり、オープン モデルの中で最先端のパフォーマンス、埋め込み機能、大規模な入力コンテキストのサポート、プログラミング タスクのゼロショット命令追従機能を提供します。 。幅広いアプリケーションをカバーするための複数のフレーバーを提供しています。基盤モデル (Code Llama)、Python 特化 (Code Llama - Python)、およびそれぞれ 7B、13B、および 34B パラメーターを備えた命令追従モデル (Code Llama - Instruct) です。すべてのモデルは 16,000 トークンのシーケンスでトレーニングされ、最大 100,000 トークンの入力で改善が見られます。 7B および 13B コード ラマとコード ラマ - 命令バリアントは、周囲のコンテンツに基づいた埋め込みをサポートします。 Code Llama は、いくつかのコード ベンチマークでオープン モデルの中で最先端のパフォーマンスに達し、HumanEval と MBPP でそれぞれ最大 53% と 55% のスコアを獲得しました。特に、Code Llama - Python 7B は HumanEval および MBPP 上で Llama 2 70B よりも優れたパフォーマンスを示し、すべてのモデルは MultiPL-E 上で公開されている他のすべてのモデルよりも優れています。私たちは、研究と商業利用の両方を許可する寛容なライセンスに基づいて Code Llama をリリースしています。

すべての Code Llama モデル チェックポイントを こちら で確認し、meta llama org で正式にリリースされたチェックポイントを確認してください。

このモデルは ArthurZucker によって提供されました。著者のオリジナルのコードは こちら にあります。

Usage tips and examples

Code Llama のベースとなるLlama2ファミリー モデルは、bfloat16を使用してトレーニングされましたが、元の推論ではfloat16を使用します。さまざまな精度を見てみましょう。

  • float32: モデルの初期化に関する PyTorch の規約では、モデルの重みがどの dtype で格納されたかに関係なく、モデルを float32 にロードします。 「transformers」も、PyTorch との一貫性を保つためにこの規則に従っています。これはデフォルトで選択されます。 AutoModel API でストレージの重み付けタイプを使用してチェックポイントのロードをキャストする場合は、dtype="auto" を指定する必要があります。 model = AutoModelForCausalLM.from_pretrained("path", dtype = "auto")
  • bfloat16: コード Llama はこの精度でトレーニングされているため、さらなるトレーニングや微調整に使用することをお勧めします。
  • float16: この精度を使用して推論を実行することをお勧めします。通常は bfloat16 より高速であり、評価メトリクスには bfloat16 と比べて明らかな低下が見られないためです。 bfloat16 を使用して推論を実行することもできます。微調整後、float16 と bfloat16 の両方で推論結果を確認することをお勧めします。

上で述べたように、モデルを初期化するときに dtype="auto" を使用しない限り、ストレージの重みの dtype はほとんど無関係です。その理由は、モデルが最初にダウンロードされ (オンラインのチェックポイントの dtype を使用)、次に torch のデフォルトの dtype にキャストされるためです (torch.float32 になります)。指定された dtype がある場合は、代わりにそれが使用されます。

チップ:

  • 充填タスクはすぐにサポートされます。入力を埋めたい場所には tokenizer.fill_token を使用する必要があります。
  • モデル変換スクリプトは、Llama2 ファミリの場合と同じです。

使用例は次のとおりです。

python src/transformers/models/llama/convert_llama_weights_to_hf.py \
    --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path

スクリプトを実行するには、(最大のバージョンであっても) float16 精度でモデル全体をホストするのに十分な CPU RAM が必要であることに注意してください。 いくつかのチェックポイントがあり、それぞれにモデルの各重みの一部が含まれているため、すべてを RAM にロードする必要があります)。

変換後、モデルとトークナイザーは次の方法でロードできます。

>>> from transformers import LlamaForCausalLM, CodeLlamaTokenizer

>>> tokenizer = CodeLlamaTokenizer.from_pretrained("meta-llama/CodeLlama-7b-hf")
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/CodeLlama-7b-hf")
>>> PROMPT = '''def remove_non_ascii(s: str) -> str:
    """ <FILL_ME>
    return result
'''
>>> input_ids = tokenizer(PROMPT, return_tensors="pt")["input_ids"]
>>> generated_ids = model.generate(input_ids, max_new_tokens=128)

>>> filling = tokenizer.batch_decode(generated_ids[:, input_ids.shape[1]:], skip_special_tokens = True)[0]
>>> print(PROMPT.replace("<FILL_ME>", filling))
def remove_non_ascii(s: str) -> str:
    """ Remove non-ASCII characters from a string.

    Args:
        s: The string to remove non-ASCII characters from.

    Returns:
        The string with non-ASCII characters removed.
    """
    result = ""
    for c in s:
        if ord(c) < 128:
            result += c
    return result

塗りつぶされた部分だけが必要な場合:

>>> from transformers import pipeline
>>> import torch

>>> generator = pipeline("text-generation",model="meta-llama/CodeLlama-7b-hf",dtype=torch.float16, device_map="auto")
>>> generator('def remove_non_ascii(s: str) -> str:\n    """ <FILL_ME>\n    return result', max_new_tokens = 128)
[{'generated_text': 'def remove_non_ascii(s: str) -> str:\n    """ <FILL_ME>\n    return resultRemove non-ASCII characters from a string. """\n    result = ""\n    for c in s:\n        if ord(c) < 128:\n            result += c'}]

内部では、トークナイザーが <FILL_ME> によって自動的に分割 して、に続く書式設定された入力文字列を作成します。オリジナルのトレーニング パターン。これは、パターンを自分で準備するよりも堅牢です。トークンの接着など、デバッグが非常に難しい落とし穴を回避できます。このモデルまたは他のモデルに必要な CPU および GPU メモリの量を確認するには、その値を決定するのに役立つ この計算ツール を試してください。

LLaMA トークナイザーは、sentencepiece に基づく BPE モデルです。センテンスピースの癖の 1 つは、シーケンスをデコードするときに、最初のトークンが単語の先頭 (例: 「Banana」) である場合、トークナイザーは文字列の先頭にプレフィックス スペースを追加しないことです。

コード Llama は、Llama2 モデルと同じアーキテクチャを持っています。API リファレンスについては、Llama2 のドキュメント ページ を参照してください。 以下の Code Llama トークナイザーのリファレンスを見つけてください。

CodeLlamaTokenizer

class transformers.CodeLlamaTokenizer

< >

( clean_up_tokenization_spaces = False unk_token = '<unk>' bos_token = '<s>' eos_token = '</s>' prefix_token = '▁<PRE>' middle_token = '▁<MID>' suffix_token = '▁<SUF>' eot_token = '▁<EOT>' fill_token = '<FILL_ME>' additional_special_tokens = None add_bos_token = True add_eos_token = False use_default_system_prompt = False add_prefix_space = None vocab = None merges = None vocab_file = None **kwargs )

Parameters

  • clean_up_tokenization_spaces (str, optional, defaults to False) — Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces.
  • unk_token (str, optional, defaults to "<unk>") — 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.
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.
  • prefix_token (str, optional, defaults to "▁<PRE>") — Prefix token used for infilling.
  • middle_token (str, optional, defaults to "▁<MID>") — Middle token used for infilling.
  • suffix_token (str, optional, defaults to "▁<SUF>") — Suffix token used for infilling.
  • eot_token (str, optional, defaults to "▁<EOT>") — End of text token used for infilling.
  • fill_token (str, optional, defaults to "<FILL_ME>") — The token used to split the input between the prefix and suffix.
  • additional_special_tokens (list[str], optional) — Additional special tokens used by the tokenizer.
  • add_bos_token (bool, optional, defaults to True) — Whether to add a beginning of sequence token at the start of sequences.
  • add_eos_token (bool, optional, defaults to False) — Whether to add an end of sequence token at the end of sequences.
  • use_default_system_prompt (bool, optional, defaults to False) — Whether or not the default system prompt for Llama should be used.
  • add_prefix_space (bool, optional) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word.
  • vocab (dict, optional) — Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
  • merges (list, optional) — Custom merges list. If not provided, merges are loaded from merges_file.
  • vocab_file (str, optional) — SentencePiece file (generally has a .model extension) that contains the vocabulary necessary to instantiate a tokenizer.

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

This uses notably ByteFallback and no normalization.

>>> from transformers import CodeLlamaTokenizer

>>> tokenizer = CodeLlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
>>> tokenizer.encode("Hello this is a test")
[1, 15043, 445, 338, 263, 1243]

If you want to change the bos_token or the eos_token, make sure to specify them when initializing the model, or call tokenizer.update_post_processor() to make sure that the post-processing is correctly done (otherwise the values of the first token and final token of an encoded sequence will not be correct). For more details, checkout [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.

This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. The default configuration match that of meta-llama/CodeLlama-7b-Instruct-hf which supports prompt infilling.

get_special_tokens_mask

< >

( token_ids_0: list token_ids_1: typing.Optional[list[int]] = None already_has_special_tokens: bool = False ) A list of integers in the range [0, 1]

Parameters

  • token_ids_0 — List of IDs for the (possibly already formatted) sequence.
  • token_ids_1 — Unused when already_has_special_tokens=True. Must be None in that case.
  • already_has_special_tokens — Whether the sequence is already formatted with special tokens.

Returns

A list of integers in the range [0, 1]

1 for a special token, 0 for a sequence token.

Retrieve sequence ids from a token list that has no special tokens added.

For fast tokenizers, data collators call this with already_has_special_tokens=True to build a mask over an already-formatted sequence. In that case, we compute the mask by checking membership in all_special_ids.

save_vocabulary

< >

( save_directory: str filename_prefix: typing.Optional[str] = None )

CodeLlamaTokenizerFast

class transformers.CodeLlamaTokenizer

< >

( clean_up_tokenization_spaces = False unk_token = '<unk>' bos_token = '<s>' eos_token = '</s>' prefix_token = '▁<PRE>' middle_token = '▁<MID>' suffix_token = '▁<SUF>' eot_token = '▁<EOT>' fill_token = '<FILL_ME>' additional_special_tokens = None add_bos_token = True add_eos_token = False use_default_system_prompt = False add_prefix_space = None vocab = None merges = None vocab_file = None **kwargs )

Parameters

  • clean_up_tokenization_spaces (str, optional, defaults to False) — Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces.
  • unk_token (str, optional, defaults to "<unk>") — 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.
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.
  • prefix_token (str, optional, defaults to "▁<PRE>") — Prefix token used for infilling.
  • middle_token (str, optional, defaults to "▁<MID>") — Middle token used for infilling.
  • suffix_token (str, optional, defaults to "▁<SUF>") — Suffix token used for infilling.
  • eot_token (str, optional, defaults to "▁<EOT>") — End of text token used for infilling.
  • fill_token (str, optional, defaults to "<FILL_ME>") — The token used to split the input between the prefix and suffix.
  • additional_special_tokens (list[str], optional) — Additional special tokens used by the tokenizer.
  • add_bos_token (bool, optional, defaults to True) — Whether to add a beginning of sequence token at the start of sequences.
  • add_eos_token (bool, optional, defaults to False) — Whether to add an end of sequence token at the end of sequences.
  • use_default_system_prompt (bool, optional, defaults to False) — Whether or not the default system prompt for Llama should be used.
  • add_prefix_space (bool, optional) — Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word.
  • vocab (dict, optional) — Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
  • merges (list, optional) — Custom merges list. If not provided, merges are loaded from merges_file.
  • vocab_file (str, optional) — SentencePiece file (generally has a .model extension) that contains the vocabulary necessary to instantiate a tokenizer.

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

This uses notably ByteFallback and no normalization.

>>> from transformers import CodeLlamaTokenizer

>>> tokenizer = CodeLlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
>>> tokenizer.encode("Hello this is a test")
[1, 15043, 445, 338, 263, 1243]

If you want to change the bos_token or the eos_token, make sure to specify them when initializing the model, or call tokenizer.update_post_processor() to make sure that the post-processing is correctly done (otherwise the values of the first token and final token of an encoded sequence will not be correct). For more details, checkout [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.

This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. The default configuration match that of meta-llama/CodeLlama-7b-Instruct-hf which supports prompt infilling.

get_special_tokens_mask

< >

( token_ids_0: list token_ids_1: typing.Optional[list[int]] = None already_has_special_tokens: bool = False ) A list of integers in the range [0, 1]

Parameters

  • token_ids_0 — List of IDs for the (possibly already formatted) sequence.
  • token_ids_1 — Unused when already_has_special_tokens=True. Must be None in that case.
  • already_has_special_tokens — Whether the sequence is already formatted with special tokens.

Returns

A list of integers in the range [0, 1]

1 for a special token, 0 for a sequence token.

Retrieve sequence ids from a token list that has no special tokens added.

For fast tokenizers, data collators call this with already_has_special_tokens=True to build a mask over an already-formatted sequence. In that case, we compute the mask by checking membership in all_special_ids.

update_post_processor

< >

( )

Updates the underlying post processor with the current bos_token and eos_token.

save_vocabulary

< >

( save_directory: str filename_prefix: typing.Optional[str] = None )

Update on GitHub