huggingface的tokenizer解读

news2025/2/26 0:34:49

文章目录

  • 前言
  • 一、huggingface的tokenizer含义
    • 1、含义
    • 2、整体概括
  • 二、加载lmsys/vicuna-7b-v1.5模型的tokenizer
  • 三、调用tokernizer方法
  • 四、字符串的tokens应用
    • 1、tokenizer应用
    • 2、tokenizer进行token分词(tokenizer.tokenize)
    • 3、tokens转模型识别ids(tokenizer.convert_tokens_to_ids)
    • 4、ids转token(tokenizer.convert_ids_to_token)
  • 五、tokenizer的decode应用(tokenizer.decode)
  • 六、tokenizer的encode应用
    • 1、tokenizer的tokenizer.encode
    • 2、tokenizer的tokenizer.encode_plus
    • 3、tokenizer的tokenizer.batch_encode_plus
      • a、tokenizer.batch_encode_plus函数含义
      • b、tokenizer.batch_encode_plus使用方法
      • c、tokenizer.batch_encode_plus运行结果
  • 七、完整代码


前言

目前很多大模型或NLP相关模型可使用huggingface实现,是一个非常好用的集成库,特别是transformer库。而Hugging Face的Tokenizer模块是该平台的重要组成部分,主要用于文本的处理和编码。Tokenizer模块提供了各种先进的文本处理工具,包括分词、编码、解码等功能。本文将以llama模型作为tokenizer列子,介绍tokenizer相关使用内容。


一、huggingface的tokenizer含义

1、含义

Tokenizers are one of the core components of the NLP pipeline. They serve one purpose: to translate text into data that can be processed by the model. Models can only process numbers, so tokenizers need to convert our text inputs to numerical data. In this section, we’ll explore exactly what happens in the tokenization pipeline.
However, models can only process numbers, so we need to find a way to convert the raw text to numbers. That’s what the tokenizers do, and there are a lot of ways to go about this. The goal is to find the most meaningful representation — that is, the one that makes the most sense to the model — and, if possible, the smallest representation.

翻译理解为:Hugging Face的tokenizer是用于将文本转换为模型可以理解的格式的工具。它可以将输入文本分解成ids,并根据模型的要求进行编码。这样可以确保模型能够正确地理解输入并进行处理。也就是说模型只能加工数字,toknizer就是处理文本到数字过程。不同模型有不同tokenizer表示。我将以小羊驼语言模型作为列子说明。

直白理解:处理文本能被模型处理的输入格式。

官网解释链接:https://huggingface.co/learn/nlp-course/chapter2/4?fw=pt

2、整体概括

其主要内容可以总结如下:

Tokenization(分词):Tokenizer模块支持多种语言的分词器,能够将输入的文本分割成单词、子词或字符,为后续的处理和编码做准备。这对于不同NLP任务来说非常重要,因为文本的分割方式直接影响到模型的输入表示。

编码和解码:Tokenizer能够将文本转换成模型可接受的输入编码,并能够将模型输出的编码解码成可读的文本。这对于使用预训练模型进行推理和生成任务非常关键。

特殊标记处理:Tokenizer能够处理特殊标记,如掩码标记(mask token)、分隔标记(separator token)等,这些标记在不同的NLP任务中扮演着重要的角色。

多种预训练模型支持:Tokenizer模块支持多种预训练模型,包括BERT、GPT、LLMA等,用户可以根据自己的需求选择合适的模型和相应的Tokenizer进行文本处理。

总之,Hugging Face的Tokenizer模块为用户提供了强大而灵活的文本处理工具,能够满足各种NLP任务对于文本处理的需求,并与Hugging Face平台上的其他模块无缝集成,为NLP研究和开发提供了便利。

二、加载lmsys/vicuna-7b-v1.5模型的tokenizer

huggingface最强大库的transformer,内有很多语言模型,也提供了很简单操作可实现tokenizer,你只需在官网下载对应模型库文件,然后使用对应包.from_pretrained(模型文件夹地址)

代码如下:

