auto_gptq format
Browse filesSigned-off-by: Zhang, Weiwei1 <weiwei1.zhang@intel.com>
- added_tokens.json +16 -0
- config.json +93 -0
- configuration_chatglm.py +66 -0
- generation_config.json +13 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +0 -0
- quantize_config.json +26 -0
- special_tokens_map.json +32 -0
- tokenization_chatglm.py +362 -0
- tokenizer.model +3 -0
- tokenizer_config.json +146 -0
added_tokens.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<eop>": 151334,
|
3 |
+
"<sop>": 151333,
|
4 |
+
"<|assistant|>": 151337,
|
5 |
+
"<|begin_of_image|>": 151339,
|
6 |
+
"<|begin_of_video|>": 151341,
|
7 |
+
"<|end_of_image|>": 151340,
|
8 |
+
"<|end_of_video|>": 151342,
|
9 |
+
"<|endoftext|>": 151329,
|
10 |
+
"<|observation|>": 151338,
|
11 |
+
"<|system|>": 151335,
|
12 |
+
"<|user|>": 151336,
|
13 |
+
"[MASK]": 151330,
|
14 |
+
"[gMASK]": 151331,
|
15 |
+
"[sMASK]": 151332
|
16 |
+
}
|
config.json
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/models//glm-4v-9b",
|
3 |
+
"add_bias_linear": false,
|
4 |
+
"add_qkv_bias": true,
|
5 |
+
"apply_query_key_layer_scaling": true,
|
6 |
+
"apply_residual_connection_post_layernorm": false,
|
7 |
+
"architectures": [
|
8 |
+
"ChatGLMForConditionalGeneration"
|
9 |
+
],
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"attention_softmax_in_fp32": true,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
14 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
15 |
+
"AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
16 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
17 |
+
"AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
|
18 |
+
},
|
19 |
+
"bias_dropout_fusion": true,
|
20 |
+
"boi_token_id": 151339,
|
21 |
+
"classifier_dropout": null,
|
22 |
+
"eoi_token_id": 151340,
|
23 |
+
"eos_token_id": [
|
24 |
+
151329,
|
25 |
+
151336,
|
26 |
+
151338
|
27 |
+
],
|
28 |
+
"ffn_hidden_size": 13696,
|
29 |
+
"fp32_residual_connection": false,
|
30 |
+
"hidden_dropout": 0.0,
|
31 |
+
"hidden_size": 4096,
|
32 |
+
"kv_channels": 128,
|
33 |
+
"layernorm_epsilon": 1.5625e-07,
|
34 |
+
"model_type": "chatglm",
|
35 |
+
"multi_query_attention": true,
|
36 |
+
"multi_query_group_num": 2,
|
37 |
+
"num_attention_heads": 32,
|
38 |
+
"num_layers": 40,
|
39 |
+
"original_rope": true,
|
40 |
+
"pad_token_id": 151329,
|
41 |
+
"padded_vocab_size": 151552,
|
42 |
+
"post_layer_norm": true,
|
43 |
+
"pre_seq_len": null,
|
44 |
+
"prefix_projection": false,
|
45 |
+
"quantization_config": {
|
46 |
+
"amp": true,
|
47 |
+
"autoround_version": "0.4.2.dev",
|
48 |
+
"batch_size": 8,
|
49 |
+
"bits": 4,
|
50 |
+
"block_name_to_quantize": "transformer.encoder.layers",
|
51 |
+
"damp_percent": 0.01,
|
52 |
+
"data_type": "int",
|
53 |
+
"desc_act": false,
|
54 |
+
"enable_minmax_tuning": true,
|
55 |
+
"enable_norm_bias_tuning": false,
|
56 |
+
"enable_quanted_input": true,
|
57 |
+
"gradient_accumulate_steps": 1,
|
58 |
+
"group_size": 128,
|
59 |
+
"iters": 1000,
|
60 |
+
"low_gpu_mem_usage": false,
|
61 |
+
"lr": 0.001,
|
62 |
+
"minmax_lr": 0.001,
|
63 |
+
"nsamples": 512,
|
64 |
+
"quant_method": "gptq",
|
65 |
+
"scale_dtype": "torch.float16",
|
66 |
+
"seqlen": 2048,
|
67 |
+
"sym": true,
|
68 |
+
"to_quant_block_names": "transformer.encoder.layers",
|
69 |
+
"true_sequential": false
|
70 |
+
},
|
71 |
+
"rmsnorm": true,
|
72 |
+
"rope_ratio": 1,
|
73 |
+
"seq_length": 8192,
|
74 |
+
"tie_word_embeddings": false,
|
75 |
+
"torch_dtype": "bfloat16",
|
76 |
+
"transformers_version": "4.46.3",
|
77 |
+
"use_cache": true,
|
78 |
+
"vision_config": {
|
79 |
+
"dropout_prob": 0.0,
|
80 |
+
"hidden_act": "gelu",
|
81 |
+
"hidden_size": 1792,
|
82 |
+
"image_size": 1120,
|
83 |
+
"in_channels": 3,
|
84 |
+
"intermediate_size": 15360,
|
85 |
+
"layer_norm_eps": 1e-06,
|
86 |
+
"num_heads": 16,
|
87 |
+
"num_hidden_layers": 63,
|
88 |
+
"num_positions": 6401,
|
89 |
+
"patch_size": 14,
|
90 |
+
"scaling_factor": 8
|
91 |
+
},
|
92 |
+
"vocab_size": 151552
|
93 |
+
}
|
configuration_chatglm.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class ChatGLMConfig(PretrainedConfig):
|
5 |
+
model_type = "chatglm"
|
6 |
+
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
num_layers=28,
|
10 |
+
padded_vocab_size=65024,
|
11 |
+
hidden_size=4096,
|
12 |
+
ffn_hidden_size=13696,
|
13 |
+
kv_channels=128,
|
14 |
+
num_attention_heads=32,
|
15 |
+
seq_length=2048,
|
16 |
+
hidden_dropout=0.0,
|
17 |
+
classifier_dropout=None,
|
18 |
+
attention_dropout=0.0,
|
19 |
+
layernorm_epsilon=1e-5,
|
20 |
+
rmsnorm=True,
|
21 |
+
apply_residual_connection_post_layernorm=False,
|
22 |
+
post_layer_norm=True,
|
23 |
+
add_bias_linear=False,
|
24 |
+
add_qkv_bias=False,
|
25 |
+
bias_dropout_fusion=True,
|
26 |
+
multi_query_attention=False,
|
27 |
+
multi_query_group_num=1,
|
28 |
+
rope_ratio=1,
|
29 |
+
apply_query_key_layer_scaling=True,
|
30 |
+
attention_softmax_in_fp32=True,
|
31 |
+
fp32_residual_connection=False,
|
32 |
+
pre_seq_len=None,
|
33 |
+
prefix_projection=False,
|
34 |
+
boi_token_id=None,
|
35 |
+
eoi_token_id=None,
|
36 |
+
**kwargs
|
37 |
+
):
|
38 |
+
self.num_layers = num_layers
|
39 |
+
self.vocab_size = padded_vocab_size
|
40 |
+
self.padded_vocab_size = padded_vocab_size
|
41 |
+
self.hidden_size = hidden_size
|
42 |
+
self.ffn_hidden_size = ffn_hidden_size
|
43 |
+
self.kv_channels = kv_channels
|
44 |
+
self.num_attention_heads = num_attention_heads
|
45 |
+
self.seq_length = seq_length
|
46 |
+
self.hidden_dropout = hidden_dropout
|
47 |
+
self.classifier_dropout = classifier_dropout
|
48 |
+
self.attention_dropout = attention_dropout
|
49 |
+
self.layernorm_epsilon = layernorm_epsilon
|
50 |
+
self.rmsnorm = rmsnorm
|
51 |
+
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
52 |
+
self.post_layer_norm = post_layer_norm
|
53 |
+
self.add_bias_linear = add_bias_linear
|
54 |
+
self.add_qkv_bias = add_qkv_bias
|
55 |
+
self.bias_dropout_fusion = bias_dropout_fusion
|
56 |
+
self.multi_query_attention = multi_query_attention
|
57 |
+
self.multi_query_group_num = multi_query_group_num
|
58 |
+
self.rope_ratio = rope_ratio
|
59 |
+
self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
|
60 |
+
self.attention_softmax_in_fp32 = attention_softmax_in_fp32
|
61 |
+
self.fp32_residual_connection = fp32_residual_connection
|
62 |
+
self.pre_seq_len = pre_seq_len
|
63 |
+
self.prefix_projection = prefix_projection
|
64 |
+
self.boi_token_id = boi_token_id
|
65 |
+
self.eoi_token_id = eoi_token_id
|
66 |
+
super().__init__(**kwargs)
|
generation_config.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_sample": true,
|
3 |
+
"eos_token_id": [
|
4 |
+
151329,
|
5 |
+
151336,
|
6 |
+
151338
|
7 |
+
],
|
8 |
+
"max_length": 8192,
|
9 |
+
"pad_token_id": 151329,
|
10 |
+
"temperature": 0.8,
|
11 |
+
"top_p": 0.8,
|
12 |
+
"transformers_version": "4.46.3"
|
13 |
+
}
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:62829b26f86cde3129ce4012e21dd67e0259bc05131c3a463b1dfb854f680949
|
3 |
+
size 4975739040
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:94f8b1740de71c38f3d7968e6c29191dbe7231dcafb898d6fbc16348efe2a203
|
3 |
+
size 4984273648
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:199a88897897b3fc9b074337076ddf320fbb3d54305ee3130244409adfb9109c
|
3 |
+
size 4971562088
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1eb45e9f635e09a3ea4b3ee9db6ae612fce6537dd82d20acc927eb8244f21858
|
3 |
+
size 810746296
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
quantize_config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bits": 4,
|
3 |
+
"group_size": 128,
|
4 |
+
"sym": true,
|
5 |
+
"data_type": "int",
|
6 |
+
"enable_quanted_input": true,
|
7 |
+
"enable_minmax_tuning": true,
|
8 |
+
"seqlen": 2048,
|
9 |
+
"batch_size": 8,
|
10 |
+
"scale_dtype": "torch.float16",
|
11 |
+
"lr": 0.001,
|
12 |
+
"minmax_lr": 0.001,
|
13 |
+
"gradient_accumulate_steps": 1,
|
14 |
+
"iters": 1000,
|
15 |
+
"amp": true,
|
16 |
+
"nsamples": 512,
|
17 |
+
"low_gpu_mem_usage": false,
|
18 |
+
"to_quant_block_names": "transformer.encoder.layers",
|
19 |
+
"enable_norm_bias_tuning": false,
|
20 |
+
"autoround_version": "0.4.2.dev",
|
21 |
+
"block_name_to_quantize": "transformer.encoder.layers",
|
22 |
+
"quant_method": "gptq",
|
23 |
+
"desc_act": false,
|
24 |
+
"true_sequential": false,
|
25 |
+
"damp_percent": 0.01
|
26 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|endoftext|>",
|
4 |
+
"[MASK]",
|
5 |
+
"[gMASK]",
|
6 |
+
"[sMASK]",
|
7 |
+
"<sop>",
|
8 |
+
"<eop>",
|
9 |
+
"<|system|>",
|
10 |
+
"<|user|>",
|
11 |
+
"<|assistant|>",
|
12 |
+
"<|observation|>",
|
13 |
+
"<|begin_of_image|>",
|
14 |
+
"<|end_of_image|>",
|
15 |
+
"<|begin_of_video|>",
|
16 |
+
"<|end_of_video|>"
|
17 |
+
],
|
18 |
+
"eos_token": {
|
19 |
+
"content": "<|endoftext|>",
|
20 |
+
"lstrip": false,
|
21 |
+
"normalized": false,
|
22 |
+
"rstrip": false,
|
23 |
+
"single_word": false
|
24 |
+
},
|
25 |
+
"pad_token": {
|
26 |
+
"content": "<|endoftext|>",
|
27 |
+
"lstrip": false,
|
28 |
+
"normalized": false,
|
29 |
+
"rstrip": false,
|
30 |
+
"single_word": false
|
31 |
+
}
|
32 |
+
}
|
tokenization_chatglm.py
ADDED
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import regex as re
|
2 |
+
import base64
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import tiktoken
|
6 |
+
import torch
|
7 |
+
from torch import TensorType
|
8 |
+
from typing import List, Optional, Union, Dict, Any
|
9 |
+
from torchvision import transforms
|
10 |
+
from transformers import PreTrainedTokenizer
|
11 |
+
from transformers.utils import logging, PaddingStrategy
|
12 |
+
from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
|
13 |
+
|
14 |
+
|
15 |
+
class ChatGLM4Tokenizer(PreTrainedTokenizer):
|
16 |
+
vocab_files_names = {"vocab_file": "tokenizer.model"}
|
17 |
+
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
18 |
+
|
19 |
+
def __init__(
|
20 |
+
self,
|
21 |
+
vocab_file,
|
22 |
+
padding_side="left",
|
23 |
+
clean_up_tokenization_spaces=False,
|
24 |
+
encode_special_tokens=False,
|
25 |
+
image_size=None,
|
26 |
+
**kwargs
|
27 |
+
):
|
28 |
+
self.name = "GLM4Tokenizer"
|
29 |
+
self.vocab_file = vocab_file
|
30 |
+
pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
|
31 |
+
self.pat_str = re.compile(pat_str)
|
32 |
+
self.encode_special_tokens = encode_special_tokens
|
33 |
+
self.image_size = image_size
|
34 |
+
|
35 |
+
mergeable_ranks = {}
|
36 |
+
with open(vocab_file) as f:
|
37 |
+
for line in f:
|
38 |
+
token, rank = line.strip().split()
|
39 |
+
rank = int(rank)
|
40 |
+
token = base64.b64decode(token)
|
41 |
+
mergeable_ranks[token] = rank
|
42 |
+
|
43 |
+
self.mergeable_ranks = mergeable_ranks
|
44 |
+
|
45 |
+
self.tokenizer = tiktoken.Encoding(
|
46 |
+
name="my_tokenizer",
|
47 |
+
pat_str=pat_str,
|
48 |
+
mergeable_ranks=mergeable_ranks,
|
49 |
+
special_tokens={}
|
50 |
+
)
|
51 |
+
self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
|
52 |
+
self.n_words = len(self.decoder)
|
53 |
+
|
54 |
+
super().__init__(
|
55 |
+
padding_side=padding_side,
|
56 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
57 |
+
**kwargs
|
58 |
+
)
|
59 |
+
|
60 |
+
@property
|
61 |
+
def vocab_size(self):
|
62 |
+
return self.n_words
|
63 |
+
|
64 |
+
def get_vocab(self):
|
65 |
+
""" Returns vocab as a dict """
|
66 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
67 |
+
vocab.update(self.added_tokens_encoder)
|
68 |
+
return vocab
|
69 |
+
|
70 |
+
def convert_tokens_to_string(self, tokens: List[Union[bytes, str, int]]) -> str:
|
71 |
+
"""
|
72 |
+
Converts a sequence of tokens in a single string.
|
73 |
+
"""
|
74 |
+
text = ""
|
75 |
+
temp = b""
|
76 |
+
for t in tokens:
|
77 |
+
if isinstance(t, int):
|
78 |
+
t = chr(t)
|
79 |
+
if isinstance(t, str):
|
80 |
+
if temp:
|
81 |
+
text += temp.decode("utf-8", errors="replace")
|
82 |
+
elif isinstance(t, bytes):
|
83 |
+
temp += t
|
84 |
+
else:
|
85 |
+
raise TypeError("token should only be of type int, bytes or str")
|
86 |
+
if temp:
|
87 |
+
text += temp.decode("utf-8", errors="replace")
|
88 |
+
return text
|
89 |
+
|
90 |
+
def _tokenize(self, text, **kwargs):
|
91 |
+
tokens = []
|
92 |
+
ids = self.tokenizer.encode(text)
|
93 |
+
for t in ids:
|
94 |
+
tokens.append(self.decoder[t])
|
95 |
+
return tokens
|
96 |
+
|
97 |
+
def _convert_token_to_id(self, token):
|
98 |
+
""" Converts a token (str) in an id using the vocab. """
|
99 |
+
return self.mergeable_ranks[token]
|
100 |
+
|
101 |
+
def _convert_id_to_token(self, index):
|
102 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
103 |
+
return self.decoder.get(index, "")
|
104 |
+
|
105 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
106 |
+
"""
|
107 |
+
Save the vocabulary and special tokens file to a directory.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
save_directory (`str`):
|
111 |
+
The directory in which to save the vocabulary.
|
112 |
+
filename_prefix (`str`, *optional*):
|
113 |
+
An optional prefix to add to the named of the saved files.
|
114 |
+
|
115 |
+
Returns:
|
116 |
+
`Tuple(str)`: Paths to the files saved.
|
117 |
+
"""
|
118 |
+
if os.path.isdir(save_directory):
|
119 |
+
vocab_file = os.path.join(
|
120 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
121 |
+
)
|
122 |
+
else:
|
123 |
+
vocab_file = save_directory
|
124 |
+
|
125 |
+
with open(self.vocab_file, 'rb') as fin:
|
126 |
+
proto_str = fin.read()
|
127 |
+
|
128 |
+
with open(vocab_file, "wb") as writer:
|
129 |
+
writer.write(proto_str)
|
130 |
+
|
131 |
+
return (vocab_file,)
|
132 |
+
|
133 |
+
def get_prefix_tokens(self):
|
134 |
+
prefix_tokens = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]
|
135 |
+
return prefix_tokens
|
136 |
+
|
137 |
+
def build_single_message(self, role, metadata, message, tokenize=True, message_prefix=None):
|
138 |
+
assert role in ["system", "user", "assistant", "observation"], role
|
139 |
+
if tokenize:
|
140 |
+
role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",
|
141 |
+
disallowed_special=())
|
142 |
+
message_tokens = self.tokenizer.encode(message, disallowed_special=())
|
143 |
+
if message_prefix is not None:
|
144 |
+
message_tokens = message_prefix + message_tokens
|
145 |
+
tokens = role_tokens + message_tokens
|
146 |
+
return tokens
|
147 |
+
else:
|
148 |
+
return str(f"<|{role}|>{metadata}\n{message}")
|
149 |
+
|
150 |
+
def apply_chat_template(
|
151 |
+
self,
|
152 |
+
conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]], "Conversation"],
|
153 |
+
add_generation_prompt: bool = False,
|
154 |
+
tokenize: bool = True,
|
155 |
+
padding: bool = False,
|
156 |
+
truncation: bool = False,
|
157 |
+
max_length: Optional[int] = None,
|
158 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
159 |
+
return_dict: bool = False,
|
160 |
+
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
|
161 |
+
add_special_tokens: bool = True,
|
162 |
+
**kwargs,
|
163 |
+
) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
|
164 |
+
|
165 |
+
if return_dict and not tokenize:
|
166 |
+
raise ValueError(
|
167 |
+
"`return_dict=True` is incompatible with `tokenize=False`, because there is no dict "
|
168 |
+
"of tokenizer outputs to return."
|
169 |
+
)
|
170 |
+
|
171 |
+
def handle_single_conversation(conversation):
|
172 |
+
input_ids = self.get_prefix_tokens() if add_special_tokens else []
|
173 |
+
input_message = "[gMASK]<sop>" if add_special_tokens else ""
|
174 |
+
input_image = None
|
175 |
+
transform = transforms.Compose(
|
176 |
+
[
|
177 |
+
transforms.Resize(
|
178 |
+
(self.image_size, self.image_size), interpolation=transforms.InterpolationMode.BICUBIC
|
179 |
+
),
|
180 |
+
transforms.ToTensor(),
|
181 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
182 |
+
]
|
183 |
+
)
|
184 |
+
for item in conversation:
|
185 |
+
if item.get("tools"):
|
186 |
+
tools = item["tools"]
|
187 |
+
content = "你是一个名为 GLM-4 的人工智能助手。你是基于智谱AI训练的语言模型 GLM-4 模型开发的,你的任务是针对用户的问题和要求提供适当的答复和支持。"
|
188 |
+
for tool in tools:
|
189 |
+
if tool["type"] == "function":
|
190 |
+
function = tool["function"]
|
191 |
+
content += f"\n\n## {function['name']}\n\n{json.dumps(function, ensure_ascii=False, indent=4)}"
|
192 |
+
content += "\n在调用上述函数时,请使用 Json 格式表示调用的参数。"
|
193 |
+
elif tool["type"] == "python":
|
194 |
+
content += "\n\n## python\n\n当你向 `python` 发送包含 Python 代码的消息时,该代码将会在一个有状态的 Jupyter notebook 环境中执行。\n`python` 返回代码执行的输出,或在执行 60 秒后返回超时。\n`/mnt/data` 将会持久化存储你的文件。在此会话中,`python` 无法访问互联网。不要使用 `python` 进行任何网络请求或者在线 API 调用,这些在线内容的访问将不会成功。"
|
195 |
+
elif tool["type"] == "simple_browser":
|
196 |
+
content += "\n\n## simple_browser\n\n你可以使用 `simple_browser` 工具。该工具支持以下函数:\n`search(query: str, recency_days: int)`:使用搜索引擎进行查询并显示结果,可以使用 `recency_days` 参数控制搜索内容的时效性。\n`mclick(ids: list[int])`:获取一系列指定 id 的页面内容。每次调用时,须选择3-10个页面。选择多个角度的页面,同时尽可能选择可信任的信息来源。考虑到部分页面是无法加载的,你也可以多打开一些可能有用的页面而不用担心内容过多。\n`open_url(url: str)`:打开指定的 URL。\n\n使用 `【{引用 id}†{引用文本}】` 来引用内容。\n\n操作步骤:1. 使用 `search` 来获得信息列表; 2. 使用 `mclick` 来获取指定 ID 页面的内容; 3. 根据获得的内容进行回复。在回复中应当引用信息来源。\n 如果用户提供了 URL,也可以用 `open_url` 直接打开页面。\n如果初次搜索结果没有找到合适的信息,也可以再次使用 `search` 进行搜索。"
|
197 |
+
elif tool["type"] == "cogview":
|
198 |
+
content += "\n\n## cogview\n\n如果用户的请求中包含了对图像的描述,你可以使用 `cogview` 来生成图像并展示给用户。你需要向 `cogview` 发送图像描述,规则:\n- 发送给 `cogview` 的消息必须使用英语。用户的中文描述必须完全翻译为英语。\n- 应当尽可能详细地描述图像生成的需求,需求描述约 100 英文单词。\n- 保持用户原始描述的意图。不要虚构内容或者没见过的人物。\n- 如无特殊说明,所在地为中国,持有中国立场并遵循中国社会主义价值观。"
|
199 |
+
else:
|
200 |
+
raise NotImplementedError(f"Unknown tool type {tool['type']}")
|
201 |
+
input = self.build_single_message("system", "", content, tokenize=tokenize)
|
202 |
+
if tokenize:
|
203 |
+
input_ids.extend(input)
|
204 |
+
else:
|
205 |
+
input_message += input
|
206 |
+
message = ""
|
207 |
+
message_prefix = None
|
208 |
+
if item.get("image"):
|
209 |
+
assert input_image is None, "Multiple images are not supported"
|
210 |
+
input_image = transform(item["image"])
|
211 |
+
message_prefix = self.convert_tokens_to_ids(
|
212 |
+
["<|begin_of_image|>", "<|endoftext|>", "<|end_of_image|>"])
|
213 |
+
if item.get("content"):
|
214 |
+
message += item["content"]
|
215 |
+
if message or message_prefix:
|
216 |
+
input = self.build_single_message(
|
217 |
+
item["role"],
|
218 |
+
item.get("metadata", ""),
|
219 |
+
message,
|
220 |
+
tokenize=tokenize,
|
221 |
+
message_prefix=message_prefix
|
222 |
+
)
|
223 |
+
if tokenize:
|
224 |
+
input_ids.extend(input)
|
225 |
+
else:
|
226 |
+
input_message += input
|
227 |
+
if add_generation_prompt:
|
228 |
+
if tokenize:
|
229 |
+
input_ids.extend([self.convert_tokens_to_ids("<|assistant|>")])
|
230 |
+
else:
|
231 |
+
input_message += "<|assistant|>"
|
232 |
+
return {"input": input_ids if tokenize else input_message, "image": input_image}
|
233 |
+
|
234 |
+
# Main logic to handle different conversation formats
|
235 |
+
if isinstance(conversation, list) and all(isinstance(i, dict) for i in conversation):
|
236 |
+
result = handle_single_conversation(conversation)
|
237 |
+
input_ids = result["input"]
|
238 |
+
input_images = [result["image"]]
|
239 |
+
elif isinstance(conversation, list) and all(isinstance(i, list) for i in conversation):
|
240 |
+
results = [handle_single_conversation(c) for c in conversation]
|
241 |
+
input_ids = [item["input"] for item in results]
|
242 |
+
input_images = [item["image"] for item in results]
|
243 |
+
elif hasattr(conversation, "messages"):
|
244 |
+
result = handle_single_conversation(conversation.messages)
|
245 |
+
input_ids = result["input"]
|
246 |
+
input_images = [result["image"]]
|
247 |
+
else:
|
248 |
+
raise ValueError("Invalid conversation format")
|
249 |
+
|
250 |
+
if tokenize:
|
251 |
+
output = self.batch_encode_plus(
|
252 |
+
[input_ids] if isinstance(input_ids[0], int) else input_ids,
|
253 |
+
padding=padding,
|
254 |
+
truncation=truncation,
|
255 |
+
max_length=max_length,
|
256 |
+
return_tensors=return_tensors,
|
257 |
+
is_split_into_words=True,
|
258 |
+
add_special_tokens=False
|
259 |
+
)
|
260 |
+
if return_dict:
|
261 |
+
found_image = False
|
262 |
+
for image in input_images:
|
263 |
+
if image is not None:
|
264 |
+
found_image = True
|
265 |
+
break
|
266 |
+
if found_image:
|
267 |
+
output["images"] = torch.stack(input_images)
|
268 |
+
return output
|
269 |
+
else:
|
270 |
+
return output["input_ids"]
|
271 |
+
else:
|
272 |
+
return input_ids
|
273 |
+
|
274 |
+
|
275 |
+
def build_inputs_with_special_tokens(
|
276 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
277 |
+
) -> List[int]:
|
278 |
+
"""
|
279 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
280 |
+
adding special tokens. A BERT sequence has the following format:
|
281 |
+
|
282 |
+
- single sequence: `[CLS] X [SEP]`
|
283 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
284 |
+
|
285 |
+
Args:
|
286 |
+
token_ids_0 (`List[int]`):
|
287 |
+
List of IDs to which the special tokens will be added.
|
288 |
+
token_ids_1 (`List[int]`, *optional*):
|
289 |
+
Optional second list of IDs for sequence pairs.
|
290 |
+
|
291 |
+
Returns:
|
292 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
293 |
+
"""
|
294 |
+
prefix_tokens = self.get_prefix_tokens()
|
295 |
+
token_ids_0 = prefix_tokens + token_ids_0
|
296 |
+
if token_ids_1 is not None:
|
297 |
+
token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]
|
298 |
+
return token_ids_0
|
299 |
+
|
300 |
+
def _pad(
|
301 |
+
self,
|
302 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
303 |
+
max_length: Optional[int] = None,
|
304 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
305 |
+
pad_to_multiple_of: Optional[int] = None,
|
306 |
+
padding_side: Optional[str] = None,
|
307 |
+
return_attention_mask: Optional[bool] = None,
|
308 |
+
) -> dict:
|
309 |
+
"""
|
310 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
311 |
+
|
312 |
+
Args:
|
313 |
+
encoded_inputs:
|
314 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
315 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
316 |
+
Will truncate by taking into account the special tokens.
|
317 |
+
padding_strategy: PaddingStrategy to use for padding.
|
318 |
+
|
319 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
320 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
321 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
322 |
+
The tokenizer padding sides are defined in self.padding_side:
|
323 |
+
|
324 |
+
- 'left': pads on the left of the sequences
|
325 |
+
- 'right': pads on the right of the sequences
|
326 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
327 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
328 |
+
`>= 7.5` (Volta).
|
329 |
+
return_attention_mask:
|
330 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
331 |
+
"""
|
332 |
+
# Load from model defaults
|
333 |
+
assert self.padding_side == "left"
|
334 |
+
|
335 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
336 |
+
seq_length = len(required_input)
|
337 |
+
|
338 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
339 |
+
max_length = len(required_input)
|
340 |
+
|
341 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
342 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
343 |
+
|
344 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
|
345 |
+
|
346 |
+
# Initialize attention mask if not present.
|
347 |
+
if "attention_mask" not in encoded_inputs:
|
348 |
+
encoded_inputs["attention_mask"] = [1] * seq_length
|
349 |
+
|
350 |
+
if "position_ids" not in encoded_inputs:
|
351 |
+
encoded_inputs["position_ids"] = list(range(seq_length))
|
352 |
+
|
353 |
+
if needs_to_be_padded:
|
354 |
+
difference = max_length - len(required_input)
|
355 |
+
|
356 |
+
if "attention_mask" in encoded_inputs:
|
357 |
+
encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
|
358 |
+
if "position_ids" in encoded_inputs:
|
359 |
+
encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
|
360 |
+
encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
|
361 |
+
|
362 |
+
return encoded_inputs
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5a493598071550244b2ee7f26118f3edec2150b9dfa967929a99052ac83fe716
|
3 |
+
size 2623634
|
tokenizer_config.json
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"151329": {
|
4 |
+
"content": "<|endoftext|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"151330": {
|
12 |
+
"content": "[MASK]",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"151331": {
|
20 |
+
"content": "[gMASK]",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"151332": {
|
28 |
+
"content": "[sMASK]",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"151333": {
|
36 |
+
"content": "<sop>",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
},
|
43 |
+
"151334": {
|
44 |
+
"content": "<eop>",
|
45 |
+
"lstrip": false,
|
46 |
+
"normalized": false,
|
47 |
+
"rstrip": false,
|
48 |
+
"single_word": false,
|
49 |
+
"special": true
|
50 |
+
},
|
51 |
+
"151335": {
|
52 |
+
"content": "<|system|>",
|
53 |
+
"lstrip": false,
|
54 |
+
"normalized": false,
|
55 |
+
"rstrip": false,
|
56 |
+
"single_word": false,
|
57 |
+
"special": true
|
58 |
+
},
|
59 |
+
"151336": {
|
60 |
+
"content": "<|user|>",
|
61 |
+
"lstrip": false,
|
62 |
+
"normalized": false,
|
63 |
+
"rstrip": false,
|
64 |
+
"single_word": false,
|
65 |
+
"special": true
|
66 |
+
},
|
67 |
+
"151337": {
|
68 |
+
"content": "<|assistant|>",
|
69 |
+
"lstrip": false,
|
70 |
+
"normalized": false,
|
71 |
+
"rstrip": false,
|
72 |
+
"single_word": false,
|
73 |
+
"special": true
|
74 |
+
},
|
75 |
+
"151338": {
|
76 |
+
"content": "<|observation|>",
|
77 |
+
"lstrip": false,
|
78 |
+
"normalized": false,
|
79 |
+
"rstrip": false,
|
80 |
+
"single_word": false,
|
81 |
+
"special": true
|
82 |
+
},
|
83 |
+
"151339": {
|
84 |
+
"content": "<|begin_of_image|>",
|
85 |
+
"lstrip": false,
|
86 |
+
"normalized": false,
|
87 |
+
"rstrip": false,
|
88 |
+
"single_word": false,
|
89 |
+
"special": true
|
90 |
+
},
|
91 |
+
"151340": {
|
92 |
+
"content": "<|end_of_image|>",
|
93 |
+
"lstrip": false,
|
94 |
+
"normalized": false,
|
95 |
+
"rstrip": false,
|
96 |
+
"single_word": false,
|
97 |
+
"special": true
|
98 |
+
},
|
99 |
+
"151341": {
|
100 |
+
"content": "<|begin_of_video|>",
|
101 |
+
"lstrip": false,
|
102 |
+
"normalized": false,
|
103 |
+
"rstrip": false,
|
104 |
+
"single_word": false,
|
105 |
+
"special": true
|
106 |
+
},
|
107 |
+
"151342": {
|
108 |
+
"content": "<|end_of_video|>",
|
109 |
+
"lstrip": false,
|
110 |
+
"normalized": false,
|
111 |
+
"rstrip": false,
|
112 |
+
"single_word": false,
|
113 |
+
"special": true
|
114 |
+
}
|
115 |
+
},
|
116 |
+
"additional_special_tokens": [
|
117 |
+
"<|endoftext|>",
|
118 |
+
"[MASK]",
|
119 |
+
"[gMASK]",
|
120 |
+
"[sMASK]",
|
121 |
+
"<sop>",
|
122 |
+
"<eop>",
|
123 |
+
"<|system|>",
|
124 |
+
"<|user|>",
|
125 |
+
"<|assistant|>",
|
126 |
+
"<|observation|>",
|
127 |
+
"<|begin_of_image|>",
|
128 |
+
"<|end_of_image|>",
|
129 |
+
"<|begin_of_video|>",
|
130 |
+
"<|end_of_video|>"
|
131 |
+
],
|
132 |
+
"auto_map": {
|
133 |
+
"AutoTokenizer": [
|
134 |
+
"tokenization_chatglm.ChatGLM4Tokenizer",
|
135 |
+
null
|
136 |
+
]
|
137 |
+
},
|
138 |
+
"clean_up_tokenization_spaces": false,
|
139 |
+
"do_lower_case": false,
|
140 |
+
"eos_token": "<|endoftext|>",
|
141 |
+
"model_max_length": 8192,
|
142 |
+
"pad_token": "<|endoftext|>",
|
143 |
+
"padding_side": "left",
|
144 |
+
"remove_space": false,
|
145 |
+
"tokenizer_class": "ChatGLM4Tokenizer"
|
146 |
+
}
|