GPTQ model commit
Browse files- License_Agreement_for_Large_Language_Models_Nanbeige.pdf +0 -0
- config.json +54 -0
- configuration_nanbeige.py +53 -0
- generation_config.json +10 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_nanbeige.py +948 -0
- quantize_config.json +16 -0
- special_tokens_map.json +24 -0
- tokenization_nanbeige.py +233 -0
- tokenizer.model +3 -0
- tokenizer_config.json +36 -0
License_Agreement_for_Large_Language_Models_Nanbeige.pdf
ADDED
Binary file (181 kB). View file
|
|
config.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/workspace/process/nanbeige_nanbeige-16b-base/source",
|
3 |
+
"architectures": [
|
4 |
+
"NanbeigeForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_nanbeige.NanbeigeConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_nanbeige.NanbeigeForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"eos_token_id": 2,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 5120,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 13824,
|
16 |
+
"max_length": 4096,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"model_type": "nanbeige",
|
19 |
+
"num_attention_heads": 40,
|
20 |
+
"num_hidden_layers": 48,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"quantization_config": {
|
24 |
+
"batch_size": 1,
|
25 |
+
"bits": 4,
|
26 |
+
"block_name_to_quantize": "model.layers",
|
27 |
+
"cache_block_outputs": true,
|
28 |
+
"damp_percent": 0.1,
|
29 |
+
"desc_act": true,
|
30 |
+
"exllama_config": {
|
31 |
+
"version": 1
|
32 |
+
},
|
33 |
+
"group_size": 128,
|
34 |
+
"max_input_length": null,
|
35 |
+
"model_seqlen": 4096,
|
36 |
+
"module_name_preceding_first_block": [
|
37 |
+
"model.embed_tokens"
|
38 |
+
],
|
39 |
+
"pad_token_id": null,
|
40 |
+
"quant_method": "gptq",
|
41 |
+
"sym": true,
|
42 |
+
"tokenizer": null,
|
43 |
+
"true_sequential": true,
|
44 |
+
"use_cuda_fp16": false,
|
45 |
+
"use_exllama": true
|
46 |
+
},
|
47 |
+
"rms_norm_eps": 1e-05,
|
48 |
+
"tie_word_embeddings": false,
|
49 |
+
"torch_dtype": "bfloat16",
|
50 |
+
"transformers_version": "4.35.2",
|
51 |
+
"use_cache": true,
|
52 |
+
"vocab_size": 59136,
|
53 |
+
"yarn_scale": 1.0
|
54 |
+
}
|
configuration_nanbeige.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023 Nanbeige LLM Lab All Rights Reserved.
|
2 |
+
|
3 |
+
""" Nanbeige model configuration"""
|
4 |
+
|
5 |
+
from transformers.configuration_utils import PretrainedConfig
|
6 |
+
from transformers.utils import logging
|
7 |
+
|
8 |
+
|
9 |
+
logger = logging.get_logger(__name__)
|
10 |
+
|
11 |
+
NANBEIGE_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
12 |
+
|
13 |
+
|
14 |
+
class NanbeigeConfig(PretrainedConfig):
|
15 |
+
model_type = "nanbeige"
|
16 |
+
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
vocab_size=32000,
|
20 |
+
hidden_size=4096,
|
21 |
+
intermediate_size=11008,
|
22 |
+
num_hidden_layers=32,
|
23 |
+
num_attention_heads=32,
|
24 |
+
hidden_act="silu",
|
25 |
+
max_position_embeddings=2048,
|
26 |
+
initializer_range=0.02,
|
27 |
+
rms_norm_eps=1e-6,
|
28 |
+
use_cache=True,
|
29 |
+
pad_token_id=0,
|
30 |
+
bos_token_id=1,
|
31 |
+
eos_token_id=2,
|
32 |
+
tie_word_embeddings=False,
|
33 |
+
yarn_scale=1.,
|
34 |
+
**kwargs,
|
35 |
+
):
|
36 |
+
self.vocab_size = vocab_size
|
37 |
+
self.max_position_embeddings = max_position_embeddings
|
38 |
+
self.hidden_size = hidden_size
|
39 |
+
self.intermediate_size = intermediate_size
|
40 |
+
self.num_hidden_layers = num_hidden_layers
|
41 |
+
self.num_attention_heads = num_attention_heads
|
42 |
+
self.hidden_act = hidden_act
|
43 |
+
self.initializer_range = initializer_range
|
44 |
+
self.rms_norm_eps = rms_norm_eps
|
45 |
+
self.use_cache = use_cache
|
46 |
+
self.yarn_scale = yarn_scale
|
47 |
+
super().__init__(
|
48 |
+
pad_token_id=pad_token_id,
|
49 |
+
bos_token_id=bos_token_id,
|
50 |
+
eos_token_id=eos_token_id,
|
51 |
+
tie_word_embeddings=tie_word_embeddings,
|
52 |
+
**kwargs,
|
53 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"max_length": 4096,
|
6 |
+
"pad_token_id": 0,
|
7 |
+
"temperature": 0.9,
|
8 |
+
"top_p": 0.6,
|
9 |
+
"transformers_version": "4.28.1"
|
10 |
+
}
|
model-00001-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1fd9bc90a3a1efc4016f07199e62fc13689ee2a3294ff924f021e9f3cf00bcc0
|
3 |
+
size 4989644496
|
model-00002-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2bb15877ddbea24997f8f59b2d599efd9415857c5f75b2e3b6401eb0220a97fc
|
3 |
+
size 4146366688
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_nanbeige.py
ADDED
@@ -0,0 +1,948 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023 Nanbeige LLM Lab All Rights Reserved.
|
2 |
+
|
3 |
+
import math
|
4 |
+
import queue
|
5 |
+
import threading
|
6 |
+
from typing import List, Optional, Tuple, Union
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.utils.checkpoint
|
10 |
+
from torch import nn
|
11 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
12 |
+
from transformers.activations import ACT2FN
|
13 |
+
from transformers.generation.streamers import BaseStreamer
|
14 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
|
15 |
+
SequenceClassifierOutputWithPast
|
16 |
+
from transformers.modeling_utils import PreTrainedModel
|
17 |
+
from transformers.utils import logging
|
18 |
+
|
19 |
+
from .configuration_nanbeige import NanbeigeConfig
|
20 |
+
|
21 |
+
logger = logging.get_logger(__name__)
|
22 |
+
NANBEIGE_SYSTEM_PROMPT = "你是一个名为\"南北阁\"的人工智能助手,正在与人类用户进行交谈。你的目标是以最有帮助和最逻辑的方式回答问题,同时确保内容的安全性。你的回答中不应包含任何有害、政治化、宗教化、不道德、种族主义、性别歧视、有毒、危险或非法的内容。请确保你的回答不带有社会偏见,并且始终积极正面,符合社会主义价值观。如果遇到的问题无意义或事实上不连贯,请不要回答错误的内容,而是解释问题为何无效或不连贯。如果你不知道问题的答案,也请勿提供错误的信息。你是由南北阁大模型实验室的LLM团队训练的。知识截止日期是2023年9月。"
|
23 |
+
|
24 |
+
try:
|
25 |
+
import flash_attn
|
26 |
+
from flash_attn import flash_attn_func
|
27 |
+
|
28 |
+
if int(flash_attn.__version__.split(".")[0]) >= 2 and int(flash_attn.__version__.split(".")[1]) >= 1:
|
29 |
+
Version_ = True
|
30 |
+
else:
|
31 |
+
Version_ = False
|
32 |
+
except:
|
33 |
+
logger.warn(
|
34 |
+
"Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
|
35 |
+
"https://github.com/Dao-AILab/flash-attention"
|
36 |
+
)
|
37 |
+
Version_ = False
|
38 |
+
flash_attn_func = None
|
39 |
+
|
40 |
+
|
41 |
+
def _make_causal_mask(
|
42 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
43 |
+
):
|
44 |
+
"""
|
45 |
+
Make causal mask used for bi-directional self-attention.
|
46 |
+
"""
|
47 |
+
bsz, tgt_len = input_ids_shape
|
48 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
49 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
50 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
51 |
+
mask = mask.to(dtype)
|
52 |
+
|
53 |
+
if past_key_values_length > 0:
|
54 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
55 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
56 |
+
|
57 |
+
|
58 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
59 |
+
"""
|
60 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
61 |
+
"""
|
62 |
+
bsz, src_len = mask.size()
|
63 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
64 |
+
|
65 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
66 |
+
|
67 |
+
inverted_mask = 1.0 - expanded_mask
|
68 |
+
|
69 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
70 |
+
|
71 |
+
|
72 |
+
def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
|
73 |
+
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
|
74 |
+
|
75 |
+
|
76 |
+
def find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
|
77 |
+
low = math.floor(find_correction_dim(
|
78 |
+
low_rot, dim, base, max_position_embeddings))
|
79 |
+
high = math.ceil(find_correction_dim(
|
80 |
+
high_rot, dim, base, max_position_embeddings))
|
81 |
+
return max(low, 0), min(high, dim - 1) # Clamp values just in case
|
82 |
+
|
83 |
+
|
84 |
+
def linear_ramp_mask(min, max, dim):
|
85 |
+
if min == max:
|
86 |
+
max += 0.001 # Prevent singularity
|
87 |
+
|
88 |
+
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
89 |
+
ramp_func = torch.clamp(linear_func, 0, 1)
|
90 |
+
return ramp_func
|
91 |
+
|
92 |
+
|
93 |
+
def get_mscale(scale=1):
|
94 |
+
if scale <= 1:
|
95 |
+
return 1.0
|
96 |
+
return 0.1 * math.log(scale) + 1.0
|
97 |
+
|
98 |
+
|
99 |
+
class YaRNScaledRotaryEmbedding(torch.nn.Module):
|
100 |
+
def __init__(self, dim, max_position_embeddings=4096, base=10000, scale=1, original_max_position_embeddings=4096,
|
101 |
+
extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
|
102 |
+
super().__init__()
|
103 |
+
self.dim = dim
|
104 |
+
self.max_position_embeddings = max_position_embeddings
|
105 |
+
self.base = base
|
106 |
+
self.scale = scale
|
107 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
108 |
+
self.extrapolation_factor = extrapolation_factor
|
109 |
+
self.attn_factor = attn_factor
|
110 |
+
self.beta_fast = beta_fast
|
111 |
+
self.beta_slow = beta_slow
|
112 |
+
|
113 |
+
self.yarn(device)
|
114 |
+
|
115 |
+
# Build here to make `torch.jit.trace` work.
|
116 |
+
self.max_seq_len_cached = max_position_embeddings
|
117 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
118 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
119 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
120 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
121 |
+
dtype = torch.get_default_dtype()
|
122 |
+
|
123 |
+
self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
|
124 |
+
self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
|
125 |
+
|
126 |
+
def forward(self, x, seq_len=None):
|
127 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
128 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
129 |
+
if seq_len > self.max_seq_len_cached:
|
130 |
+
self.max_seq_len_cached = seq_len
|
131 |
+
|
132 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
133 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
134 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
135 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
136 |
+
|
137 |
+
self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(x.dtype),
|
138 |
+
persistent=False)
|
139 |
+
self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(x.dtype),
|
140 |
+
persistent=False)
|
141 |
+
return (
|
142 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
143 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
144 |
+
)
|
145 |
+
|
146 |
+
def yarn(self, device):
|
147 |
+
pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
148 |
+
inv_freq_extrapolation = 1.0 / pos_freqs
|
149 |
+
inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
|
150 |
+
|
151 |
+
low, high = find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base,
|
152 |
+
self.original_max_position_embeddings)
|
153 |
+
inv_freq_mask = (1 - linear_ramp_mask(low, high, self.dim // 2).float().to(
|
154 |
+
device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
|
155 |
+
inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
|
156 |
+
|
157 |
+
self.register_buffer("inv_freq", inv_freq)
|
158 |
+
self.mscale = float(
|
159 |
+
get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
|
160 |
+
|
161 |
+
|
162 |
+
class RMSNorm(nn.Module):
|
163 |
+
def __init__(self, hidden_size, eps=1e-6):
|
164 |
+
super().__init__()
|
165 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
166 |
+
self.variance_epsilon = eps
|
167 |
+
|
168 |
+
def forward(self, hidden_states):
|
169 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
170 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
171 |
+
|
172 |
+
# convert into half-precision if necessary
|
173 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
174 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
175 |
+
|
176 |
+
return self.weight * hidden_states
|
177 |
+
|
178 |
+
|
179 |
+
class RotaryEmbedding(torch.nn.Module):
|
180 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
181 |
+
super().__init__()
|
182 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
183 |
+
self.register_buffer("inv_freq", inv_freq)
|
184 |
+
self.max_seq_len_cached = max_position_embeddings
|
185 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
186 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
187 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
188 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
189 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
190 |
+
|
191 |
+
def forward(self, x, seq_len=None):
|
192 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
193 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
194 |
+
if seq_len > self.max_seq_len_cached:
|
195 |
+
self.max_seq_len_cached = seq_len
|
196 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
197 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
198 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
199 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
200 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
201 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
202 |
+
return (
|
203 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
204 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
205 |
+
)
|
206 |
+
|
207 |
+
|
208 |
+
def rotate_half(x):
|
209 |
+
"""Rotates half the hidden dims of the input."""
|
210 |
+
x1 = x[..., : x.shape[-1] // 2]
|
211 |
+
x2 = x[..., x.shape[-1] // 2:]
|
212 |
+
return torch.cat((-x2, x1), dim=-1)
|
213 |
+
|
214 |
+
|
215 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
216 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
217 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
218 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
219 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
220 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
221 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
222 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
223 |
+
return q_embed, k_embed
|
224 |
+
|
225 |
+
|
226 |
+
class NanbeigeMLP(nn.Module):
|
227 |
+
def __init__(
|
228 |
+
self,
|
229 |
+
hidden_size: int,
|
230 |
+
intermediate_size: int,
|
231 |
+
hidden_act: str,
|
232 |
+
):
|
233 |
+
super().__init__()
|
234 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
235 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
236 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
237 |
+
self.act_fn = ACT2FN[hidden_act]
|
238 |
+
|
239 |
+
def forward(self, x):
|
240 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
241 |
+
|
242 |
+
|
243 |
+
class NanbeigeAttention(nn.Module):
|
244 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
245 |
+
|
246 |
+
def __init__(self, config: NanbeigeConfig):
|
247 |
+
super().__init__()
|
248 |
+
self.config = config
|
249 |
+
self.hidden_size = config.hidden_size
|
250 |
+
self.num_heads = config.num_attention_heads
|
251 |
+
self.head_dim = self.hidden_size // self.num_heads
|
252 |
+
self.max_position_embeddings = config.max_position_embeddings
|
253 |
+
|
254 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
255 |
+
raise ValueError(
|
256 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
257 |
+
f" and `num_heads`: {self.num_heads})."
|
258 |
+
)
|
259 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
260 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
261 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
262 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
263 |
+
if self.config.yarn_scale > 1:
|
264 |
+
self.rotary_emb = YaRNScaledRotaryEmbedding(self.head_dim, scale=self.config.yarn_scale,
|
265 |
+
original_max_position_embeddings=self.max_position_embeddings)
|
266 |
+
else:
|
267 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
268 |
+
|
269 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
270 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
271 |
+
|
272 |
+
def forward(
|
273 |
+
self,
|
274 |
+
hidden_states: torch.Tensor,
|
275 |
+
attention_mask: Optional[torch.Tensor] = None,
|
276 |
+
position_ids: Optional[torch.LongTensor] = None,
|
277 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
278 |
+
output_attentions: bool = False,
|
279 |
+
use_cache: bool = False,
|
280 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
281 |
+
bsz, q_len, _ = hidden_states.size()
|
282 |
+
|
283 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
284 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
285 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
286 |
+
|
287 |
+
kv_seq_len = key_states.shape[-2]
|
288 |
+
if past_key_value is not None:
|
289 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
290 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
291 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
292 |
+
|
293 |
+
if past_key_value is not None:
|
294 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
295 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
296 |
+
|
297 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
298 |
+
|
299 |
+
if Version_ or (flash_attn_func and query_states.size() == key_states.size()):
|
300 |
+
attn_output = flash_attn_func(query_states.transpose(1, 2), key_states.transpose(1, 2),
|
301 |
+
value_states.transpose(1, 2), dropout_p=0.0, softmax_scale=None, causal=True)
|
302 |
+
else:
|
303 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
304 |
+
|
305 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
306 |
+
raise ValueError(
|
307 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
308 |
+
f" {attn_weights.size()}"
|
309 |
+
)
|
310 |
+
|
311 |
+
if attention_mask is not None:
|
312 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
313 |
+
raise ValueError(
|
314 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
315 |
+
)
|
316 |
+
attn_weights = attn_weights + attention_mask
|
317 |
+
attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
|
318 |
+
|
319 |
+
# upcast attention to fp32
|
320 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
321 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
322 |
+
|
323 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
324 |
+
raise ValueError(
|
325 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
326 |
+
f" {attn_output.size()}"
|
327 |
+
)
|
328 |
+
|
329 |
+
attn_output = attn_output.transpose(1, 2)
|
330 |
+
|
331 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
332 |
+
|
333 |
+
attn_output = self.o_proj(attn_output)
|
334 |
+
|
335 |
+
if not output_attentions:
|
336 |
+
attn_weights = None
|
337 |
+
|
338 |
+
return attn_output, attn_weights, past_key_value
|
339 |
+
|
340 |
+
|
341 |
+
class NanbeigeDecoderLayer(nn.Module):
|
342 |
+
def __init__(self, config: NanbeigeConfig):
|
343 |
+
super().__init__()
|
344 |
+
self.hidden_size = config.hidden_size
|
345 |
+
self.self_attn = NanbeigeAttention(config=config)
|
346 |
+
self.mlp = NanbeigeMLP(
|
347 |
+
hidden_size=self.hidden_size,
|
348 |
+
intermediate_size=config.intermediate_size,
|
349 |
+
hidden_act=config.hidden_act,
|
350 |
+
)
|
351 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
352 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
353 |
+
|
354 |
+
def forward(
|
355 |
+
self,
|
356 |
+
hidden_states: torch.Tensor,
|
357 |
+
attention_mask: Optional[torch.Tensor] = None,
|
358 |
+
position_ids: Optional[torch.LongTensor] = None,
|
359 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
360 |
+
output_attentions: Optional[bool] = False,
|
361 |
+
use_cache: Optional[bool] = False,
|
362 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
363 |
+
"""
|
364 |
+
Args:
|
365 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
366 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
367 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
368 |
+
output_attentions (`bool`, *optional*):
|
369 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
370 |
+
returned tensors for more detail.
|
371 |
+
use_cache (`bool`, *optional*):
|
372 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
373 |
+
(see `past_key_values`).
|
374 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
375 |
+
"""
|
376 |
+
|
377 |
+
residual = hidden_states
|
378 |
+
|
379 |
+
hidden_states = self.input_layernorm(hidden_states)
|
380 |
+
|
381 |
+
# Self Attention
|
382 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
383 |
+
hidden_states=hidden_states,
|
384 |
+
attention_mask=attention_mask,
|
385 |
+
position_ids=position_ids,
|
386 |
+
past_key_value=past_key_value,
|
387 |
+
output_attentions=output_attentions,
|
388 |
+
use_cache=use_cache,
|
389 |
+
)
|
390 |
+
hidden_states = residual + hidden_states
|
391 |
+
|
392 |
+
# Fully Connected
|
393 |
+
residual = hidden_states
|
394 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
395 |
+
hidden_states = self.mlp(hidden_states)
|
396 |
+
hidden_states = residual + hidden_states
|
397 |
+
|
398 |
+
outputs = (hidden_states,)
|
399 |
+
|
400 |
+
if output_attentions:
|
401 |
+
outputs += (self_attn_weights,)
|
402 |
+
|
403 |
+
if use_cache:
|
404 |
+
outputs += (present_key_value,)
|
405 |
+
|
406 |
+
return outputs
|
407 |
+
|
408 |
+
|
409 |
+
class NanbeigePreTrainedModel(PreTrainedModel):
|
410 |
+
config_class = NanbeigeConfig
|
411 |
+
base_model_prefix = "model"
|
412 |
+
supports_gradient_checkpointing = True
|
413 |
+
_no_split_modules = ["NanbeigeDecoderLayer"]
|
414 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
415 |
+
|
416 |
+
def _init_weights(self, module):
|
417 |
+
std = self.config.initializer_range
|
418 |
+
if isinstance(module, nn.Linear):
|
419 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
420 |
+
if module.bias is not None:
|
421 |
+
module.bias.data.zero_()
|
422 |
+
elif isinstance(module, nn.Embedding):
|
423 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
424 |
+
if module.padding_idx is not None:
|
425 |
+
module.weight.data[module.padding_idx].zero_()
|
426 |
+
|
427 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
428 |
+
if isinstance(module, NanbeigeModel):
|
429 |
+
module.gradient_checkpointing = value
|
430 |
+
|
431 |
+
|
432 |
+
class NanbeigeModel(NanbeigePreTrainedModel):
|
433 |
+
def __init__(self, config: NanbeigeConfig):
|
434 |
+
super().__init__(config)
|
435 |
+
self.padding_idx = config.pad_token_id
|
436 |
+
self.vocab_size = config.vocab_size
|
437 |
+
|
438 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
439 |
+
self.layers = nn.ModuleList([NanbeigeDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
440 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
441 |
+
|
442 |
+
self.gradient_checkpointing = False
|
443 |
+
# Initialize weights and apply final processing
|
444 |
+
self.post_init()
|
445 |
+
|
446 |
+
def get_input_embeddings(self):
|
447 |
+
return self.embed_tokens
|
448 |
+
|
449 |
+
def set_input_embeddings(self, value):
|
450 |
+
self.embed_tokens = value
|
451 |
+
|
452 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
453 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
454 |
+
# create causal mask
|
455 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
456 |
+
combined_attention_mask = None
|
457 |
+
if input_shape[-1] > 1:
|
458 |
+
combined_attention_mask = _make_causal_mask(
|
459 |
+
input_shape,
|
460 |
+
inputs_embeds.dtype,
|
461 |
+
device=inputs_embeds.device,
|
462 |
+
past_key_values_length=past_key_values_length,
|
463 |
+
)
|
464 |
+
|
465 |
+
if attention_mask is not None:
|
466 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
467 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
468 |
+
inputs_embeds.device
|
469 |
+
)
|
470 |
+
combined_attention_mask = (
|
471 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
472 |
+
)
|
473 |
+
|
474 |
+
return combined_attention_mask
|
475 |
+
|
476 |
+
def forward(
|
477 |
+
self,
|
478 |
+
input_ids: torch.LongTensor = None,
|
479 |
+
attention_mask: Optional[torch.Tensor] = None,
|
480 |
+
position_ids: Optional[torch.LongTensor] = None,
|
481 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
482 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
483 |
+
use_cache: Optional[bool] = None,
|
484 |
+
output_attentions: Optional[bool] = None,
|
485 |
+
output_hidden_states: Optional[bool] = None,
|
486 |
+
return_dict: Optional[bool] = None,
|
487 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
488 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
489 |
+
output_hidden_states = (
|
490 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
491 |
+
)
|
492 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
493 |
+
|
494 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
495 |
+
|
496 |
+
# retrieve input_ids and inputs_embeds
|
497 |
+
if input_ids is not None and inputs_embeds is not None:
|
498 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
499 |
+
elif input_ids is not None:
|
500 |
+
batch_size, seq_length = input_ids.shape
|
501 |
+
elif inputs_embeds is not None:
|
502 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
503 |
+
else:
|
504 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
505 |
+
|
506 |
+
seq_length_with_past = seq_length
|
507 |
+
past_key_values_length = 0
|
508 |
+
|
509 |
+
if past_key_values is not None:
|
510 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
511 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
512 |
+
else:
|
513 |
+
past_key_values = [None for _ in range(len(self.layers))]
|
514 |
+
|
515 |
+
if position_ids is None:
|
516 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
517 |
+
position_ids = torch.arange(
|
518 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
519 |
+
)
|
520 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
521 |
+
else:
|
522 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
523 |
+
|
524 |
+
if inputs_embeds is None:
|
525 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
526 |
+
# embed positions
|
527 |
+
if attention_mask is None:
|
528 |
+
attention_mask = torch.ones(
|
529 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
530 |
+
)
|
531 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
532 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
533 |
+
)
|
534 |
+
|
535 |
+
hidden_states = inputs_embeds
|
536 |
+
|
537 |
+
if self.gradient_checkpointing and self.training:
|
538 |
+
if use_cache:
|
539 |
+
logger.warning_once(
|
540 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
541 |
+
)
|
542 |
+
use_cache = False
|
543 |
+
|
544 |
+
# decoder layers
|
545 |
+
all_hidden_states = () if output_hidden_states else None
|
546 |
+
all_self_attns = () if output_attentions else None
|
547 |
+
next_cache = [] if use_cache else None
|
548 |
+
|
549 |
+
for idx, decoder_layer in enumerate(self.layers):
|
550 |
+
if output_hidden_states:
|
551 |
+
all_hidden_states += (hidden_states,)
|
552 |
+
|
553 |
+
past_key_value = past_key_values.pop(0) if past_key_values is not None else None
|
554 |
+
|
555 |
+
if self.gradient_checkpointing and self.training:
|
556 |
+
|
557 |
+
def create_custom_forward(module):
|
558 |
+
def custom_forward(*inputs):
|
559 |
+
# None for past_key_value
|
560 |
+
return module(*inputs, output_attentions, None)
|
561 |
+
|
562 |
+
return custom_forward
|
563 |
+
|
564 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
565 |
+
create_custom_forward(decoder_layer),
|
566 |
+
hidden_states,
|
567 |
+
attention_mask,
|
568 |
+
position_ids,
|
569 |
+
None,
|
570 |
+
)
|
571 |
+
else:
|
572 |
+
layer_outputs = decoder_layer(
|
573 |
+
hidden_states,
|
574 |
+
attention_mask=attention_mask,
|
575 |
+
position_ids=position_ids,
|
576 |
+
past_key_value=past_key_value,
|
577 |
+
output_attentions=output_attentions,
|
578 |
+
use_cache=use_cache,
|
579 |
+
)
|
580 |
+
|
581 |
+
hidden_states = layer_outputs[0]
|
582 |
+
|
583 |
+
if use_cache:
|
584 |
+
next_cache.append(layer_outputs[2 if output_attentions else 1])
|
585 |
+
|
586 |
+
if output_attentions:
|
587 |
+
all_self_attns += (layer_outputs[1],)
|
588 |
+
|
589 |
+
hidden_states = self.norm(hidden_states)
|
590 |
+
|
591 |
+
# add hidden states from the last decoder layer
|
592 |
+
if output_hidden_states:
|
593 |
+
all_hidden_states += (hidden_states,)
|
594 |
+
|
595 |
+
if not return_dict:
|
596 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
597 |
+
return BaseModelOutputWithPast(
|
598 |
+
last_hidden_state=hidden_states,
|
599 |
+
past_key_values=next_cache,
|
600 |
+
hidden_states=all_hidden_states,
|
601 |
+
attentions=all_self_attns,
|
602 |
+
)
|
603 |
+
|
604 |
+
|
605 |
+
class NanbeigeForCausalLM(NanbeigePreTrainedModel):
|
606 |
+
def __init__(self, config):
|
607 |
+
super().__init__(config)
|
608 |
+
self.model = NanbeigeModel(config)
|
609 |
+
|
610 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
611 |
+
|
612 |
+
# Initialize weights and apply final processing
|
613 |
+
self.post_init()
|
614 |
+
|
615 |
+
def get_input_embeddings(self):
|
616 |
+
return self.model.embed_tokens
|
617 |
+
|
618 |
+
def set_input_embeddings(self, value):
|
619 |
+
self.model.embed_tokens = value
|
620 |
+
|
621 |
+
def get_output_embeddings(self):
|
622 |
+
return self.lm_head
|
623 |
+
|
624 |
+
def set_output_embeddings(self, new_embeddings):
|
625 |
+
self.lm_head = new_embeddings
|
626 |
+
|
627 |
+
def set_decoder(self, decoder):
|
628 |
+
self.model = decoder
|
629 |
+
|
630 |
+
def get_decoder(self):
|
631 |
+
return self.model
|
632 |
+
|
633 |
+
def forward(
|
634 |
+
self,
|
635 |
+
input_ids: torch.LongTensor = None,
|
636 |
+
attention_mask: Optional[torch.Tensor] = None,
|
637 |
+
position_ids: Optional[torch.LongTensor] = None,
|
638 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
639 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
640 |
+
labels: Optional[torch.LongTensor] = None,
|
641 |
+
use_cache: Optional[bool] = None,
|
642 |
+
output_attentions: Optional[bool] = None,
|
643 |
+
output_hidden_states: Optional[bool] = None,
|
644 |
+
return_dict: Optional[bool] = None,
|
645 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
646 |
+
|
647 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
648 |
+
output_hidden_states = (
|
649 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
650 |
+
)
|
651 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
652 |
+
|
653 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
654 |
+
outputs = self.model(
|
655 |
+
input_ids=input_ids,
|
656 |
+
attention_mask=attention_mask,
|
657 |
+
position_ids=position_ids,
|
658 |
+
past_key_values=past_key_values,
|
659 |
+
inputs_embeds=inputs_embeds,
|
660 |
+
use_cache=use_cache,
|
661 |
+
output_attentions=output_attentions,
|
662 |
+
output_hidden_states=output_hidden_states,
|
663 |
+
return_dict=return_dict,
|
664 |
+
)
|
665 |
+
|
666 |
+
hidden_states = outputs[0]
|
667 |
+
logits = self.lm_head(hidden_states)
|
668 |
+
|
669 |
+
loss = None
|
670 |
+
if labels is not None:
|
671 |
+
# Shift so that tokens < n predict n
|
672 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
673 |
+
shift_labels = labels[..., 1:].contiguous()
|
674 |
+
# Flatten the tokens
|
675 |
+
loss_fct = CrossEntropyLoss()
|
676 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
677 |
+
shift_labels = shift_labels.view(-1)
|
678 |
+
# Enable model parallelism
|
679 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
680 |
+
loss = loss_fct(shift_logits, shift_labels)
|
681 |
+
|
682 |
+
if not return_dict:
|
683 |
+
output = (logits,) + outputs[1:]
|
684 |
+
return (loss,) + output if loss is not None else output
|
685 |
+
|
686 |
+
return CausalLMOutputWithPast(
|
687 |
+
loss=loss,
|
688 |
+
logits=logits,
|
689 |
+
past_key_values=outputs.past_key_values,
|
690 |
+
hidden_states=outputs.hidden_states,
|
691 |
+
attentions=outputs.attentions,
|
692 |
+
)
|
693 |
+
|
694 |
+
def prepare_inputs_for_generation(
|
695 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
696 |
+
):
|
697 |
+
if past_key_values:
|
698 |
+
input_ids = input_ids[:, -1:]
|
699 |
+
|
700 |
+
position_ids = kwargs.get("position_ids", None)
|
701 |
+
if attention_mask is not None and position_ids is None:
|
702 |
+
# create position_ids on the fly for batch generation
|
703 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
704 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
705 |
+
if past_key_values:
|
706 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
707 |
+
|
708 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
709 |
+
if inputs_embeds is not None and past_key_values is None:
|
710 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
711 |
+
else:
|
712 |
+
model_inputs = {"input_ids": input_ids}
|
713 |
+
|
714 |
+
model_inputs.update(
|
715 |
+
{
|
716 |
+
"position_ids": position_ids,
|
717 |
+
"past_key_values": past_key_values,
|
718 |
+
"use_cache": kwargs.get("use_cache"),
|
719 |
+
"attention_mask": attention_mask,
|
720 |
+
}
|
721 |
+
)
|
722 |
+
return model_inputs
|
723 |
+
|
724 |
+
@staticmethod
|
725 |
+
def _reorder_cache(past_key_values, beam_idx):
|
726 |
+
reordered_past = ()
|
727 |
+
for layer_past in past_key_values:
|
728 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
729 |
+
return reordered_past
|
730 |
+
|
731 |
+
def build_prompt_input(self, tokenizer, query, messages):
|
732 |
+
prompt = ""
|
733 |
+
for message in messages:
|
734 |
+
if message['role'] == 'human':
|
735 |
+
prompt += f"""### Human: \n{message['content']}\n\n"""
|
736 |
+
elif message['role'] == 'assistant':
|
737 |
+
prompt += f"""### Assistant: {message['content']}</s>"""
|
738 |
+
elif message['role'] == 'system':
|
739 |
+
prompt += f"""### System:{message['content']}\n</s>"""
|
740 |
+
prompt += f"""### Human: \n{query}\n\n### Assistant: """
|
741 |
+
return tokenizer([prompt], return_tensors="pt")
|
742 |
+
|
743 |
+
@torch.no_grad()
|
744 |
+
def chat(self,
|
745 |
+
tokenizer,
|
746 |
+
query: str,
|
747 |
+
messages: List[dict] = None,
|
748 |
+
streamer: Optional[BaseStreamer] = None,
|
749 |
+
max_new_tokens: int = 512,
|
750 |
+
do_sample: bool = True,
|
751 |
+
temperature: float = 0.3,
|
752 |
+
top_p: float = 0.9,
|
753 |
+
**kwargs):
|
754 |
+
if messages is None:
|
755 |
+
messages = [{'role': 'system', 'content': NANBEIGE_SYSTEM_PROMPT}]
|
756 |
+
|
757 |
+
inputs = self.build_prompt_input(tokenizer, query, messages)
|
758 |
+
inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
|
759 |
+
outputs = self.generate(**inputs,
|
760 |
+
streamer=streamer,
|
761 |
+
max_new_tokens=max_new_tokens,
|
762 |
+
do_sample=do_sample,
|
763 |
+
temperature=temperature,
|
764 |
+
top_p=top_p,
|
765 |
+
**kwargs)
|
766 |
+
outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]):]
|
767 |
+
response = tokenizer.decode(outputs, skip_special_tokens=True)
|
768 |
+
response = response.split("</s>")[0]
|
769 |
+
messages.append({'role': 'human', 'content': query})
|
770 |
+
messages.append({'role': 'assistant', 'content': response})
|
771 |
+
return response, messages
|
772 |
+
|
773 |
+
@torch.no_grad()
|
774 |
+
def stream_chat(self,
|
775 |
+
tokenizer,
|
776 |
+
query: str,
|
777 |
+
messages: List[dict] = None,
|
778 |
+
max_new_tokens: int = 1024,
|
779 |
+
do_sample: bool = True,
|
780 |
+
temperature: float = 0.8,
|
781 |
+
top_p: float = 0.8,
|
782 |
+
**kwargs):
|
783 |
+
|
784 |
+
response_queue = queue.Queue(maxsize=20)
|
785 |
+
if messages is None:
|
786 |
+
messages = [{'role': 'system', 'content': NANBEIGE_SYSTEM_PROMPT}]
|
787 |
+
|
788 |
+
class ChatStreamer(BaseStreamer):
|
789 |
+
def __init__(self, tokenizer) -> None:
|
790 |
+
super().__init__()
|
791 |
+
self.tokenizer = tokenizer
|
792 |
+
self.queue = response_queue
|
793 |
+
self.query = query
|
794 |
+
self.messages = messages
|
795 |
+
self.response = ""
|
796 |
+
self.received_inputs = False
|
797 |
+
self.queue.put((self.response, messages + [{'role': 'human', 'content': self.query},
|
798 |
+
{'role': 'assistant', 'content': self.response}]))
|
799 |
+
|
800 |
+
def put(self, value):
|
801 |
+
if len(value.shape) > 1 and value.shape[0] > 1:
|
802 |
+
raise ValueError("ChatStreamer only supports batch size 1")
|
803 |
+
elif len(value.shape) > 1:
|
804 |
+
value = value[0]
|
805 |
+
|
806 |
+
if not self.received_inputs:
|
807 |
+
# The first received value is input_ids, ignore here
|
808 |
+
self.received_inputs = True
|
809 |
+
return
|
810 |
+
|
811 |
+
token = self.tokenizer.decode([value[-1]], skip_special_tokens=True)
|
812 |
+
if token.strip() != "</s>":
|
813 |
+
self.response = self.response + token
|
814 |
+
messages = self.messages + [{'role': 'human', 'content': self.query},
|
815 |
+
{'role': 'assistant', 'content': self.response}]
|
816 |
+
self.queue.put((self.response, messages))
|
817 |
+
|
818 |
+
def end(self):
|
819 |
+
self.queue.put(None)
|
820 |
+
|
821 |
+
def stream_task():
|
822 |
+
return self.chat(
|
823 |
+
tokenizer=tokenizer,
|
824 |
+
query=query,
|
825 |
+
messages=messages,
|
826 |
+
streamer=ChatStreamer(tokenizer=tokenizer),
|
827 |
+
max_new_tokens=max_new_tokens,
|
828 |
+
do_sample=do_sample,
|
829 |
+
temperature=temperature,
|
830 |
+
top_p=top_p,
|
831 |
+
**kwargs
|
832 |
+
)
|
833 |
+
|
834 |
+
def consumer():
|
835 |
+
threading.Thread(target=stream_task).start()
|
836 |
+
while True:
|
837 |
+
res = response_queue.get()
|
838 |
+
if res is None:
|
839 |
+
return
|
840 |
+
yield res
|
841 |
+
|
842 |
+
return consumer()
|
843 |
+
|
844 |
+
|
845 |
+
class NanbeigeForSequenceClassification(NanbeigePreTrainedModel):
|
846 |
+
_keys_to_ignore_on_load_missing = [r"lm_head.weight"]
|
847 |
+
|
848 |
+
def __init__(self, config):
|
849 |
+
super().__init__(config)
|
850 |
+
self.num_labels = config.num_labels
|
851 |
+
self.model = NanbeigeModel(config)
|
852 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
853 |
+
|
854 |
+
# Initialize weights and apply final processing
|
855 |
+
self.post_init()
|
856 |
+
|
857 |
+
def get_input_embeddings(self):
|
858 |
+
return self.model.embed_tokens
|
859 |
+
|
860 |
+
def set_input_embeddings(self, value):
|
861 |
+
self.model.embed_tokens = value
|
862 |
+
|
863 |
+
def forward(
|
864 |
+
self,
|
865 |
+
input_ids: torch.LongTensor = None,
|
866 |
+
attention_mask: Optional[torch.Tensor] = None,
|
867 |
+
position_ids: Optional[torch.LongTensor] = None,
|
868 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
869 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
870 |
+
labels: Optional[torch.LongTensor] = None,
|
871 |
+
use_cache: Optional[bool] = None,
|
872 |
+
output_attentions: Optional[bool] = None,
|
873 |
+
output_hidden_states: Optional[bool] = None,
|
874 |
+
return_dict: Optional[bool] = None,
|
875 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
876 |
+
r"""
|
877 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
878 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
879 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
880 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
881 |
+
"""
|
882 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
883 |
+
|
884 |
+
transformer_outputs = self.model(
|
885 |
+
input_ids,
|
886 |
+
attention_mask=attention_mask,
|
887 |
+
position_ids=position_ids,
|
888 |
+
past_key_values=past_key_values,
|
889 |
+
inputs_embeds=inputs_embeds,
|
890 |
+
use_cache=use_cache,
|
891 |
+
output_attentions=output_attentions,
|
892 |
+
output_hidden_states=output_hidden_states,
|
893 |
+
return_dict=return_dict,
|
894 |
+
)
|
895 |
+
hidden_states = transformer_outputs[0]
|
896 |
+
logits = self.score(hidden_states)
|
897 |
+
|
898 |
+
if input_ids is not None:
|
899 |
+
batch_size = input_ids.shape[0]
|
900 |
+
else:
|
901 |
+
batch_size = inputs_embeds.shape[0]
|
902 |
+
|
903 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
904 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
905 |
+
if self.config.pad_token_id is None:
|
906 |
+
sequence_lengths = -1
|
907 |
+
else:
|
908 |
+
if input_ids is not None:
|
909 |
+
sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
|
910 |
+
else:
|
911 |
+
sequence_lengths = -1
|
912 |
+
|
913 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
914 |
+
|
915 |
+
loss = None
|
916 |
+
if labels is not None:
|
917 |
+
labels = labels.to(logits.device)
|
918 |
+
if self.config.problem_type is None:
|
919 |
+
if self.num_labels == 1:
|
920 |
+
self.config.problem_type = "regression"
|
921 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
922 |
+
self.config.problem_type = "single_label_classification"
|
923 |
+
else:
|
924 |
+
self.config.problem_type = "multi_label_classification"
|
925 |
+
|
926 |
+
if self.config.problem_type == "regression":
|
927 |
+
loss_fct = MSELoss()
|
928 |
+
if self.num_labels == 1:
|
929 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
930 |
+
else:
|
931 |
+
loss = loss_fct(pooled_logits, labels)
|
932 |
+
elif self.config.problem_type == "single_label_classification":
|
933 |
+
loss_fct = CrossEntropyLoss()
|
934 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
935 |
+
elif self.config.problem_type == "multi_label_classification":
|
936 |
+
loss_fct = BCEWithLogitsLoss()
|
937 |
+
loss = loss_fct(pooled_logits, labels)
|
938 |
+
if not return_dict:
|
939 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
940 |
+
return ((loss,) + output) if loss is not None else output
|
941 |
+
|
942 |
+
return SequenceClassifierOutputWithPast(
|
943 |
+
loss=loss,
|
944 |
+
logits=pooled_logits,
|
945 |
+
past_key_values=transformer_outputs.past_key_values,
|
946 |
+
hidden_states=transformer_outputs.hidden_states,
|
947 |
+
attentions=transformer_outputs.attentions,
|
948 |
+
)
|
quantize_config.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bits": [
|
3 |
+
4
|
4 |
+
],
|
5 |
+
"group_size": [
|
6 |
+
128
|
7 |
+
],
|
8 |
+
"damp_percent": [
|
9 |
+
0.1
|
10 |
+
],
|
11 |
+
"desc_act": [
|
12 |
+
true
|
13 |
+
],
|
14 |
+
"sym": true,
|
15 |
+
"true_sequential": true
|
16 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"unk_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": true,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"pad_token": "</s>"
|
24 |
+
}
|
tokenization_nanbeige.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023 Nanbeige LLM Lab All Rights Reserved.
|
2 |
+
|
3 |
+
"""Tokenization classes for Nanbeige."""
|
4 |
+
import os
|
5 |
+
from shutil import copyfile
|
6 |
+
from typing import Any, Dict, List, Optional, Tuple
|
7 |
+
|
8 |
+
import sentencepiece as spm
|
9 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
10 |
+
from transformers.utils import logging
|
11 |
+
|
12 |
+
logger = logging.get_logger(__name__)
|
13 |
+
|
14 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
15 |
+
|
16 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
17 |
+
"vocab_file": {},
|
18 |
+
"tokenizer_file": {},
|
19 |
+
}
|
20 |
+
|
21 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
|
22 |
+
|
23 |
+
|
24 |
+
class NanbeigeTokenizer(PreTrainedTokenizer):
|
25 |
+
"""
|
26 |
+
Construct a Nanbeige tokenizer. Based on byte-level Byte-Pair-Encoding.
|
27 |
+
|
28 |
+
Args:
|
29 |
+
vocab_file (`str`):
|
30 |
+
Path to the vocabulary file.
|
31 |
+
"""
|
32 |
+
|
33 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
34 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
35 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
36 |
+
model_input_names = ["input_ids", "attention_mask"]
|
37 |
+
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
vocab_file,
|
41 |
+
unk_token="<unk>",
|
42 |
+
bos_token="<s>",
|
43 |
+
eos_token="</s>",
|
44 |
+
pad_token=None,
|
45 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
46 |
+
add_bos_token=True,
|
47 |
+
add_eos_token=False,
|
48 |
+
clean_up_tokenization_spaces=False,
|
49 |
+
**kwargs,
|
50 |
+
):
|
51 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
52 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
53 |
+
self.sp_model.Load(vocab_file)
|
54 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
55 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
56 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
57 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
58 |
+
super().__init__(
|
59 |
+
bos_token=bos_token,
|
60 |
+
eos_token=eos_token,
|
61 |
+
unk_token=unk_token,
|
62 |
+
pad_token=pad_token,
|
63 |
+
add_bos_token=add_bos_token,
|
64 |
+
add_eos_token=add_eos_token,
|
65 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
66 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
67 |
+
**kwargs,
|
68 |
+
)
|
69 |
+
self.vocab_file = vocab_file
|
70 |
+
self.add_bos_token = add_bos_token
|
71 |
+
self.add_eos_token = add_eos_token
|
72 |
+
|
73 |
+
def __getstate__(self):
|
74 |
+
state = self.__dict__.copy()
|
75 |
+
state["sp_model"] = None
|
76 |
+
return state
|
77 |
+
|
78 |
+
def __setstate__(self, d):
|
79 |
+
self.__dict__ = d
|
80 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
81 |
+
self.sp_model.Load(self.vocab_file)
|
82 |
+
|
83 |
+
@property
|
84 |
+
def vocab_size(self):
|
85 |
+
"""Returns vocab size"""
|
86 |
+
return self.sp_model.get_piece_size()
|
87 |
+
|
88 |
+
def get_vocab(self):
|
89 |
+
"""Returns vocab as a dict"""
|
90 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
91 |
+
vocab.update(self.added_tokens_encoder)
|
92 |
+
return vocab
|
93 |
+
|
94 |
+
def _tokenize(self, text):
|
95 |
+
"""Returns a tokenized string."""
|
96 |
+
return self.sp_model.encode(text, out_type=str)
|
97 |
+
|
98 |
+
def _convert_token_to_id(self, token):
|
99 |
+
"""Converts a token (str) in an id using the vocab."""
|
100 |
+
return self.sp_model.piece_to_id(token)
|
101 |
+
|
102 |
+
def _convert_id_to_token(self, index):
|
103 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
104 |
+
token = self.sp_model.IdToPiece(index)
|
105 |
+
return token
|
106 |
+
|
107 |
+
def convert_tokens_to_string(self, tokens):
|
108 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
109 |
+
current_sub_tokens = []
|
110 |
+
out_string = ""
|
111 |
+
prev_is_special = False
|
112 |
+
for i, token in enumerate(tokens):
|
113 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
114 |
+
if token in self.all_special_tokens:
|
115 |
+
if not prev_is_special and i != 0:
|
116 |
+
out_string += " "
|
117 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
118 |
+
prev_is_special = True
|
119 |
+
current_sub_tokens = []
|
120 |
+
else:
|
121 |
+
current_sub_tokens.append(token)
|
122 |
+
prev_is_special = False
|
123 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
124 |
+
return out_string
|
125 |
+
|
126 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
127 |
+
"""
|
128 |
+
Save the vocabulary and special tokens file to a directory.
|
129 |
+
|
130 |
+
Args:
|
131 |
+
save_directory (`str`):
|
132 |
+
The directory in which to save the vocabulary.
|
133 |
+
|
134 |
+
Returns:
|
135 |
+
`Tuple(str)`: Paths to the files saved.
|
136 |
+
"""
|
137 |
+
if not os.path.isdir(save_directory):
|
138 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
139 |
+
return
|
140 |
+
out_vocab_file = os.path.join(
|
141 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
142 |
+
)
|
143 |
+
|
144 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
145 |
+
copyfile(self.vocab_file, out_vocab_file)
|
146 |
+
elif not os.path.isfile(self.vocab_file):
|
147 |
+
with open(out_vocab_file, "wb") as fi:
|
148 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
149 |
+
fi.write(content_spiece_model)
|
150 |
+
|
151 |
+
return (out_vocab_file,)
|
152 |
+
|
153 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
154 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
155 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
156 |
+
|
157 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
158 |
+
|
159 |
+
if token_ids_1 is not None:
|
160 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
161 |
+
|
162 |
+
return output
|
163 |
+
|
164 |
+
def get_special_tokens_mask(
|
165 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None,
|
166 |
+
already_has_special_tokens: bool = False
|
167 |
+
) -> List[int]:
|
168 |
+
"""
|
169 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
170 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
171 |
+
|
172 |
+
Args:
|
173 |
+
token_ids_0 (`List[int]`):
|
174 |
+
List of IDs.
|
175 |
+
token_ids_1 (`List[int]`, *optional*):
|
176 |
+
Optional second list of IDs for sequence pairs.
|
177 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
178 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
179 |
+
|
180 |
+
Returns:
|
181 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
182 |
+
"""
|
183 |
+
if already_has_special_tokens:
|
184 |
+
return super().get_special_tokens_mask(
|
185 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
186 |
+
)
|
187 |
+
|
188 |
+
bos_token_id = [1] if self.add_bos_token else []
|
189 |
+
eos_token_id = [1] if self.add_eos_token else []
|
190 |
+
|
191 |
+
if token_ids_1 is None:
|
192 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
193 |
+
return (
|
194 |
+
bos_token_id
|
195 |
+
+ ([0] * len(token_ids_0))
|
196 |
+
+ eos_token_id
|
197 |
+
+ bos_token_id
|
198 |
+
+ ([0] * len(token_ids_1))
|
199 |
+
+ eos_token_id
|
200 |
+
)
|
201 |
+
|
202 |
+
def create_token_type_ids_from_sequences(
|
203 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
204 |
+
) -> List[int]:
|
205 |
+
"""
|
206 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
207 |
+
sequence pair mask has the following format:
|
208 |
+
|
209 |
+
```
|
210 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
211 |
+
| first sequence | second sequence |
|
212 |
+
```
|
213 |
+
|
214 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
215 |
+
|
216 |
+
Args:
|
217 |
+
token_ids_0 (`List[int]`):
|
218 |
+
List of ids.
|
219 |
+
token_ids_1 (`List[int]`, *optional*):
|
220 |
+
Optional second list of IDs for sequence pairs.
|
221 |
+
|
222 |
+
Returns:
|
223 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
224 |
+
"""
|
225 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
226 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
227 |
+
|
228 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
229 |
+
|
230 |
+
if token_ids_1 is not None:
|
231 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
232 |
+
|
233 |
+
return output
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ede13db1d0956ec033608741b0fd83d149a5ec54306af70e2ba829242f75b73b
|
3 |
+
size 851705
|
tokenizer_config.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": ["tokenization_nanbeige.NanbeigeTokenizer", null]
|
4 |
+
},
|
5 |
+
"add_bos_token": true,
|
6 |
+
"add_eos_token": false,
|
7 |
+
"bos_token": {
|
8 |
+
"__type": "AddedToken",
|
9 |
+
"content": "<s>",
|
10 |
+
"lstrip": false,
|
11 |
+
"normalized": true,
|
12 |
+
"rstrip": false,
|
13 |
+
"single_word": false
|
14 |
+
},
|
15 |
+
"clean_up_tokenization_spaces": false,
|
16 |
+
"eos_token": {
|
17 |
+
"__type": "AddedToken",
|
18 |
+
"content": "</s>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": true,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"model_max_length": 1000000000000000019884624838656,
|
25 |
+
"pad_token": null,
|
26 |
+
"sp_model_kwargs": {},
|
27 |
+
"tokenizer_class": "NanbeigeTokenizer",
|
28 |
+
"unk_token": {
|
29 |
+
"__type": "AddedToken",
|
30 |
+
"content": "<unk>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": true,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false
|
35 |
+
}
|
36 |
+
}
|