from transformers import LlamaTokenizer
def llama2_tokenizer(tokenizer_path, signal_type="base"):
    tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path)
    # 向tokenizer中添加变量与值
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token_id = 32000
    tokenizer.boi = "[IMG]"
    tokenizer.eoi = "[/IMG]"
    assert signal_type in ["base", "chat", "vqa", "chat_old"]
    tokenizer.signal_type = signal_type
    return tokenizer

以上实现基于llma模型的tokenizer方法调用,实际是文本转模型识别数字的一些包装。当然,你也可参考映射map方法博客点击这里。

三、调用tokernizer方法

下载好对应文件权重如下格式:
在这里插入图片描述
在二中实现加载tokenizer方式,在使用如下代码给出tokenizer,如下:

    llama_path = '/home/lmsys/vicuna-7b-v1.5'
    tokenizer = llama2_tokenizer(llama_path)

四、字符串的tokens应用

1、tokenizer应用

直接使用tokenizer方法,可返回input_ids与attention_mask,这里attention_mask表示每个文本对应位置值,若有文本词则为1否则为0,后面我会进一步说明。

    text = 'It is a nice day'
    t=tokenizer(text)
    print(t)
    t = tokenizer(['It is a nice day', 'nice day'])
    print(t)

结果如下:

第一个输出值为一个文本:
{'input_ids': [1, 739, 338, 263, 7575, 2462], 'attention_mask': [1, 1, 1, 1, 1, 1]}
第二个输出值为文本列表:
{'input_ids': [[1, 739, 338, 263, 7575, 2462], [1, 7575, 2462]], 'attention_mask': [[1, 1, 1, 1, 1, 1], [1, 1, 1]]}

当然,不同模型的tokenizer会多一些值,如官网返回值:

{'input_ids': [101, 7993, 170, 11303, 1200, 2443, 1110, 3014, 102],
 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0],
 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1]}

2、tokenizer进行token分词(tokenizer.tokenize)

使用tokenizer.tokenize可输出字符串列表或叫token,官网解释The output of this method is a list of strings, or tokens,其代码如下:

    text = 'It is a nice day'
    # tokenize,#仅用于分词
    tokens = tokenizer.tokenize(text)
    print("token分词结果:\n", tokens)

结果如下:

 ['▁It', '▁is', '▁a', '▁nice', '▁day']

实际是对文本text进行分词方法,完成了分词就能找到对应数字,也就是模型能识别的数字了。

3、tokens转模型识别ids(tokenizer.convert_tokens_to_ids)

使用tokenizer.convert_tokens_to_ids将token转成模型识别ids,官网解释The conversion to input IDs is handled by the convert_tokens_to_ids() tokenizer method:,其代码如下:

    # convert_tokens_to_ids,将token转化成ids,在分词之后,
    ids = tokenizer.convert_tokens_to_ids(tokens)
    print("tokens Ids:\n", ids)

结果如下:

 [739, 338, 263, 7575, 2462]

输出转为张量结构,模型可输入数字,实际是文本text分词后找映射数字。

注:映射数字id只对应分词,无开始和结束id

4、ids转token(tokenizer.convert_ids_to_token)

应用ids转回token,需要根据对应模型,有的模型提供可直接使用,若没有提供则不需要使用。恰好llama为提供该转换方法。

    # convert_ids_to_tokens,将id转化成token,通常用于模型预测出结果,查看时使用。
    tokens = tokenizer.convert_ids_to_token(ids)
    print("tokenize Id2token:\n", tokens)

五、tokenizer的decode应用(tokenizer.decode)

使用tokenizer.decode将token转成模型的ids,官网解释The conversion to input IDs is handled by the convert_tokens_to_ids() tokenizer method:,其代码如下:

    # ids映射回原来文本内容
    decoded_string = tokenizer.decode(ids)
    print('ids2text', decoded_string)

结果如下:

 [739, 338, 263, 7575, 2462]

实际是文本text分词后找映射数字。

注:映射数字id只对应分词,无开始和结束id

六、tokenizer的encode应用

1、tokenizer的tokenizer.encode

使用tokenizer.encode将文本转为对应ids,其代码如下:

    #  encode,进行分词和token转换,encode=tokenize+convert_tokens_to_ids
    encode_num = tokenizer.encode(text)
    print("text=",text)
    print('encode=', encode_num)
    decoded_string = tokenizer.decode(encode_num)
    print('decode=', decoded_string)

