BuildTools commited on
Commit
23ba7ab
1 Parent(s): 8ea28f6
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import signal
4
+ from transformers import AutoTokenizer, AutoModel, AutoConfig, AutoModelForCausalLM
5
+ import readline
6
+ import torch
7
+ from accelerate import infer_auto_device_map, init_empty_weights, load_checkpoint_and_dispatch
8
+ import gradio as gr
9
+ import time
10
+
11
+ model_path = "THUDM/chatglm-6b-int4"
12
+ # 载入Tokenizer
13
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
14
+ # Fine-tuning 后的表现测试
15
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True, pre_seq_len=128)
16
+ model = AutoModel.from_pretrained(model_path, config=config, trust_remote_code=True)
17
+ # 此处使用你的 ptuning 工作目录
18
+ prefix_state_dict = torch.load(os.path.join("./xiaowo", "pytorch_model.bin"))
19
+ new_prefix_state_dict = {}
20
+ for k, v in prefix_state_dict.items():
21
+ new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
22
+ model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
23
+
24
+ model = model.float()
25
+ model.transformer.prefix_encoder.float()
26
+ model = model.eval()
27
+
28
+ #剩下的直接抄web_demo.py了家人们
29
+ """Override Chatbot.postprocess"""
30
+
31
+
32
+ def postprocess(self, y):
33
+ if y is None:
34
+ return []
35
+ for i, (message, response) in enumerate(y):
36
+ y[i] = (
37
+ None if message is None else mdtex2html.convert((message)),
38
+ None if response is None else mdtex2html.convert(response),
39
+ )
40
+ return y
41
+
42
+
43
+ gr.Chatbot.postprocess = postprocess
44
+
45
+
46
+ def parse_text(text):
47
+ """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
48
+ lines = text.split("\n")
49
+ lines = [line for line in lines if line != ""]
50
+ count = 0
51
+ for i, line in enumerate(lines):
52
+ if "```" in line:
53
+ count += 1
54
+ items = line.split('`')
55
+ if count % 2 == 1:
56
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
57
+ else:
58
+ lines[i] = f'<br></code></pre>'
59
+ else:
60
+ if i > 0:
61
+ if count % 2 == 1:
62
+ line = line.replace("`", "\`")
63
+ line = line.replace("<", "&lt;")
64
+ line = line.replace(">", "&gt;")
65
+ line = line.replace(" ", "&nbsp;")
66
+ line = line.replace("*", "&ast;")
67
+ line = line.replace("_", "&lowbar;")
68
+ line = line.replace("-", "&#45;")
69
+ line = line.replace(".", "&#46;")
70
+ line = line.replace("!", "&#33;")
71
+ line = line.replace("(", "&#40;")
72
+ line = line.replace(")", "&#41;")
73
+ line = line.replace("$", "&#36;")
74
+ lines[i] = "<br>"+line
75
+ text = "".join(lines)
76
+ return text
77
+
78
+
79
+ def predict(input, chatbot, max_length, top_p, temperature, history):
80
+ chatbot.append((parse_text(input), ""))
81
+ for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
82
+ temperature=temperature):
83
+ chatbot[-1] = (parse_text(input), parse_text(response))
84
+
85
+ yield chatbot, history
86
+
87
+
88
+ def reset_user_input():
89
+ return gr.update(value='')
90
+
91
+
92
+ def reset_state():
93
+ return [], []
94
+
95
+
96
+ with gr.Blocks() as demo:
97
+ gr.HTML("""<h1 align="center">ChatGLM</h1>""")
98
+
99
+ chatbot = gr.Chatbot()
100
+ with gr.Row():
101
+ with gr.Column(scale=4):
102
+ with gr.Column(scale=12):
103
+ user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(
104
+ container=False)
105
+ with gr.Column(min_width=32, scale=1):
106
+ submitBtn = gr.Button("Submit", variant="primary")
107
+ with gr.Column(scale=1):
108
+ emptyBtn = gr.Button("Clear History")
109
+ max_length = gr.Slider(0, 4096, value=2048, step=1.0, label="Maximum length", interactive=True)
110
+ top_p = gr.Slider(0, 1, value=0.7, step=0.01, label="Top P", interactive=True)
111
+ temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
112
+
113
+ history = gr.State([])
114
+
115
+ submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history], [chatbot, history],
116
+ show_progress=True)
117
+ submitBtn.click(reset_user_input, [], [user_input])
118
+
119
+ emptyBtn.click(reset_state, outputs=[chatbot, history], show_progress=True)
120
+
121
+ demo.queue().launch(share=False, inbrowser=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ protobuf
2
+ transformers==4.27.1
3
+ cpm_kernels
4
+ torch>=1.10
5
+ gradio
6
+ mdtex2html
7
+ sentencepiece
8
+ accelerate
utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict, Tuple, Union, Optional
3
+
4
+ from torch.nn import Module
5
+ from transformers import AutoModel
6
+
7
+
8
+ def auto_configure_device_map(num_gpus: int) -> Dict[str, int]:
9
+ # transformer.word_embeddings 占用1层
10
+ # transformer.final_layernorm 和 lm_head 占用1层
11
+ # transformer.layers 占用 28 层
12
+ # 总共30层分配到num_gpus张卡上
13
+ num_trans_layers = 28
14
+ per_gpu_layers = 30 / num_gpus
15
+
16
+ # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError
17
+ # windows下 model.device 会被设置成 transformer.word_embeddings.device
18
+ # linux下 model.device 会被设置成 lm_head.device
19
+ # 在调用chat或者stream_chat时,input_ids会被放到model.device上
20
+ # 如果transformer.word_embeddings.device和model.device不同,则会导致RuntimeError
21
+ # 因此这里将transformer.word_embeddings,transformer.final_layernorm,lm_head都放到第一张卡上
22
+ device_map = {'transformer.word_embeddings': 0,
23
+ 'transformer.final_layernorm': 0, 'lm_head': 0}
24
+
25
+ used = 2
26
+ gpu_target = 0
27
+ for i in range(num_trans_layers):
28
+ if used >= per_gpu_layers:
29
+ gpu_target += 1
30
+ used = 0
31
+ assert gpu_target < num_gpus
32
+ device_map[f'transformer.layers.{i}'] = gpu_target
33
+ used += 1
34
+
35
+ return device_map
36
+
37
+
38
+ def load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2,
39
+ device_map: Optional[Dict[str, int]] = None, **kwargs) -> Module:
40
+ if num_gpus < 2 and device_map is None:
41
+ model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half().cuda()
42
+ else:
43
+ from accelerate import dispatch_model
44
+
45
+ model = AutoModel.from_pretrained(checkpoint_path, trust_remote_code=True, **kwargs).half()
46
+
47
+ if device_map is None:
48
+ device_map = auto_configure_device_map(num_gpus)
49
+
50
+ model = dispatch_model(model, device_map=device_map)
51
+
52
+ return model
53
+
54
+
xiaowo/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm-6b-int4",
3
+ "architectures": [
4
+ "ChatGLMForConditionalGeneration"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "bos_token_id": 130004,
12
+ "eos_token_id": 130005,
13
+ "gmask_token_id": 130001,
14
+ "hidden_size": 4096,
15
+ "inner_hidden_size": 16384,
16
+ "layernorm_epsilon": 1e-05,
17
+ "mask_token_id": 130000,
18
+ "max_sequence_length": 2048,
19
+ "model_type": "chatglm",
20
+ "num_attention_heads": 32,
21
+ "num_layers": 28,
22
+ "pad_token_id": 3,
23
+ "position_encoding_2d": true,
24
+ "pre_seq_len": 128,
25
+ "prefix_projection": false,
26
+ "quantization_bit": 4,
27
+ "quantization_embeddings": false,
28
+ "torch_dtype": "float16",
29
+ "transformers_version": "4.27.1",
30
+ "use_cache": true,
31
+ "vocab_size": 130528
32
+ }
xiaowo/configuration_chatglm.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ ChatGLM model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ class ChatGLMConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`~ChatGLMModel`].
12
+ It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
13
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
14
+ the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
15
+
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
17
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
18
+ for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 150528):
23
+ Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`~ChatGLMModel`] or
25
+ [`~TFChatGLMModel`].
26
+ hidden_size (`int`, *optional*, defaults to 4096):
27
+ Dimension of the encoder layers and the pooler layer.
28
+ num_hidden_layers (`int`, *optional*, defaults to 28):
29
+ Number of hidden layers in the Transformer encoder.
30
+ num_attention_heads (`int`, *optional*, defaults to 32):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ inner_hidden_size (`int`, *optional*, defaults to 16384):
33
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
34
+ max_sequence_length (`int`, *optional*, defaults to 512):
35
+ The maximum sequence length that this model might ever be used with.
36
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
37
+ layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
38
+ The epsilon used by the layer normalization layers.
39
+ use_cache (`bool`, *optional*, defaults to `True`):
40
+ Whether the model should return the last key/values attentions (not used by all models).
41
+ Example:
42
+
43
+ ```python
44
+ >>> from configuration_chatglm import ChatGLMConfig
45
+ >>> from modeling_chatglm import ChatGLMModel
46
+
47
+ >>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
48
+ >>> configuration = ChatGLMConfig()
49
+
50
+ >>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
51
+ >>> model = ChatGLMModel(configuration)
52
+
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```
56
+ """
57
+ model_type = "chatglm"
58
+
59
+ def __init__(
60
+ self,
61
+ vocab_size=150528,
62
+ hidden_size=4096,
63
+ num_layers=28,
64
+ num_attention_heads=32,
65
+ layernorm_epsilon=1e-5,
66
+ use_cache=False,
67
+ bos_token_id=150004,
68
+ eos_token_id=150005,
69
+ mask_token_id=150000,
70
+ gmask_token_id=150001,
71
+ pad_token_id=0,
72
+ max_sequence_length=2048,
73
+ inner_hidden_size=16384,
74
+ position_encoding_2d=True,
75
+ quantization_bit=0,
76
+ quantization_embeddings=False,
77
+ pre_seq_len=None,
78
+ prefix_projection=False,
79
+ **kwargs
80
+ ):
81
+ self.num_layers = num_layers
82
+ self.vocab_size = vocab_size
83
+ self.hidden_size = hidden_size
84
+ self.num_attention_heads = num_attention_heads
85
+ self.max_sequence_length = max_sequence_length
86
+ self.layernorm_epsilon = layernorm_epsilon
87
+ self.inner_hidden_size = inner_hidden_size
88
+ self.use_cache = use_cache
89
+ self.bos_token_id = bos_token_id
90
+ self.eos_token_id = eos_token_id
91
+ self.pad_token_id = pad_token_id
92
+ self.mask_token_id = mask_token_id
93
+ self.gmask_token_id = gmask_token_id
94
+ self.position_encoding_2d = position_encoding_2d
95
+ self.quantization_bit = quantization_bit
96
+ self.quantization_embeddings = quantization_embeddings
97
+ self.pre_seq_len = pre_seq_len
98
+ self.prefix_projection = prefix_projection
99
+
100
+ super().__init__(
101
+ pad_token_id=pad_token_id,
102
+ bos_token_id=bos_token_id,
103
+ eos_token_id=eos_token_id,
104
+ **kwargs
105
+ )
xiaowo/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 130004,
4
+ "eos_token_id": 130005,
5
+ "pad_token_id": 3,
6
+ "transformers_version": "4.27.1"
7
+ }
xiaowo/ice_text.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e974d9a69c242ce014c88c2b26089270f6198f3c0b700a887666cd3e816f17e
3
+ size 2706249
xiaowo/modeling_chatglm.py ADDED
@@ -0,0 +1,1471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+ import warnings
7
+ import re
8
+ import sys
9
+
10
+ import torch
11
+ import torch.utils.checkpoint
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+ from torch.nn import CrossEntropyLoss, LayerNorm
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+
18
+ from transformers.utils import (
19
+ add_code_sample_docstrings,
20
+ add_start_docstrings,
21
+ add_start_docstrings_to_model_forward,
22
+ )
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ )
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import logging
30
+ from transformers.generation.logits_process import LogitsProcessor
31
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
32
+
33
+ from .configuration_chatglm import ChatGLMConfig
34
+
35
+
36
+ # flags required to enable jit fusion kernels
37
+
38
+ if sys.platform != 'darwin':
39
+ torch._C._jit_set_profiling_mode(False)
40
+ torch._C._jit_set_profiling_executor(False)
41
+ torch._C._jit_override_can_fuse_on_cpu(True)
42
+ torch._C._jit_override_can_fuse_on_gpu(True)
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
47
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
48
+
49
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
50
+ "THUDM/chatglm-6b",
51
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
52
+ ]
53
+
54
+
55
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
56
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
57
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
58
+ scores.zero_()
59
+ scores[..., 5] = 5e4
60
+ return scores
61
+
62
+
63
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
64
+ """Load tf checkpoints in a pytorch model."""
65
+ try:
66
+ import re
67
+
68
+ import numpy as np
69
+ import tensorflow as tf
70
+ except ImportError:
71
+ logger.error(
72
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
73
+ "https://www.tensorflow.org/install/ for installation instructions."
74
+ )
75
+ raise
76
+ tf_path = os.path.abspath(tf_checkpoint_path)
77
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
78
+ # Load weights from TF model
79
+ init_vars = tf.train.list_variables(tf_path)
80
+ names = []
81
+ arrays = []
82
+ for name, shape in init_vars:
83
+ logger.info(f"Loading TF weight {name} with shape {shape}")
84
+ array = tf.train.load_variable(tf_path, name)
85
+ names.append(name)
86
+ arrays.append(array)
87
+
88
+ for name, array in zip(names, arrays):
89
+ name = name.split("/")
90
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
91
+ # which are not required for using pretrained model
92
+ if any(
93
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
94
+ for n in name
95
+ ):
96
+ logger.info(f"Skipping {'/'.join(name)}")
97
+ continue
98
+ pointer = model
99
+ for m_name in name:
100
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
101
+ scope_names = re.split(r"_(\d+)", m_name)
102
+ else:
103
+ scope_names = [m_name]
104
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
105
+ pointer = getattr(pointer, "weight")
106
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
107
+ pointer = getattr(pointer, "bias")
108
+ elif scope_names[0] == "output_weights":
109
+ pointer = getattr(pointer, "weight")
110
+ elif scope_names[0] == "squad":
111
+ pointer = getattr(pointer, "classifier")
112
+ else:
113
+ try:
114
+ pointer = getattr(pointer, scope_names[0])
115
+ except AttributeError:
116
+ logger.info(f"Skipping {'/'.join(name)}")
117
+ continue
118
+ if len(scope_names) >= 2:
119
+ num = int(scope_names[1])
120
+ pointer = pointer[num]
121
+ if m_name[-11:] == "_embeddings":
122
+ pointer = getattr(pointer, "weight")
123
+ elif m_name == "kernel":
124
+ array = np.transpose(array)
125
+ try:
126
+ assert (
127
+ pointer.shape == array.shape
128
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
129
+ except AssertionError as e:
130
+ e.args += (pointer.shape, array.shape)
131
+ raise
132
+ logger.info(f"Initialize PyTorch weight {name}")
133
+ pointer.data = torch.from_numpy(array)
134
+ return model
135
+
136
+
137
+ class PrefixEncoder(torch.nn.Module):
138
+ """
139
+ The torch.nn model to encode the prefix
140
+ Input shape: (batch-size, prefix-length)
141
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
142
+ """
143
+
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ self.prefix_projection = config.prefix_projection
147
+ if self.prefix_projection:
148
+ # Use a two-layer MLP to encode the prefix
149
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
150
+ self.trans = torch.nn.Sequential(
151
+ torch.nn.Linear(config.hidden_size, config.hidden_size),
152
+ torch.nn.Tanh(),
153
+ torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
154
+ )
155
+ else:
156
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
157
+
158
+ def forward(self, prefix: torch.Tensor):
159
+ if self.prefix_projection:
160
+ prefix_tokens = self.embedding(prefix)
161
+ past_key_values = self.trans(prefix_tokens)
162
+ else:
163
+ past_key_values = self.embedding(prefix)
164
+ return past_key_values
165
+
166
+
167
+ @torch.jit.script
168
+ def gelu_impl(x):
169
+ """OpenAI's gelu implementation."""
170
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
171
+ (1.0 + 0.044715 * x * x)))
172
+
173
+
174
+ def gelu(x):
175
+ return gelu_impl(x)
176
+
177
+
178
+ class RotaryEmbedding(torch.nn.Module):
179
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
180
+ super().__init__()
181
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
182
+ inv_freq = inv_freq.half()
183
+ self.learnable = learnable
184
+ if learnable:
185
+ self.inv_freq = torch.nn.Parameter(inv_freq)
186
+ self.max_seq_len_cached = None
187
+ else:
188
+ self.register_buffer('inv_freq', inv_freq)
189
+ self.max_seq_len_cached = None
190
+ self.cos_cached = None
191
+ self.sin_cached = None
192
+ self.precision = precision
193
+
194
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
195
+ error_msgs):
196
+ pass
197
+
198
+ def forward(self, x, seq_dim=1, seq_len=None):
199
+ if seq_len is None:
200
+ seq_len = x.shape[seq_dim]
201
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
202
+ self.max_seq_len_cached = None if self.learnable else seq_len
203
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
204
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
205
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
206
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
207
+ if self.precision == torch.bfloat16:
208
+ emb = emb.float()
209
+
210
+ # [sx, 1 (b * np), hn]
211
+ cos_cached = emb.cos()[:, None, :]
212
+ sin_cached = emb.sin()[:, None, :]
213
+ if self.precision == torch.bfloat16:
214
+ cos_cached = cos_cached.bfloat16()
215
+ sin_cached = sin_cached.bfloat16()
216
+ if self.learnable:
217
+ return cos_cached, sin_cached
218
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
219
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
220
+
221
+ def _apply(self, fn):
222
+ if self.cos_cached is not None:
223
+ self.cos_cached = fn(self.cos_cached)
224
+ if self.sin_cached is not None:
225
+ self.sin_cached = fn(self.sin_cached)
226
+ return super()._apply(fn)
227
+
228
+ def rotate_half(x):
229
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
230
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
231
+
232
+
233
+ @torch.jit.script
234
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
235
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
236
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
237
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
238
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
239
+ return q, k
240
+
241
+
242
+ def attention_fn(
243
+ self,
244
+ query_layer,
245
+ key_layer,
246
+ value_layer,
247
+ attention_mask,
248
+ hidden_size_per_partition,
249
+ layer_id,
250
+ layer_past=None,
251
+ scaling_attention_score=True,
252
+ use_cache=False,
253
+ ):
254
+ if layer_past is not None:
255
+ past_key, past_value = layer_past[0], layer_past[1]
256
+ key_layer = torch.cat((past_key, key_layer), dim=0)
257
+ value_layer = torch.cat((past_value, value_layer), dim=0)
258
+
259
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
260
+ seq_len, b, nh, hidden_size = key_layer.shape
261
+
262
+ if use_cache:
263
+ present = (key_layer, value_layer)
264
+ else:
265
+ present = None
266
+
267
+ query_key_layer_scaling_coeff = float(layer_id + 1)
268
+ if scaling_attention_score:
269
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
270
+
271
+ # ===================================
272
+ # Raw attention scores. [b, np, s, s]
273
+ # ===================================
274
+
275
+ # [b, np, sq, sk]
276
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
277
+
278
+ # [sq, b, np, hn] -> [sq, b * np, hn]
279
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
280
+ # [sk, b, np, hn] -> [sk, b * np, hn]
281
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
282
+
283
+ matmul_result = torch.zeros(
284
+ 1, 1, 1,
285
+ dtype=query_layer.dtype,
286
+ device=query_layer.device,
287
+ )
288
+
289
+ matmul_result = torch.baddbmm(
290
+ matmul_result,
291
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
292
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
293
+ beta=0.0,
294
+ alpha=1.0,
295
+ )
296
+
297
+ # change view to [b, np, sq, sk]
298
+ attention_scores = matmul_result.view(*output_size)
299
+
300
+ if self.scale_mask_softmax:
301
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
302
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
303
+ else:
304
+ if not (attention_mask == 0).all():
305
+ # if auto-regressive, skip
306
+ attention_scores.masked_fill_(attention_mask, -10000.0)
307
+ dtype = attention_scores.dtype
308
+ attention_scores = attention_scores.float()
309
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
310
+
311
+ attention_probs = F.softmax(attention_scores, dim=-1)
312
+
313
+ attention_probs = attention_probs.type(dtype)
314
+
315
+ # =========================
316
+ # Context layer. [sq, b, hp]
317
+ # =========================
318
+
319
+ # value_layer -> context layer.
320
+ # [sk, b, np, hn] --> [b, np, sq, hn]
321
+
322
+ # context layer shape: [b, np, sq, hn]
323
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
324
+
325
+ # change view [sk, b * np, hn]
326
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
327
+
328
+ # change view [b * np, sq, sk]
329
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
330
+
331
+ # matmul: [b * np, sq, hn]
332
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
333
+
334
+ # change view [b, np, sq, hn]
335
+ context_layer = context_layer.view(*output_size)
336
+
337
+ # [b, np, sq, hn] --> [sq, b, np, hn]
338
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
339
+
340
+ # [sq, b, np, hn] --> [sq, b, hp]
341
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
342
+ context_layer = context_layer.view(*new_context_layer_shape)
343
+
344
+ outputs = (context_layer, present, attention_probs)
345
+
346
+ return outputs
347
+
348
+
349
+ def default_init(cls, *args, **kwargs):
350
+ return cls(*args, **kwargs)
351
+
352
+
353
+ class SelfAttention(torch.nn.Module):
354
+ def __init__(self, hidden_size, num_attention_heads,
355
+ layer_id, hidden_size_per_attention_head=None, bias=True,
356
+ params_dtype=torch.float, position_encoding_2d=True, empty_init=True):
357
+ if empty_init:
358
+ init_method = skip_init
359
+ else:
360
+ init_method = default_init
361
+ super(SelfAttention, self).__init__()
362
+
363
+ self.layer_id = layer_id
364
+ self.hidden_size = hidden_size
365
+ self.hidden_size_per_partition = hidden_size
366
+ self.num_attention_heads = num_attention_heads
367
+ self.num_attention_heads_per_partition = num_attention_heads
368
+ self.position_encoding_2d = position_encoding_2d
369
+ self.rotary_emb = RotaryEmbedding(
370
+ self.hidden_size // (self.num_attention_heads * 2)
371
+ if position_encoding_2d
372
+ else self.hidden_size // self.num_attention_heads,
373
+ base=10000,
374
+ precision=torch.half,
375
+ learnable=False,
376
+ )
377
+
378
+ self.scale_mask_softmax = None
379
+
380
+ if hidden_size_per_attention_head is None:
381
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
382
+ else:
383
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
384
+
385
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
386
+
387
+ # Strided linear layer.
388
+ self.query_key_value = init_method(
389
+ torch.nn.Linear,
390
+ hidden_size,
391
+ 3 * self.inner_hidden_size,
392
+ bias=bias,
393
+ dtype=params_dtype,
394
+ )
395
+
396
+ self.dense = init_method(
397
+ torch.nn.Linear,
398
+ self.inner_hidden_size,
399
+ hidden_size,
400
+ bias=bias,
401
+ dtype=params_dtype,
402
+ )
403
+
404
+ @staticmethod
405
+ def attention_mask_func(attention_scores, attention_mask):
406
+ attention_scores.masked_fill_(attention_mask, -10000.0)
407
+ return attention_scores
408
+
409
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
410
+ contiguous_split_chunks=False):
411
+ """Split a tensor along its last dimension.
412
+ Arguments:
413
+ tensor: input tensor.
414
+ num_partitions: number of partitions to split the tensor
415
+ contiguous_split_chunks: If True, make each chunk contiguous
416
+ in memory.
417
+ """
418
+ # Get the size and dimension.
419
+ last_dim = tensor.dim() - 1
420
+ last_dim_size = tensor.size()[last_dim] // num_partitions
421
+ # Split.
422
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
423
+ # Note: torch.split does not create contiguous tensors by default.
424
+ if contiguous_split_chunks:
425
+ return tuple(chunk.contiguous() for chunk in tensor_list)
426
+
427
+ return tensor_list
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ position_ids,
433
+ attention_mask: torch.Tensor,
434
+ layer_id,
435
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
436
+ use_cache: bool = False,
437
+ output_attentions: bool = False,
438
+ ):
439
+ """
440
+ hidden_states: [seq_len, batch, hidden_size]
441
+ attention_mask: [(1, 1), seq_len, seq_len]
442
+ """
443
+
444
+ # [seq_len, batch, 3 * hidden_size]
445
+ mixed_raw_layer = self.query_key_value(hidden_states)
446
+
447
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
448
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
449
+ self.num_attention_heads_per_partition,
450
+ 3 * self.hidden_size_per_attention_head,
451
+ )
452
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
453
+
454
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
455
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
456
+
457
+ if self.position_encoding_2d:
458
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
459
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
460
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
461
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
462
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
463
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
464
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
465
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
466
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
467
+ else:
468
+ position_ids = position_ids.transpose(0, 1)
469
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
470
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
471
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
472
+
473
+ # [seq_len, batch, hidden_size]
474
+ context_layer, present, attention_probs = attention_fn(
475
+ self=self,
476
+ query_layer=query_layer,
477
+ key_layer=key_layer,
478
+ value_layer=value_layer,
479
+ attention_mask=attention_mask,
480
+ hidden_size_per_partition=self.hidden_size_per_partition,
481
+ layer_id=layer_id,
482
+ layer_past=layer_past,
483
+ use_cache=use_cache
484
+ )
485
+
486
+ output = self.dense(context_layer)
487
+
488
+ outputs = (output, present)
489
+
490
+ if output_attentions:
491
+ outputs += (attention_probs,)
492
+
493
+ return outputs # output, present, attention_probs
494
+
495
+
496
+ class GEGLU(torch.nn.Module):
497
+ def __init__(self):
498
+ super().__init__()
499
+ self.activation_fn = F.gelu
500
+
501
+ def forward(self, x):
502
+ # dim=-1 breaks in jit for pt<1.10
503
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
504
+ return x1 * self.activation_fn(x2)
505
+
506
+
507
+ class GLU(torch.nn.Module):
508
+ def __init__(self, hidden_size, inner_hidden_size=None,
509
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float, empty_init=True):
510
+ super(GLU, self).__init__()
511
+ if empty_init:
512
+ init_method = skip_init
513
+ else:
514
+ init_method = default_init
515
+ self.layer_id = layer_id
516
+ self.activation_func = activation_func
517
+
518
+ # Project to 4h.
519
+ self.hidden_size = hidden_size
520
+ if inner_hidden_size is None:
521
+ inner_hidden_size = 4 * hidden_size
522
+ self.inner_hidden_size = inner_hidden_size
523
+ self.dense_h_to_4h = init_method(
524
+ torch.nn.Linear,
525
+ self.hidden_size,
526
+ self.inner_hidden_size,
527
+ bias=bias,
528
+ dtype=params_dtype,
529
+ )
530
+ # Project back to h.
531
+ self.dense_4h_to_h = init_method(
532
+ torch.nn.Linear,
533
+ self.inner_hidden_size,
534
+ self.hidden_size,
535
+ bias=bias,
536
+ dtype=params_dtype,
537
+ )
538
+
539
+ def forward(self, hidden_states):
540
+ """
541
+ hidden_states: [seq_len, batch, hidden_size]
542
+ """
543
+
544
+ # [seq_len, batch, inner_hidden_size]
545
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
546
+
547
+ intermediate_parallel = self.activation_func(intermediate_parallel)
548
+
549
+ output = self.dense_4h_to_h(intermediate_parallel)
550
+
551
+ return output
552
+
553
+
554
+ class GLMBlock(torch.nn.Module):
555
+ def __init__(
556
+ self,
557
+ hidden_size,
558
+ num_attention_heads,
559
+ layernorm_epsilon,
560
+ layer_id,
561
+ inner_hidden_size=None,
562
+ hidden_size_per_attention_head=None,
563
+ layernorm=LayerNorm,
564
+ use_bias=True,
565
+ params_dtype=torch.float,
566
+ num_layers=28,
567
+ position_encoding_2d=True,
568
+ empty_init=True
569
+ ):
570
+ super(GLMBlock, self).__init__()
571
+ # Set output layer initialization if not provided.
572
+
573
+ self.layer_id = layer_id
574
+
575
+ # Layernorm on the input data.
576
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
577
+
578
+ self.position_encoding_2d = position_encoding_2d
579
+
580
+ # Self attention.
581
+ self.attention = SelfAttention(
582
+ hidden_size,
583
+ num_attention_heads,
584
+ layer_id,
585
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
586
+ bias=use_bias,
587
+ params_dtype=params_dtype,
588
+ position_encoding_2d=self.position_encoding_2d,
589
+ empty_init=empty_init
590
+ )
591
+
592
+ # Layernorm on the input data.
593
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
594
+
595
+ self.num_layers = num_layers
596
+
597
+ # GLU
598
+ self.mlp = GLU(
599
+ hidden_size,
600
+ inner_hidden_size=inner_hidden_size,
601
+ bias=use_bias,
602
+ layer_id=layer_id,
603
+ params_dtype=params_dtype,
604
+ empty_init=empty_init
605
+ )
606
+
607
+ def forward(
608
+ self,
609
+ hidden_states: torch.Tensor,
610
+ position_ids,
611
+ attention_mask: torch.Tensor,
612
+ layer_id,
613
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
614
+ use_cache: bool = False,
615
+ output_attentions: bool = False,
616
+ ):
617
+ """
618
+ hidden_states: [seq_len, batch, hidden_size]
619
+ attention_mask: [(1, 1), seq_len, seq_len]
620
+ """
621
+
622
+ # Layer norm at the begining of the transformer layer.
623
+ # [seq_len, batch, hidden_size]
624
+ attention_input = self.input_layernorm(hidden_states)
625
+
626
+ # Self attention.
627
+ attention_outputs = self.attention(
628
+ attention_input,
629
+ position_ids,
630
+ attention_mask=attention_mask,
631
+ layer_id=layer_id,
632
+ layer_past=layer_past,
633
+ use_cache=use_cache,
634
+ output_attentions=output_attentions
635
+ )
636
+
637
+ attention_output = attention_outputs[0]
638
+
639
+ outputs = attention_outputs[1:]
640
+
641
+ # Residual connection.
642
+ alpha = (2 * self.num_layers) ** 0.5
643
+ hidden_states = attention_input * alpha + attention_output
644
+
645
+ mlp_input = self.post_attention_layernorm(hidden_states)
646
+
647
+ # MLP.
648
+ mlp_output = self.mlp(mlp_input)
649
+
650
+ # Second residual connection.
651
+ output = mlp_input * alpha + mlp_output
652
+
653
+ if use_cache:
654
+ outputs = (output,) + outputs
655
+ else:
656
+ outputs = (output,) + outputs[1:]
657
+
658
+ return outputs # hidden_states, present, attentions
659
+
660
+
661
+ class ChatGLMPreTrainedModel(PreTrainedModel):
662
+ """
663
+ An abstract class to handle weights initialization and
664
+ a simple interface for downloading and loading pretrained models.
665
+ """
666
+
667
+ is_parallelizable = False
668
+ supports_gradient_checkpointing = True
669
+ config_class = ChatGLMConfig
670
+ base_model_prefix = "transformer"
671
+ _no_split_modules = ["GLMBlock"]
672
+
673
+ def __init__(self, *inputs, **kwargs):
674
+ super().__init__(*inputs, **kwargs)
675
+
676
+ def _init_weights(self, module: nn.Module):
677
+ """Initialize the weights."""
678
+ return
679
+
680
+ def get_masks(self, input_ids, device):
681
+ batch_size, seq_length = input_ids.shape
682
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
683
+ attention_mask = torch.ones((batch_size, seq_length, seq_length), device=device)
684
+ attention_mask.tril_()
685
+ for i, context_length in enumerate(context_lengths):
686
+ attention_mask[i, :, :context_length] = 1
687
+ attention_mask.unsqueeze_(1)
688
+ attention_mask = (attention_mask < 0.5).bool()
689
+
690
+ return attention_mask
691
+
692
+ def get_position_ids(self, input_ids, mask_positions, device, use_gmasks=None):
693
+ batch_size, seq_length = input_ids.shape
694
+ if use_gmasks is None:
695
+ use_gmasks = [False] * batch_size
696
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
697
+ if self.position_encoding_2d:
698
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
699
+ for i, context_length in enumerate(context_lengths):
700
+ position_ids[i, context_length:] = mask_positions[i]
701
+ block_position_ids = [torch.cat((
702
+ torch.zeros(context_length, dtype=torch.long, device=device),
703
+ torch.arange(seq_length - context_length, dtype=torch.long, device=device) + 1
704
+ )) for context_length in context_lengths]
705
+ block_position_ids = torch.stack(block_position_ids, dim=0)
706
+ position_ids = torch.stack((position_ids, block_position_ids), dim=1)
707
+ else:
708
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
709
+ for i, context_length in enumerate(context_lengths):
710
+ if not use_gmasks[i]:
711
+ position_ids[context_length:] = mask_positions[i]
712
+
713
+ return position_ids
714
+
715
+ def _set_gradient_checkpointing(self, module, value=False):
716
+ if isinstance(module, ChatGLMModel):
717
+ module.gradient_checkpointing = value
718
+
719
+
720
+ CHATGLM_6B_START_DOCSTRING = r"""
721
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
722
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
723
+ usage and behavior.
724
+
725
+ Parameters:
726
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
727
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
728
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
729
+ """
730
+
731
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
732
+ Args:
733
+ input_ids (`torch.LongTensor` of shape `({0})`):
734
+ Indices of input sequence tokens in the vocabulary.
735
+
736
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
737
+ See [`PreTrainedTokenizer.encode`] and
738
+ [`PreTrainedTokenizer.__call__`] for details.
739
+
740
+ [What are input IDs?](../glossary#input-ids)
741
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
742
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
743
+
744
+ - 1 for tokens that are **not masked**,
745
+ - 0 for tokens that are **masked**.
746
+
747
+ [What are attention masks?](../glossary#attention-mask)
748
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
749
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
750
+
751
+ - 0 corresponds to a *sentence A* token,
752
+ - 1 corresponds to a *sentence B* token.
753
+
754
+ [What are token type IDs?](../glossary#token-type-ids)
755
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
756
+ Indices of positions of each input sequence tokens in the position embeddings.
757
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
758
+
759
+ [What are position IDs?](../glossary#position-ids)
760
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
761
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
762
+
763
+ - 1 indicates the head is **not masked**,
764
+ - 0 indicates the head is **masked**.
765
+
766
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
767
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
768
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
769
+ than the model's internal embedding lookup matrix.
770
+ output_attentions (`bool`, *optional*):
771
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
772
+ tensors for more detail.
773
+ output_hidden_states (`bool`, *optional*):
774
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
775
+ more detail.
776
+ return_dict (`bool`, *optional*):
777
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
778
+ """
779
+
780
+
781
+ @add_start_docstrings(
782
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
783
+ CHATGLM_6B_START_DOCSTRING,
784
+ )
785
+ class ChatGLMModel(ChatGLMPreTrainedModel):
786
+ """
787
+
788
+ The model can behave as an encoder (with only self-attention) as well
789
+ as a decoder, in which case a layer of cross-attention is added between
790
+ the self-attention layers, following the architecture described in [Attention is
791
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
792
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
793
+
794
+ To behave as an decoder the model needs to be initialized with the
795
+ `is_decoder` argument of the configuration set to `True`.
796
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
797
+ argument and `add_cross_attention` set to `True`; an
798
+ `encoder_hidden_states` is then expected as an input to the forward pass.
799
+ """
800
+
801
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
802
+ super().__init__(config)
803
+ if empty_init:
804
+ init_method = skip_init
805
+ else:
806
+ init_method = default_init
807
+ # recording parameters
808
+ self.max_sequence_length = config.max_sequence_length
809
+ self.hidden_size = config.hidden_size
810
+ self.params_dtype = torch.half
811
+ self.num_attention_heads = config.num_attention_heads
812
+ self.vocab_size = config.vocab_size
813
+ self.num_layers = config.num_layers
814
+ self.layernorm_epsilon = config.layernorm_epsilon
815
+ self.inner_hidden_size = config.inner_hidden_size
816
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
817
+ self.position_encoding_2d = config.position_encoding_2d
818
+ self.pre_seq_len = config.pre_seq_len
819
+ self.prefix_projection = config.prefix_projection
820
+
821
+ self.word_embeddings = init_method(
822
+ torch.nn.Embedding,
823
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
824
+ dtype=self.params_dtype
825
+ )
826
+ self.gradient_checkpointing = False
827
+
828
+ def get_layer(layer_id):
829
+ return GLMBlock(
830
+ self.hidden_size,
831
+ self.num_attention_heads,
832
+ self.layernorm_epsilon,
833
+ layer_id,
834
+ inner_hidden_size=self.inner_hidden_size,
835
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
836
+ layernorm=LayerNorm,
837
+ use_bias=True,
838
+ params_dtype=self.params_dtype,
839
+ position_encoding_2d=self.position_encoding_2d,
840
+ empty_init=empty_init
841
+ )
842
+
843
+ self.layers = torch.nn.ModuleList(
844
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
845
+ )
846
+
847
+ # Final layer norm before output.
848
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
849
+
850
+ if self.pre_seq_len is not None:
851
+ for param in self.parameters():
852
+ param.requires_grad = False
853
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
854
+ self.prefix_encoder = PrefixEncoder(config)
855
+ self.dropout = torch.nn.Dropout(0.1)
856
+
857
+ # total_params = sum(p.numel() for p in self.parameters())
858
+ # trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
859
+ # print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
860
+
861
+ def get_input_embeddings(self):
862
+ return self.word_embeddings
863
+
864
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
865
+ self.word_embeddings = new_embeddings
866
+
867
+ def get_prompt(self, batch_size, device, dtype=torch.half):
868
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
869
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
870
+ past_key_values = past_key_values.view(
871
+ batch_size,
872
+ self.pre_seq_len,
873
+ self.num_layers * 2,
874
+ self.num_attention_heads,
875
+ self.hidden_size // self.num_attention_heads
876
+ )
877
+ # seq_len, b, nh, hidden_size
878
+ past_key_values = self.dropout(past_key_values)
879
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
880
+ # past_key_values = [(v[0], v[1]) for v in past_key_values]
881
+ return past_key_values
882
+
883
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
884
+ @add_code_sample_docstrings(
885
+ checkpoint=_CHECKPOINT_FOR_DOC,
886
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
887
+ config_class=_CONFIG_FOR_DOC,
888
+ )
889
+ def forward(
890
+ self,
891
+ input_ids: Optional[torch.LongTensor] = None,
892
+ position_ids: Optional[torch.LongTensor] = None,
893
+ attention_mask: Optional[torch.Tensor] = None,
894
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
895
+ inputs_embeds: Optional[torch.LongTensor] = None,
896
+ use_cache: Optional[bool] = None,
897
+ output_attentions: Optional[bool] = None,
898
+ output_hidden_states: Optional[bool] = None,
899
+ return_dict: Optional[bool] = None,
900
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
901
+
902
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
903
+ output_hidden_states = (
904
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
905
+ )
906
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
907
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
908
+
909
+ if self.gradient_checkpointing and self.training:
910
+ if use_cache:
911
+ logger.warning_once(
912
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
913
+ )
914
+ use_cache = False
915
+
916
+ if input_ids is not None and inputs_embeds is not None:
917
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
918
+ elif input_ids is not None:
919
+ batch_size, seq_length = input_ids.shape[:2]
920
+ elif inputs_embeds is not None:
921
+ batch_size, seq_length = inputs_embeds.shape[:2]
922
+ else:
923
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
924
+
925
+ if inputs_embeds is None:
926
+ inputs_embeds = self.word_embeddings(input_ids)
927
+
928
+ if past_key_values is None:
929
+ if self.pre_seq_len is not None:
930
+ past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device,
931
+ dtype=inputs_embeds.dtype)
932
+ else:
933
+ past_key_values = tuple([None] * len(self.layers))
934
+
935
+ if attention_mask is None:
936
+ attention_mask = self.get_masks(
937
+ input_ids,
938
+ device=input_ids.device
939
+ )
940
+
941
+
942
+ if position_ids is None:
943
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
944
+ seqs = input_ids.tolist()
945
+
946
+ mask_positions, use_gmasks = [], []
947
+ for seq in seqs:
948
+ mask_token = gMASK if gMASK in seq else MASK
949
+ use_gmask = mask_token == gMASK
950
+ mask_positions.append(seq.index(mask_token))
951
+ use_gmasks.append(use_gmask)
952
+
953
+ position_ids = self.get_position_ids(
954
+ input_ids,
955
+ mask_positions=mask_positions,
956
+ device=input_ids.device,
957
+ use_gmasks=use_gmasks
958
+ )
959
+
960
+ if self.pre_seq_len is not None and attention_mask is not None:
961
+ prefix_attention_mask = torch.ones(batch_size, 1, input_ids.size(-1), self.pre_seq_len).to(
962
+ attention_mask.device)
963
+ prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
964
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)
965
+
966
+ # [seq_len, batch, hidden_size]
967
+ hidden_states = inputs_embeds.transpose(0, 1)
968
+
969
+ presents = () if use_cache else None
970
+ all_self_attentions = () if output_attentions else None
971
+ all_hidden_states = () if output_hidden_states else None
972
+
973
+ if attention_mask is None:
974
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
975
+ else:
976
+ attention_mask = attention_mask.to(hidden_states.device)
977
+
978
+ for i, layer in enumerate(self.layers):
979
+
980
+ if output_hidden_states:
981
+ all_hidden_states = all_hidden_states + (hidden_states,)
982
+ layer_past = past_key_values[i]
983
+
984
+ if self.gradient_checkpointing and self.training:
985
+ layer_ret = torch.utils.checkpoint.checkpoint(
986
+ layer,
987
+ hidden_states,
988
+ position_ids,
989
+ attention_mask,
990
+ torch.tensor(i),
991
+ layer_past,
992
+ use_cache,
993
+ output_attentions
994
+ )
995
+ else:
996
+ layer_ret = layer(
997
+ hidden_states,
998
+ position_ids=position_ids,
999
+ attention_mask=attention_mask,
1000
+ layer_id=torch.tensor(i),
1001
+ layer_past=layer_past,
1002
+ use_cache=use_cache,
1003
+ output_attentions=output_attentions
1004
+ )
1005
+
1006
+ hidden_states = layer_ret[0]
1007
+
1008
+ if use_cache:
1009
+ presents = presents + (layer_ret[1],)
1010
+
1011
+ if output_attentions:
1012
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
1013
+
1014
+ # Final layer norm.
1015
+ hidden_states = self.final_layernorm(hidden_states)
1016
+
1017
+ if output_hidden_states:
1018
+ all_hidden_states = all_hidden_states + (hidden_states,)
1019
+
1020
+ if not return_dict:
1021
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1022
+
1023
+ return BaseModelOutputWithPast(
1024
+ last_hidden_state=hidden_states,
1025
+ past_key_values=presents,
1026
+ hidden_states=all_hidden_states,
1027
+ attentions=all_self_attentions,
1028
+ )
1029
+
1030
+
1031
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1032
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
1033
+ super().__init__(config)
1034
+ if empty_init:
1035
+ init_method = skip_init
1036
+ else:
1037
+ init_method = default_init
1038
+
1039
+ # self.hidden_size = config.hidden_size
1040
+ # self.params_dtype = torch.half
1041
+ # self.vocab_size = config.vocab_size
1042
+ self.max_sequence_length = config.max_sequence_length
1043
+
1044
+ self.position_encoding_2d = config.position_encoding_2d
1045
+
1046
+ self.transformer = ChatGLMModel(config, empty_init=empty_init)
1047
+
1048
+ self.lm_head = init_method(
1049
+ nn.Linear,
1050
+ config.hidden_size,
1051
+ config.vocab_size,
1052
+ bias=False,
1053
+ dtype=torch.half
1054
+ )
1055
+
1056
+ self.config = config
1057
+
1058
+ self.quantized = False
1059
+
1060
+ if self.config.quantization_bit:
1061
+ self.quantize(self.config.quantization_bit, self.config.quantization_embeddings, use_quantization_cache=True, empty_init=True)
1062
+
1063
+ def get_output_embeddings(self):
1064
+ return self.lm_head
1065
+
1066
+ def set_output_embeddings(self, new_embeddings):
1067
+ self.lm_head = new_embeddings
1068
+
1069
+ def _update_model_kwargs_for_generation(
1070
+ self,
1071
+ outputs: ModelOutput,
1072
+ model_kwargs: Dict[str, Any],
1073
+ is_encoder_decoder: bool = False,
1074
+ standardize_cache_format: bool = False,
1075
+ ) -> Dict[str, Any]:
1076
+ # update past_key_values
1077
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1078
+ outputs, standardize_cache_format=standardize_cache_format
1079
+ )
1080
+
1081
+ # update attention mask
1082
+ if "attention_mask" in model_kwargs:
1083
+ attention_mask = model_kwargs["attention_mask"]
1084
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1085
+ attention_mask = torch.cat(
1086
+ [attention_mask, attention_mask.new_ones((*attention_mask.shape[:3], 1))], dim=3)
1087
+ new_attention_mask = attention_mask[:, :, -1:].clone()
1088
+ new_attention_mask[..., -1] = False
1089
+ model_kwargs["attention_mask"] = torch.cat(
1090
+ [attention_mask, new_attention_mask], dim=2
1091
+ )
1092
+
1093
+ # update position ids
1094
+ if "position_ids" in model_kwargs:
1095
+ position_ids = model_kwargs["position_ids"]
1096
+ new_position_id = position_ids[..., -1:].clone()
1097
+ new_position_id[:, 1, :] += 1
1098
+ model_kwargs["position_ids"] = torch.cat(
1099
+ [position_ids, new_position_id], dim=-1
1100
+ )
1101
+
1102
+ return model_kwargs
1103
+
1104
+ def prepare_inputs_for_generation(
1105
+ self,
1106
+ input_ids: torch.LongTensor,
1107
+ past: Optional[torch.Tensor] = None,
1108
+ past_key_values: Optional[torch.Tensor] = None,
1109
+ attention_mask: Optional[torch.Tensor] = None,
1110
+ position_ids: Optional[torch.Tensor] = None,
1111
+ **kwargs
1112
+ ) -> dict:
1113
+ batch_size, seq_length = input_ids.shape
1114
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
1115
+ seqs = input_ids.tolist()
1116
+ mask_positions, use_gmasks = [], []
1117
+ for seq in seqs:
1118
+ mask_token = gMASK if gMASK in seq else MASK
1119
+ use_gmask = mask_token == gMASK
1120
+ mask_positions.append(seq.index(mask_token))
1121
+ use_gmasks.append(use_gmask)
1122
+
1123
+ # only last token for input_ids if past is not None
1124
+ if past is not None or past_key_values is not None:
1125
+ last_token = input_ids[:, -1].unsqueeze(-1)
1126
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1127
+ attention_mask = attention_mask[:, :, -1:]
1128
+ else:
1129
+ attention_mask = None
1130
+ if position_ids is not None:
1131
+ position_ids = position_ids[..., -1:]
1132
+ else:
1133
+ context_lengths = [seq.index(self.config.bos_token_id) for seq in seqs]
1134
+ if self.position_encoding_2d:
1135
+ position_ids = torch.tensor(
1136
+ [[mask_position, seq_length - context_length] for mask_position, context_length in
1137
+ zip(mask_positions, context_lengths)], dtype=torch.long, device=input_ids.device).unsqueeze(-1)
1138
+ else:
1139
+ position_ids = torch.tensor([mask_position for mask_position in mask_positions], dtype=torch.long,
1140
+ device=input_ids.device).unsqueeze(-1)
1141
+
1142
+ if past is None:
1143
+ past = past_key_values
1144
+ return {
1145
+ "input_ids": last_token,
1146
+ "past_key_values": past,
1147
+ "position_ids": position_ids,
1148
+ "attention_mask": attention_mask
1149
+ }
1150
+ else:
1151
+ if attention_mask is not None and attention_mask.dtype != torch.bool:
1152
+ logger.warning_once(f"The dtype of attention mask ({attention_mask.dtype}) is not bool")
1153
+ attention_mask = None
1154
+ if attention_mask is None:
1155
+ attention_mask = self.get_masks(
1156
+ input_ids,
1157
+ device=input_ids.device
1158
+ )
1159
+ if position_ids is None:
1160
+ position_ids = self.get_position_ids(
1161
+ input_ids,
1162
+ device=input_ids.device,
1163
+ mask_positions=mask_positions,
1164
+ use_gmasks=use_gmasks
1165
+ )
1166
+
1167
+ return {
1168
+ "input_ids": input_ids,
1169
+ "past_key_values": past,
1170
+ "position_ids": position_ids,
1171
+ "attention_mask": attention_mask
1172
+ }
1173
+
1174
+ def forward(
1175
+ self,
1176
+ input_ids: Optional[torch.Tensor] = None,
1177
+ position_ids: Optional[torch.Tensor] = None,
1178
+ attention_mask: Optional[torch.Tensor] = None,
1179
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1180
+ inputs_embeds: Optional[torch.Tensor] = None,
1181
+ labels: Optional[torch.Tensor] = None,
1182
+ use_cache: Optional[bool] = None,
1183
+ output_attentions: Optional[bool] = None,
1184
+ output_hidden_states: Optional[bool] = None,
1185
+ return_dict: Optional[bool] = None,
1186
+ ):
1187
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1188
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1189
+
1190
+ transformer_outputs = self.transformer(
1191
+ input_ids=input_ids,
1192
+ position_ids=position_ids,
1193
+ attention_mask=attention_mask,
1194
+ past_key_values=past_key_values,
1195
+ inputs_embeds=inputs_embeds,
1196
+ use_cache=use_cache,
1197
+ output_attentions=output_attentions,
1198
+ output_hidden_states=output_hidden_states,
1199
+ return_dict=return_dict,
1200
+ )
1201
+
1202
+ hidden_states = transformer_outputs[0]
1203
+
1204
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1205
+
1206
+ loss = None
1207
+ if labels is not None:
1208
+ lm_logits = lm_logits.to(torch.float32)
1209
+
1210
+ # Shift so that tokens < n predict n
1211
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1212
+ shift_labels = labels[..., 1:].contiguous()
1213
+ # Flatten the tokens
1214
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1215
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1216
+
1217
+ lm_logits = lm_logits.to(hidden_states.dtype)
1218
+ loss = loss.to(hidden_states.dtype)
1219
+
1220
+ if not return_dict:
1221
+ output = (lm_logits,) + transformer_outputs[1:]
1222
+ return ((loss,) + output) if loss is not None else output
1223
+
1224
+ return CausalLMOutputWithPast(
1225
+ loss=loss,
1226
+ logits=lm_logits,
1227
+ past_key_values=transformer_outputs.past_key_values,
1228
+ hidden_states=transformer_outputs.hidden_states,
1229
+ attentions=transformer_outputs.attentions,
1230
+ )
1231
+
1232
+ @staticmethod
1233
+ def _reorder_cache(
1234
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1235
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1236
+ """
1237
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1238
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1239
+ beam_idx at every generation step.
1240
+
1241
+ Output shares the same memory storage as `past`.
1242
+ """
1243
+ return tuple(
1244
+ (
1245
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1246
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1247
+ )
1248
+ for layer_past in past
1249
+ )
1250
+
1251
+ def process_response(self, response):
1252
+ response = response.strip()
1253
+ response = response.replace("[[训练时间]]", "2023年")
1254
+ punkts = [
1255
+ [",", ","],
1256
+ ["!", "!"],
1257
+ [":", ":"],
1258
+ [";", ";"],
1259
+ ["\?", "?"],
1260
+ ]
1261
+ for item in punkts:
1262
+ response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
1263
+ response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
1264
+ return response
1265
+
1266
+ @torch.no_grad()
1267
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1268
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1269
+ if history is None:
1270
+ history = []
1271
+ if logits_processor is None:
1272
+ logits_processor = LogitsProcessorList()
1273
+ logits_processor.append(InvalidScoreLogitsProcessor())
1274
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1275
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1276
+ if not history:
1277
+ prompt = query
1278
+ else:
1279
+ prompt = ""
1280
+ for i, (old_query, response) in enumerate(history):
1281
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1282
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1283
+ inputs = tokenizer([prompt], return_tensors="pt")
1284
+ inputs = inputs.to(self.device)
1285
+ outputs = self.generate(**inputs, **gen_kwargs)
1286
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1287
+ response = tokenizer.decode(outputs)
1288
+ response = self.process_response(response)
1289
+ history = history + [(query, response)]
1290
+ return response, history
1291
+
1292
+ @torch.no_grad()
1293
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
1294
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1295
+ if history is None:
1296
+ history = []
1297
+ if logits_processor is None:
1298
+ logits_processor = LogitsProcessorList()
1299
+ logits_processor.append(InvalidScoreLogitsProcessor())
1300
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1301
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1302
+ if not history:
1303
+ prompt = query
1304
+ else:
1305
+ prompt = ""
1306
+ for i, (old_query, response) in enumerate(history):
1307
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1308
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1309
+ inputs = tokenizer([prompt], return_tensors="pt")
1310
+ inputs = inputs.to(self.device)
1311
+ for outputs in self.stream_generate(**inputs, **gen_kwargs):
1312
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1313
+ response = tokenizer.decode(outputs)
1314
+ response = self.process_response(response)
1315
+ new_history = history + [(query, response)]
1316
+ yield response, new_history
1317
+
1318
+ @torch.no_grad()
1319
+ def stream_generate(
1320
+ self,
1321
+ input_ids,
1322
+ generation_config: Optional[GenerationConfig] = None,
1323
+ logits_processor: Optional[LogitsProcessorList] = None,
1324
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1325
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1326
+ **kwargs,
1327
+ ):
1328
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1329
+
1330
+ if generation_config is None:
1331
+ generation_config = self.generation_config
1332
+ generation_config = copy.deepcopy(generation_config)
1333
+ model_kwargs = generation_config.update(**kwargs)
1334
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1335
+
1336
+ if isinstance(eos_token_id, int):
1337
+ eos_token_id = [eos_token_id]
1338
+
1339
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1340
+ if has_default_max_length and generation_config.max_new_tokens is None:
1341
+ warnings.warn(
1342
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1343
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1344
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1345
+ UserWarning,
1346
+ )
1347
+ elif generation_config.max_new_tokens is not None:
1348
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1349
+ if not has_default_max_length:
1350
+ logger.warn(
1351
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1352
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1353
+ "Please refer to the documentation for more information. "
1354
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1355
+ UserWarning,
1356
+ )
1357
+
1358
+ if input_ids_seq_length >= generation_config.max_length:
1359
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1360
+ logger.warning(
1361
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1362
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1363
+ " increasing `max_new_tokens`."
1364
+ )
1365
+
1366
+ # 2. Set generation parameters if not already defined
1367
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1368
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1369
+
1370
+ logits_processor = self._get_logits_processor(
1371
+ generation_config=generation_config,
1372
+ input_ids_seq_length=input_ids_seq_length,
1373
+ encoder_input_ids=input_ids,
1374
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1375
+ logits_processor=logits_processor,
1376
+ )
1377
+
1378
+ stopping_criteria = self._get_stopping_criteria(
1379
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1380
+ )
1381
+ logits_warper = self._get_logits_warper(generation_config)
1382
+
1383
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1384
+ scores = None
1385
+ while True:
1386
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1387
+ # forward pass to get next token
1388
+ outputs = self(
1389
+ **model_inputs,
1390
+ return_dict=True,
1391
+ output_attentions=False,
1392
+ output_hidden_states=False,
1393
+ )
1394
+
1395
+ next_token_logits = outputs.logits[:, -1, :]
1396
+
1397
+ # pre-process distribution
1398
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1399
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1400
+
1401
+ # sample
1402
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1403
+ if generation_config.do_sample:
1404
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1405
+ else:
1406
+ next_tokens = torch.argmax(probs, dim=-1)
1407
+
1408
+ # update generated ids, model inputs, and length for next step
1409
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1410
+ model_kwargs = self._update_model_kwargs_for_generation(
1411
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1412
+ )
1413
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1414
+
1415
+ # stop when each sentence is finished, or if we exceed the maximum length
1416
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1417
+ break
1418
+ yield input_ids
1419
+
1420
+ def quantize(self, bits: int, quantize_embeddings=False, use_quantization_cache=False, empty_init=False, **kwargs):
1421
+ if bits == 0:
1422
+ return
1423
+
1424
+ from .quantization import quantize, QuantizedEmbedding, QuantizedLinear, load_cpu_kernel
1425
+
1426
+ if self.quantized:
1427
+ if self.device == torch.device("cpu"):
1428
+ logger.info("Already quantized, reloading cpu kernel.")
1429
+ load_cpu_kernel(**kwargs)
1430
+ else:
1431
+ logger.info("Already quantized.")
1432
+ return self
1433
+
1434
+ self.quantized = True
1435
+
1436
+ self.config.quantization_bit = bits
1437
+ self.config.quantization_embeddings = quantize_embeddings
1438
+
1439
+ self.transformer = quantize(self.transformer, bits, use_quantization_cache=use_quantization_cache, empty_init=empty_init, **kwargs)
1440
+
1441
+ if self.device == torch.device("cpu"):
1442
+ dtype = torch.float32
1443
+ else:
1444
+ dtype = torch.half
1445
+
1446
+ if quantize_embeddings:
1447
+ logger.info("Applying quantization to embeddings")
1448
+ self.transformer.word_embeddings = QuantizedEmbedding(
1449
+ weight_bit_width=bits,
1450
+ weight_tensor=self.transformer.word_embeddings.weight.to(self.device),
1451
+ num_embeddings=self.transformer.word_embeddings.num_embeddings,
1452
+ embedding_dim=self.transformer.word_embeddings.embedding_dim,
1453
+ dtype=dtype,
1454
+ empty_init=empty_init,
1455
+ device=self.transformer.word_embeddings.weight.device,
1456
+ )
1457
+ self.lm_head = QuantizedLinear(
1458
+ weight_bit_width=bits,
1459
+ weight_tensor=self.lm_head.weight.to(self.device),
1460
+ bias_tensor=None,
1461
+ in_features=self.lm_head.in_features,
1462
+ out_features=self.lm_head.out_features,
1463
+ bias=False,
1464
+ quantized_weight=self.transformer.word_embeddings.weight,
1465
+ quantized_weight_scale=self.transformer.word_embeddings.weight_scale,
1466
+ dtype=dtype,
1467
+ empty_init=empty_init,
1468
+ device=self.lm_head.weight.device,
1469
+ )
1470
+
1471
+ return self
xiaowo/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7736d0582427d706ac424dcfe385990b4ba35f6481b446ae1fcaf041cc5e662
3
+ size 234882351
xiaowo/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c64795fba60fdadcfd8791a3b5dd9fd877febb3c560b99a25aab42b8118421d5
3
+ size 117441341
xiaowo/quantization.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear, Embedding
2
+ from torch.nn.parameter import Parameter
3
+ import torch.nn.functional as F
4
+
5
+ import os
6
+ import bz2
7
+ import torch
8
+ import base64
9
+ import ctypes
10
+ import sys
11
+ from transformers.utils import logging
12
+
13
+ from typing import List
14
+ from functools import partial
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ try:
19
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
20
+
21
+
22
+ class Kernel:
23
+ def __init__(self, code: bytes, function_names: List[str]):
24
+ self.code = code
25
+ self._function_names = function_names
26
+ self._cmodule = LazyKernelCModule(self.code)
27
+
28
+ for name in self._function_names:
29
+ setattr(self, name, KernelFunction(self._cmodule, name))
30
+
31
+
32
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00B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wwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
33
+
34
+ kernels = Kernel(
35
+ bz2.decompress(base64.b64decode(quantization_code)),
36
+ [
37
+ "int4WeightCompression",
38
+ "int4WeightExtractionFloat",
39
+ "int4WeightExtractionHalf",
40
+ "int8WeightExtractionFloat",
41
+ "int8WeightExtractionHalf",
42
+ ],
43
+ )
44
+ except Exception as exception:
45
+ kernels = None
46
+ logger.warning("Failed to load cpm_kernels:", exception)
47
+
48
+
49
+ class W8A16Linear(torch.autograd.Function):
50
+ @staticmethod
51
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
52
+ ctx.inp_shape = inp.size()
53
+ ctx.weight_bit_width = weight_bit_width
54
+ out_features = quant_w.size(0)
55
+ inp = inp.contiguous().view(-1, inp.size(-1))
56
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
57
+ ctx.weight_shape = weight.size()
58
+ output = inp.mm(weight.t())
59
+ ctx.save_for_backward(inp, quant_w, scale_w)
60
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
61
+
62
+ @staticmethod
63
+ def backward(ctx, grad_output: torch.Tensor):
64
+ inp, quant_w, scale_w = ctx.saved_tensors
65
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
66
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
67
+ grad_input = grad_output.mm(weight)
68
+ grad_weight = grad_output.t().mm(inp)
69
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
70
+
71
+
72
+ class W8A16LinearCPU(torch.autograd.Function):
73
+ @staticmethod
74
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width,
75
+ quantization_cache=None):
76
+ ctx.inp_shape = inp.size()
77
+ ctx.weight_bit_width = weight_bit_width
78
+ out_features = quant_w.size(0)
79
+ inp = inp.contiguous().view(-1, inp.size(-1))
80
+ weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache)
81
+ ctx.weight_shape = weight.size()
82
+ output = inp.mm(weight.t())
83
+ ctx.save_for_backward(inp, quant_w, scale_w)
84
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
85
+
86
+ @staticmethod
87
+ def backward(ctx, grad_output: torch.Tensor):
88
+ inp, quant_w, scale_w = ctx.saved_tensors
89
+ weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width)
90
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
91
+ grad_input = grad_output.mm(weight)
92
+ grad_weight = grad_output.t().mm(inp)
93
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
94
+
95
+
96
+ default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c")
97
+ default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg"
98
+ default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
99
+ "quantization_kernels_parallel.c")
100
+ default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWUzax5EAALXbgERwSX1mTwAAr/ff3kACNyXUbZYwBpoaNGIyAaADQwRSaVP9QoMg0A2oAPU0AEUkU9GaaKMaQB6gA09T1ARRKnpk0niaJkaaNDJ6g0DTIKVKfZ/g6v1Kem5LJLa0WmkukkuCIHUqWbtJGJMsCSQFiPEIYHgBIZDzR8R6REbYxIqD2Cu7lMkFoPu6LmHeOAy0GF83Tc40jgmTs4HnCe60QfJa2bDBZ0Y1lhgbiZjW8SNsAKCk42UOEdjWN3KoiCIYeQUCCKWIyHewhtSoInLKSG22l4jKM2ZDCVKtBm3OTYBl3jsVqMImtj7PQw7xKxLXQzwgJaPPgW1fRhrvPJICl4YFDYfNbkbBh5JDgrazFml50xEQQwQUjxNwE0IDSofLzSg7UNVKn+Rr1KErzBHUxBqdHRlXzqYsIa5K9Y0UuE2ugw3g5KYofm7AaGNTzJSMhcchhxdaU4JZ0F1UNgQ8XcGDguypqYza8yFaEoGgNRcLej+g2t0feGKFE5OY2PFluQ3q4HgycxlfvzHqo0KcM0JI8OKXtzayJFgsqC1NdUQVu8rChnA6FO3MFyGOoC9KO8ITPpYM5pRqTlczFkLES/4u5IpwoSCZtY8i"
101
+
102
+ cpu_kernels = None
103
+
104
+
105
+ class CPUKernel:
106
+ def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None,
107
+ parallel_num=None):
108
+ self.load = False
109
+ self.int8WeightExtractionFloat = None
110
+ self.int4WeightExtractionFloat = None
111
+ self.int4WeightCompression = None
112
+ self.SetNumThreads = lambda x: x
113
+
114
+ try:
115
+ if not os.path.exists(default_cpu_kernel_code_path):
116
+ with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file:
117
+ code = default_cpu_kernel_code
118
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
119
+ file.write(cpu_quantization_code)
120
+
121
+ if not os.path.exists(default_cpu_parallel_kernel_code_path):
122
+ with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file:
123
+ code = default_cpu_parallel_kernel_code
124
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
125
+ file.write(cpu_quantization_code)
126
+
127
+ except Exception as ex:
128
+ print("Error when generating default cpu kernel code(can be ignored when using custom kernels).")
129
+
130
+ if compile_parallel_kernel is None:
131
+ compile_parallel_kernel = bool(int(os.cpu_count()) >= 4)
132
+
133
+ if compile_parallel_kernel and source_code == default_cpu_kernel_code_path:
134
+ source_code = default_cpu_parallel_kernel_code_path
135
+
136
+ kernels = None
137
+
138
+ if (not kernel_file) or (not os.path.exists(kernel_file)):
139
+ print("No compiled kernel found.")
140
+ try:
141
+ if os.path.exists(source_code):
142
+ print("Compiling kernels :", source_code)
143
+ kernel_file = source_code[:-2] + ".so"
144
+
145
+ if compile_parallel_kernel:
146
+ if sys.platform != 'darwin':
147
+ compile_command = "gcc -O3 -fPIC -pthread -fopenmp -std=c99 {} -shared -o {}".format(
148
+ source_code, kernel_file)
149
+ else:
150
+ compile_command = "clang -O3 -fPIC -pthread -Xclang -fopenmp -lomp -std=c99 {} -shared -o {}".format(
151
+ source_code, kernel_file)
152
+ print("Compiling", compile_command)
153
+ exit_state = os.system(compile_command)
154
+ if not exit_state:
155
+ try:
156
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
157
+ print("Load kernel :", kernel_file)
158
+ except:
159
+ kernels = None
160
+ print("Load parallel cpu kernel failed, using default cpu kernel code:")
161
+ import traceback
162
+ exception = traceback.format_exc()
163
+ print(exception)
164
+ else:
165
+ print("Compile default cpu kernel failed, using default cpu kernel code.")
166
+
167
+ if kernels is None: # adjust config, use default cpu kernel
168
+ compile_parallel_kernel = False
169
+ source_code = default_cpu_kernel_code_path
170
+ kernel_file = source_code[:-2] + ".so"
171
+
172
+ if kernels is None:
173
+ compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
174
+ print("Compiling", compile_command)
175
+ exit_state = os.system(compile_command)
176
+ if not exit_state:
177
+ try:
178
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
179
+ print("Load kernel :", kernel_file)
180
+ except:
181
+ kernels = None
182
+ print("Load default cpu kernel failed:")
183
+ import traceback
184
+ exception = traceback.format_exc()
185
+ print(exception)
186
+ else:
187
+ print("Compile default cpu kernel failed.")
188
+ else:
189
+ print("Kernel source code not found.")
190
+ return
191
+ except:
192
+ print("Failed to build cpu kernel:")
193
+ import traceback
194
+ exception = traceback.format_exc()
195
+ print(exception)
196
+ return
197
+ else:
198
+ try:
199
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
200
+ print("Load kernel :", kernel_file)
201
+ except:
202
+ kernels = None
203
+ print("Load custom cpu kernel failed:")
204
+ import traceback
205
+ exception = traceback.format_exc()
206
+ print(exception)
207
+
208
+ if kernels is not None:
209
+ self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float
210
+ self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float
211
+ self.int4WeightCompression = kernels.compress_int4_weight
212
+ if compile_parallel_kernel:
213
+ try:
214
+ self.SetNumThreads = kernels.set_num_threads
215
+ except:
216
+ print("No set_num_threads() found in kernel.")
217
+ self.load = True
218
+ else:
219
+ print("Failed to load kernel.")
220
+ return
221
+
222
+ if compile_parallel_kernel:
223
+ if parallel_num is None:
224
+ parallel_num = max(os.cpu_count() // 2, 1)
225
+ print("Setting CPU quantization kernel threads to", parallel_num)
226
+ if parallel_num < 4:
227
+ print("Parallel kernel is not recommended when parallel num < 4.")
228
+ self.SetNumThreads(parallel_num)
229
+
230
+ self.parallel_num = parallel_num
231
+
232
+
233
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
234
+ """compress weight on cpu or cuda to int4"""
235
+ if weight.device == torch.device("cpu"):
236
+ assert isinstance(cpu_kernels, CPUKernel)
237
+ n, m = weight.size(0), weight.size(1)
238
+ assert m % 2 == 0
239
+ m = m // 2
240
+ out = torch.empty(n, m, dtype=torch.int8, device="cpu")
241
+ cpu_kernels.int4WeightCompression(
242
+ ctypes.c_void_p(weight.data_ptr()),
243
+ ctypes.c_void_p(out.data_ptr()),
244
+ ctypes.c_int32(n),
245
+ ctypes.c_int32(m)
246
+ )
247
+ return out
248
+ else:
249
+ with torch.cuda.device(weight.device):
250
+ n, m = weight.size(0), weight.size(1)
251
+ assert m % 2 == 0
252
+ m = m // 2
253
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
254
+ stream = torch.cuda.current_stream()
255
+
256
+ gridDim = (n, 1, 1)
257
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
258
+
259
+ kernels.int4WeightCompression(
260
+ gridDim,
261
+ blockDim,
262
+ 0,
263
+ stream,
264
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n),
265
+ ctypes.c_int32(m)],
266
+ )
267
+ return out
268
+
269
+
270
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
271
+ if source_bit_width == 8:
272
+ func = kernels.int8WeightExtractionHalf
273
+ elif source_bit_width == 4:
274
+ func = kernels.int4WeightExtractionHalf
275
+ else:
276
+ assert False, "Unsupported bit-width"
277
+
278
+ with torch.cuda.device(weight.device):
279
+ n, m = weight.size(0), weight.size(1)
280
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
281
+ stream = torch.cuda.current_stream()
282
+
283
+ gridDim = (n, 1, 1)
284
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
285
+
286
+ func(
287
+ gridDim,
288
+ blockDim,
289
+ 0,
290
+ stream,
291
+ [
292
+ ctypes.c_void_p(weight.data_ptr()),
293
+ ctypes.c_void_p(scale_list.data_ptr()),
294
+ ctypes.c_void_p(out.data_ptr()),
295
+ ctypes.c_int32(n),
296
+ ctypes.c_int32(m),
297
+ ],
298
+ )
299
+ return out
300
+
301
+
302
+ def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int,
303
+ quantization_cache=None):
304
+ """extract weight on cpu to float32"""
305
+ if source_bit_width == 8:
306
+ func = cpu_kernels.int8WeightExtractionFloat
307
+ elif source_bit_width == 4:
308
+ func = cpu_kernels.int4WeightExtractionFloat
309
+ else:
310
+ assert False, "Unsupported bit-width"
311
+
312
+ n, m = weight.size(0), weight.size(1)
313
+
314
+ if quantization_cache is not None:
315
+ out = quantization_cache
316
+ func(
317
+ ctypes.c_void_p(weight.data_ptr()),
318
+ ctypes.c_void_p(scale_list.data_ptr()),
319
+ ctypes.c_void_p(out.data_ptr()),
320
+ ctypes.c_int32(n),
321
+ ctypes.c_int32(m)
322
+ )
323
+ return out.tensor
324
+ else:
325
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu")
326
+ func(
327
+ ctypes.c_void_p(weight.data_ptr()),
328
+ ctypes.c_void_p(scale_list.data_ptr()),
329
+ ctypes.c_void_p(out.data_ptr()),
330
+ ctypes.c_int32(n),
331
+ ctypes.c_int32(m)
332
+ )
333
+ return out
334
+
335
+
336
+ class CacheTensor():
337
+ def __init__(self, *args, **kwargs):
338
+ self.tensor = torch.empty(*args, **kwargs)
339
+
340
+ def to(self, *args, **kwargs):
341
+ self.tensor = self.tensor.to(*args, **kwargs)
342
+
343
+ def data_ptr(self):
344
+ return self.tensor.data_ptr()
345
+
346
+
347
+ class QuantizedLinear(Linear):
348
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None,
349
+ quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs):
350
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
351
+ self.weight_bit_width = weight_bit_width
352
+ self.quantization_cache = quantization_cache
353
+
354
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
355
+ del self.weight
356
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
357
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
358
+ else:
359
+ shape = self.weight.shape
360
+ del self.weight
361
+
362
+ if weight_tensor is None or empty_init:
363
+ self.weight = torch.empty(
364
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
365
+ )
366
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
367
+ else:
368
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(
369
+ kwargs["dtype"])
370
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
371
+ if weight_bit_width == 4:
372
+ self.weight = compress_int4_weight(self.weight)
373
+
374
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
375
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
376
+
377
+ if bias_tensor is not None:
378
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
379
+ else:
380
+ self.bias = None
381
+
382
+ def reset_parameters(self):
383
+ """To accelerate initialization"""
384
+ pass
385
+
386
+ def forward(self, input):
387
+ if self.weight.device == torch.device("cpu"):
388
+ output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width,
389
+ self.quantization_cache)
390
+ else:
391
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
392
+ if self.bias is not None:
393
+ output = output + self.bias
394
+ return output
395
+
396
+ def _apply(self, fn):
397
+ self_obj = super()._apply(fn)
398
+ if self.quantization_cache is not None:
399
+ self.quantization_cache.to(self_obj.weight.device)
400
+ self.quantization_cache.to(self_obj.weight_scale.dtype)
401
+ return self_obj
402
+
403
+
404
+ class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init
405
+ def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None,
406
+ empty_init=False, *args, **kwargs):
407
+ super(QuantizedEmbedding, self).__init__(*args, **kwargs)
408
+ self.weight_bit_width = weight_bit_width
409
+
410
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
411
+ del self.weight
412
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
413
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
414
+ else:
415
+ shape = self.weight.shape
416
+ del self.weight
417
+
418
+ if weight_tensor is None or empty_init:
419
+ self.weight = torch.empty(
420
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
421
+ )
422
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
423
+ else:
424
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(
425
+ kwargs["dtype"])
426
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
427
+ if weight_bit_width == 4:
428
+ self.weight = compress_int4_weight(self.weight)
429
+
430
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
431
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
432
+
433
+ def forward(self, input):
434
+ if self.weight.device == torch.device("cpu"):
435
+ original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale,
436
+ source_bit_width=self.weight_bit_width)
437
+ else:
438
+ original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale,
439
+ source_bit_width=self.weight_bit_width)
440
+ output = F.embedding(
441
+ input, original_weight, self.padding_idx, self.max_norm,
442
+ self.norm_type, self.scale_grad_by_freq, self.sparse
443
+ )
444
+ return output
445
+
446
+
447
+ def load_cpu_kernel(**kwargs):
448
+ global cpu_kernels
449
+ cpu_kernels = CPUKernel(**kwargs)
450
+
451
+
452
+ def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs):
453
+ """Replace fp16 linear with quantized linear"""
454
+
455
+ query_key_value_quantization_cache = None
456
+ dense_quantization_cache = None
457
+ dense_h_to_4h_quantization_cache = None
458
+ dense_4h_to_h_quantization_cache = None
459
+
460
+ load_cpu_kernel(**kwargs)
461
+ if not cpu_kernels.load:
462
+ if kernels is None: # CUDA kernels failed
463
+ print("Cannot load cpu or cuda kernel, quantization failed:")
464
+ assert kernels is not None
465
+ print("Cannot load cpu kernel, don't use quantized model on cpu.")
466
+
467
+ current_device = model.device
468
+
469
+ if model.device == torch.device("cpu"):
470
+ dtype = torch.float32
471
+ else:
472
+ dtype = torch.half
473
+
474
+ QuantizedLinearWithPara = partial(
475
+ QuantizedLinear,
476
+ weight_bit_width=weight_bit_width,
477
+ bias=True,
478
+ dtype=dtype,
479
+ empty_init=empty_init
480
+ )
481
+
482
+ if use_quantization_cache:
483
+ print("Using quantization cache")
484
+ layer = model.layers[0]
485
+ weight = layer.attention.query_key_value.weight
486
+ n, m = weight.size(0), weight.size(1)
487
+ query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
488
+ weight = layer.attention.dense.weight
489
+ n, m = weight.size(0), weight.size(1)
490
+ dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
491
+ weight = layer.mlp.dense_h_to_4h.weight
492
+ n, m = weight.size(0), weight.size(1)
493
+ dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
494
+ weight = layer.mlp.dense_4h_to_h.weight
495
+ n, m = weight.size(0), weight.size(1)
496
+ dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
497
+
498
+ print("Applying quantization to glm layers")
499
+
500
+ for layer in model.layers:
501
+ layer.attention.query_key_value = QuantizedLinearWithPara(
502
+ weight_tensor=layer.attention.query_key_value.weight.to(current_device),
503
+ bias_tensor=layer.attention.query_key_value.bias,
504
+ in_features=layer.attention.query_key_value.in_features,
505
+ out_features=layer.attention.query_key_value.out_features,
506
+ device=layer.attention.query_key_value.weight.device,
507
+ quantization_cache=query_key_value_quantization_cache
508
+ )
509
+ layer.attention.dense = QuantizedLinearWithPara(
510
+ weight_tensor=layer.attention.dense.weight.to(current_device),
511
+ bias_tensor=layer.attention.dense.bias,
512
+ in_features=layer.attention.dense.in_features,
513
+ out_features=layer.attention.dense.out_features,
514
+ device=layer.attention.dense.weight.device,
515
+ quantization_cache=dense_quantization_cache
516
+ )
517
+ layer.mlp.dense_h_to_4h = QuantizedLinearWithPara(
518
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device),
519
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
520
+ in_features=layer.mlp.dense_h_to_4h.in_features,
521
+ out_features=layer.mlp.dense_h_to_4h.out_features,
522
+ device=layer.mlp.dense_h_to_4h.weight.device,
523
+ quantization_cache=dense_h_to_4h_quantization_cache
524
+ )
525
+ layer.mlp.dense_4h_to_h = QuantizedLinearWithPara(
526
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device),
527
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
528
+ in_features=layer.mlp.dense_4h_to_h.in_features,
529
+ out_features=layer.mlp.dense_4h_to_h.out_features,
530
+ device=layer.mlp.dense_4h_to_h.weight.device,
531
+ quantization_cache=dense_4h_to_h_quantization_cache
532
+ )
533
+ return model
xiaowo/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bb7f4ea82efa2762df9b1d92c3cd635e2f206648536bff15c82e5349882c08b
3
+ size 14575
xiaowo/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76865769b4b6b37c95369d34996cca04197a697394c214078eea0941cf10ccb9
3
+ size 627
xiaowo/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<sop>",
3
+ "eos_token": "<eop>",
4
+ "mask_token": "[MASK]",
5
+ "pad_token": "<pad>",
6
+ "unk_token": "<unk>"
7
+ }
xiaowo/tokenization_chatglm.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ from typing import List, Optional, Union
3
+ import os
4
+
5
+ from transformers.tokenization_utils import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+ from typing import Dict
9
+ import sentencepiece as spm
10
+ import numpy as np
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
15
+ "THUDM/chatglm-6b": 2048,
16
+ }
17
+
18
+
19
+ class TextTokenizer:
20
+ def __init__(self, model_path):
21
+ self.sp = spm.SentencePieceProcessor()
22
+ self.sp.Load(model_path)
23
+ self.num_tokens = self.sp.vocab_size()
24
+
25
+ def encode(self, text):
26
+ return self.sp.EncodeAsIds(text)
27
+
28
+ def decode(self, ids: List[int]):
29
+ return self.sp.DecodeIds(ids)
30
+
31
+ def tokenize(self, text):
32
+ return self.sp.EncodeAsPieces(text)
33
+
34
+ def convert_tokens_to_string(self, tokens):
35
+ return self.sp.DecodePieces(tokens)
36
+
37
+ def convert_tokens_to_ids(self, tokens):
38
+ return [self.sp.PieceToId(token) for token in tokens]
39
+
40
+ def convert_token_to_id(self, token):
41
+ return self.sp.PieceToId(token)
42
+
43
+ def convert_id_to_token(self, idx):
44
+ return self.sp.IdToPiece(idx)
45
+
46
+ def __len__(self):
47
+ return self.num_tokens
48
+
49
+
50
+ class SPTokenizer:
51
+ def __init__(
52
+ self,
53
+ vocab_file,
54
+ num_image_tokens=20000,
55
+ max_blank_length=80,
56
+ byte_fallback=True,
57
+ ):
58
+ assert vocab_file is not None
59
+ self.vocab_file = vocab_file
60
+ self.num_image_tokens = num_image_tokens
61
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
62
+ self.max_blank_length = max_blank_length
63
+ self.byte_fallback = byte_fallback
64
+ self.text_tokenizer = TextTokenizer(vocab_file)
65
+
66
+ def _get_text_tokenizer(self):
67
+ return self.text_tokenizer
68
+
69
+ @staticmethod
70
+ def get_blank_token(length: int):
71
+ assert length >= 2
72
+ return f"<|blank_{length}|>"
73
+
74
+ @staticmethod
75
+ def get_tab_token():
76
+ return f"<|tab|>"
77
+
78
+ @property
79
+ def num_text_tokens(self):
80
+ return self.text_tokenizer.num_tokens
81
+
82
+ @property
83
+ def num_tokens(self):
84
+ return self.num_image_tokens + self.num_text_tokens
85
+
86
+ @staticmethod
87
+ def _encode_whitespaces(text: str, max_len: int = 80):
88
+ text = text.replace("\t", SPTokenizer.get_tab_token())
89
+ for i in range(max_len, 1, -1):
90
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
91
+ return text
92
+
93
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
94
+ if linebreak:
95
+ text = text.replace("\n", "<n>")
96
+ if whitespaces:
97
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
98
+ return text
99
+
100
+ def encode(
101
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
102
+ ) -> List[int]:
103
+ """
104
+ @param text: Text to encode.
105
+ @param linebreak: Whether to encode newline (\n) in text.
106
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
107
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
108
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
109
+ """
110
+ text = self._preprocess(text, linebreak, whitespaces)
111
+ if not add_dummy_prefix:
112
+ text = "<n>" + text
113
+ tmp = self._get_text_tokenizer().encode(text)
114
+ tokens = [x + self.num_image_tokens for x in tmp]
115
+ return tokens if add_dummy_prefix else tokens[2:]
116
+
117
+ def postprocess(self, text):
118
+ text = text.replace("<n>", "\n")
119
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
120
+ for i in range(2, self.max_blank_length + 1):
121
+ text = text.replace(self.get_blank_token(i), " " * i)
122
+ return text
123
+
124
+ def decode(self, text_ids: List[int]) -> str:
125
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
126
+ ids = [_id for _id in ids if _id >= 0]
127
+ text = self._get_text_tokenizer().decode(ids)
128
+ text = self.postprocess(text)
129
+ return text
130
+
131
+ def decode_tokens(self, tokens: List[str]) -> str:
132
+ text = self._get_text_tokenizer().convert_tokens_to_string(tokens)
133
+ text = self.postprocess(text)
134
+ return text
135
+
136
+ def tokenize(
137
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
138
+ ) -> List[str]:
139
+ """
140
+ @param text: Text to encode.
141
+ @param linebreak: Whether to encode newline (\n) in text.
142
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
143
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
144
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
145
+ """
146
+ text = self._preprocess(text, linebreak, whitespaces)
147
+ if not add_dummy_prefix:
148
+ text = "<n>" + text
149
+ tokens = self._get_text_tokenizer().tokenize(text)
150
+ return tokens if add_dummy_prefix else tokens[2:]
151
+
152
+ def __getitem__(self, x: Union[int, str]):
153
+ if isinstance(x, int):
154
+ if x < self.num_image_tokens:
155
+ return "<image_{}>".format(x)
156
+ else:
157
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
158
+ elif isinstance(x, str):
159
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
160
+ return int(x[7:-1])
161
+ else:
162
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
163
+ else:
164
+ raise ValueError("The key should be str or int.")
165
+
166
+
167
+ class ChatGLMTokenizer(PreTrainedTokenizer):
168
+ """
169
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
170
+
171
+ Args:
172
+ vocab_file (`str`):
173
+ Path to the vocabulary file.
174
+ """
175
+
176
+ vocab_files_names = {"vocab_file": "ice_text.model"}
177
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
178
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
179
+
180
+ def __init__(
181
+ self,
182
+ vocab_file,
183
+ do_lower_case=False,
184
+ remove_space=False,
185
+ bos_token='<sop>',
186
+ eos_token='<eop>',
187
+ end_token='</s>',
188
+ mask_token='[MASK]',
189
+ gmask_token='[gMASK]',
190
+ padding_side="left",
191
+ pad_token="<pad>",
192
+ unk_token="<unk>",
193
+ num_image_tokens=20000,
194
+ **kwargs
195
+ ) -> None:
196
+ super().__init__(
197
+ do_lower_case=do_lower_case,
198
+ remove_space=remove_space,
199
+ padding_side=padding_side,
200
+ bos_token=bos_token,
201
+ eos_token=eos_token,
202
+ end_token=end_token,
203
+ mask_token=mask_token,
204
+ gmask_token=gmask_token,
205
+ pad_token=pad_token,
206
+ unk_token=unk_token,
207
+ num_image_tokens=num_image_tokens,
208
+ **kwargs
209
+ )
210
+
211
+ self.do_lower_case = do_lower_case
212
+ self.remove_space = remove_space
213
+ self.vocab_file = vocab_file
214
+
215
+ self.bos_token = bos_token
216
+ self.eos_token = eos_token
217
+ self.end_token = end_token
218
+ self.mask_token = mask_token
219
+ self.gmask_token = gmask_token
220
+
221
+ self.sp_tokenizer = SPTokenizer(vocab_file, num_image_tokens=num_image_tokens)
222
+
223
+ """ Initialisation """
224
+
225
+ @property
226
+ def gmask_token_id(self) -> Optional[int]:
227
+ if self.gmask_token is None:
228
+ return None
229
+ return self.convert_tokens_to_ids(self.gmask_token)
230
+
231
+ @property
232
+ def end_token_id(self) -> Optional[int]:
233
+ """
234
+ `Optional[int]`: Id of the end of context token in the vocabulary. Returns `None` if the token has not been
235
+ set.
236
+ """
237
+ if self.end_token is None:
238
+ return None
239
+ return self.convert_tokens_to_ids(self.end_token)
240
+
241
+ @property
242
+ def vocab_size(self):
243
+ """ Returns vocab size """
244
+ return self.sp_tokenizer.num_tokens
245
+
246
+ def get_vocab(self):
247
+ """ Returns vocab as a dict """
248
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
249
+ vocab.update(self.added_tokens_encoder)
250
+ return vocab
251
+
252
+ def preprocess_text(self, inputs):
253
+ if self.remove_space:
254
+ outputs = " ".join(inputs.strip().split())
255
+ else:
256
+ outputs = inputs
257
+
258
+ if self.do_lower_case:
259
+ outputs = outputs.lower()
260
+
261
+ return outputs
262
+
263
+ def _tokenize(self, text, **kwargs):
264
+ """ Returns a tokenized string. """
265
+ text = self.preprocess_text(text)
266
+
267
+ seq = self.sp_tokenizer.tokenize(text)
268
+
269
+ return seq
270
+
271
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
272
+ return self.sp_tokenizer.decode_tokens(tokens)
273
+
274
+ def _decode(
275
+ self,
276
+ token_ids: Union[int, List[int]],
277
+ **kwargs
278
+ ) -> str:
279
+ if isinstance(token_ids, int):
280
+ token_ids = [token_ids]
281
+ if len(token_ids) == 0:
282
+ return ""
283
+ if self.pad_token_id in token_ids: # remove pad
284
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
285
+ return super()._decode(token_ids, **kwargs)
286
+
287
+ def _convert_token_to_id(self, token):
288
+ """ Converts a token (str) in an id using the vocab. """
289
+ return self.sp_tokenizer[token]
290
+
291
+ def _convert_id_to_token(self, index):
292
+ """Converts an index (integer) in a token (str) using the vocab."""
293
+ return self.sp_tokenizer[index]
294
+
295
+ def save_vocabulary(self, save_directory, filename_prefix=None):
296
+ """
297
+ Save the vocabulary and special tokens file to a directory.
298
+
299
+ Args:
300
+ save_directory (`str`):
301
+ The directory in which to save the vocabulary.
302
+ filename_prefix (`str`, *optional*):
303
+ An optional prefix to add to the named of the saved files.
304
+
305
+ Returns:
306
+ `Tuple(str)`: Paths to the files saved.
307
+ """
308
+ if os.path.isdir(save_directory):
309
+ vocab_file = os.path.join(
310
+ save_directory, self.vocab_files_names["vocab_file"]
311
+ )
312
+ else:
313
+ vocab_file = save_directory
314
+
315
+ with open(self.vocab_file, 'rb') as fin:
316
+ proto_str = fin.read()
317
+
318
+ with open(vocab_file, "wb") as writer:
319
+ writer.write(proto_str)
320
+
321
+ return (vocab_file,)
322
+
323
+ def build_inputs_with_special_tokens(
324
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
325
+ ) -> List[int]:
326
+ """
327
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
328
+ adding special tokens. A BERT sequence has the following format:
329
+
330
+ - single sequence: `[CLS] X [SEP]`
331
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
332
+
333
+ Args:
334
+ token_ids_0 (`List[int]`):
335
+ List of IDs to which the special tokens will be added.
336
+ token_ids_1 (`List[int]`, *optional*):
337
+ Optional second list of IDs for sequence pairs.
338
+
339
+ Returns:
340
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
341
+ """
342
+ gmask_id = self.sp_tokenizer[self.gmask_token]
343
+ eos_id = self.sp_tokenizer[self.eos_token]
344
+ token_ids_0 = token_ids_0 + [gmask_id, self.sp_tokenizer[self.bos_token]]
345
+ if token_ids_1 is not None:
346
+ token_ids_0 = token_ids_0 + token_ids_1 + [eos_id]
347
+ return token_ids_0
348
+
349
+ def _pad(
350
+ self,
351
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
352
+ max_length: Optional[int] = None,
353
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
354
+ pad_to_multiple_of: Optional[int] = None,
355
+ return_attention_mask: Optional[bool] = None,
356
+ ) -> dict:
357
+ """
358
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
359
+
360
+ Args:
361
+ encoded_inputs:
362
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
363
+ max_length: maximum length of the returned list and optionally padding length (see below).
364
+ Will truncate by taking into account the special tokens.
365
+ padding_strategy: PaddingStrategy to use for padding.
366
+
367
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
368
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
369
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
370
+ The tokenizer padding sides are defined in self.padding_side:
371
+
372
+ - 'left': pads on the left of the sequences
373
+ - 'right': pads on the right of the sequences
374
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
375
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
376
+ `>= 7.5` (Volta).
377
+ return_attention_mask:
378
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
379
+ """
380
+ # Load from model defaults
381
+ bos_token_id = self.sp_tokenizer[self.bos_token]
382
+ mask_token_id = self.sp_tokenizer[self.mask_token]
383
+ gmask_token_id = self.sp_tokenizer[self.gmask_token]
384
+ assert self.padding_side == "left"
385
+
386
+ required_input = encoded_inputs[self.model_input_names[0]]
387
+ seq_length = len(required_input)
388
+
389
+ if padding_strategy == PaddingStrategy.LONGEST:
390
+ max_length = len(required_input)
391
+
392
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
393
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
394
+
395
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
396
+
397
+ # Initialize attention mask if not present.
398
+ if max_length is not None:
399
+ if "attention_mask" not in encoded_inputs:
400
+ if bos_token_id in required_input:
401
+ context_length = required_input.index(bos_token_id)
402
+ else:
403
+ context_length = seq_length
404
+ attention_mask = np.ones((1, seq_length, seq_length))
405
+ attention_mask = np.tril(attention_mask)
406
+ attention_mask[:, :, :context_length] = 1
407
+ attention_mask = np.bool_(attention_mask < 0.5)
408
+ encoded_inputs["attention_mask"] = attention_mask
409
+
410
+ if "position_ids" not in encoded_inputs:
411
+ if bos_token_id in required_input:
412
+ context_length = required_input.index(bos_token_id)
413
+ else:
414
+ context_length = seq_length
415
+ position_ids = np.arange(seq_length, dtype=np.int64)
416
+ mask_token = mask_token_id if mask_token_id in required_input else gmask_token_id
417
+ if mask_token in required_input:
418
+ mask_position = required_input.index(mask_token)
419
+ position_ids[context_length:] = mask_position
420
+ block_position_ids = np.concatenate(
421
+ [np.zeros(context_length, dtype=np.int64),
422
+ np.arange(1, seq_length - context_length + 1, dtype=np.int64)])
423
+ encoded_inputs["position_ids"] = np.stack([position_ids, block_position_ids], axis=0)
424
+
425
+ if needs_to_be_padded:
426
+ difference = max_length - len(required_input)
427
+
428
+ if "attention_mask" in encoded_inputs:
429
+ encoded_inputs["attention_mask"] = np.pad(encoded_inputs["attention_mask"],
430
+ pad_width=[(0, 0), (difference, 0), (difference, 0)],
431
+ mode='constant', constant_values=True)
432
+ if "token_type_ids" in encoded_inputs:
433
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
434
+ "token_type_ids"
435
+ ]
436
+ if "special_tokens_mask" in encoded_inputs:
437
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
438
+ if "position_ids" in encoded_inputs:
439
+ encoded_inputs["position_ids"] = np.pad(encoded_inputs["position_ids"],
440
+ pad_width=[(0, 0), (difference, 0)])
441
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
442
+
443
+ return encoded_inputs
xiaowo/tokenizer_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_chatglm.ChatGLMTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "bos_token": "<sop>",
9
+ "do_lower_case": false,
10
+ "end_token": "</s>",
11
+ "eos_token": "<eop>",
12
+ "gmask_token": "[gMASK]",
13
+ "mask_token": "[MASK]",
14
+ "model_max_length": 1000000000000000019884624838656,
15
+ "num_image_tokens": 0,
16
+ "pad_token": "<pad>",
17
+ "padding_side": "left",
18
+ "remove_space": false,
19
+ "special_tokens_map_file": null,
20
+ "tokenizer_class": "ChatGLMTokenizer",
21
+ "unk_token": "<unk>"
22
+ }
xiaowo/trainer_state.json ADDED
@@ -0,0 +1,3016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.305008235222351,
5
+ "global_step": 5000,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 0.0,
12
+ "learning_rate": 0.0024984848484848484,
13
+ "loss": 8.3168,
14
+ "step": 10
15
+ },
16
+ {
17
+ "epoch": 0.0,
18
+ "learning_rate": 0.002496969696969697,
19
+ "loss": 7.4992,
20
+ "step": 20
21
+ },
22
+ {
23
+ "epoch": 0.0,
24
+ "learning_rate": 0.0024954545454545455,
25
+ "loss": 7.1773,
26
+ "step": 30
27
+ },
28
+ {
29
+ "epoch": 0.0,
30
+ "learning_rate": 0.002493939393939394,
31
+ "loss": 6.7129,
32
+ "step": 40
33
+ },
34
+ {
35
+ "epoch": 0.0,
36
+ "learning_rate": 0.0024924242424242426,
37
+ "loss": 5.6141,
38
+ "step": 50
39
+ },
40
+ {
41
+ "epoch": 0.0,
42
+ "learning_rate": 0.002490909090909091,
43
+ "loss": 5.4168,
44
+ "step": 60
45
+ },
46
+ {
47
+ "epoch": 0.0,
48
+ "learning_rate": 0.0024893939393939393,
49
+ "loss": 5.2236,
50
+ "step": 70
51
+ },
52
+ {
53
+ "epoch": 0.0,
54
+ "learning_rate": 0.002487878787878788,
55
+ "loss": 5.5969,
56
+ "step": 80
57
+ },
58
+ {
59
+ "epoch": 0.01,
60
+ "learning_rate": 0.0024863636363636364,
61
+ "loss": 5.2027,
62
+ "step": 90
63
+ },
64
+ {
65
+ "epoch": 0.01,
66
+ "learning_rate": 0.0024848484848484847,
67
+ "loss": 4.7475,
68
+ "step": 100
69
+ },
70
+ {
71
+ "epoch": 0.01,
72
+ "learning_rate": 0.0024833333333333335,
73
+ "loss": 4.7779,
74
+ "step": 110
75
+ },
76
+ {
77
+ "epoch": 0.01,
78
+ "learning_rate": 0.002481818181818182,
79
+ "loss": 4.4724,
80
+ "step": 120
81
+ },
82
+ {
83
+ "epoch": 0.01,
84
+ "learning_rate": 0.00248030303030303,
85
+ "loss": 5.1906,
86
+ "step": 130
87
+ },
88
+ {
89
+ "epoch": 0.01,
90
+ "learning_rate": 0.0024787878787878785,
91
+ "loss": 4.949,
92
+ "step": 140
93
+ },
94
+ {
95
+ "epoch": 0.01,
96
+ "learning_rate": 0.0024772727272727273,
97
+ "loss": 4.3598,
98
+ "step": 150
99
+ },
100
+ {
101
+ "epoch": 0.01,
102
+ "learning_rate": 0.002475757575757576,
103
+ "loss": 4.6328,
104
+ "step": 160
105
+ },
106
+ {
107
+ "epoch": 0.01,
108
+ "learning_rate": 0.0024742424242424244,
109
+ "loss": 4.6934,
110
+ "step": 170
111
+ },
112
+ {
113
+ "epoch": 0.01,
114
+ "learning_rate": 0.0024727272727272727,
115
+ "loss": 4.8184,
116
+ "step": 180
117
+ },
118
+ {
119
+ "epoch": 0.01,
120
+ "learning_rate": 0.0024712121212121215,
121
+ "loss": 4.6488,
122
+ "step": 190
123
+ },
124
+ {
125
+ "epoch": 0.01,
126
+ "learning_rate": 0.00246969696969697,
127
+ "loss": 4.7639,
128
+ "step": 200
129
+ },
130
+ {
131
+ "epoch": 0.01,
132
+ "learning_rate": 0.002468181818181818,
133
+ "loss": 4.6092,
134
+ "step": 210
135
+ },
136
+ {
137
+ "epoch": 0.01,
138
+ "learning_rate": 0.002466666666666667,
139
+ "loss": 4.8875,
140
+ "step": 220
141
+ },
142
+ {
143
+ "epoch": 0.01,
144
+ "learning_rate": 0.0024651515151515153,
145
+ "loss": 4.7232,
146
+ "step": 230
147
+ },
148
+ {
149
+ "epoch": 0.01,
150
+ "learning_rate": 0.0024636363636363636,
151
+ "loss": 5.1139,
152
+ "step": 240
153
+ },
154
+ {
155
+ "epoch": 0.02,
156
+ "learning_rate": 0.0024621212121212124,
157
+ "loss": 4.3293,
158
+ "step": 250
159
+ },
160
+ {
161
+ "epoch": 0.02,
162
+ "learning_rate": 0.0024606060606060607,
163
+ "loss": 4.6564,
164
+ "step": 260
165
+ },
166
+ {
167
+ "epoch": 0.02,
168
+ "learning_rate": 0.002459090909090909,
169
+ "loss": 4.7779,
170
+ "step": 270
171
+ },
172
+ {
173
+ "epoch": 0.02,
174
+ "learning_rate": 0.002457575757575758,
175
+ "loss": 4.6312,
176
+ "step": 280
177
+ },
178
+ {
179
+ "epoch": 0.02,
180
+ "learning_rate": 0.002456060606060606,
181
+ "loss": 4.4924,
182
+ "step": 290
183
+ },
184
+ {
185
+ "epoch": 0.02,
186
+ "learning_rate": 0.0024545454545454545,
187
+ "loss": 4.418,
188
+ "step": 300
189
+ },
190
+ {
191
+ "epoch": 0.02,
192
+ "learning_rate": 0.0024530303030303032,
193
+ "loss": 4.2307,
194
+ "step": 310
195
+ },
196
+ {
197
+ "epoch": 0.02,
198
+ "learning_rate": 0.0024515151515151516,
199
+ "loss": 4.3598,
200
+ "step": 320
201
+ },
202
+ {
203
+ "epoch": 0.02,
204
+ "learning_rate": 0.00245,
205
+ "loss": 4.6166,
206
+ "step": 330
207
+ },
208
+ {
209
+ "epoch": 0.02,
210
+ "learning_rate": 0.0024484848484848487,
211
+ "loss": 4.7531,
212
+ "step": 340
213
+ },
214
+ {
215
+ "epoch": 0.02,
216
+ "learning_rate": 0.002446969696969697,
217
+ "loss": 4.5492,
218
+ "step": 350
219
+ },
220
+ {
221
+ "epoch": 0.02,
222
+ "learning_rate": 0.0024454545454545454,
223
+ "loss": 4.5928,
224
+ "step": 360
225
+ },
226
+ {
227
+ "epoch": 0.02,
228
+ "learning_rate": 0.0024439393939393937,
229
+ "loss": 4.576,
230
+ "step": 370
231
+ },
232
+ {
233
+ "epoch": 0.02,
234
+ "learning_rate": 0.0024424242424242425,
235
+ "loss": 4.5797,
236
+ "step": 380
237
+ },
238
+ {
239
+ "epoch": 0.02,
240
+ "learning_rate": 0.002440909090909091,
241
+ "loss": 4.3904,
242
+ "step": 390
243
+ },
244
+ {
245
+ "epoch": 0.02,
246
+ "learning_rate": 0.002439393939393939,
247
+ "loss": 4.6285,
248
+ "step": 400
249
+ },
250
+ {
251
+ "epoch": 0.03,
252
+ "learning_rate": 0.002437878787878788,
253
+ "loss": 4.6023,
254
+ "step": 410
255
+ },
256
+ {
257
+ "epoch": 0.03,
258
+ "learning_rate": 0.0024363636363636362,
259
+ "loss": 4.3693,
260
+ "step": 420
261
+ },
262
+ {
263
+ "epoch": 0.03,
264
+ "learning_rate": 0.002434848484848485,
265
+ "loss": 4.585,
266
+ "step": 430
267
+ },
268
+ {
269
+ "epoch": 0.03,
270
+ "learning_rate": 0.0024333333333333334,
271
+ "loss": 4.7988,
272
+ "step": 440
273
+ },
274
+ {
275
+ "epoch": 0.03,
276
+ "learning_rate": 0.002431818181818182,
277
+ "loss": 4.2064,
278
+ "step": 450
279
+ },
280
+ {
281
+ "epoch": 0.03,
282
+ "learning_rate": 0.0024303030303030305,
283
+ "loss": 4.5627,
284
+ "step": 460
285
+ },
286
+ {
287
+ "epoch": 0.03,
288
+ "learning_rate": 0.002428787878787879,
289
+ "loss": 4.0707,
290
+ "step": 470
291
+ },
292
+ {
293
+ "epoch": 0.03,
294
+ "learning_rate": 0.0024272727272727276,
295
+ "loss": 4.5716,
296
+ "step": 480
297
+ },
298
+ {
299
+ "epoch": 0.03,
300
+ "learning_rate": 0.002425757575757576,
301
+ "loss": 4.3047,
302
+ "step": 490
303
+ },
304
+ {
305
+ "epoch": 0.03,
306
+ "learning_rate": 0.0024242424242424242,
307
+ "loss": 4.5617,
308
+ "step": 500
309
+ },
310
+ {
311
+ "epoch": 0.03,
312
+ "learning_rate": 0.002422727272727273,
313
+ "loss": 4.4297,
314
+ "step": 510
315
+ },
316
+ {
317
+ "epoch": 0.03,
318
+ "learning_rate": 0.0024212121212121213,
319
+ "loss": 4.8227,
320
+ "step": 520
321
+ },
322
+ {
323
+ "epoch": 0.03,
324
+ "learning_rate": 0.0024196969696969697,
325
+ "loss": 4.4693,
326
+ "step": 530
327
+ },
328
+ {
329
+ "epoch": 0.03,
330
+ "learning_rate": 0.0024181818181818185,
331
+ "loss": 4.3514,
332
+ "step": 540
333
+ },
334
+ {
335
+ "epoch": 0.03,
336
+ "learning_rate": 0.002416666666666667,
337
+ "loss": 4.368,
338
+ "step": 550
339
+ },
340
+ {
341
+ "epoch": 0.03,
342
+ "learning_rate": 0.002415151515151515,
343
+ "loss": 4.049,
344
+ "step": 560
345
+ },
346
+ {
347
+ "epoch": 0.03,
348
+ "learning_rate": 0.002413636363636364,
349
+ "loss": 4.5527,
350
+ "step": 570
351
+ },
352
+ {
353
+ "epoch": 0.04,
354
+ "learning_rate": 0.0024121212121212122,
355
+ "loss": 4.7082,
356
+ "step": 580
357
+ },
358
+ {
359
+ "epoch": 0.04,
360
+ "learning_rate": 0.0024106060606060606,
361
+ "loss": 4.2236,
362
+ "step": 590
363
+ },
364
+ {
365
+ "epoch": 0.04,
366
+ "learning_rate": 0.002409090909090909,
367
+ "loss": 4.5283,
368
+ "step": 600
369
+ },
370
+ {
371
+ "epoch": 0.04,
372
+ "learning_rate": 0.0024075757575757577,
373
+ "loss": 4.5746,
374
+ "step": 610
375
+ },
376
+ {
377
+ "epoch": 0.04,
378
+ "learning_rate": 0.002406060606060606,
379
+ "loss": 4.6463,
380
+ "step": 620
381
+ },
382
+ {
383
+ "epoch": 0.04,
384
+ "learning_rate": 0.0024045454545454543,
385
+ "loss": 4.4469,
386
+ "step": 630
387
+ },
388
+ {
389
+ "epoch": 0.04,
390
+ "learning_rate": 0.002403030303030303,
391
+ "loss": 4.6049,
392
+ "step": 640
393
+ },
394
+ {
395
+ "epoch": 0.04,
396
+ "learning_rate": 0.0024015151515151515,
397
+ "loss": 4.5684,
398
+ "step": 650
399
+ },
400
+ {
401
+ "epoch": 0.04,
402
+ "learning_rate": 0.0024,
403
+ "loss": 4.3484,
404
+ "step": 660
405
+ },
406
+ {
407
+ "epoch": 0.04,
408
+ "learning_rate": 0.0023984848484848486,
409
+ "loss": 4.8201,
410
+ "step": 670
411
+ },
412
+ {
413
+ "epoch": 0.04,
414
+ "learning_rate": 0.002396969696969697,
415
+ "loss": 4.2961,
416
+ "step": 680
417
+ },
418
+ {
419
+ "epoch": 0.04,
420
+ "learning_rate": 0.0023954545454545452,
421
+ "loss": 3.9297,
422
+ "step": 690
423
+ },
424
+ {
425
+ "epoch": 0.04,
426
+ "learning_rate": 0.002393939393939394,
427
+ "loss": 4.7969,
428
+ "step": 700
429
+ },
430
+ {
431
+ "epoch": 0.04,
432
+ "learning_rate": 0.0023924242424242423,
433
+ "loss": 4.5076,
434
+ "step": 710
435
+ },
436
+ {
437
+ "epoch": 0.04,
438
+ "learning_rate": 0.002390909090909091,
439
+ "loss": 4.8527,
440
+ "step": 720
441
+ },
442
+ {
443
+ "epoch": 0.04,
444
+ "learning_rate": 0.0023893939393939394,
445
+ "loss": 4.5695,
446
+ "step": 730
447
+ },
448
+ {
449
+ "epoch": 0.05,
450
+ "learning_rate": 0.002387878787878788,
451
+ "loss": 4.425,
452
+ "step": 740
453
+ },
454
+ {
455
+ "epoch": 0.05,
456
+ "learning_rate": 0.0023863636363636366,
457
+ "loss": 4.2727,
458
+ "step": 750
459
+ },
460
+ {
461
+ "epoch": 0.05,
462
+ "learning_rate": 0.002384848484848485,
463
+ "loss": 4.5701,
464
+ "step": 760
465
+ },
466
+ {
467
+ "epoch": 0.05,
468
+ "learning_rate": 0.0023833333333333337,
469
+ "loss": 3.857,
470
+ "step": 770
471
+ },
472
+ {
473
+ "epoch": 0.05,
474
+ "learning_rate": 0.002381818181818182,
475
+ "loss": 4.6637,
476
+ "step": 780
477
+ },
478
+ {
479
+ "epoch": 0.05,
480
+ "learning_rate": 0.0023803030303030303,
481
+ "loss": 4.6662,
482
+ "step": 790
483
+ },
484
+ {
485
+ "epoch": 0.05,
486
+ "learning_rate": 0.002378787878787879,
487
+ "loss": 4.6828,
488
+ "step": 800
489
+ },
490
+ {
491
+ "epoch": 0.05,
492
+ "learning_rate": 0.0023772727272727274,
493
+ "loss": 4.4822,
494
+ "step": 810
495
+ },
496
+ {
497
+ "epoch": 0.05,
498
+ "learning_rate": 0.0023757575757575758,
499
+ "loss": 4.5971,
500
+ "step": 820
501
+ },
502
+ {
503
+ "epoch": 0.05,
504
+ "learning_rate": 0.002374242424242424,
505
+ "loss": 4.2271,
506
+ "step": 830
507
+ },
508
+ {
509
+ "epoch": 0.05,
510
+ "learning_rate": 0.002372727272727273,
511
+ "loss": 3.6249,
512
+ "step": 840
513
+ },
514
+ {
515
+ "epoch": 0.05,
516
+ "learning_rate": 0.002371212121212121,
517
+ "loss": 4.3729,
518
+ "step": 850
519
+ },
520
+ {
521
+ "epoch": 0.05,
522
+ "learning_rate": 0.0023696969696969696,
523
+ "loss": 4.3625,
524
+ "step": 860
525
+ },
526
+ {
527
+ "epoch": 0.05,
528
+ "learning_rate": 0.0023681818181818183,
529
+ "loss": 3.9025,
530
+ "step": 870
531
+ },
532
+ {
533
+ "epoch": 0.05,
534
+ "learning_rate": 0.0023666666666666667,
535
+ "loss": 4.1387,
536
+ "step": 880
537
+ },
538
+ {
539
+ "epoch": 0.05,
540
+ "learning_rate": 0.002365151515151515,
541
+ "loss": 4.1297,
542
+ "step": 890
543
+ },
544
+ {
545
+ "epoch": 0.05,
546
+ "learning_rate": 0.0023636363636363638,
547
+ "loss": 4.4295,
548
+ "step": 900
549
+ },
550
+ {
551
+ "epoch": 0.06,
552
+ "learning_rate": 0.002362121212121212,
553
+ "loss": 4.315,
554
+ "step": 910
555
+ },
556
+ {
557
+ "epoch": 0.06,
558
+ "learning_rate": 0.0023606060606060604,
559
+ "loss": 4.6844,
560
+ "step": 920
561
+ },
562
+ {
563
+ "epoch": 0.06,
564
+ "learning_rate": 0.002359090909090909,
565
+ "loss": 4.3967,
566
+ "step": 930
567
+ },
568
+ {
569
+ "epoch": 0.06,
570
+ "learning_rate": 0.0023575757575757575,
571
+ "loss": 4.3477,
572
+ "step": 940
573
+ },
574
+ {
575
+ "epoch": 0.06,
576
+ "learning_rate": 0.002356060606060606,
577
+ "loss": 4.3279,
578
+ "step": 950
579
+ },
580
+ {
581
+ "epoch": 0.06,
582
+ "learning_rate": 0.0023545454545454546,
583
+ "loss": 4.6373,
584
+ "step": 960
585
+ },
586
+ {
587
+ "epoch": 0.06,
588
+ "learning_rate": 0.002353030303030303,
589
+ "loss": 4.1047,
590
+ "step": 970
591
+ },
592
+ {
593
+ "epoch": 0.06,
594
+ "learning_rate": 0.0023515151515151513,
595
+ "loss": 4.2828,
596
+ "step": 980
597
+ },
598
+ {
599
+ "epoch": 0.06,
600
+ "learning_rate": 0.00235,
601
+ "loss": 4.559,
602
+ "step": 990
603
+ },
604
+ {
605
+ "epoch": 0.06,
606
+ "learning_rate": 0.002348484848484849,
607
+ "loss": 4.6342,
608
+ "step": 1000
609
+ },
610
+ {
611
+ "epoch": 0.06,
612
+ "learning_rate": 0.002346969696969697,
613
+ "loss": 4.5187,
614
+ "step": 1010
615
+ },
616
+ {
617
+ "epoch": 0.06,
618
+ "learning_rate": 0.0023454545454545455,
619
+ "loss": 4.242,
620
+ "step": 1020
621
+ },
622
+ {
623
+ "epoch": 0.06,
624
+ "learning_rate": 0.0023439393939393943,
625
+ "loss": 4.442,
626
+ "step": 1030
627
+ },
628
+ {
629
+ "epoch": 0.06,
630
+ "learning_rate": 0.0023424242424242426,
631
+ "loss": 4.3424,
632
+ "step": 1040
633
+ },
634
+ {
635
+ "epoch": 0.06,
636
+ "learning_rate": 0.002340909090909091,
637
+ "loss": 4.191,
638
+ "step": 1050
639
+ },
640
+ {
641
+ "epoch": 0.06,
642
+ "learning_rate": 0.0023393939393939393,
643
+ "loss": 4.4494,
644
+ "step": 1060
645
+ },
646
+ {
647
+ "epoch": 0.07,
648
+ "learning_rate": 0.002337878787878788,
649
+ "loss": 4.3324,
650
+ "step": 1070
651
+ },
652
+ {
653
+ "epoch": 0.07,
654
+ "learning_rate": 0.0023363636363636364,
655
+ "loss": 4.1201,
656
+ "step": 1080
657
+ },
658
+ {
659
+ "epoch": 0.07,
660
+ "learning_rate": 0.0023348484848484848,
661
+ "loss": 4.2084,
662
+ "step": 1090
663
+ },
664
+ {
665
+ "epoch": 0.07,
666
+ "learning_rate": 0.0023333333333333335,
667
+ "loss": 4.3176,
668
+ "step": 1100
669
+ },
670
+ {
671
+ "epoch": 0.07,
672
+ "learning_rate": 0.002331818181818182,
673
+ "loss": 4.4791,
674
+ "step": 1110
675
+ },
676
+ {
677
+ "epoch": 0.07,
678
+ "learning_rate": 0.00233030303030303,
679
+ "loss": 3.9592,
680
+ "step": 1120
681
+ },
682
+ {
683
+ "epoch": 0.07,
684
+ "learning_rate": 0.002328787878787879,
685
+ "loss": 4.3406,
686
+ "step": 1130
687
+ },
688
+ {
689
+ "epoch": 0.07,
690
+ "learning_rate": 0.0023272727272727273,
691
+ "loss": 4.1566,
692
+ "step": 1140
693
+ },
694
+ {
695
+ "epoch": 0.07,
696
+ "learning_rate": 0.0023257575757575756,
697
+ "loss": 4.4951,
698
+ "step": 1150
699
+ },
700
+ {
701
+ "epoch": 0.07,
702
+ "learning_rate": 0.0023242424242424244,
703
+ "loss": 3.873,
704
+ "step": 1160
705
+ },
706
+ {
707
+ "epoch": 0.07,
708
+ "learning_rate": 0.0023227272727272727,
709
+ "loss": 4.4193,
710
+ "step": 1170
711
+ },
712
+ {
713
+ "epoch": 0.07,
714
+ "learning_rate": 0.002321212121212121,
715
+ "loss": 4.2574,
716
+ "step": 1180
717
+ },
718
+ {
719
+ "epoch": 0.07,
720
+ "learning_rate": 0.00231969696969697,
721
+ "loss": 4.7572,
722
+ "step": 1190
723
+ },
724
+ {
725
+ "epoch": 0.07,
726
+ "learning_rate": 0.002318181818181818,
727
+ "loss": 4.3244,
728
+ "step": 1200
729
+ },
730
+ {
731
+ "epoch": 0.07,
732
+ "learning_rate": 0.0023166666666666665,
733
+ "loss": 4.2613,
734
+ "step": 1210
735
+ },
736
+ {
737
+ "epoch": 0.07,
738
+ "learning_rate": 0.0023151515151515153,
739
+ "loss": 4.5949,
740
+ "step": 1220
741
+ },
742
+ {
743
+ "epoch": 0.08,
744
+ "learning_rate": 0.0023136363636363636,
745
+ "loss": 4.1111,
746
+ "step": 1230
747
+ },
748
+ {
749
+ "epoch": 0.08,
750
+ "learning_rate": 0.002312121212121212,
751
+ "loss": 4.3355,
752
+ "step": 1240
753
+ },
754
+ {
755
+ "epoch": 0.08,
756
+ "learning_rate": 0.0023106060606060607,
757
+ "loss": 4.5539,
758
+ "step": 1250
759
+ },
760
+ {
761
+ "epoch": 0.08,
762
+ "learning_rate": 0.002309090909090909,
763
+ "loss": 4.221,
764
+ "step": 1260
765
+ },
766
+ {
767
+ "epoch": 0.08,
768
+ "learning_rate": 0.0023075757575757574,
769
+ "loss": 4.0617,
770
+ "step": 1270
771
+ },
772
+ {
773
+ "epoch": 0.08,
774
+ "learning_rate": 0.002306060606060606,
775
+ "loss": 4.2396,
776
+ "step": 1280
777
+ },
778
+ {
779
+ "epoch": 0.08,
780
+ "learning_rate": 0.0023045454545454545,
781
+ "loss": 4.6004,
782
+ "step": 1290
783
+ },
784
+ {
785
+ "epoch": 0.08,
786
+ "learning_rate": 0.0023030303030303033,
787
+ "loss": 4.533,
788
+ "step": 1300
789
+ },
790
+ {
791
+ "epoch": 0.08,
792
+ "learning_rate": 0.0023015151515151516,
793
+ "loss": 4.3018,
794
+ "step": 1310
795
+ },
796
+ {
797
+ "epoch": 0.08,
798
+ "learning_rate": 0.0023,
799
+ "loss": 3.9908,
800
+ "step": 1320
801
+ },
802
+ {
803
+ "epoch": 0.08,
804
+ "learning_rate": 0.0022984848484848487,
805
+ "loss": 4.4869,
806
+ "step": 1330
807
+ },
808
+ {
809
+ "epoch": 0.08,
810
+ "learning_rate": 0.002296969696969697,
811
+ "loss": 4.1631,
812
+ "step": 1340
813
+ },
814
+ {
815
+ "epoch": 0.08,
816
+ "learning_rate": 0.0022954545454545454,
817
+ "loss": 4.3191,
818
+ "step": 1350
819
+ },
820
+ {
821
+ "epoch": 0.08,
822
+ "learning_rate": 0.002293939393939394,
823
+ "loss": 4.4717,
824
+ "step": 1360
825
+ },
826
+ {
827
+ "epoch": 0.08,
828
+ "learning_rate": 0.0022924242424242425,
829
+ "loss": 4.0645,
830
+ "step": 1370
831
+ },
832
+ {
833
+ "epoch": 0.08,
834
+ "learning_rate": 0.002290909090909091,
835
+ "loss": 4.2992,
836
+ "step": 1380
837
+ },
838
+ {
839
+ "epoch": 0.08,
840
+ "learning_rate": 0.0022893939393939396,
841
+ "loss": 4.2506,
842
+ "step": 1390
843
+ },
844
+ {
845
+ "epoch": 0.09,
846
+ "learning_rate": 0.002287878787878788,
847
+ "loss": 4.1289,
848
+ "step": 1400
849
+ },
850
+ {
851
+ "epoch": 0.09,
852
+ "learning_rate": 0.0022863636363636363,
853
+ "loss": 4.5553,
854
+ "step": 1410
855
+ },
856
+ {
857
+ "epoch": 0.09,
858
+ "learning_rate": 0.002284848484848485,
859
+ "loss": 4.1268,
860
+ "step": 1420
861
+ },
862
+ {
863
+ "epoch": 0.09,
864
+ "learning_rate": 0.0022833333333333334,
865
+ "loss": 4.3211,
866
+ "step": 1430
867
+ },
868
+ {
869
+ "epoch": 0.09,
870
+ "learning_rate": 0.0022818181818181817,
871
+ "loss": 3.8847,
872
+ "step": 1440
873
+ },
874
+ {
875
+ "epoch": 0.09,
876
+ "learning_rate": 0.0022803030303030305,
877
+ "loss": 3.9451,
878
+ "step": 1450
879
+ },
880
+ {
881
+ "epoch": 0.09,
882
+ "learning_rate": 0.002278787878787879,
883
+ "loss": 3.6887,
884
+ "step": 1460
885
+ },
886
+ {
887
+ "epoch": 0.09,
888
+ "learning_rate": 0.002277272727272727,
889
+ "loss": 4.0348,
890
+ "step": 1470
891
+ },
892
+ {
893
+ "epoch": 0.09,
894
+ "learning_rate": 0.002275757575757576,
895
+ "loss": 4.1012,
896
+ "step": 1480
897
+ },
898
+ {
899
+ "epoch": 0.09,
900
+ "learning_rate": 0.0022742424242424243,
901
+ "loss": 4.2861,
902
+ "step": 1490
903
+ },
904
+ {
905
+ "epoch": 0.09,
906
+ "learning_rate": 0.0022727272727272726,
907
+ "loss": 4.2572,
908
+ "step": 1500
909
+ },
910
+ {
911
+ "epoch": 0.09,
912
+ "learning_rate": 0.0022712121212121214,
913
+ "loss": 4.5604,
914
+ "step": 1510
915
+ },
916
+ {
917
+ "epoch": 0.09,
918
+ "learning_rate": 0.0022696969696969697,
919
+ "loss": 4.2148,
920
+ "step": 1520
921
+ },
922
+ {
923
+ "epoch": 0.09,
924
+ "learning_rate": 0.002268181818181818,
925
+ "loss": 4.3568,
926
+ "step": 1530
927
+ },
928
+ {
929
+ "epoch": 0.09,
930
+ "learning_rate": 0.0022666666666666664,
931
+ "loss": 4.293,
932
+ "step": 1540
933
+ },
934
+ {
935
+ "epoch": 0.09,
936
+ "learning_rate": 0.002265151515151515,
937
+ "loss": 4.658,
938
+ "step": 1550
939
+ },
940
+ {
941
+ "epoch": 0.1,
942
+ "learning_rate": 0.0022636363636363635,
943
+ "loss": 4.4127,
944
+ "step": 1560
945
+ },
946
+ {
947
+ "epoch": 0.1,
948
+ "learning_rate": 0.0022621212121212123,
949
+ "loss": 4.3584,
950
+ "step": 1570
951
+ },
952
+ {
953
+ "epoch": 0.1,
954
+ "learning_rate": 0.0022606060606060606,
955
+ "loss": 4.3832,
956
+ "step": 1580
957
+ },
958
+ {
959
+ "epoch": 0.1,
960
+ "learning_rate": 0.0022590909090909094,
961
+ "loss": 4.1822,
962
+ "step": 1590
963
+ },
964
+ {
965
+ "epoch": 0.1,
966
+ "learning_rate": 0.0022575757575757577,
967
+ "loss": 4.4045,
968
+ "step": 1600
969
+ },
970
+ {
971
+ "epoch": 0.1,
972
+ "learning_rate": 0.002256060606060606,
973
+ "loss": 4.4514,
974
+ "step": 1610
975
+ },
976
+ {
977
+ "epoch": 0.1,
978
+ "learning_rate": 0.002254545454545455,
979
+ "loss": 3.8766,
980
+ "step": 1620
981
+ },
982
+ {
983
+ "epoch": 0.1,
984
+ "learning_rate": 0.002253030303030303,
985
+ "loss": 4.6047,
986
+ "step": 1630
987
+ },
988
+ {
989
+ "epoch": 0.1,
990
+ "learning_rate": 0.0022515151515151515,
991
+ "loss": 4.1969,
992
+ "step": 1640
993
+ },
994
+ {
995
+ "epoch": 0.1,
996
+ "learning_rate": 0.0022500000000000003,
997
+ "loss": 4.1688,
998
+ "step": 1650
999
+ },
1000
+ {
1001
+ "epoch": 0.1,
1002
+ "learning_rate": 0.0022484848484848486,
1003
+ "loss": 4.5,
1004
+ "step": 1660
1005
+ },
1006
+ {
1007
+ "epoch": 0.1,
1008
+ "learning_rate": 0.002246969696969697,
1009
+ "loss": 4.1338,
1010
+ "step": 1670
1011
+ },
1012
+ {
1013
+ "epoch": 0.1,
1014
+ "learning_rate": 0.0022454545454545457,
1015
+ "loss": 4.4885,
1016
+ "step": 1680
1017
+ },
1018
+ {
1019
+ "epoch": 0.1,
1020
+ "learning_rate": 0.002243939393939394,
1021
+ "loss": 3.8264,
1022
+ "step": 1690
1023
+ },
1024
+ {
1025
+ "epoch": 0.1,
1026
+ "learning_rate": 0.0022424242424242424,
1027
+ "loss": 4.1896,
1028
+ "step": 1700
1029
+ },
1030
+ {
1031
+ "epoch": 0.1,
1032
+ "learning_rate": 0.002240909090909091,
1033
+ "loss": 4.1893,
1034
+ "step": 1710
1035
+ },
1036
+ {
1037
+ "epoch": 0.1,
1038
+ "learning_rate": 0.0022393939393939395,
1039
+ "loss": 4.3912,
1040
+ "step": 1720
1041
+ },
1042
+ {
1043
+ "epoch": 0.11,
1044
+ "learning_rate": 0.002237878787878788,
1045
+ "loss": 4.2867,
1046
+ "step": 1730
1047
+ },
1048
+ {
1049
+ "epoch": 0.11,
1050
+ "learning_rate": 0.0022363636363636366,
1051
+ "loss": 4.3912,
1052
+ "step": 1740
1053
+ },
1054
+ {
1055
+ "epoch": 0.11,
1056
+ "learning_rate": 0.002234848484848485,
1057
+ "loss": 4.1045,
1058
+ "step": 1750
1059
+ },
1060
+ {
1061
+ "epoch": 0.11,
1062
+ "learning_rate": 0.0022333333333333333,
1063
+ "loss": 4.1043,
1064
+ "step": 1760
1065
+ },
1066
+ {
1067
+ "epoch": 0.11,
1068
+ "learning_rate": 0.0022318181818181816,
1069
+ "loss": 4.2686,
1070
+ "step": 1770
1071
+ },
1072
+ {
1073
+ "epoch": 0.11,
1074
+ "learning_rate": 0.0022303030303030304,
1075
+ "loss": 4.4639,
1076
+ "step": 1780
1077
+ },
1078
+ {
1079
+ "epoch": 0.11,
1080
+ "learning_rate": 0.0022287878787878787,
1081
+ "loss": 4.0201,
1082
+ "step": 1790
1083
+ },
1084
+ {
1085
+ "epoch": 0.11,
1086
+ "learning_rate": 0.002227272727272727,
1087
+ "loss": 4.0189,
1088
+ "step": 1800
1089
+ },
1090
+ {
1091
+ "epoch": 0.11,
1092
+ "learning_rate": 0.002225757575757576,
1093
+ "loss": 4.0787,
1094
+ "step": 1810
1095
+ },
1096
+ {
1097
+ "epoch": 0.11,
1098
+ "learning_rate": 0.002224242424242424,
1099
+ "loss": 3.8324,
1100
+ "step": 1820
1101
+ },
1102
+ {
1103
+ "epoch": 0.11,
1104
+ "learning_rate": 0.0022227272727272725,
1105
+ "loss": 4.4113,
1106
+ "step": 1830
1107
+ },
1108
+ {
1109
+ "epoch": 0.11,
1110
+ "learning_rate": 0.0022212121212121213,
1111
+ "loss": 4.117,
1112
+ "step": 1840
1113
+ },
1114
+ {
1115
+ "epoch": 0.11,
1116
+ "learning_rate": 0.00221969696969697,
1117
+ "loss": 4.1695,
1118
+ "step": 1850
1119
+ },
1120
+ {
1121
+ "epoch": 0.11,
1122
+ "learning_rate": 0.0022181818181818184,
1123
+ "loss": 4.2963,
1124
+ "step": 1860
1125
+ },
1126
+ {
1127
+ "epoch": 0.11,
1128
+ "learning_rate": 0.0022166666666666667,
1129
+ "loss": 4.4145,
1130
+ "step": 1870
1131
+ },
1132
+ {
1133
+ "epoch": 0.11,
1134
+ "learning_rate": 0.0022151515151515155,
1135
+ "loss": 4.076,
1136
+ "step": 1880
1137
+ },
1138
+ {
1139
+ "epoch": 0.12,
1140
+ "learning_rate": 0.002213636363636364,
1141
+ "loss": 4.3945,
1142
+ "step": 1890
1143
+ },
1144
+ {
1145
+ "epoch": 0.12,
1146
+ "learning_rate": 0.002212121212121212,
1147
+ "loss": 4.042,
1148
+ "step": 1900
1149
+ },
1150
+ {
1151
+ "epoch": 0.12,
1152
+ "learning_rate": 0.002210606060606061,
1153
+ "loss": 3.8959,
1154
+ "step": 1910
1155
+ },
1156
+ {
1157
+ "epoch": 0.12,
1158
+ "learning_rate": 0.0022090909090909092,
1159
+ "loss": 3.8939,
1160
+ "step": 1920
1161
+ },
1162
+ {
1163
+ "epoch": 0.12,
1164
+ "learning_rate": 0.0022075757575757576,
1165
+ "loss": 4.3057,
1166
+ "step": 1930
1167
+ },
1168
+ {
1169
+ "epoch": 0.12,
1170
+ "learning_rate": 0.0022060606060606064,
1171
+ "loss": 4.5699,
1172
+ "step": 1940
1173
+ },
1174
+ {
1175
+ "epoch": 0.12,
1176
+ "learning_rate": 0.0022045454545454547,
1177
+ "loss": 3.8951,
1178
+ "step": 1950
1179
+ },
1180
+ {
1181
+ "epoch": 0.12,
1182
+ "learning_rate": 0.002203030303030303,
1183
+ "loss": 4.041,
1184
+ "step": 1960
1185
+ },
1186
+ {
1187
+ "epoch": 0.12,
1188
+ "learning_rate": 0.002201515151515152,
1189
+ "loss": 4.4762,
1190
+ "step": 1970
1191
+ },
1192
+ {
1193
+ "epoch": 0.12,
1194
+ "learning_rate": 0.0022,
1195
+ "loss": 4.225,
1196
+ "step": 1980
1197
+ },
1198
+ {
1199
+ "epoch": 0.12,
1200
+ "learning_rate": 0.0021984848484848485,
1201
+ "loss": 4.4705,
1202
+ "step": 1990
1203
+ },
1204
+ {
1205
+ "epoch": 0.12,
1206
+ "learning_rate": 0.002196969696969697,
1207
+ "loss": 4.2803,
1208
+ "step": 2000
1209
+ },
1210
+ {
1211
+ "epoch": 0.12,
1212
+ "learning_rate": 0.0021954545454545456,
1213
+ "loss": 4.0248,
1214
+ "step": 2010
1215
+ },
1216
+ {
1217
+ "epoch": 0.12,
1218
+ "learning_rate": 0.002193939393939394,
1219
+ "loss": 4.09,
1220
+ "step": 2020
1221
+ },
1222
+ {
1223
+ "epoch": 0.12,
1224
+ "learning_rate": 0.0021924242424242422,
1225
+ "loss": 4.2914,
1226
+ "step": 2030
1227
+ },
1228
+ {
1229
+ "epoch": 0.12,
1230
+ "learning_rate": 0.002190909090909091,
1231
+ "loss": 4.1557,
1232
+ "step": 2040
1233
+ },
1234
+ {
1235
+ "epoch": 0.13,
1236
+ "learning_rate": 0.0021893939393939394,
1237
+ "loss": 4.041,
1238
+ "step": 2050
1239
+ },
1240
+ {
1241
+ "epoch": 0.13,
1242
+ "learning_rate": 0.0021878787878787877,
1243
+ "loss": 4.6293,
1244
+ "step": 2060
1245
+ },
1246
+ {
1247
+ "epoch": 0.13,
1248
+ "learning_rate": 0.0021863636363636365,
1249
+ "loss": 4.2543,
1250
+ "step": 2070
1251
+ },
1252
+ {
1253
+ "epoch": 0.13,
1254
+ "learning_rate": 0.002184848484848485,
1255
+ "loss": 4.3525,
1256
+ "step": 2080
1257
+ },
1258
+ {
1259
+ "epoch": 0.13,
1260
+ "learning_rate": 0.002183333333333333,
1261
+ "loss": 4.2623,
1262
+ "step": 2090
1263
+ },
1264
+ {
1265
+ "epoch": 0.13,
1266
+ "learning_rate": 0.002181818181818182,
1267
+ "loss": 4.3332,
1268
+ "step": 2100
1269
+ },
1270
+ {
1271
+ "epoch": 0.13,
1272
+ "learning_rate": 0.0021803030303030302,
1273
+ "loss": 4.4281,
1274
+ "step": 2110
1275
+ },
1276
+ {
1277
+ "epoch": 0.13,
1278
+ "learning_rate": 0.0021787878787878786,
1279
+ "loss": 4.3771,
1280
+ "step": 2120
1281
+ },
1282
+ {
1283
+ "epoch": 0.13,
1284
+ "learning_rate": 0.0021772727272727273,
1285
+ "loss": 4.4289,
1286
+ "step": 2130
1287
+ },
1288
+ {
1289
+ "epoch": 0.13,
1290
+ "learning_rate": 0.002175757575757576,
1291
+ "loss": 3.9854,
1292
+ "step": 2140
1293
+ },
1294
+ {
1295
+ "epoch": 0.13,
1296
+ "learning_rate": 0.0021742424242424245,
1297
+ "loss": 4.7166,
1298
+ "step": 2150
1299
+ },
1300
+ {
1301
+ "epoch": 0.13,
1302
+ "learning_rate": 0.002172727272727273,
1303
+ "loss": 4.2908,
1304
+ "step": 2160
1305
+ },
1306
+ {
1307
+ "epoch": 0.13,
1308
+ "learning_rate": 0.0021712121212121216,
1309
+ "loss": 4.5039,
1310
+ "step": 2170
1311
+ },
1312
+ {
1313
+ "epoch": 0.13,
1314
+ "learning_rate": 0.00216969696969697,
1315
+ "loss": 4.2756,
1316
+ "step": 2180
1317
+ },
1318
+ {
1319
+ "epoch": 0.13,
1320
+ "learning_rate": 0.0021681818181818182,
1321
+ "loss": 4.1209,
1322
+ "step": 2190
1323
+ },
1324
+ {
1325
+ "epoch": 0.13,
1326
+ "learning_rate": 0.002166666666666667,
1327
+ "loss": 3.9537,
1328
+ "step": 2200
1329
+ },
1330
+ {
1331
+ "epoch": 0.13,
1332
+ "learning_rate": 0.0021651515151515153,
1333
+ "loss": 4.2012,
1334
+ "step": 2210
1335
+ },
1336
+ {
1337
+ "epoch": 0.14,
1338
+ "learning_rate": 0.0021636363636363637,
1339
+ "loss": 4.1775,
1340
+ "step": 2220
1341
+ },
1342
+ {
1343
+ "epoch": 0.14,
1344
+ "learning_rate": 0.002162121212121212,
1345
+ "loss": 4.1004,
1346
+ "step": 2230
1347
+ },
1348
+ {
1349
+ "epoch": 0.14,
1350
+ "learning_rate": 0.0021606060606060608,
1351
+ "loss": 4.5125,
1352
+ "step": 2240
1353
+ },
1354
+ {
1355
+ "epoch": 0.14,
1356
+ "learning_rate": 0.002159090909090909,
1357
+ "loss": 4.1016,
1358
+ "step": 2250
1359
+ },
1360
+ {
1361
+ "epoch": 0.14,
1362
+ "learning_rate": 0.0021575757575757575,
1363
+ "loss": 4.1955,
1364
+ "step": 2260
1365
+ },
1366
+ {
1367
+ "epoch": 0.14,
1368
+ "learning_rate": 0.0021560606060606062,
1369
+ "loss": 4.3717,
1370
+ "step": 2270
1371
+ },
1372
+ {
1373
+ "epoch": 0.14,
1374
+ "learning_rate": 0.0021545454545454546,
1375
+ "loss": 4.6578,
1376
+ "step": 2280
1377
+ },
1378
+ {
1379
+ "epoch": 0.14,
1380
+ "learning_rate": 0.002153030303030303,
1381
+ "loss": 4.5115,
1382
+ "step": 2290
1383
+ },
1384
+ {
1385
+ "epoch": 0.14,
1386
+ "learning_rate": 0.0021515151515151517,
1387
+ "loss": 4.4395,
1388
+ "step": 2300
1389
+ },
1390
+ {
1391
+ "epoch": 0.14,
1392
+ "learning_rate": 0.00215,
1393
+ "loss": 4.1674,
1394
+ "step": 2310
1395
+ },
1396
+ {
1397
+ "epoch": 0.14,
1398
+ "learning_rate": 0.0021484848484848483,
1399
+ "loss": 4.1488,
1400
+ "step": 2320
1401
+ },
1402
+ {
1403
+ "epoch": 0.14,
1404
+ "learning_rate": 0.002146969696969697,
1405
+ "loss": 4.0652,
1406
+ "step": 2330
1407
+ },
1408
+ {
1409
+ "epoch": 0.14,
1410
+ "learning_rate": 0.0021454545454545454,
1411
+ "loss": 4.2736,
1412
+ "step": 2340
1413
+ },
1414
+ {
1415
+ "epoch": 0.14,
1416
+ "learning_rate": 0.0021439393939393938,
1417
+ "loss": 4.2018,
1418
+ "step": 2350
1419
+ },
1420
+ {
1421
+ "epoch": 0.14,
1422
+ "learning_rate": 0.0021424242424242426,
1423
+ "loss": 4.3178,
1424
+ "step": 2360
1425
+ },
1426
+ {
1427
+ "epoch": 0.14,
1428
+ "learning_rate": 0.002140909090909091,
1429
+ "loss": 4.5182,
1430
+ "step": 2370
1431
+ },
1432
+ {
1433
+ "epoch": 0.15,
1434
+ "learning_rate": 0.0021393939393939392,
1435
+ "loss": 4.4102,
1436
+ "step": 2380
1437
+ },
1438
+ {
1439
+ "epoch": 0.15,
1440
+ "learning_rate": 0.002137878787878788,
1441
+ "loss": 4.392,
1442
+ "step": 2390
1443
+ },
1444
+ {
1445
+ "epoch": 0.15,
1446
+ "learning_rate": 0.0021363636363636363,
1447
+ "loss": 4.2674,
1448
+ "step": 2400
1449
+ },
1450
+ {
1451
+ "epoch": 0.15,
1452
+ "learning_rate": 0.0021348484848484847,
1453
+ "loss": 3.9971,
1454
+ "step": 2410
1455
+ },
1456
+ {
1457
+ "epoch": 0.15,
1458
+ "learning_rate": 0.0021333333333333334,
1459
+ "loss": 4.4205,
1460
+ "step": 2420
1461
+ },
1462
+ {
1463
+ "epoch": 0.15,
1464
+ "learning_rate": 0.002131818181818182,
1465
+ "loss": 4.0297,
1466
+ "step": 2430
1467
+ },
1468
+ {
1469
+ "epoch": 0.15,
1470
+ "learning_rate": 0.0021303030303030305,
1471
+ "loss": 4.0076,
1472
+ "step": 2440
1473
+ },
1474
+ {
1475
+ "epoch": 0.15,
1476
+ "learning_rate": 0.002128787878787879,
1477
+ "loss": 4.1734,
1478
+ "step": 2450
1479
+ },
1480
+ {
1481
+ "epoch": 0.15,
1482
+ "learning_rate": 0.002127272727272727,
1483
+ "loss": 4.0545,
1484
+ "step": 2460
1485
+ },
1486
+ {
1487
+ "epoch": 0.15,
1488
+ "learning_rate": 0.002125757575757576,
1489
+ "loss": 3.9951,
1490
+ "step": 2470
1491
+ },
1492
+ {
1493
+ "epoch": 0.15,
1494
+ "learning_rate": 0.0021242424242424243,
1495
+ "loss": 4.2332,
1496
+ "step": 2480
1497
+ },
1498
+ {
1499
+ "epoch": 0.15,
1500
+ "learning_rate": 0.0021227272727272727,
1501
+ "loss": 3.9803,
1502
+ "step": 2490
1503
+ },
1504
+ {
1505
+ "epoch": 0.15,
1506
+ "learning_rate": 0.0021212121212121214,
1507
+ "loss": 4.5166,
1508
+ "step": 2500
1509
+ },
1510
+ {
1511
+ "epoch": 0.15,
1512
+ "learning_rate": 0.0021196969696969698,
1513
+ "loss": 4.1238,
1514
+ "step": 2510
1515
+ },
1516
+ {
1517
+ "epoch": 0.15,
1518
+ "learning_rate": 0.002118181818181818,
1519
+ "loss": 3.9596,
1520
+ "step": 2520
1521
+ },
1522
+ {
1523
+ "epoch": 0.15,
1524
+ "learning_rate": 0.002116666666666667,
1525
+ "loss": 4.0205,
1526
+ "step": 2530
1527
+ },
1528
+ {
1529
+ "epoch": 0.15,
1530
+ "learning_rate": 0.002115151515151515,
1531
+ "loss": 4.4902,
1532
+ "step": 2540
1533
+ },
1534
+ {
1535
+ "epoch": 0.16,
1536
+ "learning_rate": 0.0021136363636363635,
1537
+ "loss": 4.3045,
1538
+ "step": 2550
1539
+ },
1540
+ {
1541
+ "epoch": 0.16,
1542
+ "learning_rate": 0.0021121212121212123,
1543
+ "loss": 3.9855,
1544
+ "step": 2560
1545
+ },
1546
+ {
1547
+ "epoch": 0.16,
1548
+ "learning_rate": 0.0021106060606060606,
1549
+ "loss": 4.216,
1550
+ "step": 2570
1551
+ },
1552
+ {
1553
+ "epoch": 0.16,
1554
+ "learning_rate": 0.002109090909090909,
1555
+ "loss": 4.4146,
1556
+ "step": 2580
1557
+ },
1558
+ {
1559
+ "epoch": 0.16,
1560
+ "learning_rate": 0.0021075757575757578,
1561
+ "loss": 3.9723,
1562
+ "step": 2590
1563
+ },
1564
+ {
1565
+ "epoch": 0.16,
1566
+ "learning_rate": 0.002106060606060606,
1567
+ "loss": 4.2469,
1568
+ "step": 2600
1569
+ },
1570
+ {
1571
+ "epoch": 0.16,
1572
+ "learning_rate": 0.0021045454545454544,
1573
+ "loss": 3.9295,
1574
+ "step": 2610
1575
+ },
1576
+ {
1577
+ "epoch": 0.16,
1578
+ "learning_rate": 0.002103030303030303,
1579
+ "loss": 4.2799,
1580
+ "step": 2620
1581
+ },
1582
+ {
1583
+ "epoch": 0.16,
1584
+ "learning_rate": 0.0021015151515151515,
1585
+ "loss": 4.1453,
1586
+ "step": 2630
1587
+ },
1588
+ {
1589
+ "epoch": 0.16,
1590
+ "learning_rate": 0.0021,
1591
+ "loss": 4.1547,
1592
+ "step": 2640
1593
+ },
1594
+ {
1595
+ "epoch": 0.16,
1596
+ "learning_rate": 0.0020984848484848486,
1597
+ "loss": 4.2727,
1598
+ "step": 2650
1599
+ },
1600
+ {
1601
+ "epoch": 0.16,
1602
+ "learning_rate": 0.002096969696969697,
1603
+ "loss": 4.1533,
1604
+ "step": 2660
1605
+ },
1606
+ {
1607
+ "epoch": 0.16,
1608
+ "learning_rate": 0.0020954545454545453,
1609
+ "loss": 3.9719,
1610
+ "step": 2670
1611
+ },
1612
+ {
1613
+ "epoch": 0.16,
1614
+ "learning_rate": 0.002093939393939394,
1615
+ "loss": 4.3705,
1616
+ "step": 2680
1617
+ },
1618
+ {
1619
+ "epoch": 0.16,
1620
+ "learning_rate": 0.0020924242424242424,
1621
+ "loss": 3.7813,
1622
+ "step": 2690
1623
+ },
1624
+ {
1625
+ "epoch": 0.16,
1626
+ "learning_rate": 0.0020909090909090908,
1627
+ "loss": 4.1619,
1628
+ "step": 2700
1629
+ },
1630
+ {
1631
+ "epoch": 0.17,
1632
+ "learning_rate": 0.0020893939393939395,
1633
+ "loss": 3.8096,
1634
+ "step": 2710
1635
+ },
1636
+ {
1637
+ "epoch": 0.17,
1638
+ "learning_rate": 0.002087878787878788,
1639
+ "loss": 4.2779,
1640
+ "step": 2720
1641
+ },
1642
+ {
1643
+ "epoch": 0.17,
1644
+ "learning_rate": 0.0020863636363636366,
1645
+ "loss": 4.152,
1646
+ "step": 2730
1647
+ },
1648
+ {
1649
+ "epoch": 0.17,
1650
+ "learning_rate": 0.002084848484848485,
1651
+ "loss": 4.6047,
1652
+ "step": 2740
1653
+ },
1654
+ {
1655
+ "epoch": 0.17,
1656
+ "learning_rate": 0.0020833333333333333,
1657
+ "loss": 3.9848,
1658
+ "step": 2750
1659
+ },
1660
+ {
1661
+ "epoch": 0.17,
1662
+ "learning_rate": 0.002081818181818182,
1663
+ "loss": 4.068,
1664
+ "step": 2760
1665
+ },
1666
+ {
1667
+ "epoch": 0.17,
1668
+ "learning_rate": 0.0020803030303030304,
1669
+ "loss": 4.0783,
1670
+ "step": 2770
1671
+ },
1672
+ {
1673
+ "epoch": 0.17,
1674
+ "learning_rate": 0.0020787878787878787,
1675
+ "loss": 3.8646,
1676
+ "step": 2780
1677
+ },
1678
+ {
1679
+ "epoch": 0.17,
1680
+ "learning_rate": 0.0020772727272727275,
1681
+ "loss": 4.4756,
1682
+ "step": 2790
1683
+ },
1684
+ {
1685
+ "epoch": 0.17,
1686
+ "learning_rate": 0.002075757575757576,
1687
+ "loss": 4.0518,
1688
+ "step": 2800
1689
+ },
1690
+ {
1691
+ "epoch": 0.17,
1692
+ "learning_rate": 0.002074242424242424,
1693
+ "loss": 4.1688,
1694
+ "step": 2810
1695
+ },
1696
+ {
1697
+ "epoch": 0.17,
1698
+ "learning_rate": 0.002072727272727273,
1699
+ "loss": 4.3254,
1700
+ "step": 2820
1701
+ },
1702
+ {
1703
+ "epoch": 0.17,
1704
+ "learning_rate": 0.0020712121212121213,
1705
+ "loss": 4.3361,
1706
+ "step": 2830
1707
+ },
1708
+ {
1709
+ "epoch": 0.17,
1710
+ "learning_rate": 0.0020696969696969696,
1711
+ "loss": 4.5381,
1712
+ "step": 2840
1713
+ },
1714
+ {
1715
+ "epoch": 0.17,
1716
+ "learning_rate": 0.0020681818181818184,
1717
+ "loss": 4.1404,
1718
+ "step": 2850
1719
+ },
1720
+ {
1721
+ "epoch": 0.17,
1722
+ "learning_rate": 0.0020666666666666667,
1723
+ "loss": 4.3307,
1724
+ "step": 2860
1725
+ },
1726
+ {
1727
+ "epoch": 0.18,
1728
+ "learning_rate": 0.002065151515151515,
1729
+ "loss": 4.2369,
1730
+ "step": 2870
1731
+ },
1732
+ {
1733
+ "epoch": 0.18,
1734
+ "learning_rate": 0.002063636363636364,
1735
+ "loss": 3.973,
1736
+ "step": 2880
1737
+ },
1738
+ {
1739
+ "epoch": 0.18,
1740
+ "learning_rate": 0.002062121212121212,
1741
+ "loss": 4.0045,
1742
+ "step": 2890
1743
+ },
1744
+ {
1745
+ "epoch": 0.18,
1746
+ "learning_rate": 0.0020606060606060605,
1747
+ "loss": 3.717,
1748
+ "step": 2900
1749
+ },
1750
+ {
1751
+ "epoch": 0.18,
1752
+ "learning_rate": 0.002059090909090909,
1753
+ "loss": 4.3682,
1754
+ "step": 2910
1755
+ },
1756
+ {
1757
+ "epoch": 0.18,
1758
+ "learning_rate": 0.0020575757575757576,
1759
+ "loss": 4.2744,
1760
+ "step": 2920
1761
+ },
1762
+ {
1763
+ "epoch": 0.18,
1764
+ "learning_rate": 0.002056060606060606,
1765
+ "loss": 4.0842,
1766
+ "step": 2930
1767
+ },
1768
+ {
1769
+ "epoch": 0.18,
1770
+ "learning_rate": 0.0020545454545454543,
1771
+ "loss": 4.4441,
1772
+ "step": 2940
1773
+ },
1774
+ {
1775
+ "epoch": 0.18,
1776
+ "learning_rate": 0.002053030303030303,
1777
+ "loss": 3.993,
1778
+ "step": 2950
1779
+ },
1780
+ {
1781
+ "epoch": 0.18,
1782
+ "learning_rate": 0.0020515151515151514,
1783
+ "loss": 3.9664,
1784
+ "step": 2960
1785
+ },
1786
+ {
1787
+ "epoch": 0.18,
1788
+ "learning_rate": 0.0020499999999999997,
1789
+ "loss": 4.2275,
1790
+ "step": 2970
1791
+ },
1792
+ {
1793
+ "epoch": 0.18,
1794
+ "learning_rate": 0.0020484848484848485,
1795
+ "loss": 3.7014,
1796
+ "step": 2980
1797
+ },
1798
+ {
1799
+ "epoch": 0.18,
1800
+ "learning_rate": 0.0020469696969696973,
1801
+ "loss": 3.8799,
1802
+ "step": 2990
1803
+ },
1804
+ {
1805
+ "epoch": 0.18,
1806
+ "learning_rate": 0.0020454545454545456,
1807
+ "loss": 3.9643,
1808
+ "step": 3000
1809
+ },
1810
+ {
1811
+ "epoch": 0.18,
1812
+ "learning_rate": 0.002043939393939394,
1813
+ "loss": 4.0553,
1814
+ "step": 3010
1815
+ },
1816
+ {
1817
+ "epoch": 0.18,
1818
+ "learning_rate": 0.0020424242424242427,
1819
+ "loss": 4.0256,
1820
+ "step": 3020
1821
+ },
1822
+ {
1823
+ "epoch": 0.18,
1824
+ "learning_rate": 0.002040909090909091,
1825
+ "loss": 4.1273,
1826
+ "step": 3030
1827
+ },
1828
+ {
1829
+ "epoch": 0.19,
1830
+ "learning_rate": 0.0020393939393939394,
1831
+ "loss": 4.0736,
1832
+ "step": 3040
1833
+ },
1834
+ {
1835
+ "epoch": 0.19,
1836
+ "learning_rate": 0.002037878787878788,
1837
+ "loss": 4.1354,
1838
+ "step": 3050
1839
+ },
1840
+ {
1841
+ "epoch": 0.19,
1842
+ "learning_rate": 0.0020363636363636365,
1843
+ "loss": 4.2006,
1844
+ "step": 3060
1845
+ },
1846
+ {
1847
+ "epoch": 0.19,
1848
+ "learning_rate": 0.002034848484848485,
1849
+ "loss": 4.284,
1850
+ "step": 3070
1851
+ },
1852
+ {
1853
+ "epoch": 0.19,
1854
+ "learning_rate": 0.0020333333333333336,
1855
+ "loss": 4.191,
1856
+ "step": 3080
1857
+ },
1858
+ {
1859
+ "epoch": 0.19,
1860
+ "learning_rate": 0.002031818181818182,
1861
+ "loss": 4.3771,
1862
+ "step": 3090
1863
+ },
1864
+ {
1865
+ "epoch": 0.19,
1866
+ "learning_rate": 0.0020303030303030303,
1867
+ "loss": 3.9966,
1868
+ "step": 3100
1869
+ },
1870
+ {
1871
+ "epoch": 0.19,
1872
+ "learning_rate": 0.002028787878787879,
1873
+ "loss": 4.1867,
1874
+ "step": 3110
1875
+ },
1876
+ {
1877
+ "epoch": 0.19,
1878
+ "learning_rate": 0.0020272727272727274,
1879
+ "loss": 3.9691,
1880
+ "step": 3120
1881
+ },
1882
+ {
1883
+ "epoch": 0.19,
1884
+ "learning_rate": 0.0020257575757575757,
1885
+ "loss": 3.9979,
1886
+ "step": 3130
1887
+ },
1888
+ {
1889
+ "epoch": 0.19,
1890
+ "learning_rate": 0.002024242424242424,
1891
+ "loss": 4.3219,
1892
+ "step": 3140
1893
+ },
1894
+ {
1895
+ "epoch": 0.19,
1896
+ "learning_rate": 0.002022727272727273,
1897
+ "loss": 3.9918,
1898
+ "step": 3150
1899
+ },
1900
+ {
1901
+ "epoch": 0.19,
1902
+ "learning_rate": 0.002021212121212121,
1903
+ "loss": 4.3541,
1904
+ "step": 3160
1905
+ },
1906
+ {
1907
+ "epoch": 0.19,
1908
+ "learning_rate": 0.0020196969696969695,
1909
+ "loss": 4.2801,
1910
+ "step": 3170
1911
+ },
1912
+ {
1913
+ "epoch": 0.19,
1914
+ "learning_rate": 0.0020181818181818183,
1915
+ "loss": 3.8957,
1916
+ "step": 3180
1917
+ },
1918
+ {
1919
+ "epoch": 0.19,
1920
+ "learning_rate": 0.0020166666666666666,
1921
+ "loss": 4.8797,
1922
+ "step": 3190
1923
+ },
1924
+ {
1925
+ "epoch": 0.2,
1926
+ "learning_rate": 0.002015151515151515,
1927
+ "loss": 4.1672,
1928
+ "step": 3200
1929
+ },
1930
+ {
1931
+ "epoch": 0.2,
1932
+ "learning_rate": 0.0020136363636363637,
1933
+ "loss": 4.1686,
1934
+ "step": 3210
1935
+ },
1936
+ {
1937
+ "epoch": 0.2,
1938
+ "learning_rate": 0.002012121212121212,
1939
+ "loss": 4.3756,
1940
+ "step": 3220
1941
+ },
1942
+ {
1943
+ "epoch": 0.2,
1944
+ "learning_rate": 0.0020106060606060604,
1945
+ "loss": 4.307,
1946
+ "step": 3230
1947
+ },
1948
+ {
1949
+ "epoch": 0.2,
1950
+ "learning_rate": 0.002009090909090909,
1951
+ "loss": 4.0963,
1952
+ "step": 3240
1953
+ },
1954
+ {
1955
+ "epoch": 0.2,
1956
+ "learning_rate": 0.0020075757575757575,
1957
+ "loss": 3.9398,
1958
+ "step": 3250
1959
+ },
1960
+ {
1961
+ "epoch": 0.2,
1962
+ "learning_rate": 0.002006060606060606,
1963
+ "loss": 4.008,
1964
+ "step": 3260
1965
+ },
1966
+ {
1967
+ "epoch": 0.2,
1968
+ "learning_rate": 0.0020045454545454546,
1969
+ "loss": 3.7615,
1970
+ "step": 3270
1971
+ },
1972
+ {
1973
+ "epoch": 0.2,
1974
+ "learning_rate": 0.0020030303030303034,
1975
+ "loss": 4.1881,
1976
+ "step": 3280
1977
+ },
1978
+ {
1979
+ "epoch": 0.2,
1980
+ "learning_rate": 0.0020015151515151517,
1981
+ "loss": 3.8508,
1982
+ "step": 3290
1983
+ },
1984
+ {
1985
+ "epoch": 0.2,
1986
+ "learning_rate": 0.002,
1987
+ "loss": 4.3887,
1988
+ "step": 3300
1989
+ },
1990
+ {
1991
+ "epoch": 0.2,
1992
+ "learning_rate": 0.001998484848484849,
1993
+ "loss": 4.0209,
1994
+ "step": 3310
1995
+ },
1996
+ {
1997
+ "epoch": 0.2,
1998
+ "learning_rate": 0.001996969696969697,
1999
+ "loss": 4.1906,
2000
+ "step": 3320
2001
+ },
2002
+ {
2003
+ "epoch": 0.2,
2004
+ "learning_rate": 0.0019954545454545455,
2005
+ "loss": 4.1512,
2006
+ "step": 3330
2007
+ },
2008
+ {
2009
+ "epoch": 0.2,
2010
+ "learning_rate": 0.0019939393939393943,
2011
+ "loss": 4.2525,
2012
+ "step": 3340
2013
+ },
2014
+ {
2015
+ "epoch": 0.2,
2016
+ "learning_rate": 0.0019924242424242426,
2017
+ "loss": 4.3814,
2018
+ "step": 3350
2019
+ },
2020
+ {
2021
+ "epoch": 0.2,
2022
+ "learning_rate": 0.001990909090909091,
2023
+ "loss": 4.0068,
2024
+ "step": 3360
2025
+ },
2026
+ {
2027
+ "epoch": 0.21,
2028
+ "learning_rate": 0.0019893939393939393,
2029
+ "loss": 4.3184,
2030
+ "step": 3370
2031
+ },
2032
+ {
2033
+ "epoch": 0.21,
2034
+ "learning_rate": 0.001987878787878788,
2035
+ "loss": 4.4627,
2036
+ "step": 3380
2037
+ },
2038
+ {
2039
+ "epoch": 0.21,
2040
+ "learning_rate": 0.0019863636363636364,
2041
+ "loss": 4.1746,
2042
+ "step": 3390
2043
+ },
2044
+ {
2045
+ "epoch": 0.21,
2046
+ "learning_rate": 0.0019848484848484847,
2047
+ "loss": 3.9419,
2048
+ "step": 3400
2049
+ },
2050
+ {
2051
+ "epoch": 0.21,
2052
+ "learning_rate": 0.0019833333333333335,
2053
+ "loss": 4.0953,
2054
+ "step": 3410
2055
+ },
2056
+ {
2057
+ "epoch": 0.21,
2058
+ "learning_rate": 0.001981818181818182,
2059
+ "loss": 4.3074,
2060
+ "step": 3420
2061
+ },
2062
+ {
2063
+ "epoch": 0.21,
2064
+ "learning_rate": 0.00198030303030303,
2065
+ "loss": 4.2008,
2066
+ "step": 3430
2067
+ },
2068
+ {
2069
+ "epoch": 0.21,
2070
+ "learning_rate": 0.001978787878787879,
2071
+ "loss": 4.1914,
2072
+ "step": 3440
2073
+ },
2074
+ {
2075
+ "epoch": 0.21,
2076
+ "learning_rate": 0.0019772727272727273,
2077
+ "loss": 4.0264,
2078
+ "step": 3450
2079
+ },
2080
+ {
2081
+ "epoch": 0.21,
2082
+ "learning_rate": 0.0019757575757575756,
2083
+ "loss": 4.1937,
2084
+ "step": 3460
2085
+ },
2086
+ {
2087
+ "epoch": 0.21,
2088
+ "learning_rate": 0.0019742424242424244,
2089
+ "loss": 4.067,
2090
+ "step": 3470
2091
+ },
2092
+ {
2093
+ "epoch": 0.21,
2094
+ "learning_rate": 0.0019727272727272727,
2095
+ "loss": 4.2822,
2096
+ "step": 3480
2097
+ },
2098
+ {
2099
+ "epoch": 0.21,
2100
+ "learning_rate": 0.001971212121212121,
2101
+ "loss": 3.798,
2102
+ "step": 3490
2103
+ },
2104
+ {
2105
+ "epoch": 0.21,
2106
+ "learning_rate": 0.00196969696969697,
2107
+ "loss": 4.3059,
2108
+ "step": 3500
2109
+ },
2110
+ {
2111
+ "epoch": 0.21,
2112
+ "learning_rate": 0.001968181818181818,
2113
+ "loss": 3.8936,
2114
+ "step": 3510
2115
+ },
2116
+ {
2117
+ "epoch": 0.21,
2118
+ "learning_rate": 0.0019666666666666665,
2119
+ "loss": 4.3832,
2120
+ "step": 3520
2121
+ },
2122
+ {
2123
+ "epoch": 0.22,
2124
+ "learning_rate": 0.0019651515151515152,
2125
+ "loss": 4.3246,
2126
+ "step": 3530
2127
+ },
2128
+ {
2129
+ "epoch": 0.22,
2130
+ "learning_rate": 0.0019636363636363636,
2131
+ "loss": 4.0193,
2132
+ "step": 3540
2133
+ },
2134
+ {
2135
+ "epoch": 0.22,
2136
+ "learning_rate": 0.001962121212121212,
2137
+ "loss": 4.2828,
2138
+ "step": 3550
2139
+ },
2140
+ {
2141
+ "epoch": 0.22,
2142
+ "learning_rate": 0.0019606060606060607,
2143
+ "loss": 4.468,
2144
+ "step": 3560
2145
+ },
2146
+ {
2147
+ "epoch": 0.22,
2148
+ "learning_rate": 0.0019590909090909095,
2149
+ "loss": 4.2574,
2150
+ "step": 3570
2151
+ },
2152
+ {
2153
+ "epoch": 0.22,
2154
+ "learning_rate": 0.001957575757575758,
2155
+ "loss": 4.2453,
2156
+ "step": 3580
2157
+ },
2158
+ {
2159
+ "epoch": 0.22,
2160
+ "learning_rate": 0.001956060606060606,
2161
+ "loss": 4.1461,
2162
+ "step": 3590
2163
+ },
2164
+ {
2165
+ "epoch": 0.22,
2166
+ "learning_rate": 0.0019545454545454545,
2167
+ "loss": 4.1102,
2168
+ "step": 3600
2169
+ },
2170
+ {
2171
+ "epoch": 0.22,
2172
+ "learning_rate": 0.0019530303030303032,
2173
+ "loss": 4.5449,
2174
+ "step": 3610
2175
+ },
2176
+ {
2177
+ "epoch": 0.22,
2178
+ "learning_rate": 0.0019515151515151516,
2179
+ "loss": 3.9111,
2180
+ "step": 3620
2181
+ },
2182
+ {
2183
+ "epoch": 0.22,
2184
+ "learning_rate": 0.0019500000000000001,
2185
+ "loss": 3.9598,
2186
+ "step": 3630
2187
+ },
2188
+ {
2189
+ "epoch": 0.22,
2190
+ "learning_rate": 0.0019484848484848487,
2191
+ "loss": 4.2061,
2192
+ "step": 3640
2193
+ },
2194
+ {
2195
+ "epoch": 0.22,
2196
+ "learning_rate": 0.001946969696969697,
2197
+ "loss": 4.4254,
2198
+ "step": 3650
2199
+ },
2200
+ {
2201
+ "epoch": 0.22,
2202
+ "learning_rate": 0.0019454545454545456,
2203
+ "loss": 3.7582,
2204
+ "step": 3660
2205
+ },
2206
+ {
2207
+ "epoch": 0.22,
2208
+ "learning_rate": 0.001943939393939394,
2209
+ "loss": 4.152,
2210
+ "step": 3670
2211
+ },
2212
+ {
2213
+ "epoch": 0.22,
2214
+ "learning_rate": 0.0019424242424242425,
2215
+ "loss": 4.0951,
2216
+ "step": 3680
2217
+ },
2218
+ {
2219
+ "epoch": 0.23,
2220
+ "learning_rate": 0.001940909090909091,
2221
+ "loss": 4.1152,
2222
+ "step": 3690
2223
+ },
2224
+ {
2225
+ "epoch": 0.23,
2226
+ "learning_rate": 0.0019393939393939393,
2227
+ "loss": 4.3834,
2228
+ "step": 3700
2229
+ },
2230
+ {
2231
+ "epoch": 0.23,
2232
+ "learning_rate": 0.001937878787878788,
2233
+ "loss": 4.3691,
2234
+ "step": 3710
2235
+ },
2236
+ {
2237
+ "epoch": 0.23,
2238
+ "learning_rate": 0.0019363636363636365,
2239
+ "loss": 4.1271,
2240
+ "step": 3720
2241
+ },
2242
+ {
2243
+ "epoch": 0.23,
2244
+ "learning_rate": 0.0019348484848484848,
2245
+ "loss": 4.2613,
2246
+ "step": 3730
2247
+ },
2248
+ {
2249
+ "epoch": 0.23,
2250
+ "learning_rate": 0.0019333333333333333,
2251
+ "loss": 3.8348,
2252
+ "step": 3740
2253
+ },
2254
+ {
2255
+ "epoch": 0.23,
2256
+ "learning_rate": 0.001931818181818182,
2257
+ "loss": 4.1611,
2258
+ "step": 3750
2259
+ },
2260
+ {
2261
+ "epoch": 0.23,
2262
+ "learning_rate": 0.0019303030303030302,
2263
+ "loss": 4.2691,
2264
+ "step": 3760
2265
+ },
2266
+ {
2267
+ "epoch": 0.23,
2268
+ "learning_rate": 0.0019287878787878788,
2269
+ "loss": 4.2182,
2270
+ "step": 3770
2271
+ },
2272
+ {
2273
+ "epoch": 0.23,
2274
+ "learning_rate": 0.0019272727272727273,
2275
+ "loss": 4.1658,
2276
+ "step": 3780
2277
+ },
2278
+ {
2279
+ "epoch": 0.23,
2280
+ "learning_rate": 0.0019257575757575757,
2281
+ "loss": 3.9271,
2282
+ "step": 3790
2283
+ },
2284
+ {
2285
+ "epoch": 0.23,
2286
+ "learning_rate": 0.0019242424242424242,
2287
+ "loss": 3.7492,
2288
+ "step": 3800
2289
+ },
2290
+ {
2291
+ "epoch": 0.23,
2292
+ "learning_rate": 0.0019227272727272726,
2293
+ "loss": 4.0193,
2294
+ "step": 3810
2295
+ },
2296
+ {
2297
+ "epoch": 0.23,
2298
+ "learning_rate": 0.0019212121212121211,
2299
+ "loss": 4.4439,
2300
+ "step": 3820
2301
+ },
2302
+ {
2303
+ "epoch": 0.23,
2304
+ "learning_rate": 0.0019196969696969697,
2305
+ "loss": 4.0443,
2306
+ "step": 3830
2307
+ },
2308
+ {
2309
+ "epoch": 0.23,
2310
+ "learning_rate": 0.001918181818181818,
2311
+ "loss": 4.2902,
2312
+ "step": 3840
2313
+ },
2314
+ {
2315
+ "epoch": 0.23,
2316
+ "learning_rate": 0.0019166666666666668,
2317
+ "loss": 4.0879,
2318
+ "step": 3850
2319
+ },
2320
+ {
2321
+ "epoch": 0.24,
2322
+ "learning_rate": 0.0019151515151515153,
2323
+ "loss": 4.509,
2324
+ "step": 3860
2325
+ },
2326
+ {
2327
+ "epoch": 0.24,
2328
+ "learning_rate": 0.0019136363636363639,
2329
+ "loss": 4.2645,
2330
+ "step": 3870
2331
+ },
2332
+ {
2333
+ "epoch": 0.24,
2334
+ "learning_rate": 0.0019121212121212122,
2335
+ "loss": 3.8994,
2336
+ "step": 3880
2337
+ },
2338
+ {
2339
+ "epoch": 0.24,
2340
+ "learning_rate": 0.0019106060606060608,
2341
+ "loss": 3.8268,
2342
+ "step": 3890
2343
+ },
2344
+ {
2345
+ "epoch": 0.24,
2346
+ "learning_rate": 0.0019090909090909091,
2347
+ "loss": 4.0371,
2348
+ "step": 3900
2349
+ },
2350
+ {
2351
+ "epoch": 0.24,
2352
+ "learning_rate": 0.0019075757575757577,
2353
+ "loss": 4.2105,
2354
+ "step": 3910
2355
+ },
2356
+ {
2357
+ "epoch": 0.24,
2358
+ "learning_rate": 0.0019060606060606062,
2359
+ "loss": 4.0234,
2360
+ "step": 3920
2361
+ },
2362
+ {
2363
+ "epoch": 0.24,
2364
+ "learning_rate": 0.0019045454545454546,
2365
+ "loss": 3.8813,
2366
+ "step": 3930
2367
+ },
2368
+ {
2369
+ "epoch": 0.24,
2370
+ "learning_rate": 0.001903030303030303,
2371
+ "loss": 4.4242,
2372
+ "step": 3940
2373
+ },
2374
+ {
2375
+ "epoch": 0.24,
2376
+ "learning_rate": 0.0019015151515151517,
2377
+ "loss": 3.7244,
2378
+ "step": 3950
2379
+ },
2380
+ {
2381
+ "epoch": 0.24,
2382
+ "learning_rate": 0.0019,
2383
+ "loss": 4.2068,
2384
+ "step": 3960
2385
+ },
2386
+ {
2387
+ "epoch": 0.24,
2388
+ "learning_rate": 0.0018984848484848485,
2389
+ "loss": 4.008,
2390
+ "step": 3970
2391
+ },
2392
+ {
2393
+ "epoch": 0.24,
2394
+ "learning_rate": 0.001896969696969697,
2395
+ "loss": 4.1963,
2396
+ "step": 3980
2397
+ },
2398
+ {
2399
+ "epoch": 0.24,
2400
+ "learning_rate": 0.0018954545454545454,
2401
+ "loss": 4.5043,
2402
+ "step": 3990
2403
+ },
2404
+ {
2405
+ "epoch": 0.24,
2406
+ "learning_rate": 0.001893939393939394,
2407
+ "loss": 4.0703,
2408
+ "step": 4000
2409
+ },
2410
+ {
2411
+ "epoch": 0.24,
2412
+ "learning_rate": 0.0018924242424242425,
2413
+ "loss": 3.9598,
2414
+ "step": 4010
2415
+ },
2416
+ {
2417
+ "epoch": 0.25,
2418
+ "learning_rate": 0.0018909090909090909,
2419
+ "loss": 4.1252,
2420
+ "step": 4020
2421
+ },
2422
+ {
2423
+ "epoch": 0.25,
2424
+ "learning_rate": 0.0018893939393939394,
2425
+ "loss": 4.2848,
2426
+ "step": 4030
2427
+ },
2428
+ {
2429
+ "epoch": 0.25,
2430
+ "learning_rate": 0.0018878787878787878,
2431
+ "loss": 3.9209,
2432
+ "step": 4040
2433
+ },
2434
+ {
2435
+ "epoch": 0.25,
2436
+ "learning_rate": 0.0018863636363636363,
2437
+ "loss": 4.2768,
2438
+ "step": 4050
2439
+ },
2440
+ {
2441
+ "epoch": 0.25,
2442
+ "learning_rate": 0.0018848484848484849,
2443
+ "loss": 4.1338,
2444
+ "step": 4060
2445
+ },
2446
+ {
2447
+ "epoch": 0.25,
2448
+ "learning_rate": 0.0018833333333333332,
2449
+ "loss": 4.1549,
2450
+ "step": 4070
2451
+ },
2452
+ {
2453
+ "epoch": 0.25,
2454
+ "learning_rate": 0.0018818181818181818,
2455
+ "loss": 3.7658,
2456
+ "step": 4080
2457
+ },
2458
+ {
2459
+ "epoch": 0.25,
2460
+ "learning_rate": 0.0018803030303030303,
2461
+ "loss": 3.865,
2462
+ "step": 4090
2463
+ },
2464
+ {
2465
+ "epoch": 0.25,
2466
+ "learning_rate": 0.0018787878787878787,
2467
+ "loss": 3.9766,
2468
+ "step": 4100
2469
+ },
2470
+ {
2471
+ "epoch": 0.25,
2472
+ "learning_rate": 0.0018772727272727272,
2473
+ "loss": 4.2186,
2474
+ "step": 4110
2475
+ },
2476
+ {
2477
+ "epoch": 0.25,
2478
+ "learning_rate": 0.0018757575757575758,
2479
+ "loss": 4.3256,
2480
+ "step": 4120
2481
+ },
2482
+ {
2483
+ "epoch": 0.25,
2484
+ "learning_rate": 0.0018742424242424243,
2485
+ "loss": 4.1537,
2486
+ "step": 4130
2487
+ },
2488
+ {
2489
+ "epoch": 0.25,
2490
+ "learning_rate": 0.0018727272727272729,
2491
+ "loss": 3.8939,
2492
+ "step": 4140
2493
+ },
2494
+ {
2495
+ "epoch": 0.25,
2496
+ "learning_rate": 0.0018712121212121214,
2497
+ "loss": 4.201,
2498
+ "step": 4150
2499
+ },
2500
+ {
2501
+ "epoch": 0.25,
2502
+ "learning_rate": 0.0018696969696969698,
2503
+ "loss": 4.3982,
2504
+ "step": 4160
2505
+ },
2506
+ {
2507
+ "epoch": 0.25,
2508
+ "learning_rate": 0.0018681818181818183,
2509
+ "loss": 4.3611,
2510
+ "step": 4170
2511
+ },
2512
+ {
2513
+ "epoch": 0.25,
2514
+ "learning_rate": 0.0018666666666666669,
2515
+ "loss": 3.9762,
2516
+ "step": 4180
2517
+ },
2518
+ {
2519
+ "epoch": 0.26,
2520
+ "learning_rate": 0.0018651515151515152,
2521
+ "loss": 4.0193,
2522
+ "step": 4190
2523
+ },
2524
+ {
2525
+ "epoch": 0.26,
2526
+ "learning_rate": 0.0018636363636363638,
2527
+ "loss": 4.507,
2528
+ "step": 4200
2529
+ },
2530
+ {
2531
+ "epoch": 0.26,
2532
+ "learning_rate": 0.0018621212121212123,
2533
+ "loss": 4.2193,
2534
+ "step": 4210
2535
+ },
2536
+ {
2537
+ "epoch": 0.26,
2538
+ "learning_rate": 0.0018606060606060606,
2539
+ "loss": 4.0932,
2540
+ "step": 4220
2541
+ },
2542
+ {
2543
+ "epoch": 0.26,
2544
+ "learning_rate": 0.0018590909090909092,
2545
+ "loss": 3.9719,
2546
+ "step": 4230
2547
+ },
2548
+ {
2549
+ "epoch": 0.26,
2550
+ "learning_rate": 0.0018575757575757575,
2551
+ "loss": 4.4113,
2552
+ "step": 4240
2553
+ },
2554
+ {
2555
+ "epoch": 0.26,
2556
+ "learning_rate": 0.001856060606060606,
2557
+ "loss": 4.0824,
2558
+ "step": 4250
2559
+ },
2560
+ {
2561
+ "epoch": 0.26,
2562
+ "learning_rate": 0.0018545454545454546,
2563
+ "loss": 3.5553,
2564
+ "step": 4260
2565
+ },
2566
+ {
2567
+ "epoch": 0.26,
2568
+ "learning_rate": 0.001853030303030303,
2569
+ "loss": 3.9251,
2570
+ "step": 4270
2571
+ },
2572
+ {
2573
+ "epoch": 0.26,
2574
+ "learning_rate": 0.0018515151515151515,
2575
+ "loss": 4.3514,
2576
+ "step": 4280
2577
+ },
2578
+ {
2579
+ "epoch": 0.26,
2580
+ "learning_rate": 0.00185,
2581
+ "loss": 4.2945,
2582
+ "step": 4290
2583
+ },
2584
+ {
2585
+ "epoch": 0.26,
2586
+ "learning_rate": 0.0018484848484848484,
2587
+ "loss": 4.1324,
2588
+ "step": 4300
2589
+ },
2590
+ {
2591
+ "epoch": 0.26,
2592
+ "learning_rate": 0.001846969696969697,
2593
+ "loss": 4.3477,
2594
+ "step": 4310
2595
+ },
2596
+ {
2597
+ "epoch": 0.26,
2598
+ "learning_rate": 0.0018454545454545455,
2599
+ "loss": 3.9568,
2600
+ "step": 4320
2601
+ },
2602
+ {
2603
+ "epoch": 0.26,
2604
+ "learning_rate": 0.0018439393939393939,
2605
+ "loss": 4.1842,
2606
+ "step": 4330
2607
+ },
2608
+ {
2609
+ "epoch": 0.26,
2610
+ "learning_rate": 0.0018424242424242424,
2611
+ "loss": 3.8381,
2612
+ "step": 4340
2613
+ },
2614
+ {
2615
+ "epoch": 0.27,
2616
+ "learning_rate": 0.001840909090909091,
2617
+ "loss": 3.9949,
2618
+ "step": 4350
2619
+ },
2620
+ {
2621
+ "epoch": 0.27,
2622
+ "learning_rate": 0.0018393939393939393,
2623
+ "loss": 3.9988,
2624
+ "step": 4360
2625
+ },
2626
+ {
2627
+ "epoch": 0.27,
2628
+ "learning_rate": 0.0018378787878787879,
2629
+ "loss": 3.8552,
2630
+ "step": 4370
2631
+ },
2632
+ {
2633
+ "epoch": 0.27,
2634
+ "learning_rate": 0.0018363636363636362,
2635
+ "loss": 4.0248,
2636
+ "step": 4380
2637
+ },
2638
+ {
2639
+ "epoch": 0.27,
2640
+ "learning_rate": 0.0018348484848484847,
2641
+ "loss": 4.0281,
2642
+ "step": 4390
2643
+ },
2644
+ {
2645
+ "epoch": 0.27,
2646
+ "learning_rate": 0.0018333333333333333,
2647
+ "loss": 3.7404,
2648
+ "step": 4400
2649
+ },
2650
+ {
2651
+ "epoch": 0.27,
2652
+ "learning_rate": 0.001831818181818182,
2653
+ "loss": 4.2635,
2654
+ "step": 4410
2655
+ },
2656
+ {
2657
+ "epoch": 0.27,
2658
+ "learning_rate": 0.0018303030303030304,
2659
+ "loss": 4.283,
2660
+ "step": 4420
2661
+ },
2662
+ {
2663
+ "epoch": 0.27,
2664
+ "learning_rate": 0.001828787878787879,
2665
+ "loss": 4.2484,
2666
+ "step": 4430
2667
+ },
2668
+ {
2669
+ "epoch": 0.27,
2670
+ "learning_rate": 0.0018272727272727275,
2671
+ "loss": 3.4916,
2672
+ "step": 4440
2673
+ },
2674
+ {
2675
+ "epoch": 0.27,
2676
+ "learning_rate": 0.0018257575757575758,
2677
+ "loss": 3.9377,
2678
+ "step": 4450
2679
+ },
2680
+ {
2681
+ "epoch": 0.27,
2682
+ "learning_rate": 0.0018242424242424244,
2683
+ "loss": 3.9158,
2684
+ "step": 4460
2685
+ },
2686
+ {
2687
+ "epoch": 0.27,
2688
+ "learning_rate": 0.0018227272727272727,
2689
+ "loss": 3.6584,
2690
+ "step": 4470
2691
+ },
2692
+ {
2693
+ "epoch": 0.27,
2694
+ "learning_rate": 0.0018212121212121213,
2695
+ "loss": 3.9092,
2696
+ "step": 4480
2697
+ },
2698
+ {
2699
+ "epoch": 0.27,
2700
+ "learning_rate": 0.0018196969696969698,
2701
+ "loss": 4.0258,
2702
+ "step": 4490
2703
+ },
2704
+ {
2705
+ "epoch": 0.27,
2706
+ "learning_rate": 0.0018181818181818182,
2707
+ "loss": 4.1592,
2708
+ "step": 4500
2709
+ },
2710
+ {
2711
+ "epoch": 0.28,
2712
+ "learning_rate": 0.0018166666666666667,
2713
+ "loss": 3.96,
2714
+ "step": 4510
2715
+ },
2716
+ {
2717
+ "epoch": 0.28,
2718
+ "learning_rate": 0.0018151515151515153,
2719
+ "loss": 4.0961,
2720
+ "step": 4520
2721
+ },
2722
+ {
2723
+ "epoch": 0.28,
2724
+ "learning_rate": 0.0018136363636363636,
2725
+ "loss": 4.3369,
2726
+ "step": 4530
2727
+ },
2728
+ {
2729
+ "epoch": 0.28,
2730
+ "learning_rate": 0.0018121212121212122,
2731
+ "loss": 4.26,
2732
+ "step": 4540
2733
+ },
2734
+ {
2735
+ "epoch": 0.28,
2736
+ "learning_rate": 0.0018106060606060607,
2737
+ "loss": 3.7775,
2738
+ "step": 4550
2739
+ },
2740
+ {
2741
+ "epoch": 0.28,
2742
+ "learning_rate": 0.001809090909090909,
2743
+ "loss": 4.2238,
2744
+ "step": 4560
2745
+ },
2746
+ {
2747
+ "epoch": 0.28,
2748
+ "learning_rate": 0.0018075757575757576,
2749
+ "loss": 4.024,
2750
+ "step": 4570
2751
+ },
2752
+ {
2753
+ "epoch": 0.28,
2754
+ "learning_rate": 0.0018060606060606062,
2755
+ "loss": 4.4203,
2756
+ "step": 4580
2757
+ },
2758
+ {
2759
+ "epoch": 0.28,
2760
+ "learning_rate": 0.0018045454545454545,
2761
+ "loss": 3.927,
2762
+ "step": 4590
2763
+ },
2764
+ {
2765
+ "epoch": 0.28,
2766
+ "learning_rate": 0.001803030303030303,
2767
+ "loss": 4.0777,
2768
+ "step": 4600
2769
+ },
2770
+ {
2771
+ "epoch": 0.28,
2772
+ "learning_rate": 0.0018015151515151514,
2773
+ "loss": 4.002,
2774
+ "step": 4610
2775
+ },
2776
+ {
2777
+ "epoch": 0.28,
2778
+ "learning_rate": 0.0018,
2779
+ "loss": 4.4143,
2780
+ "step": 4620
2781
+ },
2782
+ {
2783
+ "epoch": 0.28,
2784
+ "learning_rate": 0.0017984848484848485,
2785
+ "loss": 3.9836,
2786
+ "step": 4630
2787
+ },
2788
+ {
2789
+ "epoch": 0.28,
2790
+ "learning_rate": 0.0017969696969696968,
2791
+ "loss": 4.1457,
2792
+ "step": 4640
2793
+ },
2794
+ {
2795
+ "epoch": 0.28,
2796
+ "learning_rate": 0.0017954545454545454,
2797
+ "loss": 3.8955,
2798
+ "step": 4650
2799
+ },
2800
+ {
2801
+ "epoch": 0.28,
2802
+ "learning_rate": 0.001793939393939394,
2803
+ "loss": 4.282,
2804
+ "step": 4660
2805
+ },
2806
+ {
2807
+ "epoch": 0.28,
2808
+ "learning_rate": 0.0017924242424242423,
2809
+ "loss": 4.1152,
2810
+ "step": 4670
2811
+ },
2812
+ {
2813
+ "epoch": 0.29,
2814
+ "learning_rate": 0.0017909090909090908,
2815
+ "loss": 4.4537,
2816
+ "step": 4680
2817
+ },
2818
+ {
2819
+ "epoch": 0.29,
2820
+ "learning_rate": 0.0017893939393939394,
2821
+ "loss": 4.3918,
2822
+ "step": 4690
2823
+ },
2824
+ {
2825
+ "epoch": 0.29,
2826
+ "learning_rate": 0.001787878787878788,
2827
+ "loss": 3.9969,
2828
+ "step": 4700
2829
+ },
2830
+ {
2831
+ "epoch": 0.29,
2832
+ "learning_rate": 0.0017863636363636365,
2833
+ "loss": 4.4594,
2834
+ "step": 4710
2835
+ },
2836
+ {
2837
+ "epoch": 0.29,
2838
+ "learning_rate": 0.001784848484848485,
2839
+ "loss": 3.8802,
2840
+ "step": 4720
2841
+ },
2842
+ {
2843
+ "epoch": 0.29,
2844
+ "learning_rate": 0.0017833333333333334,
2845
+ "loss": 4.3977,
2846
+ "step": 4730
2847
+ },
2848
+ {
2849
+ "epoch": 0.29,
2850
+ "learning_rate": 0.001781818181818182,
2851
+ "loss": 3.9135,
2852
+ "step": 4740
2853
+ },
2854
+ {
2855
+ "epoch": 0.29,
2856
+ "learning_rate": 0.0017803030303030305,
2857
+ "loss": 4.2225,
2858
+ "step": 4750
2859
+ },
2860
+ {
2861
+ "epoch": 0.29,
2862
+ "learning_rate": 0.0017787878787878788,
2863
+ "loss": 4.1572,
2864
+ "step": 4760
2865
+ },
2866
+ {
2867
+ "epoch": 0.29,
2868
+ "learning_rate": 0.0017772727272727274,
2869
+ "loss": 3.9195,
2870
+ "step": 4770
2871
+ },
2872
+ {
2873
+ "epoch": 0.29,
2874
+ "learning_rate": 0.001775757575757576,
2875
+ "loss": 4.1182,
2876
+ "step": 4780
2877
+ },
2878
+ {
2879
+ "epoch": 0.29,
2880
+ "learning_rate": 0.0017742424242424243,
2881
+ "loss": 4.0127,
2882
+ "step": 4790
2883
+ },
2884
+ {
2885
+ "epoch": 0.29,
2886
+ "learning_rate": 0.0017727272727272728,
2887
+ "loss": 3.725,
2888
+ "step": 4800
2889
+ },
2890
+ {
2891
+ "epoch": 0.29,
2892
+ "learning_rate": 0.0017712121212121214,
2893
+ "loss": 3.9258,
2894
+ "step": 4810
2895
+ },
2896
+ {
2897
+ "epoch": 0.29,
2898
+ "learning_rate": 0.0017696969696969697,
2899
+ "loss": 3.6133,
2900
+ "step": 4820
2901
+ },
2902
+ {
2903
+ "epoch": 0.29,
2904
+ "learning_rate": 0.0017681818181818183,
2905
+ "loss": 3.6561,
2906
+ "step": 4830
2907
+ },
2908
+ {
2909
+ "epoch": 0.3,
2910
+ "learning_rate": 0.0017666666666666666,
2911
+ "loss": 3.9838,
2912
+ "step": 4840
2913
+ },
2914
+ {
2915
+ "epoch": 0.3,
2916
+ "learning_rate": 0.0017651515151515152,
2917
+ "loss": 4.0107,
2918
+ "step": 4850
2919
+ },
2920
+ {
2921
+ "epoch": 0.3,
2922
+ "learning_rate": 0.0017636363636363637,
2923
+ "loss": 4.1814,
2924
+ "step": 4860
2925
+ },
2926
+ {
2927
+ "epoch": 0.3,
2928
+ "learning_rate": 0.001762121212121212,
2929
+ "loss": 4.0902,
2930
+ "step": 4870
2931
+ },
2932
+ {
2933
+ "epoch": 0.3,
2934
+ "learning_rate": 0.0017606060606060606,
2935
+ "loss": 4.418,
2936
+ "step": 4880
2937
+ },
2938
+ {
2939
+ "epoch": 0.3,
2940
+ "learning_rate": 0.0017590909090909092,
2941
+ "loss": 4.008,
2942
+ "step": 4890
2943
+ },
2944
+ {
2945
+ "epoch": 0.3,
2946
+ "learning_rate": 0.0017575757575757575,
2947
+ "loss": 4.2344,
2948
+ "step": 4900
2949
+ },
2950
+ {
2951
+ "epoch": 0.3,
2952
+ "learning_rate": 0.001756060606060606,
2953
+ "loss": 3.9775,
2954
+ "step": 4910
2955
+ },
2956
+ {
2957
+ "epoch": 0.3,
2958
+ "learning_rate": 0.0017545454545454546,
2959
+ "loss": 4.8027,
2960
+ "step": 4920
2961
+ },
2962
+ {
2963
+ "epoch": 0.3,
2964
+ "learning_rate": 0.001753030303030303,
2965
+ "loss": 4.2629,
2966
+ "step": 4930
2967
+ },
2968
+ {
2969
+ "epoch": 0.3,
2970
+ "learning_rate": 0.0017515151515151515,
2971
+ "loss": 4.198,
2972
+ "step": 4940
2973
+ },
2974
+ {
2975
+ "epoch": 0.3,
2976
+ "learning_rate": 0.0017499999999999998,
2977
+ "loss": 4.0887,
2978
+ "step": 4950
2979
+ },
2980
+ {
2981
+ "epoch": 0.3,
2982
+ "learning_rate": 0.0017484848484848484,
2983
+ "loss": 4.1445,
2984
+ "step": 4960
2985
+ },
2986
+ {
2987
+ "epoch": 0.3,
2988
+ "learning_rate": 0.001746969696969697,
2989
+ "loss": 3.9627,
2990
+ "step": 4970
2991
+ },
2992
+ {
2993
+ "epoch": 0.3,
2994
+ "learning_rate": 0.0017454545454545457,
2995
+ "loss": 4.4545,
2996
+ "step": 4980
2997
+ },
2998
+ {
2999
+ "epoch": 0.3,
3000
+ "learning_rate": 0.001743939393939394,
3001
+ "loss": 4.0764,
3002
+ "step": 4990
3003
+ },
3004
+ {
3005
+ "epoch": 0.31,
3006
+ "learning_rate": 0.0017424242424242426,
3007
+ "loss": 4.1914,
3008
+ "step": 5000
3009
+ }
3010
+ ],
3011
+ "max_steps": 16500,
3012
+ "num_train_epochs": 2,
3013
+ "total_flos": 1.7332860616704e+17,
3014
+ "trial_name": null,
3015
+ "trial_params": null
3016
+ }
xiaowo/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bab6fefeccf33ecae53947b1c444bd9a1f0f1f040993b12582eba666e374911
3
+ size 3771