初始化项目,由ModelHub XC社区提供模型

Model: Shanghai_AI_Laboratory/internlm2_5-7b-chat-1m
Source: Original Platform
This commit is contained in:
ModelHub XC
2026-10-07 06:15:13 +08:00
commit ca2a0842a4
21 changed files with 3220 additions and 0 deletions

35
.gitattributes vendored Normal file
View File

@@ -0,0 +1,35 @@
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text

301
README.md Normal file
View File

@@ -0,0 +1,301 @@
---
pipeline_tag: text-generation
license: other
---
# InternLM
<div align="center">
<img src="https://github.com/InternLM/InternLM/assets/22529082/b9788105-8892-4398-8b47-b513a292378e" width="200"/>
<div>&nbsp;</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>&nbsp;</div>
</div>
[![evaluation](https://github.com/InternLM/InternLM/assets/22529082/f80a2a58-5ddf-471a-8da4-32ab65c8fd3b)](https://github.com/internLM/OpenCompass/)
[💻Github Repo](https://github.com/InternLM/InternLM) • [🤔Reporting Issues](https://github.com/InternLM/InternLM/issues/new) • [📜Technical Report](https://arxiv.org/abs/2403.17297)
</div>
<p align="center">
👋 join us on <a href="https://discord.gg/xa29JuW87d" target="_blank">Discord</a> and <a href="https://github.com/InternLM/InternLM/assets/25839884/a6aad896-7232-4220-ac84-9e070c2633ce" target="_blank">WeChat</a>
</p>
## Introduction
InternLM2.5 has open-sourced a 7 billion parameter base model and a chat model tailored for practical scenarios. The model has the following characteristics:
- **Outstanding reasoning capability**: State-of-the-art performance on Math reasoning, surpassing models like Llama3 and Gemma2-9B.
- **1M Context window**: Nearly perfect at finding needles in the haystack with 1M-long context, with leading performance on long-context tasks like LongBench. Try it with [LMDeploy](https://github.com/InternLM/InternLM/blob/main/chat/lmdeploy.md) for 1M-context inference and a [file chat demo](https://github.com/InternLM/InternLM/tree/main/long_context).
- **Stronger tool use**: InternLM2.5 supports gathering information from more than 100 web pages, corresponding implementation will be released in [Lagent](https://github.com/InternLM/lagent/tree/main) soon. InternLM2.5 has better tool utilization-related capabilities in instruction following, tool selection and reflection. See [examples](https://github.com/InternLM/InternLM/blob/main/agent/lagent.md).
## InternLM2.5-7B-Chat-1M
InternLM2.5-7B-Chat-1M is the 1M-long-context version of InternLM2.5-7B-Chat.
### Performance Evaluation
We employed the "*needle in a haystack approach*" to evaluate the model's ability to retrieve information from long texts. Results show that InternLM2.5-7B-Chat-1M can accurately locate key information in documents up to 1M tokens in length.
<p align="center">
<img src="https://github.com/libowen2121/InternLM/assets/19970308/2ce3745f-26f5-4a39-bdcd-2075790d7b1d" alt="drawing" width="700"/>
</p>
We also used the [LongBench](https://github.com/THUDM/LongBench) benchmark to assess long-document comprehension capabilities. Our model achieved optimal performance in these tests.
<p align="center">
<img src="https://github.com/libowen2121/InternLM/assets/19970308/1e8f7da8-8193-4def-8b06-0550bab6a12f" alt="drawing" width="800"/>
</p>
### LMDeploy
Since huggingface Transformers does not directly support inference with 1M-long context, we recommand to use LMDeploy. The conventional usage with huggingface Transformers is also shown below.
LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
Here is an example of 1M-long context inference. **Note: 1M context length requires 4xA100-80G!**
```bash
pip install lmdeploy
```
You can run batch inference locally with the following python code:
```python
from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig
backend_config = TurbomindEngineConfig(
rope_scaling_factor=2.5,
session_len=1048576, # 1M context length
max_batch_size=1,
cache_max_entry_count=0.7,
tp=4) # 4xA100-80G.
pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config)
prompt = 'Use a long prompt to replace this sentence'
response = pipe(prompt)
print(response)
```
Find more details in the [LMDeploy documentation](https://lmdeploy.readthedocs.io/en/latest/)
### Import from Transformers
Since Transformers does not support 1M long context, we only show the usage of non-long context.
To load the InternLM2 7B Chat model using Transformers, use the following code:
```python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-7b-chat-1m", trust_remote_code=True)
# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and cause OOM Error.
model = AutoModelForCausalLM.from_pretrained("internlm/internlm2_5-7b-chat-1m", torch_dtype=torch.float16, trust_remote_code=True).cuda()
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
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_path = "internlm/internlm2_5-7b-chat-1m"
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16, trust_remote_code=True).cuda()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = model.eval()
length = 0
for response, history in model.stream_chat(tokenizer, "Hello", history=[]):
print(response[length:], flush=True, end="")
length = len(response)
```
### vLLM
Launch OpenAI compatible server with `vLLM>=0.3.2`:
```bash
pip install vllm
```
```bash
python -m vllm.entrypoints.openai.api_server --model internlm/internlm2_5-7b-chat-1m --served-model-name internlm2_5-7b-chat-1m --trust-remote-code
```
If you encounter OOM, try to reduce `--max-model-len` or increase `--tensor-parallel-size`.
Then you can send a chat request to the server:
```bash
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "internlm2_5-7b-chat-1m",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Introduce deep learning to me."}
]
}'
```
Find more details in the [vLLM documentation](https://docs.vllm.ai/en/latest/index.html)
## 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>.
## Citation
```
@misc{cai2024internlm2,
title={InternLM2 Technical Report},
author={Zheng Cai and Maosong Cao and Haojiong Chen and Kai Chen and Keyu Chen and Xin Chen and Xun Chen and Zehui Chen and Zhi Chen and Pei Chu and Xiaoyi Dong and Haodong Duan and Qi Fan and Zhaoye Fei and Yang Gao and Jiaye Ge and Chenya Gu and Yuzhe Gu and Tao Gui and Aijia Guo and Qipeng Guo and Conghui He and Yingfan Hu and Ting Huang and Tao Jiang and Penglong Jiao and Zhenjiang Jin and Zhikai Lei and Jiaxing Li and Jingwen Li and Linyang Li and Shuaibin Li and Wei Li and Yining Li and Hongwei Liu and Jiangning Liu and Jiawei Hong and Kaiwen Liu and Kuikun Liu and Xiaoran Liu and Chengqi Lv and Haijun Lv and Kai Lv and Li Ma and Runyuan Ma and Zerun Ma and Wenchang Ning and Linke Ouyang and Jiantao Qiu and Yuan Qu and Fukai Shang and Yunfan Shao and Demin Song and Zifan Song and Zhihao Sui and Peng Sun and Yu Sun and Huanze Tang and Bin Wang and Guoteng Wang and Jiaqi Wang and Jiayu Wang and Rui Wang and Yudong Wang and Ziyi Wang and Xingjian Wei and Qizhen Weng and Fan Wu and Yingtong Xiong and Chao Xu and Ruiliang Xu and Hang Yan and Yirong Yan and Xiaogui Yang and Haochen Ye and Huaiyuan Ying and Jia Yu and Jing Yu and Yuhang Zang and Chuyu Zhang and Li Zhang and Pan Zhang and Peng Zhang and Ruijie Zhang and Shuo Zhang and Songyang Zhang and Wenjian Zhang and Wenwei Zhang and Xingcheng Zhang and Xinyue Zhang and Hui Zhao and Qian Zhao and Xiaomeng Zhao and Fengzhe Zhou and Zaida Zhou and Jingming Zhuo and Yicheng Zou and Xipeng Qiu and Yu Qiao and Dahua Lin},
year={2024},
eprint={2403.17297},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
```
## 简介
InternLM2.5 ,即书生·浦语大模型第 2.5 代,开源了面向实用场景的70亿参数基础模型与对话模型 (InternLM2.5-7B-Chat)。模型具有以下特点:
- 卓越的推理性能:在数学推理方面取得了同量级模型最优精度,超越了 Llama3 和 Gemma2-9B。
- 有效支持百万字超长上下文:模型在 1 百万字长输入中几乎完美地实现长文“大海捞针”,而且在 LongBench 等长文任务中的表现也达到开源模型中的领先水平。 可以通过 [LMDeploy](https://github.com/InternLM/InternLM/blob/main/chat/lmdeploy_zh_cn.md) 尝试百万字超长上下文推理。
- 工具调用能力整体升级:InternLM2.5 支持从上百个网页搜集有效信息进行分析推理,相关实现将于近期开源到 [Lagent](https://github.com/InternLM/lagent/tree/main)。InternLM2.5 具有更强和更具有泛化性的指令理解、工具筛选与结果反思等能力,新版模型可以更可靠地支持复杂智能体的搭建,支持对工具进行有效的多轮调用,完成较复杂的任务。可以查看更多[样例](https://github.com/InternLM/InternLM/blob/main/agent/lagent.md)。
## InternLM2.5-7B-Chat-1M
InternLM2.5-7B-Chat-1M 支持 1 百万字超长上下文推理,且性能和 InternLM2.5-7B-Chat 相当。考虑到 huggingface Transformers 不直接支持 1M 上下文推理,我们优先推荐使用 lmdeploy 进行百万字超长上下文推理演示。在非超长上下文推理的情况下,你仍然可以使用 huggingface transformers,参考下面的样例代码。
### LMDeploy
LMDeploy 由 MMDeploy 和 MMRazor 团队联合开发,是涵盖了 LLM 任务的全套轻量化、部署和服务解决方案。
以下是一个 1M 上下文推理的例子. **注意: 1M 上下文需要 4xA100-80G!**
```bash
pip install lmdeploy
```
你可以使用以下 python 代码进行本地批量推理:
```python
from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig
backend_config = TurbomindEngineConfig(
rope_scaling_factor=2.5,
session_len=1048576, # 1M context length
max_batch_size=1,
cache_max_entry_count=0.7,
tp=4) # 4xA100-80G.
pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config)
prompt = 'Use a long prompt to replace this sentence'
response = pipe(prompt)
print(response)
```
### 通过 Transformers 加载
由于 Transformers 无法支持 1M 长上下文推理,这里仅演示非长文本的用法。
通过以下的代码加载 InternLM2.5 7B Chat 1M 模型
```python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-7b-chat-1m", trust_remote_code=True)
# `torch_dtype=torch.float16` 可以令模型以 float16 精度加载,否则 transformers 会将模型加载为 float32,导致显存不足
model = AutoModelForCausalLM.from_pretrained("internlm/internlm2_5-7b-chat-1m", torch_dtype=torch.float16, trust_remote_code=True).cuda()
model = model.eval()
response, history = model.chat(tokenizer, "你好", history=[])
print(response)
# 你好!有什么我可以帮助你的吗?
response, history = model.chat(tokenizer, "请提供三个管理时间的建议。", history=history)
print(response)
```
如果想进行流式生成,则可以使用 `stream_chat` 接口:
```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_path = "internlm/internlm2_5-7b-chat-1m"
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dype=torch.float16, trust_remote_code=True).cuda()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = model.eval()
length = 0
for response, history in model.stream_chat(tokenizer, "你好", history=[]):
print(response[length:], flush=True, end="")
length = len(response)
```
### vLLM
使用`vLLM>=0.3.2`启动兼容 OpenAI API 的服务:
```bash
pip install vllm
```
```bash
python -m vllm.entrypoints.openai.api_server --model internlm/internlm2_5-7b-chat-1m --trust-remote-code
```
如果你遇到 OOM, 请减小 `--max-model-len` 或增加 `--tensor-parallel-size` 参数.
然后你可以向服务端发起一个聊天请求:
```bash
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "internlm2_5-7b-chat-1m",
"messages": [
{"role": "system", "content": "你是个友善的AI助手。"},
{"role": "user", "content": "介绍一下深度学习。"}
]
}'
```
更多信息请查看 [vLLM 文档](https://docs.vllm.ai/en/latest/index.html)
## 开源许可证
本仓库的代码依照 Apache-2.0 协议开源。模型权重对学术研究完全开放,也可申请免费的商业使用授权([申请表](https://wj.qq.com/s2/12725412/f7c1/))。其他问题与合作请联系 <internlm@pjlab.org.cn>。
## 引用
```
@misc{cai2024internlm2,
title={InternLM2 Technical Report},
author={Zheng Cai and Maosong Cao and Haojiong Chen and Kai Chen and Keyu Chen and Xin Chen and Xun Chen and Zehui Chen and Zhi Chen and Pei Chu and Xiaoyi Dong and Haodong Duan and Qi Fan and Zhaoye Fei and Yang Gao and Jiaye Ge and Chenya Gu and Yuzhe Gu and Tao Gui and Aijia Guo and Qipeng Guo and Conghui He and Yingfan Hu and Ting Huang and Tao Jiang and Penglong Jiao and Zhenjiang Jin and Zhikai Lei and Jiaxing Li and Jingwen Li and Linyang Li and Shuaibin Li and Wei Li and Yining Li and Hongwei Liu and Jiangning Liu and Jiawei Hong and Kaiwen Liu and Kuikun Liu and Xiaoran Liu and Chengqi Lv and Haijun Lv and Kai Lv and Li Ma and Runyuan Ma and Zerun Ma and Wenchang Ning and Linke Ouyang and Jiantao Qiu and Yuan Qu and Fukai Shang and Yunfan Shao and Demin Song and Zifan Song and Zhihao Sui and Peng Sun and Yu Sun and Huanze Tang and Bin Wang and Guoteng Wang and Jiaqi Wang and Jiayu Wang and Rui Wang and Yudong Wang and Ziyi Wang and Xingjian Wei and Qizhen Weng and Fan Wu and Yingtong Xiong and Chao Xu and Ruiliang Xu and Hang Yan and Yirong Yan and Xiaogui Yang and Haochen Ye and Huaiyuan Ying and Jia Yu and Jing Yu and Yuhang Zang and Chuyu Zhang and Li Zhang and Pan Zhang and Peng Zhang and Ruijie Zhang and Shuo Zhang and Songyang Zhang and Wenjian Zhang and Wenwei Zhang and Xingcheng Zhang and Xinyue Zhang and Hui Zhao and Qian Zhao and Xiaomeng Zhao and Fengzhe Zhou and Zaida Zhou and Jingming Zhuo and Yicheng Zou and Xipeng Qiu and Yu Qiao and Dahua Lin},
year={2024},
eprint={2403.17297},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
```

35
config.json Normal file
View File

@@ -0,0 +1,35 @@
{
"architectures": [
"InternLM2ForCausalLM"
],
"attn_implementation": "eager",
"auto_map": {
"AutoConfig": "configuration_internlm2.InternLM2Config",
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
},
"bias": false,
"bos_token_id": 1,
"eos_token_id": 2,
"hidden_act": "silu",
"hidden_size": 4096,
"initializer_range": 0.02,
"intermediate_size": 14336,
"max_position_embeddings": 262144,
"model_type": "internlm2",
"num_attention_heads": 32,
"num_hidden_layers": 32,
"num_key_value_heads": 8,
"pad_token_id": 2,
"rms_norm_eps": 1e-05,
"rope_scaling": {
"factor": 2.5,
"type": "dynamic"
},
"rope_theta": 50000000,
"tie_word_embeddings": false,
"torch_dtype": "bfloat16",
"transformers_version": "4.41.0",
"use_cache": true,
"vocab_size": 92544
}

1
configuration.json Normal file
View File

@@ -0,0 +1 @@
{"framework":"Pytorch","task":"text-generation"}

180
configuration_internlm2.py Normal file
View File

@@ -0,0 +1,180 @@
# 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 decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
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. InternLM2 supports up to 32768 tokens.
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-06):
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`.
pad_token_id (`int`, *optional*):
Padding token id.
bos_token_id (`int`, *optional*, defaults to 1):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 2):
End of stream token id.
pretraining_tp (`int`, *optional*, defaults to 1):
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)
to understand more about it. This value is necessary to ensure exact reproducibility
of the pretraining results. Please refer to [this
issue](https://github.com/pytorch/pytorch/issues/76232).
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
rope_theta (`float`, *optional*, defaults to 10000.0):
The base period of the RoPE embeddings.
rope_scaling (`Dict`, *optional*):
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
these scaling strategies behave:
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
experimental feature, subject to breaking API changes in future versions.
"""
_auto_class = "AutoConfig"
model_type = "internlm2"
keys_to_ignore_at_inference = ["past_key_values"]
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,
pretraining_tp=1,
tie_word_embeddings=False,
bias=True,
rope_theta=10000,
rope_scaling=None,
attn_implementation=None,
**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.pretraining_tp = pretraining_tp
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, int))
or rope_scaling_factor < 1.0
):
raise ValueError(
f"`rope_scaling`'s factor field must be a number >= 1, got {rope_scaling_factor} "
f"of type {type(rope_scaling_factor)}"
)

9
generation_config.json Normal file
View File

@@ -0,0 +1,9 @@
{
"bos_token_id": 1,
"eos_token_id": [
2,
92542
],
"pad_token_id": 2,
"transformers_version": "4.37.1"
}

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:70132792d1c2e36bfb27310c6b0401e4ad9357d7efce17349b74f231421447e4
size 1949337704

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:47b6946a54b869baa87987150ed0fd7b774099e80ed3400ba95723b194cfb202
size 1946242696

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7b21570aceec13e14a47de0e22fc71ee8a023edab3476f41fc74fc5ef6e0e26c
size 1979780440

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7fdaa0a5d76effa93973ffc081eb54a801196f47f9f29ff4dac4d5fe6b78e8a1
size 1946242728

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:91673f5c2a9c3f8aa36c771807eeaf0917c026359f8c07028b71c275a79ef332
size 1979780456

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:48c24a309037b0dd8b159a6c9a20c38130828b2cc165269e05d97553b8f44524
size 1946242728

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:da0a12686d8625baec87036da9a50f6e84ae8a974875c70d94f2f2e00838dfcd
size 1979780456

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:539eb5340747568df28ff4420abd6638254088ade498198ed02af8a0c42707a7
size 1748035640

View File

@@ -0,0 +1,234 @@
{
"metadata": {
"total_size": 15475417088
},
"weight_map": {
"model.layers.0.attention.wo.weight": "model-00001-of-00008.safetensors",
"model.layers.0.attention.wqkv.weight": "model-00001-of-00008.safetensors",
"model.layers.0.attention_norm.weight": "model-00001-of-00008.safetensors",
"model.layers.0.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
"model.layers.0.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
"model.layers.0.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
"model.layers.0.ffn_norm.weight": "model-00001-of-00008.safetensors",
"model.layers.1.attention.wo.weight": "model-00001-of-00008.safetensors",
"model.layers.1.attention.wqkv.weight": "model-00001-of-00008.safetensors",
"model.layers.1.attention_norm.weight": "model-00001-of-00008.safetensors",
"model.layers.1.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
"model.layers.1.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
"model.layers.1.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
"model.layers.1.ffn_norm.weight": "model-00001-of-00008.safetensors",
"model.layers.10.attention.wo.weight": "model-00003-of-00008.safetensors",
"model.layers.10.attention.wqkv.weight": "model-00003-of-00008.safetensors",
"model.layers.10.attention_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.10.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
"model.layers.10.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
"model.layers.10.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
"model.layers.10.ffn_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.11.attention.wo.weight": "model-00003-of-00008.safetensors",
"model.layers.11.attention.wqkv.weight": "model-00003-of-00008.safetensors",
"model.layers.11.attention_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.11.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
"model.layers.11.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
"model.layers.11.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
"model.layers.11.ffn_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.12.attention.wo.weight": "model-00004-of-00008.safetensors",
"model.layers.12.attention.wqkv.weight": "model-00004-of-00008.safetensors",
"model.layers.12.attention_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.12.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
"model.layers.12.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
"model.layers.12.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
"model.layers.12.ffn_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.13.attention.wo.weight": "model-00004-of-00008.safetensors",
"model.layers.13.attention.wqkv.weight": "model-00004-of-00008.safetensors",
"model.layers.13.attention_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.13.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
"model.layers.13.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
"model.layers.13.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
"model.layers.13.ffn_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.14.attention.wo.weight": "model-00004-of-00008.safetensors",
"model.layers.14.attention.wqkv.weight": "model-00004-of-00008.safetensors",
"model.layers.14.attention_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.14.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
"model.layers.14.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
"model.layers.14.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
"model.layers.14.ffn_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.15.attention.wo.weight": "model-00004-of-00008.safetensors",
"model.layers.15.attention.wqkv.weight": "model-00004-of-00008.safetensors",
"model.layers.15.attention_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.15.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
"model.layers.15.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
"model.layers.15.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
"model.layers.15.ffn_norm.weight": "model-00004-of-00008.safetensors",
"model.layers.16.attention.wo.weight": "model-00004-of-00008.safetensors",
"model.layers.16.attention.wqkv.weight": "model-00004-of-00008.safetensors",
"model.layers.16.attention_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.16.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
"model.layers.16.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
"model.layers.16.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
"model.layers.16.ffn_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.17.attention.wo.weight": "model-00005-of-00008.safetensors",
"model.layers.17.attention.wqkv.weight": "model-00005-of-00008.safetensors",
"model.layers.17.attention_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.17.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
"model.layers.17.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
"model.layers.17.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
"model.layers.17.ffn_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.18.attention.wo.weight": "model-00005-of-00008.safetensors",
"model.layers.18.attention.wqkv.weight": "model-00005-of-00008.safetensors",
"model.layers.18.attention_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.18.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
"model.layers.18.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
"model.layers.18.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
"model.layers.18.ffn_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.19.attention.wo.weight": "model-00005-of-00008.safetensors",
"model.layers.19.attention.wqkv.weight": "model-00005-of-00008.safetensors",
"model.layers.19.attention_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.19.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
"model.layers.19.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
"model.layers.19.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
"model.layers.19.ffn_norm.weight": "model-00005-of-00008.safetensors",
"model.layers.2.attention.wo.weight": "model-00001-of-00008.safetensors",
"model.layers.2.attention.wqkv.weight": "model-00001-of-00008.safetensors",
"model.layers.2.attention_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.2.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
"model.layers.2.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
"model.layers.2.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
"model.layers.2.ffn_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.20.attention.wo.weight": "model-00005-of-00008.safetensors",
"model.layers.20.attention.wqkv.weight": "model-00005-of-00008.safetensors",
"model.layers.20.attention_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.20.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
"model.layers.20.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
"model.layers.20.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
"model.layers.20.ffn_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.21.attention.wo.weight": "model-00006-of-00008.safetensors",
"model.layers.21.attention.wqkv.weight": "model-00006-of-00008.safetensors",
"model.layers.21.attention_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.21.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
"model.layers.21.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
"model.layers.21.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
"model.layers.21.ffn_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.22.attention.wo.weight": "model-00006-of-00008.safetensors",
"model.layers.22.attention.wqkv.weight": "model-00006-of-00008.safetensors",
"model.layers.22.attention_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.22.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
"model.layers.22.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
"model.layers.22.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
"model.layers.22.ffn_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.23.attention.wo.weight": "model-00006-of-00008.safetensors",
"model.layers.23.attention.wqkv.weight": "model-00006-of-00008.safetensors",
"model.layers.23.attention_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.23.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
"model.layers.23.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
"model.layers.23.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
"model.layers.23.ffn_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.24.attention.wo.weight": "model-00006-of-00008.safetensors",
"model.layers.24.attention.wqkv.weight": "model-00006-of-00008.safetensors",
"model.layers.24.attention_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.24.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
"model.layers.24.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
"model.layers.24.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
"model.layers.24.ffn_norm.weight": "model-00006-of-00008.safetensors",
"model.layers.25.attention.wo.weight": "model-00006-of-00008.safetensors",
"model.layers.25.attention.wqkv.weight": "model-00006-of-00008.safetensors",
"model.layers.25.attention_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.25.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
"model.layers.25.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
"model.layers.25.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
"model.layers.25.ffn_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.26.attention.wo.weight": "model-00007-of-00008.safetensors",
"model.layers.26.attention.wqkv.weight": "model-00007-of-00008.safetensors",
"model.layers.26.attention_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.26.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
"model.layers.26.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
"model.layers.26.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
"model.layers.26.ffn_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.27.attention.wo.weight": "model-00007-of-00008.safetensors",
"model.layers.27.attention.wqkv.weight": "model-00007-of-00008.safetensors",
"model.layers.27.attention_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.27.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
"model.layers.27.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
"model.layers.27.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
"model.layers.27.ffn_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.28.attention.wo.weight": "model-00007-of-00008.safetensors",
"model.layers.28.attention.wqkv.weight": "model-00007-of-00008.safetensors",
"model.layers.28.attention_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.28.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
"model.layers.28.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
"model.layers.28.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
"model.layers.28.ffn_norm.weight": "model-00007-of-00008.safetensors",
"model.layers.29.attention.wo.weight": "model-00007-of-00008.safetensors",
"model.layers.29.attention.wqkv.weight": "model-00007-of-00008.safetensors",
"model.layers.29.attention_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.29.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
"model.layers.29.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
"model.layers.29.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
"model.layers.29.ffn_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.3.attention.wo.weight": "model-00002-of-00008.safetensors",
"model.layers.3.attention.wqkv.weight": "model-00002-of-00008.safetensors",
"model.layers.3.attention_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.3.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
"model.layers.3.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
"model.layers.3.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
"model.layers.3.ffn_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.30.attention.wo.weight": "model-00008-of-00008.safetensors",
"model.layers.30.attention.wqkv.weight": "model-00008-of-00008.safetensors",
"model.layers.30.attention_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.30.feed_forward.w1.weight": "model-00008-of-00008.safetensors",
"model.layers.30.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
"model.layers.30.feed_forward.w3.weight": "model-00008-of-00008.safetensors",
"model.layers.30.ffn_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.31.attention.wo.weight": "model-00008-of-00008.safetensors",
"model.layers.31.attention.wqkv.weight": "model-00008-of-00008.safetensors",
"model.layers.31.attention_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.31.feed_forward.w1.weight": "model-00008-of-00008.safetensors",
"model.layers.31.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
"model.layers.31.feed_forward.w3.weight": "model-00008-of-00008.safetensors",
"model.layers.31.ffn_norm.weight": "model-00008-of-00008.safetensors",
"model.layers.4.attention.wo.weight": "model-00002-of-00008.safetensors",
"model.layers.4.attention.wqkv.weight": "model-00002-of-00008.safetensors",
"model.layers.4.attention_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.4.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
"model.layers.4.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
"model.layers.4.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
"model.layers.4.ffn_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.5.attention.wo.weight": "model-00002-of-00008.safetensors",
"model.layers.5.attention.wqkv.weight": "model-00002-of-00008.safetensors",
"model.layers.5.attention_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.5.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
"model.layers.5.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
"model.layers.5.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
"model.layers.5.ffn_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.6.attention.wo.weight": "model-00002-of-00008.safetensors",
"model.layers.6.attention.wqkv.weight": "model-00002-of-00008.safetensors",
"model.layers.6.attention_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.6.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
"model.layers.6.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
"model.layers.6.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
"model.layers.6.ffn_norm.weight": "model-00002-of-00008.safetensors",
"model.layers.7.attention.wo.weight": "model-00002-of-00008.safetensors",
"model.layers.7.attention.wqkv.weight": "model-00002-of-00008.safetensors",
"model.layers.7.attention_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.7.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
"model.layers.7.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
"model.layers.7.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
"model.layers.7.ffn_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.8.attention.wo.weight": "model-00003-of-00008.safetensors",
"model.layers.8.attention.wqkv.weight": "model-00003-of-00008.safetensors",
"model.layers.8.attention_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.8.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
"model.layers.8.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
"model.layers.8.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
"model.layers.8.ffn_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.9.attention.wo.weight": "model-00003-of-00008.safetensors",
"model.layers.9.attention.wqkv.weight": "model-00003-of-00008.safetensors",
"model.layers.9.attention_norm.weight": "model-00003-of-00008.safetensors",
"model.layers.9.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
"model.layers.9.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
"model.layers.9.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
"model.layers.9.ffn_norm.weight": "model-00003-of-00008.safetensors",
"model.norm.weight": "model-00008-of-00008.safetensors",
"model.tok_embeddings.weight": "model-00001-of-00008.safetensors",
"output.weight": "model-00008-of-00008.safetensors"
}
}

1808
modeling_internlm2.py Normal file

File diff suppressed because it is too large Load Diff

38
special_tokens_map.json Normal file
View File

@@ -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
}
}

236
tokenization_internlm2.py Normal file
View File

@@ -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]

View File

@@ -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,)

3
tokenizer.model Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
size 1477754

102
tokenizer_config.json Normal file
View File

@@ -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>"
}