结果如下:

text= It is a nice day
encode= [1, 739, 338, 263, 7575, 2462]
decoded_string= <s> It is a nice day

可看出输出多了文字,这个应该是模型需要的,类似seq

2、tokenizer的tokenizer.encode_plus

将encode的输出变成input_ids变量,其值完全不变,且多出attention_mask变量,也会根据模型方法会多出其它变量,其代码如下:

    # encode_plus,在encode的基础之上生成input_ids、token_type_ids、attention_mask
    encode_plus_text = tokenizer.encode_plus(text)
    print("验证encode_plus编码\nencode_plus=", encode_plus_text)

结果如下:


encode_plus= {'input_ids': [1, 739, 338, 263, 7575, 2462], 'attention_mask': [1, 1, 1, 1, 1, 1]}

在encode基础上多了attention_mask内容,有的模型会提供一些其它多余输出结果(如:token_type_ids)。

3、tokenizer的tokenizer.batch_encode_plus

a、tokenizer.batch_encode_plus函数含义

tokenizer.batch_encode_plus函数用于批量对文本进行编码处理,它可以同时处理多个文本,并提供填充、截断、返回张量类型等选项。

texts: 待编码的文本列表
return_tensors: 指定返回的张量类型,如'tensor''pt'
padding: 是否对文本进行填充
truncation: 是否对文本进行截断
max_length: 最大长度限制
return_attention_mask: 是否返回注意力掩码张量

b、tokenizer.batch_encode_plus使用方法

    batch_encode_plus = tokenizer.batch_encode_plus(text_batch, max_length=10, padding='max_length', truncation='longest_first')  # 长的截,短的补
    print("验证batch_encode_plus编码\nbatch_encode_plus=", batch_encode_plus)

c、tokenizer.batch_encode_plus运行结果

batch_encode_plus= {'input_ids': [[1, 739, 338, 263, 7575, 2462, 0, 0, 0, 0], [1, 7575, 2462, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]]}

七、完整代码

from transformers import LlamaTokenizer
def llama2_tokenizer(tokenizer_path, signal_type="base"):
    tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path)
    # 向tokenizer中添加变量与值
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token_id = 32000
    tokenizer.boi = "[IMG]"
    tokenizer.eoi = "[/IMG]"
    assert signal_type in ["base", "chat", "vqa", "chat_old"]
    tokenizer.signal_type = signal_type
    return tokenizer


def tokenizer_tutor():
    llama_path = '/extend_disk/tj/CogVLM-main/lmsys/vicuna-7b-v1.5'
    tokenizer = llama2_tokenizer(llama_path)
    text_batch = ['It is a nice day', 'nice day']
    text = 'It is a nice day'
    
    t=tokenizer(text)
    print(t)
    t = tokenizer(text_batch)
    print(t)

    # tokenize,#仅用于分词
    tokens = tokenizer.tokenize(text)
    print("token分词结果:\n", tokens)
    
    # convert_tokens_to_ids,将token转化成ids,在分词之后,
    ids = tokenizer.convert_tokens_to_ids(tokens)
    print("tokens Ids:\n", ids)

    # # convert_ids_to_tokens,将id转化成token,通常用于模型预测出结果,查看时使用。
    # tokens = tokenizer.convert_ids_to_token(ids)
    # print("tokenize Id2token:\n", tokens)

    # ids映射回原来文本内容
    decoded_string = tokenizer.decode(ids)
    print('decode=', decoded_string)

    #  encode,进行分词和token转换,encode=tokenize+convert_tokens_to_ids
    encode_num = tokenizer.encode(text)
    print("验证encode编码\ntext=",text)
    print('encode=', encode_num)
    decoded_string = tokenizer.decode(encode_num)
    print('decoded_string=', decoded_string)

    # encode_plus,在encode的基础之上生成input_ids、token_type_ids、attention_mask
    encode_plus_text = tokenizer.encode_plus(text)
    print("验证encode_plus编码\nencode_plus=", encode_plus_text)

    batch_encode_plus = tokenizer.batch_encode_plus(text_batch, max_length=10, padding='max_length', truncation='longest_first')  # 长的截,短的补
    print("验证batch_encode_plus编码\nbatch_encode_plus=", batch_encode_plus)

