first commit
This commit is contained in:
parent
9abad9dbb2
commit
6b5c3722de
181
README.md
181
README.md
|
@ -1,3 +1,180 @@
|
|||
# internlm2-chat-1_8b_a13569596008165376146657
|
||||
---
|
||||
pipeline_tag: text-generation
|
||||
license: other
|
||||
---
|
||||
# InternLM
|
||||
|
||||
internlm2-chat-1_8b
|
||||
<div align="center">
|
||||
|
||||
<img src="https://github.com/InternLM/InternLM/assets/22529082/b9788105-8892-4398-8b47-b513a292378e" width="200"/>
|
||||
<div> </div>
|
||||
<div align="center">
|
||||
<b><font size="5">InternLM</font></b>
|
||||
<sup>
|
||||
<a href="https://internlm.intern-ai.org.cn/">
|
||||
<i><font size="4">HOT</font></i>
|
||||
</a>
|
||||
</sup>
|
||||
<div> </div>
|
||||
</div>
|
||||
|
||||
[](https://github.com/internLM/OpenCompass/)
|
||||
|
||||
[💻Github Repo](https://github.com/InternLM/InternLM) • [🤔Reporting Issues](https://github.com/InternLM/InternLM/issues/new)
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Introduction
|
||||
InternLM2-1.8B is the 1.8 billion parameter version of the second generation InternLM series. In order to facilitate user use and research, InternLM2-1.8B has three versions of open-source models. They are:
|
||||
|
||||
- InternLM2-1.8B: Foundation models with high quality and high adaptation flexibility, which serve as a good starting point for downstream deep adaptations.
|
||||
- InternLM2-Chat-1.8B-SFT: Chat model after supervised fine-tuning (SFT) on InternLM2-1.8B.
|
||||
- InternLM2-Chat-1.8B: Further aligned on top of InternLM2-Chat-1.8B-SFT through online RLHF. InternLM2-Chat-1.8B exhibits better instruction following, chat experience, and function calling, which is recommended for downstream applications.
|
||||
|
||||
The InternLM2 has the following technical features:
|
||||
|
||||
- Effective support for ultra-long contexts of up to 200,000 characters: The model nearly perfectly achieves "finding a needle in a haystack" in long inputs of 200,000 characters. It also leads among open-source models in performance on long-text tasks such as LongBench and L-Eval.
|
||||
- Comprehensive performance enhancement: Compared to the previous generation model, it shows significant improvements in various capabilities, including reasoning, mathematics, and coding.
|
||||
|
||||
|
||||
## InternLM2-1.8B
|
||||
|
||||
### Performance Evaluation
|
||||
|
||||
We have evaluated InternLM2 on several important benchmarks using the open-source evaluation tool [OpenCompass](https://github.com/open-compass/opencompass). Some of the evaluation results are shown in the table below. You are welcome to visit the [OpenCompass Leaderboard](https://opencompass.org.cn/rank) for more evaluation results.
|
||||
|
||||
| Dataset\Models | InternLM2-1.8B | InternLM2-Chat-1.8B-SFT | InternLM2-7B | InternLM2-Chat-7B |
|
||||
| :---: | :---: | :---: | :---: | :---: |
|
||||
| MMLU | 46.9 | 47.1 | 65.8 | 63.7 |
|
||||
| AGIEval | 33.4 | 38.8 | 49.9 | 47.2 |
|
||||
| BBH | 37.5 | 35.2 | 65.0 | 61.2 |
|
||||
| GSM8K | 31.2 | 39.7 | 70.8 | 70.7 |
|
||||
| MATH | 5.6 | 11.8 | 20.2 | 23.0 |
|
||||
| HumanEval | 25.0 | 32.9 | 43.3 | 59.8 |
|
||||
| MBPP(Sanitized) | 22.2 | 23.2 | 51.8 | 51.4 |
|
||||
|
||||
|
||||
- The evaluation results were obtained from [OpenCompass](https://github.com/open-compass/opencompass) , and evaluation configuration can be found in the configuration files provided by [OpenCompass](https://github.com/open-compass/opencompass).
|
||||
- The evaluation data may have numerical differences due to the version iteration of [OpenCompass](https://github.com/open-compass/opencompass), so please refer to the latest evaluation results of [OpenCompass](https://github.com/open-compass/opencompass).
|
||||
|
||||
|
||||
|
||||
**Limitations:** Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information.
|
||||
|
||||
### Import from ModelScope
|
||||
|
||||
To load the InternLM2 1.8B Chat model using ModelScope, use the following code:
|
||||
|
||||
```python
|
||||
from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM
|
||||
import torch
|
||||
|
||||
model_dir = snapshot_download("Shanghai_AI_Laboratory/internlm2-chat-1_8b")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, device_map="auto", trust_remote_code=True)
|
||||
# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error.
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16)
|
||||
model = model.eval()
|
||||
response, history = model.chat(tokenizer, "hello", history=[])
|
||||
print(response)
|
||||
# Hello! How can I help you today?
|
||||
response, history = model.chat(tokenizer, "please provide three suggestions about time management", history=history)
|
||||
print(response)
|
||||
```
|
||||
|
||||
The responses can be streamed using `stream_chat`:
|
||||
|
||||
```python
|
||||
from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM
|
||||
import torch
|
||||
|
||||
model_dir = snapshot_download("Shanghai_AI_Laboratory/internlm2-chat-1_8b")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, device_map="auto", trust_remote_code=True)
|
||||
# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and might cause OOM Error.
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16)
|
||||
model = model.eval()
|
||||
length = 0
|
||||
for response, history in model.stream_chat(tokenizer, "Hello", history=[]):
|
||||
print(response[length:], flush=True, end="")
|
||||
length = len(response)
|
||||
```
|
||||
|
||||
## Open Source License
|
||||
|
||||
The code is licensed under Apache-2.0, while model weights are fully open for academic research and also allow **free** commercial usage. To apply for a commercial license, please fill in the [application form (English)](https://wj.qq.com/s2/12727483/5dba/)/[申请表(中文)](https://wj.qq.com/s2/12725412/f7c1/). For other questions or collaborations, please contact <internlm@pjlab.org.cn>.
|
||||
|
||||
## 简介
|
||||
书生·浦语-1.8B (InternLM2-1.8B) 是第二代浦语模型系列的18亿参数版本。为了方便用户使用和研究,书生·浦语-1.8B (InternLM2-1.8B) 共有三个版本的开源模型,他们分别是:
|
||||
|
||||
- InternLM2-1.8B: 具有高质量和高适应灵活性的基础模型,为下游深度适应提供了良好的起点。
|
||||
- InternLM2-Chat-1.8B-SFT:在 InternLM2-1.8B 上进行监督微调 (SFT) 后得到的对话模型。
|
||||
- InternLM2-Chat-1.8B:通过在线 RLHF 在 InternLM2-Chat-1.8B-SFT 之上进一步对齐。 InternLM2-Chat-1.8B 表现出更好的指令跟随、聊天体验和函数调用,推荐下游应用程序使用。
|
||||
|
||||
InternLM2 模型具备以下的技术特点
|
||||
|
||||
- 有效支持20万字超长上下文:模型在20万字长输入中几乎完美地实现长文“大海捞针”,而且在 LongBench 和 L-Eval 等长文任务中的表现也达到开源模型中的领先水平。
|
||||
- 综合性能全面提升:各能力维度相比上一代模型全面进步,在推理、数学、代码等方面的能力提升显著。
|
||||
|
||||
## InternLM2-1.8B
|
||||
|
||||
### 性能评测
|
||||
|
||||
我们使用开源评测工具 [OpenCompass](https://github.com/internLM/OpenCompass/) 对 InternLM2 在几个重要的评测集进行了评测 ,部分评测结果如下表所示,欢迎访问[ OpenCompass 榜单 ](https://opencompass.org.cn/rank)获取更多的评测结果。
|
||||
|
||||
| 评测集 | InternLM2-1.8B | InternLM2-Chat-1.8B-SFT | InternLM2-7B | InternLM2-Chat-7B |
|
||||
| :---: | :---: | :---: | :---: | :---: |
|
||||
| MMLU | 46.9 | 47.1 | 65.8 | 63.7 |
|
||||
| AGIEval | 33.4 | 38.8 | 49.9 | 47.2 |
|
||||
| BBH | 37.5 | 35.2 | 65.0 | 61.2 |
|
||||
| GSM8K | 31.2 | 39.7 | 70.8 | 70.7 |
|
||||
| MATH | 5.6 | 11.8 | 20.2 | 23.0 |
|
||||
| HumanEval | 25.0 | 32.9 | 43.3 | 59.8 |
|
||||
| MBPP(Sanitized) | 22.2 | 23.2 | 51.8 | 51.4 |
|
||||
|
||||
- 以上评测结果基于 [OpenCompass](https://github.com/open-compass/opencompass) 获得(部分数据标注`*`代表数据来自原始论文),具体测试细节可参见 [OpenCompass](https://github.com/open-compass/opencompass) 中提供的配置文件。
|
||||
- 评测数据会因 [OpenCompass](https://github.com/open-compass/opencompass) 的版本迭代而存在数值差异,请以 [OpenCompass](https://github.com/open-compass/opencompass) 最新版的评测结果为主。
|
||||
|
||||
|
||||
**局限性:** 尽管在训练过程中我们非常注重模型的安全性,尽力促使模型输出符合伦理和法律要求的文本,但受限于模型大小以及概率生成范式,模型可能会产生各种不符合预期的输出,例如回复内容包含偏见、歧视等有害内容,请勿传播这些内容。由于传播不良信息导致的任何后果,本项目不承担责任。
|
||||
|
||||
### 通过 ModelScope 加载
|
||||
|
||||
通过以下的代码加载 InternLM2 1.8B Chat 模型
|
||||
|
||||
```python
|
||||
from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM
|
||||
import torch
|
||||
|
||||
model_dir = snapshot_download("Shanghai_AI_Laboratory/internlm2-chat-1_8b")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, device_map="auto", trust_remote_code=True)
|
||||
# `torch_dtype=torch.float16` 可以令模型以 float16 精度加载,否则 modelscope 会将模型加载为 float32,导致显存不足
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16)
|
||||
model = model.eval()
|
||||
response, history = model.chat(tokenizer, "你好", history=[])
|
||||
print(response)
|
||||
# 你好!有什么我可以帮助你的吗?
|
||||
response, history = model.chat(tokenizer, "请提供三个管理时间的建议。", history=history)
|
||||
print(response)
|
||||
```
|
||||
|
||||
如果想进行流式生成,则可以使用 `stream_chat` 接口:
|
||||
|
||||
```python
|
||||
from modelscope import snapshot_download, AutoTokenizer, AutoModelForCausalLM
|
||||
import torch
|
||||
|
||||
model_dir = snapshot_download("Shanghai_AI_Laboratory/internlm2-chat-1_8b")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, device_map="auto", trust_remote_code=True)
|
||||
# `torch_dtype=torch.float16` 可以令模型以 float16 精度加载,否则 modelscope 会将模型加载为 float32,导致显存不足
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16)
|
||||
model = model.eval()
|
||||
length = 0
|
||||
for response, history in model.stream_chat(tokenizer, "你好", history=[]):
|
||||
print(response[length:], flush=True, end="")
|
||||
length = len(response)
|
||||
```
|
||||
|
||||
|
||||
## 开源许可证
|
||||
|
||||
本仓库的代码依照 Apache-2.0 协议开源。模型权重对学术研究完全开放,也可申请免费的商业使用授权([申请表](https://wj.qq.com/s2/12725412/f7c1/))。其他问题与合作请联系 <internlm@pjlab.org.cn>。
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"architectures": [
|
||||
"InternLM2ForCausalLM"
|
||||
],
|
||||
"attn_implementation": "eager",
|
||||
"auto_map": {
|
||||
"AutoConfig": "configuration_internlm2.InternLM2Config",
|
||||
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM",
|
||||
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM"
|
||||
},
|
||||
"bias": false,
|
||||
"bos_token_id": 1,
|
||||
"eos_token_id": 2,
|
||||
"hidden_act": "silu",
|
||||
"hidden_size": 2048,
|
||||
"initializer_range": 0.02,
|
||||
"intermediate_size": 8192,
|
||||
"max_position_embeddings": 32768,
|
||||
"model_type": "internlm2",
|
||||
"num_attention_heads": 16,
|
||||
"num_hidden_layers": 24,
|
||||
"num_key_value_heads": 8,
|
||||
"pad_token_id": 2,
|
||||
"rms_norm_eps": 1e-05,
|
||||
"rope_scaling": null,
|
||||
"rope_theta": 1000000,
|
||||
"tie_word_embeddings": false,
|
||||
"torch_dtype": "bfloat16",
|
||||
"transformers_version": "4.37.1",
|
||||
"use_cache": true,
|
||||
"vocab_size": 92544
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{"framework":"Pytorch","task":"text-generation"}
|
|
@ -0,0 +1,151 @@
|
|||
# coding=utf-8
|
||||
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on transformers/src/transformers/models/llama/configuration_llama.py
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
""" InternLM2 model configuration"""
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
||||
|
||||
|
||||
# Modified from transformers.model.llama.configuration_llama.LlamaConfig
|
||||
class InternLM2Config(PretrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
|
||||
an InternLM2 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 InternLM2-7B.
|
||||
|
||||
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PretrainedConfig`] for more information.
|
||||
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 32000):
|
||||
Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
|
||||
`inputs_ids` passed when calling [`InternLM2Model`]
|
||||
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.
|
||||
num_key_value_heads (`int`, *optional*):
|
||||
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
||||
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
||||
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
||||
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
||||
by meanpooling all the original heads within that group. For more details checkout [this
|
||||
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
||||
`num_attention_heads`.
|
||||
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:
|
||||
|
||||
"""
|
||||
model_type = "internlm2"
|
||||
_auto_class = "AutoConfig"
|
||||
|
||||
def __init__( # pylint: disable=W0102
|
||||
self,
|
||||
vocab_size=103168,
|
||||
hidden_size=4096,
|
||||
intermediate_size=11008,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=None,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=2048,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
pad_token_id=0,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
tie_word_embeddings=False,
|
||||
bias=True,
|
||||
rope_theta=10000,
|
||||
rope_scaling=None,
|
||||
attn_implementation="eager",
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.bias = bias
|
||||
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self._rope_scaling_validation()
|
||||
|
||||
self.attn_implementation = attn_implementation
|
||||
if self.attn_implementation is None:
|
||||
self.attn_implementation = "eager"
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _rope_scaling_validation(self):
|
||||
"""
|
||||
Validate the `rope_scaling` configuration.
|
||||
"""
|
||||
if self.rope_scaling is None:
|
||||
return
|
||||
|
||||
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
||||
raise ValueError(
|
||||
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
||||
f"got {self.rope_scaling}"
|
||||
)
|
||||
rope_scaling_type = self.rope_scaling.get("type", None)
|
||||
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
||||
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
||||
raise ValueError(
|
||||
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
||||
)
|
||||
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
|
||||
raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"_from_model_config": true,
|
||||
"bos_token_id": 1,
|
||||
"eos_token_id": 2,
|
||||
"pad_token_id": 2,
|
||||
"transformers_version": "4.37.1"
|
||||
}
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,178 @@
|
|||
{
|
||||
"metadata": {
|
||||
"total_size": 3778220032
|
||||
},
|
||||
"weight_map": {
|
||||
"model.layers.0.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.0.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.1.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.10.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.11.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.12.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.12.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.12.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.12.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.12.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.12.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.12.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.13.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.14.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.15.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.16.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.17.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.18.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.19.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.2.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.2.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.20.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.20.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.21.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.22.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.attention.wo.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.attention.wqkv.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.attention_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.feed_forward.w1.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.feed_forward.w2.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.feed_forward.w3.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.23.ffn_norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.layers.3.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.3.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.4.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.5.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.6.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.7.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.8.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.attention.wo.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.attention.wqkv.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.attention_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
|
||||
"model.layers.9.ffn_norm.weight": "model-00001-of-00002.safetensors",
|
||||
"model.norm.weight": "model-00002-of-00002.safetensors",
|
||||
"model.tok_embeddings.weight": "model-00001-of-00002.safetensors",
|
||||
"output.weight": "model-00002-of-00002.safetensors"
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"additional_special_tokens": [
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
"<|action_start|>",
|
||||
"<|action_end|>",
|
||||
"<|interpreter|>",
|
||||
"<|plugin|>"
|
||||
],
|
||||
"bos_token": {
|
||||
"content": "<s>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
},
|
||||
"eos_token": {
|
||||
"content": "</s>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
},
|
||||
"pad_token": {
|
||||
"content": "</s>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
},
|
||||
"unk_token": {
|
||||
"content": "<unk>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,236 @@
|
|||
# coding=utf-8
|
||||
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tokenization classes for InternLM."""
|
||||
import os
|
||||
from shutil import copyfile
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import sentencepiece as spm
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
||||
|
||||
PRETRAINED_VOCAB_FILES_MAP = {}
|
||||
|
||||
|
||||
# Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
|
||||
class InternLM2Tokenizer(PreTrainedTokenizer):
|
||||
"""
|
||||
Construct a InternLM2 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
|
||||
model_input_names = ["input_ids", "attention_mask"]
|
||||
_auto_class = "AutoTokenizer"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_file,
|
||||
unk_token="<unk>",
|
||||
bos_token="<s>",
|
||||
eos_token="</s>",
|
||||
pad_token="</s>",
|
||||
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
||||
add_bos_token=True,
|
||||
add_eos_token=False,
|
||||
decode_with_prefix_space=False,
|
||||
clean_up_tokenization_spaces=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
||||
self.vocab_file = vocab_file
|
||||
self.add_bos_token = add_bos_token
|
||||
self.add_eos_token = add_eos_token
|
||||
self.decode_with_prefix_space = decode_with_prefix_space
|
||||
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
||||
self.sp_model.Load(vocab_file)
|
||||
self._no_prefix_space_tokens = None
|
||||
super().__init__(
|
||||
bos_token=bos_token,
|
||||
eos_token=eos_token,
|
||||
unk_token=unk_token,
|
||||
pad_token=pad_token,
|
||||
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def no_prefix_space_tokens(self):
|
||||
if self._no_prefix_space_tokens is None:
|
||||
vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
|
||||
self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
|
||||
return self._no_prefix_space_tokens
|
||||
|
||||
@property
|
||||
def vocab_size(self):
|
||||
"""Returns vocab size"""
|
||||
return self.sp_model.get_piece_size()
|
||||
|
||||
@property
|
||||
def bos_token_id(self) -> Optional[int]:
|
||||
return self.sp_model.bos_id()
|
||||
|
||||
@property
|
||||
def eos_token_id(self) -> Optional[int]:
|
||||
return self.sp_model.eos_id()
|
||||
|
||||
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
|
||||
|
||||
def _tokenize(self, text):
|
||||
"""Returns a tokenized string."""
|
||||
return self.sp_model.encode(text, out_type=str)
|
||||
|
||||
def _convert_token_to_id(self, token):
|
||||
"""Converts a token (str) in an id using the vocab."""
|
||||
return self.sp_model.piece_to_id(token)
|
||||
|
||||
def _convert_id_to_token(self, index):
|
||||
"""Converts an index (integer) in a token (str) using the vocab."""
|
||||
token = self.sp_model.IdToPiece(index)
|
||||
return token
|
||||
|
||||
def _maybe_add_prefix_space(self, tokens, decoded):
|
||||
if tokens and tokens[0] not in self.no_prefix_space_tokens:
|
||||
return " " + decoded
|
||||
else:
|
||||
return decoded
|
||||
|
||||
def convert_tokens_to_string(self, tokens):
|
||||
"""Converts a sequence of tokens (string) in a single string."""
|
||||
current_sub_tokens = []
|
||||
out_string = ""
|
||||
prev_is_special = False
|
||||
for token in tokens:
|
||||
# make sure that special tokens are not decoded using sentencepiece model
|
||||
if token in self.all_special_tokens:
|
||||
if not prev_is_special:
|
||||
out_string += " "
|
||||
out_string += self.sp_model.decode(current_sub_tokens) + token
|
||||
prev_is_special = True
|
||||
current_sub_tokens = []
|
||||
else:
|
||||
current_sub_tokens.append(token)
|
||||
prev_is_special = False
|
||||
out_string += self.sp_model.decode(current_sub_tokens)
|
||||
out_string = self.clean_up_tokenization(out_string)
|
||||
out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
|
||||
return out_string[1:]
|
||||
|
||||
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
||||
"""
|
||||
Save the vocabulary and special tokens file to a directory.
|
||||
|
||||
Args:
|
||||
save_directory (`str`):
|
||||
The directory in which to save the vocabulary.
|
||||
|
||||
Returns:
|
||||
`Tuple(str)`: Paths to the files saved.
|
||||
"""
|
||||
if not os.path.isdir(save_directory):
|
||||
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
||||
return
|
||||
out_vocab_file = os.path.join(
|
||||
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
||||
)
|
||||
|
||||
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
||||
copyfile(self.vocab_file, out_vocab_file)
|
||||
elif not os.path.isfile(self.vocab_file):
|
||||
with open(out_vocab_file, "wb") as fi:
|
||||
content_spiece_model = self.sp_model.serialized_model_proto()
|
||||
fi.write(content_spiece_model)
|
||||
|
||||
return (out_vocab_file,)
|
||||
|
||||
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
||||
if self.add_bos_token:
|
||||
bos_token_ids = [self.bos_token_id]
|
||||
else:
|
||||
bos_token_ids = []
|
||||
|
||||
output = bos_token_ids + token_ids_0
|
||||
|
||||
if token_ids_1 is not None:
|
||||
output = output + token_ids_1
|
||||
|
||||
if self.add_eos_token:
|
||||
output = output + [self.eos_token_id]
|
||||
|
||||
return output
|
||||
|
||||
def get_special_tokens_mask(
|
||||
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
||||
) -> List[int]:
|
||||
"""
|
||||
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
||||
special tokens using the tokenizer `prepare_for_model` method.
|
||||
|
||||
Args:
|
||||
token_ids_0 (`List[int]`):
|
||||
List of IDs.
|
||||
token_ids_1 (`List[int]`, *optional*):
|
||||
Optional second list of IDs for sequence pairs.
|
||||
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
||||
Whether or not the token list is already formatted with special tokens for the model.
|
||||
|
||||
Returns:
|
||||
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
||||
"""
|
||||
if already_has_special_tokens:
|
||||
return super().get_special_tokens_mask(
|
||||
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
||||
)
|
||||
|
||||
if token_ids_1 is None:
|
||||
return [1] + ([0] * len(token_ids_0)) + [1]
|
||||
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
||||
|
||||
def create_token_type_ids_from_sequences(
|
||||
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
||||
) -> List[int]:
|
||||
"""
|
||||
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
|
||||
use of token type ids, therefore a list of zeros is returned.
|
||||
|
||||
Args:
|
||||
token_ids_0 (`List[int]`):
|
||||
List of IDs.
|
||||
token_ids_1 (`List[int]`, *optional*):
|
||||
Optional second list of IDs for sequence pairs.
|
||||
|
||||
Returns:
|
||||
`List[int]`: List of zeros.
|
||||
"""
|
||||
eos = [self.eos_token_id]
|
||||
|
||||
if token_ids_1 is None:
|
||||
return len(token_ids_0 + eos) * [0]
|
||||
return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
|
|
@ -0,0 +1,214 @@
|
|||
# coding=utf-8
|
||||
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tokenization Fast class for InternLM."""
|
||||
import os
|
||||
from shutil import copyfile
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from tokenizers import processors, decoders, Tokenizer, normalizers
|
||||
from tokenizers.models import BPE
|
||||
|
||||
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
||||
from transformers.utils import logging
|
||||
|
||||
from transformers.convert_slow_tokenizer import (
|
||||
SLOW_TO_FAST_CONVERTERS,
|
||||
SpmConverter,
|
||||
SentencePieceExtractor,
|
||||
)
|
||||
|
||||
from .tokenization_internlm2 import InternLM2Tokenizer
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
||||
|
||||
# Modified from transformers.convert_slow_tokenizer.LlamaConverter
|
||||
class InternLM2Converter(SpmConverter):
|
||||
handle_byte_fallback = True
|
||||
|
||||
def vocab(self, proto):
|
||||
vocab = [
|
||||
("<unk>", 0.0),
|
||||
("<s>", 0.0),
|
||||
("</s>", 0.0),
|
||||
]
|
||||
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
||||
return vocab
|
||||
|
||||
def unk_id(self, proto):
|
||||
unk_id = 0
|
||||
return unk_id
|
||||
|
||||
def decoder(self, replacement, add_prefix_space):
|
||||
decoders_sequence = [
|
||||
decoders.Replace("▁", " "),
|
||||
decoders.ByteFallback(),
|
||||
decoders.Fuse(),
|
||||
]
|
||||
if self.proto.normalizer_spec.add_dummy_prefix:
|
||||
decoders_sequence.append(decoders.Strip(content=" ", left=1))
|
||||
return decoders.Sequence(decoders_sequence)
|
||||
|
||||
def tokenizer(self, proto):
|
||||
model_type = proto.trainer_spec.model_type
|
||||
vocab_scores = self.vocab(proto)
|
||||
# special tokens
|
||||
added_tokens = self.original_tokenizer.added_tokens_decoder
|
||||
for i in range(len(vocab_scores)):
|
||||
piece, score = vocab_scores[i]
|
||||
if i in added_tokens:
|
||||
vocab_scores[i] = (added_tokens[i].content, score)
|
||||
if model_type == 1:
|
||||
raise RuntimeError("InternLM2 is supposed to be a BPE model!")
|
||||
|
||||
elif model_type == 2:
|
||||
_, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
|
||||
bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
|
||||
tokenizer = Tokenizer(
|
||||
BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
|
||||
)
|
||||
tokenizer.add_special_tokens(
|
||||
[ added_token for index, added_token in added_tokens.items()]
|
||||
)
|
||||
else:
|
||||
raise Exception(
|
||||
"You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
|
||||
)
|
||||
|
||||
return tokenizer
|
||||
|
||||
def normalizer(self, proto):
|
||||
normalizers_list = []
|
||||
if proto.normalizer_spec.add_dummy_prefix:
|
||||
normalizers_list.append(normalizers.Prepend(prepend="▁"))
|
||||
normalizers_list.append(normalizers.Replace(pattern=" ", content="▁"))
|
||||
return normalizers.Sequence(normalizers_list)
|
||||
|
||||
def pre_tokenizer(self, replacement, add_prefix_space):
|
||||
return None
|
||||
|
||||
SLOW_TO_FAST_CONVERTERS["InternLM2Tokenizer"] = InternLM2Converter
|
||||
|
||||
|
||||
# Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
|
||||
class InternLM2TokenizerFast(PreTrainedTokenizerFast):
|
||||
vocab_files_names = VOCAB_FILES_NAMES
|
||||
slow_tokenizer_class = InternLM2Tokenizer
|
||||
padding_side = "left"
|
||||
model_input_names = ["input_ids", "attention_mask"]
|
||||
_auto_class = "AutoTokenizer"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_file,
|
||||
unk_token="<unk>",
|
||||
bos_token="<s>",
|
||||
eos_token="</s>",
|
||||
pad_token="</s>",
|
||||
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
||||
add_bos_token=True,
|
||||
add_eos_token=False,
|
||||
decode_with_prefix_space=False,
|
||||
clean_up_tokenization_spaces=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
vocab_file=vocab_file,
|
||||
unk_token=unk_token,
|
||||
bos_token=bos_token,
|
||||
eos_token=eos_token,
|
||||
pad_token=pad_token,
|
||||
sp_model_kwargs=sp_model_kwargs,
|
||||
add_bos_token=add_bos_token,
|
||||
add_eos_token=add_eos_token,
|
||||
decode_with_prefix_space=decode_with_prefix_space,
|
||||
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
||||
**kwargs,
|
||||
)
|
||||
self._add_bos_token = add_bos_token
|
||||
self._add_eos_token = add_eos_token
|
||||
self.update_post_processor()
|
||||
self.vocab_file = vocab_file
|
||||
|
||||
@property
|
||||
def can_save_slow_tokenizer(self) -> bool:
|
||||
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
||||
|
||||
def update_post_processor(self):
|
||||
"""
|
||||
Updates the underlying post processor with the current `bos_token` and `eos_token`.
|
||||
"""
|
||||
bos = self.bos_token
|
||||
bos_token_id = self.bos_token_id
|
||||
if bos is None and self.add_bos_token:
|
||||
raise ValueError("add_bos_token = True but bos_token = None")
|
||||
|
||||
eos = self.eos_token
|
||||
eos_token_id = self.eos_token_id
|
||||
if eos is None and self.add_eos_token:
|
||||
raise ValueError("add_eos_token = True but eos_token = None")
|
||||
|
||||
single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
|
||||
pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
|
||||
|
||||
special_tokens = []
|
||||
if self.add_bos_token:
|
||||
special_tokens.append((bos, bos_token_id))
|
||||
if self.add_eos_token:
|
||||
special_tokens.append((eos, eos_token_id))
|
||||
self._tokenizer.post_processor = processors.TemplateProcessing(
|
||||
single=single, pair=pair, special_tokens=special_tokens
|
||||
)
|
||||
|
||||
@property
|
||||
def add_eos_token(self):
|
||||
return self._add_eos_token
|
||||
|
||||
@property
|
||||
def add_bos_token(self):
|
||||
return self._add_bos_token
|
||||
|
||||
@add_eos_token.setter
|
||||
def add_eos_token(self, value):
|
||||
self._add_eos_token = value
|
||||
self.update_post_processor()
|
||||
|
||||
@add_bos_token.setter
|
||||
def add_bos_token(self, value):
|
||||
self._add_bos_token = value
|
||||
self.update_post_processor()
|
||||
|
||||
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
||||
if not self.can_save_slow_tokenizer:
|
||||
raise ValueError(
|
||||
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
||||
"tokenizer."
|
||||
)
|
||||
|
||||
if not os.path.isdir(save_directory):
|
||||
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
||||
return
|
||||
out_vocab_file = os.path.join(
|
||||
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
||||
)
|
||||
|
||||
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
||||
copyfile(self.vocab_file, out_vocab_file)
|
||||
|
||||
return (out_vocab_file,)
|
Binary file not shown.
|
@ -0,0 +1,102 @@
|
|||
{
|
||||
"add_bos_token": true,
|
||||
"add_eos_token": false,
|
||||
"added_tokens_decoder": {
|
||||
"0": {
|
||||
"content": "<unk>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"1": {
|
||||
"content": "<s>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"2": {
|
||||
"content": "</s>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92538": {
|
||||
"content": "<|plugin|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92539": {
|
||||
"content": "<|interpreter|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92540": {
|
||||
"content": "<|action_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92541": {
|
||||
"content": "<|action_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92542": {
|
||||
"content": "<|im_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"92543": {
|
||||
"content": "<|im_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
}
|
||||
},
|
||||
"additional_special_tokens": [
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
"<|action_start|>",
|
||||
"<|action_end|>",
|
||||
"<|interpreter|>",
|
||||
"<|plugin|>"
|
||||
],
|
||||
"auto_map": {
|
||||
"AutoTokenizer": [
|
||||
"tokenization_internlm2.InternLM2Tokenizer",
|
||||
"tokenization_internlm2_fast.InternLM2TokenizerFast"
|
||||
]
|
||||
},
|
||||
"bos_token": "<s>",
|
||||
"chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
|
||||
"clean_up_tokenization_spaces": false,
|
||||
"decode_with_prefix_space": false,
|
||||
"eos_token": "</s>",
|
||||
"model_max_length": 1000000000000000019884624838656,
|
||||
"pad_token": "</s>",
|
||||
"sp_model_kwargs": null,
|
||||
"tokenizer_class": "InternLM2Tokenizer",
|
||||
"unk_token": "<unk>"
|
||||
}
|
Loading…
Reference in New Issue