【Python】科研代码学习:十五 configuration,tokenization 的代码细节:Llama 为例

【Python】科研代码学习:十五 configuration,tokenization 的代码细节:Llama 为例

    正在检查是否收录...

【Python】科研代码学习:十五 tokenizer的代码细节:Llama_Tokenization 为例

前言 `LlamaConfig`:网络参数配置 `LlamaTokenizer`:分词工具

前言

对于 HFTransformers 库的经典 API 以及大致架构我们都从前面已经学习的差不多了
【动机】那还剩下几个小问题,就是:
TokenizerSpecific Model 的运作原理是什么?
我如何查看与修改模型的架构?前向与反向传播过程?损失计算?激活函数?
这些模型层面的内容,如何学习与具体操作? 这里,建议是 【Github:Transformers/model/llama】 查看自己使用的模型,并学习其中 tokenizationconfigmodeling 三个最重要的类

LlamaConfig:网络参数配置

首先看定义类的地方,我们之前已经学习过了,SpecificConfig 都是从 PretrainedConfig 继承过来的
class LlamaConfig(PretrainedConfig): 
然后看一下解释文档,这里设置了一些比较重要的配置参数,主要是设置神经网络的大小和编码的一些参数。
vocab_size:词汇表大小,默认 32000
hidden_size:隐藏层维度(即每一层的神经元个数),默认 4096
num_hidden_layers:隐藏层层数,默认 32
intermediate_sizeMLP 层的层数,默认 11008
num_attention_head:每一个注意力层的注意力头的个数,默认 32
hidden_act:非线性层的激活函数,默认为 silu
max_position_embeddings:最大位置编码(也就是输入到的序列长度),用于位置编码
initializer_range truncated_normal_initializer 初始化方法的 std dev
不同的 config 他们的参数可能不相同。
 Args: vocab_size (`int`, *optional*, defaults to 32000): Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`LlamaModel`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 11008): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer encoder. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings(`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings Example: ```python >>> from transformers import LlamaModel, LlamaConfig >>> # Initializing a LLaMA llama-7b style configuration >>> configuration = LlamaConfig() >>> # Initializing a model from the llama-7b style configuration >>> model = LlamaModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" 
在代码中,它除了设置这些参数外,还做了几个额外的事情:
设置 model_type = "llama"
设置几个特殊的 token_id
pad_token_id=0 bos_token_id=1 eos_token_id=2 

LlamaTokenizer:分词工具

LlamaTokenizer 自然也是继承自 PretrainedTokenizer
第一件事情,设置 词汇表文件和 tokenizer文件
设置位置编码的大小
设置模型的输入名称,分为 input_ids 和注意力遮罩 attention_mask
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model", }, "tokenizer_file": { "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json", }, } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "hf-internal-testing/llama-tokenizer": 2048, } class LlamaTokenizer(PreTrainedTokenizer): """ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. Args: vocab_file (`str`): Path to the vocabulary file. """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids", "attention_mask"] 
第二步,在 init 方法中加载一些参数,并且添加了 bos, eos, unk, pad tokens
添加了分词工具,使用的是 sentencepiece .SentencePieceProcessor;并加载了对应的词汇表文件
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(vocab_file) 
它提供了一些简单的 get, set, convert 等方法
比如可以获得词汇大小 vocab_size,可以 get_vocab 获得所有词汇
调用 convert_tokens_to_string(tokens) 可以把输入的 tokens 转成对应的字符串文本
调用 _tokenize(text) 可以把输入的文本进行分词
调用 _convert_token_to_id 可以把一个 token(str) 转成一个 id
调用 _convert_id_to_token 可以把一个 id 转成一个 token(str)
@property def vocab_size(self): """Returns vocab size""" return self.sp_model.get_piece_size() def get_vocab(self): """Returns vocab as a dict""" vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab 
发现好多这些都是单下划线开头的方法,表示是形式上是私有方法。
※ 所以我们只要知道该类可以做:
输入的字符串(str),进行分词成 tokens (List[str])
然后对 tokens 进行转成对应的 ids (List[int])
也可以反过来,把 ids (List[int]) 还原成原来的 tokens (List[str])
也可以反过来,把 tokens (List[str]) 还原成原来的字符串 str

tokenllamatransformermaccode注意力transformerspythonhuggingfaceapicodingwordjsonimuiva神经网络gitdefigithub代码学习
  • 本文作者:李琛
  • 本文链接: https://wapzz.net/post-12484.html
  • 版权声明:本博客所有文章除特别声明外,均默认采用 CC BY-NC-SA 4.0 许可协议。
本站部分内容来源于网络转载,仅供学习交流使用。如涉及版权问题,请及时联系我们,我们将第一时间处理。
文章很赞!支持一下吧 还没有人为TA充电
为TA充电
还没有人为TA充电
0
  • 支付宝打赏
    支付宝扫一扫
  • 微信打赏
    微信扫一扫
感谢支持
文章很赞!支持一下吧
关于作者
2.3W+
5
0
1
WAP站长官方

批量打造“AI主播”:谁在涨粉,谁在赚钱?

上一篇

OceanPen Art AI绘画系统 运营教程(二)AI视频AI创作PPT

下一篇
  • 复制图片
按住ctrl可打开默认菜单