目录

分词器

分词器是任何 LLM 的关键组成部分。它们将原始文本转换为标记 ID,这些标记 ID 索引到嵌入向量中,这些向量是 被模型理解。

在 torchtune 中,分词器的作用是将对象转换为令牌 ID 和任何必要的特定于模型的特殊令牌。

from torchtune.data import Message
from torchtune.models.phi3 import phi3_mini_tokenizer

sample = {
    "input": "user prompt",
    "output": "model response",
}

msgs = [
    Message(role="user", content=sample["input"]),
    Message(role="assistant", content=sample["output"])
]

p_tokenizer = phi3_mini_tokenizer("/tmp/Phi-3-mini-4k-instruct/tokenizer.model")
tokens, mask = p_tokenizer.tokenize_messages(msgs)
print(tokens)
# [1, 32010, 29871, 13, 1792, 9508, 32007, 29871, 13, 32001, 29871, 13, 4299, 2933, 32007, 29871, 13]
print(p_tokenizer.decode(tokens))
# '\nuser prompt \n \nmodel response \n'

模型分词器通常基于底层字节对编码算法,例如 SentencePiece 或 TikToken,它们都是 在 Torchtune 中受支持。

从 Hugging Face 下载分词器

托管在 Hugging Face 上的模型也与它们训练时使用的分词器一起分发。这些会自动与 model weights (使用 .例如,此命令下载 Mistral-7B 模型权重和分词器:tune download

tune download mistralai/Mistral-7B-v0.1 --output-dir /tmp/Mistral-7B-v0.1 --hf-token <HF_TOKEN>
cd /tmp/Mistral-7B-v0.1/
ls tokenizer.model
# tokenizer.model

从文件加载分词器

下载 tokenizer 文件后,您可以通过指向 添加到配置或构造函数中 tokenizer 模型的文件路径。如果您已经传入自定义文件路径 已将其下载到其他位置。

# In code
from torchtune.models.mistral import mistral_tokenizer

m_tokenizer = mistral_tokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model")
type(m_tokenizer)
# <class 'torchtune.models.mistral._tokenizer.MistralTokenizer'>
# In config
tokenizer:
  _component_: torchtune.models.mistral.mistral_tokenizer
  path: /tmp/Mistral-7B-v0.1/tokenizer.model

设置最大序列长度

设置最大序列长度可以控制内存使用并遵守模型规范。

# In code
from torchtune.models.mistral import mistral_tokenizer

m_tokenizer = mistral_tokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model", max_seq_len=8192)

# Set an arbitrarily small seq len for demonstration
from torchtune.data import Message

m_tokenizer = mistral_tokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model", max_seq_len=7)
msg = Message(role="user", content="hello world")
tokens, mask = m_tokenizer.tokenize_messages([msg])
print(len(tokens))
# 7
print(tokens)
# [1, 733, 16289, 28793, 6312, 28709, 2]
print(m_tokenizer.decode(tokens))
# '[INST] hello'
# In config
tokenizer:
  _component_: torchtune.models.mistral.mistral_tokenizer
  path: /tmp/Mistral-7B-v0.1/tokenizer.model
  max_seq_len: 8192

提示模板

通过将提示模板传递到任何模型分词器来启用提示模板。有关更多详细信息,请参阅 Prompt Templates

特殊令牌

特殊标记是提示模型所需的特定于模型的标记。它们与提示模板不同 ,因为它们被分配了自己的唯一令牌 ID。有关特殊令牌之间区别的扩展讨论 和提示模板,请参阅 提示模板

特殊令牌由模型分词器自动添加到您的数据中,不需要任何其他配置 从你那里。您还可以通过传入文件路径 JSON 文件中的新特殊令牌映射。这不会修改底层以支持新的 特殊令牌 ID - 您有责任确保 Tokenizer 文件对其进行正确编码。另请注意, 某些模型需要存在某些特殊令牌才能正确使用,例如 Llama3 Struct 中的令牌。tokenizer.model"<|eot_id|>"

例如,这里我们更改 Llama3 Instruct 中的 和 token ID:"<|begin_of_text|>""<|end_of_text|>"

# tokenizer/special_tokens.json
{
    "added_tokens": [
        {
            "id": 128257,
            "content": "<|begin_of_text|>",
        },
        {
            "id": 128258,
            "content": "<|end_of_text|>",
        },
        # Remaining required special tokens
        ...
    ]
}
# In code
from torchtune.models.llama3 import llama3_tokenizer

tokenizer = llama3_tokenizer(
    path="/tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model",
    special_tokens_path="tokenizer/special_tokens.json",
)
print(tokenizer.special_tokens)
# {'<|begin_of_text|>': 128257, '<|end_of_text|>': 128258, ...}
# In config
tokenizer:
  _component_: torchtune.models.llama3.llama3_tokenizer
  path: /tmp/Meta-Llama-3-8B-Instruct/original/tokenizer.model
  special_tokens_path: tokenizer/special_tokens.json

基础分词器

是执行实际原始字符串到令牌 ID 转换的基础字节对编码模块。 在 torchtune 中,它们需要实现 and 方法,这些方法由 Model 分词器调用以转换 在原始文本和令牌 ID 之间。encodedecode

class BaseTokenizer(Protocol):

    def encode(self, text: str, **kwargs: Dict[str, Any]) -> List[int]:
        """
        Given a string, return the encoded list of token ids.

        Args:
            text (str): The text to encode.
            **kwargs (Dict[str, Any]): kwargs.

        Returns:
            List[int]: The encoded list of token ids.
        """
        pass

    def decode(self, token_ids: List[int], **kwargs: Dict[str, Any]) -> str:
        """
        Given a list of token ids, return the decoded text, optionally including special tokens.

        Args:
            token_ids (List[int]): The list of token ids to decode.
            **kwargs (Dict[str, Any]): kwargs.

        Returns:
            str: The decoded text.
        """
        pass

如果你加载任何 Model 分词器,你可以看到它调用其底层来执行实际的编码和解码。

from torchtune.models.mistral import mistral_tokenizer
from torchtune.modules.tokenizers import SentencePieceBaseTokenizer

m_tokenizer = mistral_tokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model")
# Mistral uses SentencePiece for its underlying BPE
sp_tokenizer = SentencePieceBaseTokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model")

text = "hello world"

print(m_tokenizer.encode(text))
# [1, 6312, 28709, 1526, 2]

print(sp_tokenizer.encode(text))
# [1, 6312, 28709, 1526, 2]

模型分词器

特定于特定模型。他们需要实现方法 它将 Messages 列表转换为令牌 ID 列表。tokenize_messages

class ModelTokenizer(Protocol):

    special_tokens: Dict[str, int]
    max_seq_len: Optional[int]

    def tokenize_messages(
        self, messages: List[Message], **kwargs: Dict[str, Any]
    ) -> Tuple[List[int], List[bool]]:
        """
        Given a list of messages, return a list of tokens and list of masks for
        the concatenated and formatted messages.

        Args:
            messages (List[Message]): The list of messages to tokenize.
            **kwargs (Dict[str, Any]): kwargs.

        Returns:
            Tuple[List[int], List[bool]]: The list of token ids and the list of masks.
        """
        pass

它们是特定于模型的并且与 Base 分词器不同的原因是,它们添加了提示模型所需的所有必要特殊分词或提示模板。

from torchtune.models.mistral import mistral_tokenizer
from torchtune.modules.tokenizers import SentencePieceBaseTokenizer
from torchtune.data import Message

m_tokenizer = mistral_tokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model")
# Mistral uses SentencePiece for its underlying BPE
sp_tokenizer = SentencePieceBaseTokenizer("/tmp/Mistral-7B-v0.1/tokenizer.model")

text = "hello world"
msg = Message(role="user", content=text)

tokens, mask = m_tokenizer.tokenize_messages([msg])
print(tokens)
# [1, 733, 16289, 28793, 6312, 28709, 1526, 28705, 733, 28748, 16289, 28793]
print(sp_tokenizer.encode(text))
# [1, 6312, 28709, 1526, 2]
print(m_tokenizer.decode(tokens))
# [INST] hello world  [/INST]
print(sp_tokenizer.decode(sp_tokenizer.encode(text)))
# hello world

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源