if __name__ == '__main__':
    tokenizer_tutor()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1347461.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring Cloud + Vue前后端分离-第9章 大文件断点续与极速秒传

源代码在GitHub - 629y/course: Spring Cloud Vue前后端分离-在线课程 ​​​​​​Spring Cloud Vue前后端分离-第9章 大文件断点续与极速秒传 作为一个视频网站&#xff0c;一个文件小则几十M&#xff0c;大则上G&#xff0c;上传一个大文件受网络影响很大&#xff0c;文…

vue-springboot基于JavaWeb的汽配汽车配件销售采购管理系统

过对知识内容的学习研究&#xff0c;进而设计并实现一个基于JavaWeb的汽配销售管理系统。系统能实现的主要功能应包括&#xff1b;汽车配件、销售订单、采购订单、采购入库等的一些操作&#xff0c;ide工具&#xff1a;IDEA 或者eclipse 编程语言: java 数据库: mysql5.7 框架&…

PyTorch中常用的工具(4)Visdom

文章目录 前言3.2 Visdom 前言 在训练神经网络的过程中需要用到很多的工具&#xff0c;最重要的是数据处理、可视化和GPU加速。本章主要介绍PyTorch在这些方面常用的工具模块&#xff0c;合理使用这些工具可以极大地提高编程效率。 由于内容较多&#xff0c;本文分成了五篇文…

修改jenkins的目录(JENKINS_HOME)

默认JENKINS_HOME是/var/lib/jenkins/ 现要修改为/home/jenkins_data/jenkins 最开始 sudo cp -a /var/lib/jenkins/ /home/jenkins_data/ 然后如下操作&#xff1a; 1、首先 /etc/sysconfig/jenkins&#xff1a;jenkins配置文件&#xff0c;“端口”&#xff0c;“JENKIN…

使用opencv+tesseract识别图片中的表格

描述 在java环境中使用opencv和tesserac识别一个图片表格 环境&#xff1a;opencv和tesseract安装在linux环境下&#xff0c;docker将运行springboot服务 opencv和tesseract的安装和docker加载可参考之前的文章 过程 将图片进行预处理&#xff0c;过滤掉颜色等干扰元素 提…

2023 年四川省职业院校技能大赛“信息安全管理与评估”样题

2023 年四川省职业院校技能大赛&#xff08;高等职业教育&#xff09; “信息安全管理与评估”样题 竞赛需要完成三个阶段的任务&#xff0c;分别完成三个模块&#xff0c;总分共计 1000分。三个模块内容和分值分别是&#xff1a; 第一阶段&#xff1a;模块一 网络平台搭建与设…

Windows系统历史版本简介详细版

学习目标&#xff1a; 目录 学习目标&#xff1a; 学习内容&#xff1a; 学习产出&#xff1a; Windows 11的全新用户界面设计&#xff1a;学习新的任务栏、开始菜单、窗口管理等界面元素的使用与操作。 Windows 11的新功能和特点&#xff1a;学习新的虚拟桌面、Microsoft Team…

【MMdetection】MMdetection从入门到进阶

基础环境安装 步骤 0. 从官方网站下载并安装 Miniconda。 步骤 1. 创建并激活一个 conda 环境。 conda create --name openmmlab python3.8 -y conda activate openmmlab步骤 2. 基于 PyTorch 官方说明安装 PyTorch。 pip install torch2.0.1 torchvision0.15.2 torchaudio…

前端--基础 目录文件夹和根目录 VScode打开目录文件夹

目录 目录文件夹和根目录 &#xff1a; 目录文件夹 &#xff1a; 根目录 &#xff1a; VScode 打开目录文件夹 &#xff1a; VScode 打开文件夹 &#xff1a; 拖拽目录文件夹 &#xff1a; 目录文件夹和根目录 &#xff1a; 我们都清楚&#xff0c;在实际的工作中会…

[python]python使用M-LSD直线检测算法onnx部署模型实时检测

介绍 github地址&#xff1a;https://github.com/navervision/mlsd LSD (M-LSD)一种用于资源受限环境的实时轻量线段检测器。它利用了极其高效的 LSD 架构和新颖的训练方案&#xff0c;包括 SoL 增强和几何学习方案。模型可以在GPU、CPU甚至移动设备上实时运行。算法已开源&a…

ChatGPT 对SEO的影响

ChatGPT 的兴起是否预示着 SEO 的终结&#xff1f; 一点也不。事实上&#xff0c;如果使用得当&#xff0c;它可以让你的 SEO 工作变得更加容易。 强调“正确使用时”。 你可以使用ChatGPT来帮助进行关键字研究的头脑风暴部分、重新措辞你的内容、生成架构标记等等。 但你不…

LeetCode每日一题.02(螺旋矩阵||)

螺旋矩阵&#xff1a; 给你一个正整数 n &#xff0c;生成一个包含 1 到 n2 所有元素&#xff0c;且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1&#xff1a; 输入&#xff1a;n 3 输出&#xff1a;[[1,2,3],[8,9,4],[7,6,5]] 示例 2&#xff1a; 输入…

HarmonyOS应用程序包快速修复

快速修复概述 快速修复是HarmonyOS系统提供给开发者的一种技术手段&#xff0c;支持开发者以远快于应用升级的方式对应用程序包进行缺陷修复。和全量应用升级软件版本相比&#xff0c;快速修复的主要优势在小、快和用户体验好。在较短的时间内不中断正在运行的应用的情况下&am…

<Icon-ResizER>support

If you get any questions in using app, email me caohechunhotmail.com.

【leetcode100-025】【链表/快慢指针】环形链表

【题干】 给你一个链表的头节点 head &#xff0c;判断链表中是否有环。 如果链表中有某个节点&#xff0c;可以通过连续跟踪 next 指针再次到达&#xff0c;则链表中存在环。 为了表示给定链表中的环&#xff0c;评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置&a…

AI电商时代开始:阿里能否反杀拼多多

“AI电商时代刚刚开始&#xff0c;对谁都是机会&#xff0c;也是挑战。” 针对阿里员工对于拼多多财报和电商等的讨论&#xff0c;马云在阿里内网罕见地参与了谈论并发言。 阿里巴巴一向雷厉风行&#xff0c;已打响了AI电商的“第一炮”。 根据《晚点LatePost》报道&#xff…

C Primer Plus 第6版 编程练习 chapter 12

文章目录 1. 第1题1.1 题目描述1.2 编程源码1.3 结果显示 2. 第2题2.1 题目描述2.2 编程源码2.2.1 pe12-2a.h源码2.2.2 pe12-2a.c源码2.2.3 pe12-2b.c源码 2.3 结果显示 3. 第3题3.1 题目描述3.2 编程源码3.2.1 pe12-2a.h源码3.2.2 pe12-2a.c源码3.2.3 pe12-2b.c源码 3.3 结果显…

2024年【安全员-B证】考试报名及安全员-B证新版试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 安全员-B证考试报名考前必练&#xff01;安全生产模拟考试一点通每个月更新安全员-B证新版试题题目及答案&#xff01;多做几遍&#xff0c;其实通过安全员-B证考试试题很简单。 1、【多选题】《中华人民共和国消防法…

液晶时钟设计

#include<reg51.h> //包含单片机寄存器的头文件 #include<stdlib.h> //包含随机函数rand()的定义文件 #include<intrins.h> //包含_nop_()函数定义的头文件 sbit RSP2^0; //寄存器选择位&#xff0c;将RS位定义为P2.0引脚 sbit RWP2^1; //读写选…

《Python机器学习原理与算法实现》学习笔记

以下为《Python机器学习原理与算法实现》&#xff08;杨维忠 张甜 著 2023年2月新书 清华大学出版社&#xff09;的学习笔记。 根据输入数据是否具有“响应变量”信息&#xff0c;机器学习被分为“监督式学习”和“非监督式学习”。 “监督式学习”即输入数据中即有X变量&…